iptables.go 19 KB

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