iptables.go 20 KB

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