iptables.go 19 KB

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