iptables.go 19 KB

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