iptables.go 17 KB

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