iptables.go 18 KB

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