iptables.go 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662
  1. //go:build linux
  2. // +build linux
  3. package iptables
  4. import (
  5. "errors"
  6. "fmt"
  7. "net"
  8. "os/exec"
  9. "regexp"
  10. "strconv"
  11. "strings"
  12. "sync"
  13. "time"
  14. "github.com/docker/docker/rootless"
  15. "github.com/sirupsen/logrus"
  16. )
  17. // Action signifies the iptable action.
  18. type Action string
  19. // Policy is the default iptable policies
  20. type Policy string
  21. // Table refers to Nat, Filter or Mangle.
  22. type Table string
  23. // IPVersion refers to IP version, v4 or v6
  24. type IPVersion string
  25. const (
  26. // Append appends the rule at the end of the chain.
  27. Append Action = "-A"
  28. // Delete deletes the rule from the chain.
  29. Delete Action = "-D"
  30. // Insert inserts the rule at the top of the chain.
  31. Insert Action = "-I"
  32. // Nat table is used for nat translation rules.
  33. Nat Table = "nat"
  34. // Filter table is used for filter rules.
  35. Filter Table = "filter"
  36. // Mangle table is used for mangling the packet.
  37. Mangle Table = "mangle"
  38. // Drop is the default iptables DROP policy
  39. Drop Policy = "DROP"
  40. // Accept is the default iptables ACCEPT policy
  41. Accept Policy = "ACCEPT"
  42. // IPv4 is version 4
  43. IPv4 IPVersion = "IPV4"
  44. // IPv6 is version 6
  45. IPv6 IPVersion = "IPV6"
  46. )
  47. var (
  48. iptablesPath string
  49. ip6tablesPath string
  50. supportsXlock = false
  51. supportsCOpt = false
  52. xLockWaitMsg = "Another app is currently holding the xtables lock"
  53. // used to lock iptables commands if xtables lock is not supported
  54. bestEffortLock sync.Mutex
  55. // ErrIptablesNotFound is returned when the rule is not found.
  56. ErrIptablesNotFound = errors.New("Iptables not found")
  57. initOnce sync.Once
  58. )
  59. // IPTable defines struct with IPVersion
  60. type IPTable struct {
  61. Version IPVersion
  62. }
  63. // ChainInfo defines the iptables chain.
  64. type ChainInfo struct {
  65. Name string
  66. Table Table
  67. HairpinMode bool
  68. IPTable IPTable
  69. }
  70. // ChainError is returned to represent errors during ip table operation.
  71. type ChainError struct {
  72. Chain string
  73. Output []byte
  74. }
  75. func (e ChainError) Error() string {
  76. return fmt.Sprintf("Error iptables %s: %s", e.Chain, string(e.Output))
  77. }
  78. func probe() {
  79. path, err := exec.LookPath("iptables")
  80. if err != nil {
  81. logrus.Warnf("Failed to find iptables: %v", err)
  82. return
  83. }
  84. if out, err := exec.Command(path, "--wait", "-t", "nat", "-L", "-n").CombinedOutput(); err != nil {
  85. logrus.Warnf("Running iptables --wait -t nat -L -n failed with message: `%s`, error: %v", strings.TrimSpace(string(out)), err)
  86. }
  87. _, err = exec.LookPath("ip6tables")
  88. if err != nil {
  89. logrus.Warnf("Failed to find ip6tables: %v", err)
  90. return
  91. }
  92. }
  93. func initFirewalld() {
  94. // When running with RootlessKit, firewalld is running as the root outside our network namespace
  95. // https://github.com/moby/moby/issues/43781
  96. if rootless.RunningWithRootlessKit() {
  97. logrus.Info("skipping firewalld management for rootless mode")
  98. return
  99. }
  100. if err := FirewalldInit(); err != nil {
  101. logrus.Debugf("Fail to initialize firewalld: %v, using raw iptables instead", err)
  102. }
  103. }
  104. func detectIptables() {
  105. path, err := exec.LookPath("iptables")
  106. if err != nil {
  107. return
  108. }
  109. iptablesPath = path
  110. path, err = exec.LookPath("ip6tables")
  111. if err != nil {
  112. return
  113. }
  114. ip6tablesPath = path
  115. supportsXlock = exec.Command(iptablesPath, "--wait", "-L", "-n").Run() == nil
  116. mj, mn, mc, err := GetVersion()
  117. if err != nil {
  118. logrus.Warnf("Failed to read iptables version: %v", err)
  119. return
  120. }
  121. supportsCOpt = supportsCOption(mj, mn, mc)
  122. }
  123. func initDependencies() {
  124. probe()
  125. initFirewalld()
  126. detectIptables()
  127. }
  128. func initCheck() error {
  129. initOnce.Do(initDependencies)
  130. if iptablesPath == "" {
  131. return ErrIptablesNotFound
  132. }
  133. return nil
  134. }
  135. // GetIptable returns an instance of IPTable with specified version
  136. func GetIptable(version IPVersion) *IPTable {
  137. return &IPTable{Version: version}
  138. }
  139. // NewChain adds a new chain to ip table.
  140. func (iptable IPTable) NewChain(name string, table Table, hairpinMode bool) (*ChainInfo, error) {
  141. c := &ChainInfo{
  142. Name: name,
  143. Table: table,
  144. HairpinMode: hairpinMode,
  145. IPTable: iptable,
  146. }
  147. if string(c.Table) == "" {
  148. c.Table = Filter
  149. }
  150. // Add chain if it doesn't exist
  151. if _, err := iptable.Raw("-t", string(c.Table), "-n", "-L", c.Name); err != nil {
  152. if output, err := iptable.Raw("-t", string(c.Table), "-N", c.Name); err != nil {
  153. return nil, err
  154. } else if len(output) != 0 {
  155. return nil, fmt.Errorf("Could not create %s/%s chain: %s", c.Table, c.Name, output)
  156. }
  157. }
  158. return c, nil
  159. }
  160. // LoopbackByVersion returns loopback address by version
  161. func (iptable IPTable) LoopbackByVersion() string {
  162. if iptable.Version == IPv6 {
  163. return "::1/128"
  164. }
  165. return "127.0.0.0/8"
  166. }
  167. // ProgramChain is used to add rules to a chain
  168. func (iptable IPTable) ProgramChain(c *ChainInfo, bridgeName string, hairpinMode, enable bool) error {
  169. if c.Name == "" {
  170. return errors.New("Could not program chain, missing chain name")
  171. }
  172. // Either add or remove the interface from the firewalld zone
  173. if firewalldRunning {
  174. if enable {
  175. if err := AddInterfaceFirewalld(bridgeName); err != nil {
  176. return err
  177. }
  178. } else {
  179. if err := DelInterfaceFirewalld(bridgeName); err != nil {
  180. return err
  181. }
  182. }
  183. }
  184. switch c.Table {
  185. case Nat:
  186. preroute := []string{
  187. "-m", "addrtype",
  188. "--dst-type", "LOCAL",
  189. "-j", c.Name}
  190. if !iptable.Exists(Nat, "PREROUTING", preroute...) && enable {
  191. if err := c.Prerouting(Append, preroute...); err != nil {
  192. return fmt.Errorf("Failed to inject %s in PREROUTING chain: %s", c.Name, err)
  193. }
  194. } else if iptable.Exists(Nat, "PREROUTING", preroute...) && !enable {
  195. if err := c.Prerouting(Delete, preroute...); err != nil {
  196. return fmt.Errorf("Failed to remove %s in PREROUTING chain: %s", c.Name, err)
  197. }
  198. }
  199. output := []string{
  200. "-m", "addrtype",
  201. "--dst-type", "LOCAL",
  202. "-j", c.Name}
  203. if !hairpinMode {
  204. output = append(output, "!", "--dst", iptable.LoopbackByVersion())
  205. }
  206. if !iptable.Exists(Nat, "OUTPUT", output...) && enable {
  207. if err := c.Output(Append, output...); err != nil {
  208. return fmt.Errorf("Failed to inject %s in OUTPUT chain: %s", c.Name, err)
  209. }
  210. } else if iptable.Exists(Nat, "OUTPUT", output...) && !enable {
  211. if err := c.Output(Delete, output...); err != nil {
  212. return fmt.Errorf("Failed to inject %s in OUTPUT chain: %s", c.Name, err)
  213. }
  214. }
  215. case Filter:
  216. if bridgeName == "" {
  217. return fmt.Errorf("Could not program chain %s/%s, missing bridge name",
  218. c.Table, c.Name)
  219. }
  220. link := []string{
  221. "-o", bridgeName,
  222. "-j", c.Name}
  223. if !iptable.Exists(Filter, "FORWARD", link...) && enable {
  224. insert := append([]string{string(Insert), "FORWARD"}, link...)
  225. if output, err := iptable.Raw(insert...); err != nil {
  226. return err
  227. } else if len(output) != 0 {
  228. return fmt.Errorf("Could not create linking rule to %s/%s: %s", c.Table, c.Name, output)
  229. }
  230. } else if iptable.Exists(Filter, "FORWARD", link...) && !enable {
  231. del := append([]string{string(Delete), "FORWARD"}, link...)
  232. if output, err := iptable.Raw(del...); err != nil {
  233. return err
  234. } else if len(output) != 0 {
  235. return fmt.Errorf("Could not delete linking rule from %s/%s: %s", c.Table, c.Name, output)
  236. }
  237. }
  238. establish := []string{
  239. "-o", bridgeName,
  240. "-m", "conntrack",
  241. "--ctstate", "RELATED,ESTABLISHED",
  242. "-j", "ACCEPT"}
  243. if !iptable.Exists(Filter, "FORWARD", establish...) && enable {
  244. insert := append([]string{string(Insert), "FORWARD"}, establish...)
  245. if output, err := iptable.Raw(insert...); err != nil {
  246. return err
  247. } else if len(output) != 0 {
  248. return fmt.Errorf("Could not create establish rule to %s: %s", c.Table, output)
  249. }
  250. } else if iptable.Exists(Filter, "FORWARD", establish...) && !enable {
  251. del := append([]string{string(Delete), "FORWARD"}, establish...)
  252. if output, err := iptable.Raw(del...); err != nil {
  253. return err
  254. } else if len(output) != 0 {
  255. return fmt.Errorf("Could not delete establish rule from %s: %s", c.Table, output)
  256. }
  257. }
  258. }
  259. return nil
  260. }
  261. // RemoveExistingChain removes existing chain from the table.
  262. func (iptable IPTable) RemoveExistingChain(name string, table Table) error {
  263. c := &ChainInfo{
  264. Name: name,
  265. Table: table,
  266. IPTable: iptable,
  267. }
  268. if string(c.Table) == "" {
  269. c.Table = Filter
  270. }
  271. return c.Remove()
  272. }
  273. // Forward adds forwarding rule to 'filter' table and corresponding nat rule to 'nat' table.
  274. func (c *ChainInfo) Forward(action Action, ip net.IP, port int, proto, destAddr string, destPort int, bridgeName string) error {
  275. iptable := GetIptable(c.IPTable.Version)
  276. daddr := ip.String()
  277. if ip.IsUnspecified() {
  278. // iptables interprets "0.0.0.0" as "0.0.0.0/32", whereas we
  279. // want "0.0.0.0/0". "0/0" is correctly interpreted as "any
  280. // value" by both iptables and ip6tables.
  281. daddr = "0/0"
  282. }
  283. args := []string{
  284. "-p", proto,
  285. "-d", daddr,
  286. "--dport", strconv.Itoa(port),
  287. "-j", "DNAT",
  288. "--to-destination", net.JoinHostPort(destAddr, strconv.Itoa(destPort))}
  289. if !c.HairpinMode {
  290. args = append(args, "!", "-i", bridgeName)
  291. }
  292. if err := iptable.ProgramRule(Nat, c.Name, action, args); err != nil {
  293. return err
  294. }
  295. args = []string{
  296. "!", "-i", bridgeName,
  297. "-o", bridgeName,
  298. "-p", proto,
  299. "-d", destAddr,
  300. "--dport", strconv.Itoa(destPort),
  301. "-j", "ACCEPT",
  302. }
  303. if err := iptable.ProgramRule(Filter, c.Name, action, args); err != nil {
  304. return err
  305. }
  306. args = []string{
  307. "-p", proto,
  308. "-s", destAddr,
  309. "-d", destAddr,
  310. "--dport", strconv.Itoa(destPort),
  311. "-j", "MASQUERADE",
  312. }
  313. if err := iptable.ProgramRule(Nat, "POSTROUTING", action, args); err != nil {
  314. return err
  315. }
  316. if proto == "sctp" {
  317. // Linux kernel v4.9 and below enables NETIF_F_SCTP_CRC for veth by
  318. // the following commit.
  319. // This introduces a problem when conbined with a physical NIC without
  320. // NETIF_F_SCTP_CRC. As for a workaround, here we add an iptables entry
  321. // to fill the checksum.
  322. //
  323. // https://github.com/torvalds/linux/commit/c80fafbbb59ef9924962f83aac85531039395b18
  324. args = []string{
  325. "-p", proto,
  326. "--sport", strconv.Itoa(destPort),
  327. "-j", "CHECKSUM",
  328. "--checksum-fill",
  329. }
  330. if err := iptable.ProgramRule(Mangle, "POSTROUTING", action, args); err != nil {
  331. return err
  332. }
  333. }
  334. return nil
  335. }
  336. // Link adds reciprocal ACCEPT rule for two supplied IP addresses.
  337. // Traffic is allowed from ip1 to ip2 and vice-versa
  338. func (c *ChainInfo) Link(action Action, ip1, ip2 net.IP, port int, proto string, bridgeName string) error {
  339. iptable := GetIptable(c.IPTable.Version)
  340. // forward
  341. args := []string{
  342. "-i", bridgeName, "-o", bridgeName,
  343. "-p", proto,
  344. "-s", ip1.String(),
  345. "-d", ip2.String(),
  346. "--dport", strconv.Itoa(port),
  347. "-j", "ACCEPT",
  348. }
  349. if err := iptable.ProgramRule(Filter, c.Name, action, args); err != nil {
  350. return err
  351. }
  352. // reverse
  353. args[7], args[9] = args[9], args[7]
  354. args[10] = "--sport"
  355. return iptable.ProgramRule(Filter, c.Name, action, args)
  356. }
  357. // ProgramRule adds the rule specified by args only if the
  358. // rule is not already present in the chain. Reciprocally,
  359. // it removes the rule only if present.
  360. func (iptable IPTable) ProgramRule(table Table, chain string, action Action, args []string) error {
  361. if iptable.Exists(table, chain, args...) != (action == Delete) {
  362. return nil
  363. }
  364. return iptable.RawCombinedOutput(append([]string{"-t", string(table), string(action), chain}, args...)...)
  365. }
  366. // Prerouting adds linking rule to nat/PREROUTING chain.
  367. func (c *ChainInfo) Prerouting(action Action, args ...string) error {
  368. iptable := GetIptable(c.IPTable.Version)
  369. a := []string{"-t", string(Nat), string(action), "PREROUTING"}
  370. if len(args) > 0 {
  371. a = append(a, args...)
  372. }
  373. if output, err := iptable.Raw(a...); err != nil {
  374. return err
  375. } else if len(output) != 0 {
  376. return ChainError{Chain: "PREROUTING", Output: output}
  377. }
  378. return nil
  379. }
  380. // Output adds linking rule to an OUTPUT chain.
  381. func (c *ChainInfo) Output(action Action, args ...string) error {
  382. iptable := GetIptable(c.IPTable.Version)
  383. a := []string{"-t", string(c.Table), string(action), "OUTPUT"}
  384. if len(args) > 0 {
  385. a = append(a, args...)
  386. }
  387. if output, err := iptable.Raw(a...); err != nil {
  388. return err
  389. } else if len(output) != 0 {
  390. return ChainError{Chain: "OUTPUT", Output: output}
  391. }
  392. return nil
  393. }
  394. // Remove removes the chain.
  395. func (c *ChainInfo) Remove() error {
  396. iptable := GetIptable(c.IPTable.Version)
  397. // Ignore errors - This could mean the chains were never set up
  398. if c.Table == Nat {
  399. c.Prerouting(Delete, "-m", "addrtype", "--dst-type", "LOCAL", "-j", c.Name)
  400. c.Output(Delete, "-m", "addrtype", "--dst-type", "LOCAL", "!", "--dst", iptable.LoopbackByVersion(), "-j", c.Name)
  401. c.Output(Delete, "-m", "addrtype", "--dst-type", "LOCAL", "-j", c.Name) // Created in versions <= 0.1.6
  402. c.Prerouting(Delete)
  403. c.Output(Delete)
  404. }
  405. iptable.Raw("-t", string(c.Table), "-F", c.Name)
  406. iptable.Raw("-t", string(c.Table), "-X", c.Name)
  407. return nil
  408. }
  409. // Exists checks if a rule exists
  410. func (iptable IPTable) Exists(table Table, chain string, rule ...string) bool {
  411. return iptable.exists(false, table, chain, rule...)
  412. }
  413. // ExistsNative behaves as Exists with the difference it
  414. // will always invoke `iptables` binary.
  415. func (iptable IPTable) ExistsNative(table Table, chain string, rule ...string) bool {
  416. return iptable.exists(true, table, chain, rule...)
  417. }
  418. func (iptable IPTable) exists(native bool, table Table, chain string, rule ...string) bool {
  419. f := iptable.Raw
  420. if native {
  421. f = iptable.raw
  422. }
  423. if string(table) == "" {
  424. table = Filter
  425. }
  426. if err := initCheck(); err != nil {
  427. // The exists() signature does not allow us to return an error, but at least
  428. // we can skip the (likely invalid) exec invocation.
  429. return false
  430. }
  431. if supportsCOpt {
  432. // if exit status is 0 then return true, the rule exists
  433. _, err := f(append([]string{"-t", string(table), "-C", chain}, rule...)...)
  434. return err == nil
  435. }
  436. // parse "iptables -S" for the rule (it checks rules in a specific chain
  437. // in a specific table and it is very unreliable)
  438. return iptable.existsRaw(table, chain, rule...)
  439. }
  440. func (iptable IPTable) existsRaw(table Table, chain string, rule ...string) bool {
  441. path := iptablesPath
  442. if iptable.Version == IPv6 {
  443. path = ip6tablesPath
  444. }
  445. ruleString := fmt.Sprintf("%s %s\n", chain, strings.Join(rule, " "))
  446. existingRules, _ := exec.Command(path, "-t", string(table), "-S", chain).Output()
  447. return strings.Contains(string(existingRules), ruleString)
  448. }
  449. // Maximum duration that an iptables operation can take
  450. // before flagging a warning.
  451. const opWarnTime = 2 * time.Second
  452. func filterOutput(start time.Time, output []byte, args ...string) []byte {
  453. // Flag operations that have taken a long time to complete
  454. opTime := time.Since(start)
  455. if opTime > opWarnTime {
  456. logrus.Warnf("xtables contention detected while running [%s]: Waited for %.2f seconds and received %q", strings.Join(args, " "), float64(opTime)/float64(time.Second), string(output))
  457. }
  458. // ignore iptables' message about xtables lock:
  459. // it is a warning, not an error.
  460. if strings.Contains(string(output), xLockWaitMsg) {
  461. output = []byte("")
  462. }
  463. // Put further filters here if desired
  464. return output
  465. }
  466. // Raw calls 'iptables' system command, passing supplied arguments.
  467. func (iptable IPTable) Raw(args ...string) ([]byte, error) {
  468. if firewalldRunning {
  469. // select correct IP version for firewalld
  470. ipv := Iptables
  471. if iptable.Version == IPv6 {
  472. ipv = IP6Tables
  473. }
  474. startTime := time.Now()
  475. output, err := Passthrough(ipv, args...)
  476. if err == nil || !strings.Contains(err.Error(), "was not provided by any .service files") {
  477. return filterOutput(startTime, output, args...), err
  478. }
  479. }
  480. return iptable.raw(args...)
  481. }
  482. func (iptable IPTable) raw(args ...string) ([]byte, error) {
  483. if err := initCheck(); err != nil {
  484. return nil, err
  485. }
  486. if supportsXlock {
  487. args = append([]string{"--wait"}, args...)
  488. } else {
  489. bestEffortLock.Lock()
  490. defer bestEffortLock.Unlock()
  491. }
  492. path := iptablesPath
  493. commandName := "iptables"
  494. if iptable.Version == IPv6 {
  495. path = ip6tablesPath
  496. commandName = "ip6tables"
  497. }
  498. logrus.Debugf("%s, %v", path, args)
  499. startTime := time.Now()
  500. output, err := exec.Command(path, args...).CombinedOutput()
  501. if err != nil {
  502. return nil, fmt.Errorf("iptables failed: %s %v: %s (%s)", commandName, strings.Join(args, " "), output, err)
  503. }
  504. return filterOutput(startTime, output, args...), err
  505. }
  506. // RawCombinedOutput internally calls the Raw function and returns a non nil
  507. // error if Raw returned a non nil error or a non empty output
  508. func (iptable IPTable) RawCombinedOutput(args ...string) error {
  509. if output, err := iptable.Raw(args...); err != nil || len(output) != 0 {
  510. return fmt.Errorf("%s (%v)", string(output), err)
  511. }
  512. return nil
  513. }
  514. // RawCombinedOutputNative behave as RawCombinedOutput with the difference it
  515. // will always invoke `iptables` binary
  516. func (iptable IPTable) RawCombinedOutputNative(args ...string) error {
  517. if output, err := iptable.raw(args...); err != nil || len(output) != 0 {
  518. return fmt.Errorf("%s (%v)", string(output), err)
  519. }
  520. return nil
  521. }
  522. // ExistChain checks if a chain exists
  523. func (iptable IPTable) ExistChain(chain string, table Table) bool {
  524. if _, err := iptable.Raw("-t", string(table), "-nL", chain); err == nil {
  525. return true
  526. }
  527. return false
  528. }
  529. // GetVersion reads the iptables version numbers during initialization
  530. func GetVersion() (major, minor, micro int, err error) {
  531. out, err := exec.Command(iptablesPath, "--version").CombinedOutput()
  532. if err == nil {
  533. major, minor, micro = parseVersionNumbers(string(out))
  534. }
  535. return
  536. }
  537. // SetDefaultPolicy sets the passed default policy for the table/chain
  538. func (iptable IPTable) SetDefaultPolicy(table Table, chain string, policy Policy) error {
  539. if err := iptable.RawCombinedOutput("-t", string(table), "-P", chain, string(policy)); err != nil {
  540. return fmt.Errorf("setting default policy to %v in %v chain failed: %v", policy, chain, err)
  541. }
  542. return nil
  543. }
  544. func parseVersionNumbers(input string) (major, minor, micro int) {
  545. re := regexp.MustCompile(`v\d*.\d*.\d*`)
  546. line := re.FindString(input)
  547. fmt.Sscanf(line, "v%d.%d.%d", &major, &minor, &micro)
  548. return
  549. }
  550. // iptables -C, --check option was added in v.1.4.11
  551. // http://ftp.netfilter.org/pub/iptables/changes-iptables-1.4.11.txt
  552. func supportsCOption(mj, mn, mc int) bool {
  553. return mj > 1 || (mj == 1 && (mn > 4 || (mn == 4 && mc >= 11)))
  554. }
  555. // AddReturnRule adds a return rule for the chain in the filter table
  556. func (iptable IPTable) AddReturnRule(chain string) error {
  557. var (
  558. table = Filter
  559. args = []string{"-j", "RETURN"}
  560. )
  561. if iptable.Exists(table, chain, args...) {
  562. return nil
  563. }
  564. err := iptable.RawCombinedOutput(append([]string{"-A", chain}, args...)...)
  565. if err != nil {
  566. return fmt.Errorf("unable to add return rule in %s chain: %s", chain, err.Error())
  567. }
  568. return nil
  569. }
  570. // EnsureJumpRule ensures the jump rule is on top
  571. func (iptable IPTable) EnsureJumpRule(fromChain, toChain string) error {
  572. var (
  573. table = Filter
  574. args = []string{"-j", toChain}
  575. )
  576. if iptable.Exists(table, fromChain, args...) {
  577. err := iptable.RawCombinedOutput(append([]string{"-D", fromChain}, args...)...)
  578. if err != nil {
  579. return fmt.Errorf("unable to remove jump to %s rule in %s chain: %s", toChain, fromChain, err.Error())
  580. }
  581. }
  582. err := iptable.RawCombinedOutput(append([]string{"-I", fromChain}, args...)...)
  583. if err != nil {
  584. return fmt.Errorf("unable to insert jump to %s rule in %s chain: %s", toChain, fromChain, err.Error())
  585. }
  586. return nil
  587. }