setup_ip_tables_linux.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495
  1. package bridge
  2. import (
  3. "context"
  4. "errors"
  5. "fmt"
  6. "net"
  7. "strings"
  8. "github.com/containerd/log"
  9. "github.com/docker/docker/errdefs"
  10. "github.com/docker/docker/libnetwork/iptables"
  11. "github.com/docker/docker/libnetwork/types"
  12. "github.com/vishvananda/netlink"
  13. )
  14. // DockerChain: DOCKER iptable chain name
  15. const (
  16. DockerChain = "DOCKER"
  17. // Isolation between bridge networks is achieved in two stages by means
  18. // of the following two chains in the filter table. The first chain matches
  19. // on the source interface being a bridge network's bridge and the
  20. // destination being a different interface. A positive match leads to the
  21. // second isolation chain. No match returns to the parent chain. The second
  22. // isolation chain matches on destination interface being a bridge network's
  23. // bridge. A positive match identifies a packet originated from one bridge
  24. // network's bridge destined to another bridge network's bridge and will
  25. // result in the packet being dropped. No match returns to the parent chain.
  26. IsolationChain1 = "DOCKER-ISOLATION-STAGE-1"
  27. IsolationChain2 = "DOCKER-ISOLATION-STAGE-2"
  28. )
  29. func setupIPChains(config configuration, version iptables.IPVersion) (natChain *iptables.ChainInfo, filterChain *iptables.ChainInfo, isolationChain1 *iptables.ChainInfo, isolationChain2 *iptables.ChainInfo, retErr error) {
  30. // Sanity check.
  31. if !config.EnableIPTables {
  32. return nil, nil, nil, nil, errors.New("cannot create new chains, EnableIPTable is disabled")
  33. }
  34. hairpinMode := !config.EnableUserlandProxy
  35. iptable := iptables.GetIptable(version)
  36. natChain, err := iptable.NewChain(DockerChain, iptables.Nat, hairpinMode)
  37. if err != nil {
  38. return nil, nil, nil, nil, fmt.Errorf("failed to create NAT chain %s: %v", DockerChain, err)
  39. }
  40. defer func() {
  41. if retErr != nil {
  42. if err := iptable.RemoveExistingChain(DockerChain, iptables.Nat); err != nil {
  43. log.G(context.TODO()).Warnf("failed on removing iptables NAT chain %s on cleanup: %v", DockerChain, err)
  44. }
  45. }
  46. }()
  47. filterChain, err = iptable.NewChain(DockerChain, iptables.Filter, false)
  48. if err != nil {
  49. return nil, nil, nil, nil, fmt.Errorf("failed to create FILTER chain %s: %v", DockerChain, err)
  50. }
  51. defer func() {
  52. if err != nil {
  53. if err := iptable.RemoveExistingChain(DockerChain, iptables.Filter); err != nil {
  54. log.G(context.TODO()).Warnf("failed on removing iptables FILTER chain %s on cleanup: %v", DockerChain, err)
  55. }
  56. }
  57. }()
  58. isolationChain1, err = iptable.NewChain(IsolationChain1, iptables.Filter, false)
  59. if err != nil {
  60. return nil, nil, nil, nil, fmt.Errorf("failed to create FILTER isolation chain: %v", err)
  61. }
  62. defer func() {
  63. if retErr != nil {
  64. if err := iptable.RemoveExistingChain(IsolationChain1, iptables.Filter); err != nil {
  65. log.G(context.TODO()).Warnf("failed on removing iptables FILTER chain %s on cleanup: %v", IsolationChain1, err)
  66. }
  67. }
  68. }()
  69. isolationChain2, err = iptable.NewChain(IsolationChain2, iptables.Filter, false)
  70. if err != nil {
  71. return nil, nil, nil, nil, fmt.Errorf("failed to create FILTER isolation chain: %v", err)
  72. }
  73. defer func() {
  74. if retErr != nil {
  75. if err := iptable.RemoveExistingChain(IsolationChain2, iptables.Filter); err != nil {
  76. log.G(context.TODO()).Warnf("failed on removing iptables FILTER chain %s on cleanup: %v", IsolationChain2, err)
  77. }
  78. }
  79. }()
  80. if err := iptable.AddReturnRule(IsolationChain1); err != nil {
  81. return nil, nil, nil, nil, err
  82. }
  83. if err := iptable.AddReturnRule(IsolationChain2); err != nil {
  84. return nil, nil, nil, nil, err
  85. }
  86. return natChain, filterChain, isolationChain1, isolationChain2, nil
  87. }
  88. func (n *bridgeNetwork) setupIP4Tables(config *networkConfiguration, i *bridgeInterface) error {
  89. d := n.driver
  90. d.Lock()
  91. driverConfig := d.config
  92. d.Unlock()
  93. // Sanity check.
  94. if !driverConfig.EnableIPTables {
  95. return errors.New("Cannot program chains, EnableIPTable is disabled")
  96. }
  97. maskedAddrv4 := &net.IPNet{
  98. IP: i.bridgeIPv4.IP.Mask(i.bridgeIPv4.Mask),
  99. Mask: i.bridgeIPv4.Mask,
  100. }
  101. return n.setupIPTables(iptables.IPv4, maskedAddrv4, config, i)
  102. }
  103. func (n *bridgeNetwork) setupIP6Tables(config *networkConfiguration, i *bridgeInterface) error {
  104. d := n.driver
  105. d.Lock()
  106. driverConfig := d.config
  107. d.Unlock()
  108. // Sanity check.
  109. if !driverConfig.EnableIP6Tables {
  110. return errors.New("Cannot program chains, EnableIP6Tables is disabled")
  111. }
  112. maskedAddrv6 := &net.IPNet{
  113. IP: i.bridgeIPv6.IP.Mask(i.bridgeIPv6.Mask),
  114. Mask: i.bridgeIPv6.Mask,
  115. }
  116. return n.setupIPTables(iptables.IPv6, maskedAddrv6, config, i)
  117. }
  118. func (n *bridgeNetwork) setupIPTables(ipVersion iptables.IPVersion, maskedAddr *net.IPNet, config *networkConfiguration, i *bridgeInterface) error {
  119. var err error
  120. d := n.driver
  121. d.Lock()
  122. driverConfig := d.config
  123. d.Unlock()
  124. // Pickup this configuration option from driver
  125. hairpinMode := !driverConfig.EnableUserlandProxy
  126. iptable := iptables.GetIptable(ipVersion)
  127. if config.Internal {
  128. if err = setupInternalNetworkRules(config.BridgeName, maskedAddr, config.EnableICC, true); err != nil {
  129. return fmt.Errorf("Failed to Setup IP tables: %s", err.Error())
  130. }
  131. n.registerIptCleanFunc(func() error {
  132. return setupInternalNetworkRules(config.BridgeName, maskedAddr, config.EnableICC, false)
  133. })
  134. } else {
  135. if err = setupIPTablesInternal(ipVersion, config, maskedAddr, hairpinMode, true); err != nil {
  136. return fmt.Errorf("Failed to Setup IP tables: %s", err.Error())
  137. }
  138. n.registerIptCleanFunc(func() error {
  139. return setupIPTablesInternal(ipVersion, config, maskedAddr, hairpinMode, false)
  140. })
  141. natChain, filterChain, _, _, err := n.getDriverChains(ipVersion)
  142. if err != nil {
  143. return fmt.Errorf("Failed to setup IP tables, cannot acquire chain info %s", err.Error())
  144. }
  145. err = iptable.ProgramChain(natChain, config.BridgeName, hairpinMode, true)
  146. if err != nil {
  147. return fmt.Errorf("Failed to program NAT chain: %s", err.Error())
  148. }
  149. err = iptable.ProgramChain(filterChain, config.BridgeName, hairpinMode, true)
  150. if err != nil {
  151. return fmt.Errorf("Failed to program FILTER chain: %s", err.Error())
  152. }
  153. n.registerIptCleanFunc(func() error {
  154. return iptable.ProgramChain(filterChain, config.BridgeName, hairpinMode, false)
  155. })
  156. if ipVersion == iptables.IPv4 {
  157. n.portMapper.SetIptablesChain(natChain, n.getNetworkBridgeName())
  158. } else {
  159. n.portMapperV6.SetIptablesChain(natChain, n.getNetworkBridgeName())
  160. }
  161. }
  162. d.Lock()
  163. err = iptable.EnsureJumpRule("FORWARD", IsolationChain1)
  164. d.Unlock()
  165. return err
  166. }
  167. type iptRule struct {
  168. ipv iptables.IPVersion
  169. table iptables.Table
  170. chain string
  171. args []string
  172. }
  173. // Exists returns true if the rule exists in the kernel.
  174. func (r iptRule) Exists() bool {
  175. return iptables.GetIptable(r.ipv).Exists(r.table, r.chain, r.args...)
  176. }
  177. func (r iptRule) cmdArgs(op iptables.Action) []string {
  178. return append([]string{"-t", string(r.table), string(op), r.chain}, r.args...)
  179. }
  180. func (r iptRule) exec(op iptables.Action) error {
  181. return iptables.GetIptable(r.ipv).RawCombinedOutput(r.cmdArgs(op)...)
  182. }
  183. // Append appends the rule to the end of the chain. If the rule already exists anywhere in the
  184. // chain, this is a no-op.
  185. func (r iptRule) Append() error {
  186. if r.Exists() {
  187. return nil
  188. }
  189. return r.exec(iptables.Append)
  190. }
  191. // Insert inserts the rule at the head of the chain. If the rule already exists anywhere in the
  192. // chain, this is a no-op.
  193. func (r iptRule) Insert() error {
  194. if r.Exists() {
  195. return nil
  196. }
  197. return r.exec(iptables.Insert)
  198. }
  199. // Delete deletes the rule from the kernel. If the rule does not exist, this is a no-op.
  200. func (r iptRule) Delete() error {
  201. if !r.Exists() {
  202. return nil
  203. }
  204. return r.exec(iptables.Delete)
  205. }
  206. func (r iptRule) String() string {
  207. cmd := append([]string{"iptables"}, r.cmdArgs("-A")...)
  208. if r.ipv == iptables.IPv6 {
  209. cmd[0] = "ip6tables"
  210. }
  211. return strings.Join(cmd, " ")
  212. }
  213. func setupIPTablesInternal(ipVer iptables.IPVersion, config *networkConfiguration, addr *net.IPNet, hairpin, enable bool) error {
  214. var (
  215. address = addr.String()
  216. skipDNAT = iptRule{ipv: ipVer, table: iptables.Nat, chain: DockerChain, args: []string{"-i", config.BridgeName, "-j", "RETURN"}}
  217. outRule = iptRule{ipv: ipVer, table: iptables.Filter, chain: "FORWARD", args: []string{"-i", config.BridgeName, "!", "-o", config.BridgeName, "-j", "ACCEPT"}}
  218. natArgs []string
  219. hpNatArgs []string
  220. )
  221. hostIP := config.HostIPv4
  222. if ipVer == iptables.IPv6 {
  223. hostIP = config.HostIPv6
  224. }
  225. // If hostIP is set, the user wants IPv4/IPv6 SNAT with the given address.
  226. if hostIP != nil {
  227. hostAddr := hostIP.String()
  228. natArgs = []string{"-s", address, "!", "-o", config.BridgeName, "-j", "SNAT", "--to-source", hostAddr}
  229. hpNatArgs = []string{"-m", "addrtype", "--src-type", "LOCAL", "-o", config.BridgeName, "-j", "SNAT", "--to-source", hostAddr}
  230. // Else use MASQUERADE which picks the src-ip based on NH from the route table
  231. } else {
  232. natArgs = []string{"-s", address, "!", "-o", config.BridgeName, "-j", "MASQUERADE"}
  233. hpNatArgs = []string{"-m", "addrtype", "--src-type", "LOCAL", "-o", config.BridgeName, "-j", "MASQUERADE"}
  234. }
  235. natRule := iptRule{ipv: ipVer, table: iptables.Nat, chain: "POSTROUTING", args: natArgs}
  236. hpNatRule := iptRule{ipv: ipVer, table: iptables.Nat, chain: "POSTROUTING", args: hpNatArgs}
  237. // Set NAT.
  238. if config.EnableIPMasquerade {
  239. if err := programChainRule(natRule, "NAT", enable); err != nil {
  240. return err
  241. }
  242. }
  243. if config.EnableIPMasquerade && !hairpin {
  244. if err := programChainRule(skipDNAT, "SKIP DNAT", enable); err != nil {
  245. return err
  246. }
  247. }
  248. // In hairpin mode, masquerade traffic from localhost. If hairpin is disabled or if we're tearing down
  249. // that bridge, make sure the iptables rule isn't lying around.
  250. if err := programChainRule(hpNatRule, "MASQ LOCAL HOST", enable && hairpin); err != nil {
  251. return err
  252. }
  253. // Set Inter Container Communication.
  254. if err := setIcc(ipVer, config.BridgeName, config.EnableICC, enable); err != nil {
  255. return err
  256. }
  257. // Set Accept on all non-intercontainer outgoing packets.
  258. return programChainRule(outRule, "ACCEPT NON_ICC OUTGOING", enable)
  259. }
  260. func programChainRule(rule iptRule, ruleDescr string, insert bool) error {
  261. operation := "disable"
  262. fn := rule.Delete
  263. if insert {
  264. operation = "enable"
  265. fn = rule.Insert
  266. }
  267. if err := fn(); err != nil {
  268. return fmt.Errorf("Unable to %s %s rule: %s", operation, ruleDescr, err.Error())
  269. }
  270. return nil
  271. }
  272. func setIcc(version iptables.IPVersion, bridgeIface string, iccEnable, insert bool) error {
  273. args := []string{"-i", bridgeIface, "-o", bridgeIface, "-j"}
  274. acceptRule := iptRule{ipv: version, table: iptables.Filter, chain: "FORWARD", args: append(args, "ACCEPT")}
  275. dropRule := iptRule{ipv: version, table: iptables.Filter, chain: "FORWARD", args: append(args, "DROP")}
  276. if insert {
  277. if !iccEnable {
  278. acceptRule.Delete()
  279. if err := dropRule.Append(); err != nil {
  280. return fmt.Errorf("Unable to prevent intercontainer communication: %s", err.Error())
  281. }
  282. } else {
  283. dropRule.Delete()
  284. if err := acceptRule.Insert(); err != nil {
  285. return fmt.Errorf("Unable to allow intercontainer communication: %s", err.Error())
  286. }
  287. }
  288. } else {
  289. // Remove any ICC rule.
  290. if !iccEnable {
  291. dropRule.Delete()
  292. } else {
  293. acceptRule.Delete()
  294. }
  295. }
  296. return nil
  297. }
  298. // Control Inter Network Communication. Install[Remove] only if it is [not] present.
  299. func setINC(version iptables.IPVersion, iface string, enable bool) error {
  300. iptable := iptables.GetIptable(version)
  301. var (
  302. action = iptables.Insert
  303. actionMsg = "add"
  304. chains = []string{IsolationChain1, IsolationChain2}
  305. rules = [][]string{
  306. {"-i", iface, "!", "-o", iface, "-j", IsolationChain2},
  307. {"-o", iface, "-j", "DROP"},
  308. }
  309. )
  310. if !enable {
  311. action = iptables.Delete
  312. actionMsg = "remove"
  313. }
  314. for i, chain := range chains {
  315. if err := iptable.ProgramRule(iptables.Filter, chain, action, rules[i]); err != nil {
  316. msg := fmt.Sprintf("unable to %s inter-network communication rule: %v", actionMsg, err)
  317. if enable {
  318. if i == 1 {
  319. // Rollback the rule installed on first chain
  320. if err2 := iptable.ProgramRule(iptables.Filter, chains[0], iptables.Delete, rules[0]); err2 != nil {
  321. log.G(context.TODO()).Warnf("Failed to rollback iptables rule after failure (%v): %v", err, err2)
  322. }
  323. }
  324. return fmt.Errorf(msg)
  325. }
  326. log.G(context.TODO()).Warn(msg)
  327. }
  328. }
  329. return nil
  330. }
  331. // Obsolete chain from previous docker versions
  332. const oldIsolationChain = "DOCKER-ISOLATION"
  333. func removeIPChains(version iptables.IPVersion) {
  334. ipt := iptables.GetIptable(version)
  335. // Remove obsolete rules from default chains
  336. ipt.ProgramRule(iptables.Filter, "FORWARD", iptables.Delete, []string{"-j", oldIsolationChain})
  337. // Remove chains
  338. for _, chainInfo := range []iptables.ChainInfo{
  339. {Name: DockerChain, Table: iptables.Nat, IPVersion: version},
  340. {Name: DockerChain, Table: iptables.Filter, IPVersion: version},
  341. {Name: IsolationChain1, Table: iptables.Filter, IPVersion: version},
  342. {Name: IsolationChain2, Table: iptables.Filter, IPVersion: version},
  343. {Name: oldIsolationChain, Table: iptables.Filter, IPVersion: version},
  344. } {
  345. if err := chainInfo.Remove(); err != nil {
  346. log.G(context.TODO()).Warnf("Failed to remove existing iptables entries in table %s chain %s : %v", chainInfo.Table, chainInfo.Name, err)
  347. }
  348. }
  349. }
  350. func setupInternalNetworkRules(bridgeIface string, addr *net.IPNet, icc, insert bool) error {
  351. var version iptables.IPVersion
  352. var inDropRule, outDropRule iptRule
  353. // Either add or remove the interface from the firewalld zone, if firewalld is running.
  354. if insert {
  355. if err := iptables.AddInterfaceFirewalld(bridgeIface); err != nil {
  356. return err
  357. }
  358. } else {
  359. if err := iptables.DelInterfaceFirewalld(bridgeIface); err != nil && !errdefs.IsNotFound(err) {
  360. return err
  361. }
  362. }
  363. if addr.IP.To4() != nil {
  364. version = iptables.IPv4
  365. inDropRule = iptRule{
  366. ipv: version,
  367. table: iptables.Filter,
  368. chain: IsolationChain1,
  369. args: []string{"-i", bridgeIface, "!", "-d", addr.String(), "-j", "DROP"},
  370. }
  371. outDropRule = iptRule{
  372. ipv: version,
  373. table: iptables.Filter,
  374. chain: IsolationChain1,
  375. args: []string{"-o", bridgeIface, "!", "-s", addr.String(), "-j", "DROP"},
  376. }
  377. } else {
  378. version = iptables.IPv6
  379. inDropRule = iptRule{
  380. ipv: version,
  381. table: iptables.Filter,
  382. chain: IsolationChain1,
  383. args: []string{"-i", bridgeIface, "!", "-o", bridgeIface, "!", "-d", addr.String(), "-j", "DROP"},
  384. }
  385. outDropRule = iptRule{
  386. ipv: version,
  387. table: iptables.Filter,
  388. chain: IsolationChain1,
  389. args: []string{"!", "-i", bridgeIface, "-o", bridgeIface, "!", "-s", addr.String(), "-j", "DROP"},
  390. }
  391. }
  392. if err := programChainRule(inDropRule, "DROP INCOMING", insert); err != nil {
  393. return err
  394. }
  395. if err := programChainRule(outDropRule, "DROP OUTGOING", insert); err != nil {
  396. return err
  397. }
  398. // Set Inter Container Communication.
  399. return setIcc(version, bridgeIface, icc, insert)
  400. }
  401. // clearConntrackEntries flushes conntrack entries matching endpoint IP address
  402. // or matching one of the exposed UDP port.
  403. // In the first case, this could happen if packets were received by the host
  404. // between userland proxy startup and iptables setup.
  405. // In the latter case, this could happen if packets were received whereas there
  406. // were nowhere to route them, as netfilter creates entries in such case.
  407. // This is required because iptables NAT rules are evaluated by netfilter only
  408. // when creating a new conntrack entry. When Docker latter adds NAT rules,
  409. // netfilter ignore them for any packet matching a pre-existing conntrack entry.
  410. // As such, we need to flush all those conntrack entries to make sure NAT rules
  411. // are correctly applied to all packets.
  412. // See: #8795, #44688 & #44742.
  413. func clearConntrackEntries(nlh *netlink.Handle, ep *bridgeEndpoint) {
  414. var ipv4List []net.IP
  415. var ipv6List []net.IP
  416. var udpPorts []uint16
  417. if ep.addr != nil {
  418. ipv4List = append(ipv4List, ep.addr.IP)
  419. }
  420. if ep.addrv6 != nil {
  421. ipv6List = append(ipv6List, ep.addrv6.IP)
  422. }
  423. for _, pb := range ep.portMapping {
  424. if pb.Proto == types.UDP {
  425. udpPorts = append(udpPorts, pb.HostPort)
  426. }
  427. }
  428. iptables.DeleteConntrackEntries(nlh, ipv4List, ipv6List)
  429. iptables.DeleteConntrackEntriesByPort(nlh, types.UDP, udpPorts)
  430. }