iptables.go 19 KB

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