iptables.go 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713
  1. // Copyright 2015 CoreOS, Inc.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package iptables
  15. import (
  16. "bytes"
  17. "fmt"
  18. "io"
  19. "net"
  20. "os/exec"
  21. "regexp"
  22. "strconv"
  23. "strings"
  24. "syscall"
  25. )
  26. // Adds the output of stderr to exec.ExitError
  27. type Error struct {
  28. exec.ExitError
  29. cmd exec.Cmd
  30. msg string
  31. exitStatus *int //for overriding
  32. }
  33. func (e *Error) ExitStatus() int {
  34. if e.exitStatus != nil {
  35. return *e.exitStatus
  36. }
  37. return e.Sys().(syscall.WaitStatus).ExitStatus()
  38. }
  39. func (e *Error) Error() string {
  40. return fmt.Sprintf("running %v: exit status %v: %v", e.cmd.Args, e.ExitStatus(), e.msg)
  41. }
  42. // IsNotExist returns true if the error is due to the chain or rule not existing
  43. func (e *Error) IsNotExist() bool {
  44. if e.ExitStatus() != 1 {
  45. return false
  46. }
  47. msgNoRuleExist := "Bad rule (does a matching rule exist in that chain?).\n"
  48. msgNoChainExist := "No chain/target/match by that name.\n"
  49. return strings.Contains(e.msg, msgNoRuleExist) || strings.Contains(e.msg, msgNoChainExist)
  50. }
  51. // Protocol to differentiate between IPv4 and IPv6
  52. type Protocol byte
  53. const (
  54. ProtocolIPv4 Protocol = iota
  55. ProtocolIPv6
  56. )
  57. type IPTables struct {
  58. path string
  59. proto Protocol
  60. hasCheck bool
  61. hasWait bool
  62. waitSupportSecond bool
  63. hasRandomFully bool
  64. v1 int
  65. v2 int
  66. v3 int
  67. mode string // the underlying iptables operating mode, e.g. nf_tables
  68. timeout int // time to wait for the iptables lock, default waits forever
  69. }
  70. // Stat represents a structured statistic entry.
  71. type Stat struct {
  72. Packets uint64 `json:"pkts"`
  73. Bytes uint64 `json:"bytes"`
  74. Target string `json:"target"`
  75. Protocol string `json:"prot"`
  76. Opt string `json:"opt"`
  77. Input string `json:"in"`
  78. Output string `json:"out"`
  79. Source *net.IPNet `json:"source"`
  80. Destination *net.IPNet `json:"destination"`
  81. Options string `json:"options"`
  82. }
  83. type option func(*IPTables)
  84. func IPFamily(proto Protocol) option {
  85. return func(ipt *IPTables) {
  86. ipt.proto = proto
  87. }
  88. }
  89. func Timeout(timeout int) option {
  90. return func(ipt *IPTables) {
  91. ipt.timeout = timeout
  92. }
  93. }
  94. // New creates a new IPTables configured with the options passed as parameter.
  95. // For backwards compatibility, by default always uses IPv4 and timeout 0.
  96. // i.e. you can create an IPv6 IPTables using a timeout of 5 seconds passing
  97. // the IPFamily and Timeout options as follow:
  98. //
  99. // ip6t := New(IPFamily(ProtocolIPv6), Timeout(5))
  100. func New(opts ...option) (*IPTables, error) {
  101. ipt := &IPTables{
  102. proto: ProtocolIPv4,
  103. timeout: 0,
  104. }
  105. for _, opt := range opts {
  106. opt(ipt)
  107. }
  108. path, err := exec.LookPath(getIptablesCommand(ipt.proto))
  109. if err != nil {
  110. return nil, err
  111. }
  112. ipt.path = path
  113. vstring, err := getIptablesVersionString(path)
  114. if err != nil {
  115. return nil, fmt.Errorf("could not get iptables version: %v", err)
  116. }
  117. v1, v2, v3, mode, err := extractIptablesVersion(vstring)
  118. if err != nil {
  119. return nil, fmt.Errorf("failed to extract iptables version from [%s]: %v", vstring, err)
  120. }
  121. ipt.v1 = v1
  122. ipt.v2 = v2
  123. ipt.v3 = v3
  124. ipt.mode = mode
  125. checkPresent, waitPresent, waitSupportSecond, randomFullyPresent := getIptablesCommandSupport(v1, v2, v3)
  126. ipt.hasCheck = checkPresent
  127. ipt.hasWait = waitPresent
  128. ipt.waitSupportSecond = waitSupportSecond
  129. ipt.hasRandomFully = randomFullyPresent
  130. return ipt, nil
  131. }
  132. // New creates a new IPTables for the given proto.
  133. // The proto will determine which command is used, either "iptables" or "ip6tables".
  134. func NewWithProtocol(proto Protocol) (*IPTables, error) {
  135. return New(IPFamily(proto), Timeout(0))
  136. }
  137. // Proto returns the protocol used by this IPTables.
  138. func (ipt *IPTables) Proto() Protocol {
  139. return ipt.proto
  140. }
  141. // Exists checks if given rulespec in specified table/chain exists
  142. func (ipt *IPTables) Exists(table, chain string, rulespec ...string) (bool, error) {
  143. if !ipt.hasCheck {
  144. return ipt.existsForOldIptables(table, chain, rulespec)
  145. }
  146. cmd := append([]string{"-t", table, "-C", chain}, rulespec...)
  147. err := ipt.run(cmd...)
  148. eerr, eok := err.(*Error)
  149. switch {
  150. case err == nil:
  151. return true, nil
  152. case eok && eerr.ExitStatus() == 1:
  153. return false, nil
  154. default:
  155. return false, err
  156. }
  157. }
  158. // Insert inserts rulespec to specified table/chain (in specified pos)
  159. func (ipt *IPTables) Insert(table, chain string, pos int, rulespec ...string) error {
  160. cmd := append([]string{"-t", table, "-I", chain, strconv.Itoa(pos)}, rulespec...)
  161. return ipt.run(cmd...)
  162. }
  163. // Replace replaces rulespec to specified table/chain (in specified pos)
  164. func (ipt *IPTables) Replace(table, chain string, pos int, rulespec ...string) error {
  165. cmd := append([]string{"-t", table, "-R", chain, strconv.Itoa(pos)}, rulespec...)
  166. return ipt.run(cmd...)
  167. }
  168. // InsertUnique acts like Insert except that it won't insert a duplicate (no matter the position in the chain)
  169. func (ipt *IPTables) InsertUnique(table, chain string, pos int, rulespec ...string) error {
  170. exists, err := ipt.Exists(table, chain, rulespec...)
  171. if err != nil {
  172. return err
  173. }
  174. if !exists {
  175. return ipt.Insert(table, chain, pos, rulespec...)
  176. }
  177. return nil
  178. }
  179. // Append appends rulespec to specified table/chain
  180. func (ipt *IPTables) Append(table, chain string, rulespec ...string) error {
  181. cmd := append([]string{"-t", table, "-A", chain}, rulespec...)
  182. return ipt.run(cmd...)
  183. }
  184. // AppendUnique acts like Append except that it won't add a duplicate
  185. func (ipt *IPTables) AppendUnique(table, chain string, rulespec ...string) error {
  186. exists, err := ipt.Exists(table, chain, rulespec...)
  187. if err != nil {
  188. return err
  189. }
  190. if !exists {
  191. return ipt.Append(table, chain, rulespec...)
  192. }
  193. return nil
  194. }
  195. // Delete removes rulespec in specified table/chain
  196. func (ipt *IPTables) Delete(table, chain string, rulespec ...string) error {
  197. cmd := append([]string{"-t", table, "-D", chain}, rulespec...)
  198. return ipt.run(cmd...)
  199. }
  200. func (ipt *IPTables) DeleteIfExists(table, chain string, rulespec ...string) error {
  201. exists, err := ipt.Exists(table, chain, rulespec...)
  202. if err == nil && exists {
  203. err = ipt.Delete(table, chain, rulespec...)
  204. }
  205. return err
  206. }
  207. // List rules in specified table/chain
  208. func (ipt *IPTables) ListById(table, chain string, id int) (string, error) {
  209. args := []string{"-t", table, "-S", chain, strconv.Itoa(id)}
  210. rule, err := ipt.executeList(args)
  211. if err != nil {
  212. return "", err
  213. }
  214. return rule[0], nil
  215. }
  216. // List rules in specified table/chain
  217. func (ipt *IPTables) List(table, chain string) ([]string, error) {
  218. args := []string{"-t", table, "-S", chain}
  219. return ipt.executeList(args)
  220. }
  221. // List rules (with counters) in specified table/chain
  222. func (ipt *IPTables) ListWithCounters(table, chain string) ([]string, error) {
  223. args := []string{"-t", table, "-v", "-S", chain}
  224. return ipt.executeList(args)
  225. }
  226. // ListChains returns a slice containing the name of each chain in the specified table.
  227. func (ipt *IPTables) ListChains(table string) ([]string, error) {
  228. args := []string{"-t", table, "-S"}
  229. result, err := ipt.executeList(args)
  230. if err != nil {
  231. return nil, err
  232. }
  233. // Iterate over rules to find all default (-P) and user-specified (-N) chains.
  234. // Chains definition always come before rules.
  235. // Format is the following:
  236. // -P OUTPUT ACCEPT
  237. // -N Custom
  238. var chains []string
  239. for _, val := range result {
  240. if strings.HasPrefix(val, "-P") || strings.HasPrefix(val, "-N") {
  241. chains = append(chains, strings.Fields(val)[1])
  242. } else {
  243. break
  244. }
  245. }
  246. return chains, nil
  247. }
  248. // '-S' is fine with non existing rule index as long as the chain exists
  249. // therefore pass index 1 to reduce overhead for large chains
  250. func (ipt *IPTables) ChainExists(table, chain string) (bool, error) {
  251. err := ipt.run("-t", table, "-S", chain, "1")
  252. eerr, eok := err.(*Error)
  253. switch {
  254. case err == nil:
  255. return true, nil
  256. case eok && eerr.ExitStatus() == 1:
  257. return false, nil
  258. default:
  259. return false, err
  260. }
  261. }
  262. // Stats lists rules including the byte and packet counts
  263. func (ipt *IPTables) Stats(table, chain string) ([][]string, error) {
  264. args := []string{"-t", table, "-L", chain, "-n", "-v", "-x"}
  265. lines, err := ipt.executeList(args)
  266. if err != nil {
  267. return nil, err
  268. }
  269. appendSubnet := func(addr string) string {
  270. if strings.IndexByte(addr, byte('/')) < 0 {
  271. if strings.IndexByte(addr, '.') < 0 {
  272. return addr + "/128"
  273. }
  274. return addr + "/32"
  275. }
  276. return addr
  277. }
  278. ipv6 := ipt.proto == ProtocolIPv6
  279. rows := [][]string{}
  280. for i, line := range lines {
  281. // Skip over chain name and field header
  282. if i < 2 {
  283. continue
  284. }
  285. // Fields:
  286. // 0=pkts 1=bytes 2=target 3=prot 4=opt 5=in 6=out 7=source 8=destination 9=options
  287. line = strings.TrimSpace(line)
  288. fields := strings.Fields(line)
  289. // The ip6tables verbose output cannot be naively split due to the default "opt"
  290. // field containing 2 single spaces.
  291. if ipv6 {
  292. // Check if field 6 is "opt" or "source" address
  293. dest := fields[6]
  294. ip, _, _ := net.ParseCIDR(dest)
  295. if ip == nil {
  296. ip = net.ParseIP(dest)
  297. }
  298. // If we detected a CIDR or IP, the "opt" field is empty.. insert it.
  299. if ip != nil {
  300. f := []string{}
  301. f = append(f, fields[:4]...)
  302. f = append(f, " ") // Empty "opt" field for ip6tables
  303. f = append(f, fields[4:]...)
  304. fields = f
  305. }
  306. }
  307. // Adjust "source" and "destination" to include netmask, to match regular
  308. // List output
  309. fields[7] = appendSubnet(fields[7])
  310. fields[8] = appendSubnet(fields[8])
  311. // Combine "options" fields 9... into a single space-delimited field.
  312. options := fields[9:]
  313. fields = fields[:9]
  314. fields = append(fields, strings.Join(options, " "))
  315. rows = append(rows, fields)
  316. }
  317. return rows, nil
  318. }
  319. // ParseStat parses a single statistic row into a Stat struct. The input should
  320. // be a string slice that is returned from calling the Stat method.
  321. func (ipt *IPTables) ParseStat(stat []string) (parsed Stat, err error) {
  322. // For forward-compatibility, expect at least 10 fields in the stat
  323. if len(stat) < 10 {
  324. return parsed, fmt.Errorf("stat contained fewer fields than expected")
  325. }
  326. // Convert the fields that are not plain strings
  327. parsed.Packets, err = strconv.ParseUint(stat[0], 0, 64)
  328. if err != nil {
  329. return parsed, fmt.Errorf(err.Error(), "could not parse packets")
  330. }
  331. parsed.Bytes, err = strconv.ParseUint(stat[1], 0, 64)
  332. if err != nil {
  333. return parsed, fmt.Errorf(err.Error(), "could not parse bytes")
  334. }
  335. _, parsed.Source, err = net.ParseCIDR(stat[7])
  336. if err != nil {
  337. return parsed, fmt.Errorf(err.Error(), "could not parse source")
  338. }
  339. _, parsed.Destination, err = net.ParseCIDR(stat[8])
  340. if err != nil {
  341. return parsed, fmt.Errorf(err.Error(), "could not parse destination")
  342. }
  343. // Put the fields that are strings
  344. parsed.Target = stat[2]
  345. parsed.Protocol = stat[3]
  346. parsed.Opt = stat[4]
  347. parsed.Input = stat[5]
  348. parsed.Output = stat[6]
  349. parsed.Options = stat[9]
  350. return parsed, nil
  351. }
  352. // StructuredStats returns statistics as structured data which may be further
  353. // parsed and marshaled.
  354. func (ipt *IPTables) StructuredStats(table, chain string) ([]Stat, error) {
  355. rawStats, err := ipt.Stats(table, chain)
  356. if err != nil {
  357. return nil, err
  358. }
  359. structStats := []Stat{}
  360. for _, rawStat := range rawStats {
  361. stat, err := ipt.ParseStat(rawStat)
  362. if err != nil {
  363. return nil, err
  364. }
  365. structStats = append(structStats, stat)
  366. }
  367. return structStats, nil
  368. }
  369. func (ipt *IPTables) executeList(args []string) ([]string, error) {
  370. var stdout bytes.Buffer
  371. if err := ipt.runWithOutput(args, &stdout); err != nil {
  372. return nil, err
  373. }
  374. rules := strings.Split(stdout.String(), "\n")
  375. // strip trailing newline
  376. if len(rules) > 0 && rules[len(rules)-1] == "" {
  377. rules = rules[:len(rules)-1]
  378. }
  379. for i, rule := range rules {
  380. rules[i] = filterRuleOutput(rule)
  381. }
  382. return rules, nil
  383. }
  384. // NewChain creates a new chain in the specified table.
  385. // If the chain already exists, it will result in an error.
  386. func (ipt *IPTables) NewChain(table, chain string) error {
  387. return ipt.run("-t", table, "-N", chain)
  388. }
  389. const existsErr = 1
  390. // ClearChain flushed (deletes all rules) in the specified table/chain.
  391. // If the chain does not exist, a new one will be created
  392. func (ipt *IPTables) ClearChain(table, chain string) error {
  393. err := ipt.NewChain(table, chain)
  394. eerr, eok := err.(*Error)
  395. switch {
  396. case err == nil:
  397. return nil
  398. case eok && eerr.ExitStatus() == existsErr:
  399. // chain already exists. Flush (clear) it.
  400. return ipt.run("-t", table, "-F", chain)
  401. default:
  402. return err
  403. }
  404. }
  405. // RenameChain renames the old chain to the new one.
  406. func (ipt *IPTables) RenameChain(table, oldChain, newChain string) error {
  407. return ipt.run("-t", table, "-E", oldChain, newChain)
  408. }
  409. // DeleteChain deletes the chain in the specified table.
  410. // The chain must be empty
  411. func (ipt *IPTables) DeleteChain(table, chain string) error {
  412. return ipt.run("-t", table, "-X", chain)
  413. }
  414. func (ipt *IPTables) ClearAndDeleteChain(table, chain string) error {
  415. exists, err := ipt.ChainExists(table, chain)
  416. if err != nil || !exists {
  417. return err
  418. }
  419. err = ipt.run("-t", table, "-F", chain)
  420. if err == nil {
  421. err = ipt.run("-t", table, "-X", chain)
  422. }
  423. return err
  424. }
  425. func (ipt *IPTables) ClearAll() error {
  426. return ipt.run("-F")
  427. }
  428. func (ipt *IPTables) DeleteAll() error {
  429. return ipt.run("-X")
  430. }
  431. // ChangePolicy changes policy on chain to target
  432. func (ipt *IPTables) ChangePolicy(table, chain, target string) error {
  433. return ipt.run("-t", table, "-P", chain, target)
  434. }
  435. // Check if the underlying iptables command supports the --random-fully flag
  436. func (ipt *IPTables) HasRandomFully() bool {
  437. return ipt.hasRandomFully
  438. }
  439. // Return version components of the underlying iptables command
  440. func (ipt *IPTables) GetIptablesVersion() (int, int, int) {
  441. return ipt.v1, ipt.v2, ipt.v3
  442. }
  443. // run runs an iptables command with the given arguments, ignoring
  444. // any stdout output
  445. func (ipt *IPTables) run(args ...string) error {
  446. return ipt.runWithOutput(args, nil)
  447. }
  448. // runWithOutput runs an iptables command with the given arguments,
  449. // writing any stdout output to the given writer
  450. func (ipt *IPTables) runWithOutput(args []string, stdout io.Writer) error {
  451. args = append([]string{ipt.path}, args...)
  452. if ipt.hasWait {
  453. args = append(args, "--wait")
  454. if ipt.timeout != 0 && ipt.waitSupportSecond {
  455. args = append(args, strconv.Itoa(ipt.timeout))
  456. }
  457. } else {
  458. fmu, err := newXtablesFileLock()
  459. if err != nil {
  460. return err
  461. }
  462. ul, err := fmu.tryLock()
  463. if err != nil {
  464. syscall.Close(fmu.fd)
  465. return err
  466. }
  467. defer func() {
  468. _ = ul.Unlock()
  469. }()
  470. }
  471. var stderr bytes.Buffer
  472. cmd := exec.Cmd{
  473. Path: ipt.path,
  474. Args: args,
  475. Stdout: stdout,
  476. Stderr: &stderr,
  477. }
  478. if err := cmd.Run(); err != nil {
  479. switch e := err.(type) {
  480. case *exec.ExitError:
  481. return &Error{*e, cmd, stderr.String(), nil}
  482. default:
  483. return err
  484. }
  485. }
  486. return nil
  487. }
  488. // getIptablesCommand returns the correct command for the given protocol, either "iptables" or "ip6tables".
  489. func getIptablesCommand(proto Protocol) string {
  490. if proto == ProtocolIPv6 {
  491. return "ip6tables"
  492. } else {
  493. return "iptables"
  494. }
  495. }
  496. // Checks if iptables has the "-C" and "--wait" flag
  497. func getIptablesCommandSupport(v1 int, v2 int, v3 int) (bool, bool, bool, bool) {
  498. return iptablesHasCheckCommand(v1, v2, v3), iptablesHasWaitCommand(v1, v2, v3), iptablesWaitSupportSecond(v1, v2, v3), iptablesHasRandomFully(v1, v2, v3)
  499. }
  500. // getIptablesVersion returns the first three components of the iptables version
  501. // and the operating mode (e.g. nf_tables or legacy)
  502. // e.g. "iptables v1.3.66" would return (1, 3, 66, legacy, nil)
  503. func extractIptablesVersion(str string) (int, int, int, string, error) {
  504. versionMatcher := regexp.MustCompile(`v([0-9]+)\.([0-9]+)\.([0-9]+)(?:\s+\((\w+))?`)
  505. result := versionMatcher.FindStringSubmatch(str)
  506. if result == nil {
  507. return 0, 0, 0, "", fmt.Errorf("no iptables version found in string: %s", str)
  508. }
  509. v1, err := strconv.Atoi(result[1])
  510. if err != nil {
  511. return 0, 0, 0, "", err
  512. }
  513. v2, err := strconv.Atoi(result[2])
  514. if err != nil {
  515. return 0, 0, 0, "", err
  516. }
  517. v3, err := strconv.Atoi(result[3])
  518. if err != nil {
  519. return 0, 0, 0, "", err
  520. }
  521. mode := "legacy"
  522. if result[4] != "" {
  523. mode = result[4]
  524. }
  525. return v1, v2, v3, mode, nil
  526. }
  527. // Runs "iptables --version" to get the version string
  528. func getIptablesVersionString(path string) (string, error) {
  529. cmd := exec.Command(path, "--version")
  530. var out bytes.Buffer
  531. cmd.Stdout = &out
  532. err := cmd.Run()
  533. if err != nil {
  534. return "", err
  535. }
  536. return out.String(), nil
  537. }
  538. // Checks if an iptables version is after 1.4.11, when --check was added
  539. func iptablesHasCheckCommand(v1 int, v2 int, v3 int) bool {
  540. if v1 > 1 {
  541. return true
  542. }
  543. if v1 == 1 && v2 > 4 {
  544. return true
  545. }
  546. if v1 == 1 && v2 == 4 && v3 >= 11 {
  547. return true
  548. }
  549. return false
  550. }
  551. // Checks if an iptables version is after 1.4.20, when --wait was added
  552. func iptablesHasWaitCommand(v1 int, v2 int, v3 int) bool {
  553. if v1 > 1 {
  554. return true
  555. }
  556. if v1 == 1 && v2 > 4 {
  557. return true
  558. }
  559. if v1 == 1 && v2 == 4 && v3 >= 20 {
  560. return true
  561. }
  562. return false
  563. }
  564. // Checks if an iptablse version is after 1.6.0, when --wait support second
  565. func iptablesWaitSupportSecond(v1 int, v2 int, v3 int) bool {
  566. if v1 > 1 {
  567. return true
  568. }
  569. if v1 == 1 && v2 >= 6 {
  570. return true
  571. }
  572. return false
  573. }
  574. // Checks if an iptables version is after 1.6.2, when --random-fully was added
  575. func iptablesHasRandomFully(v1 int, v2 int, v3 int) bool {
  576. if v1 > 1 {
  577. return true
  578. }
  579. if v1 == 1 && v2 > 6 {
  580. return true
  581. }
  582. if v1 == 1 && v2 == 6 && v3 >= 2 {
  583. return true
  584. }
  585. return false
  586. }
  587. // Checks if a rule specification exists for a table
  588. func (ipt *IPTables) existsForOldIptables(table, chain string, rulespec []string) (bool, error) {
  589. rs := strings.Join(append([]string{"-A", chain}, rulespec...), " ")
  590. args := []string{"-t", table, "-S"}
  591. var stdout bytes.Buffer
  592. err := ipt.runWithOutput(args, &stdout)
  593. if err != nil {
  594. return false, err
  595. }
  596. return strings.Contains(stdout.String(), rs), nil
  597. }
  598. // counterRegex is the regex used to detect nftables counter format
  599. var counterRegex = regexp.MustCompile(`^\[([0-9]+):([0-9]+)\] `)
  600. // filterRuleOutput works around some inconsistencies in output.
  601. // For example, when iptables is in legacy vs. nftables mode, it produces
  602. // different results.
  603. func filterRuleOutput(rule string) string {
  604. out := rule
  605. // work around an output difference in nftables mode where counters
  606. // are output in iptables-save format, rather than iptables -S format
  607. // The string begins with "[0:0]"
  608. //
  609. // Fixes #49
  610. if groups := counterRegex.FindStringSubmatch(out); groups != nil {
  611. // drop the brackets
  612. out = out[len(groups[0]):]
  613. out = fmt.Sprintf("%s -c %s %s", out, groups[1], groups[2])
  614. }
  615. return out
  616. }