setup_ip_tables_linux.go 15 KB

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