setup_ip_tables.go 15 KB

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