iptables.go 19 KB

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