setup_ip_tables_linux.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468
  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) (*iptables.ChainInfo, *iptables.ChainInfo, *iptables.ChainInfo, *iptables.ChainInfo, 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 err != 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 err != 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 err != 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. if err = setupIPTablesInternal(config.HostIP, config.BridgeName, maskedAddr, config.EnableICC, config.EnableIPMasquerade, hairpinMode, true); err != nil {
  134. return fmt.Errorf("Failed to Setup IP tables: %s", err.Error())
  135. }
  136. n.registerIptCleanFunc(func() error {
  137. return setupIPTablesInternal(config.HostIP, config.BridgeName, maskedAddr, config.EnableICC, config.EnableIPMasquerade, hairpinMode, false)
  138. })
  139. natChain, filterChain, _, _, err := n.getDriverChains(ipVersion)
  140. if err != nil {
  141. return fmt.Errorf("Failed to setup IP tables, cannot acquire chain info %s", err.Error())
  142. }
  143. err = iptable.ProgramChain(natChain, config.BridgeName, hairpinMode, true)
  144. if err != nil {
  145. return fmt.Errorf("Failed to program NAT chain: %s", err.Error())
  146. }
  147. err = iptable.ProgramChain(filterChain, config.BridgeName, hairpinMode, true)
  148. if err != nil {
  149. return fmt.Errorf("Failed to program FILTER chain: %s", err.Error())
  150. }
  151. n.registerIptCleanFunc(func() error {
  152. return iptable.ProgramChain(filterChain, config.BridgeName, hairpinMode, false)
  153. })
  154. if ipVersion == iptables.IPv4 {
  155. n.portMapper.SetIptablesChain(natChain, n.getNetworkBridgeName())
  156. } else {
  157. n.portMapperV6.SetIptablesChain(natChain, n.getNetworkBridgeName())
  158. }
  159. }
  160. d.Lock()
  161. err = iptable.EnsureJumpRule("FORWARD", IsolationChain1)
  162. d.Unlock()
  163. return err
  164. }
  165. type iptRule struct {
  166. table iptables.Table
  167. chain string
  168. preArgs []string
  169. args []string
  170. }
  171. func setupIPTablesInternal(hostIP net.IP, bridgeIface string, addr *net.IPNet, icc, ipmasq, hairpin, enable bool) error {
  172. var (
  173. address = addr.String()
  174. skipDNAT = iptRule{table: iptables.Nat, chain: DockerChain, preArgs: []string{"-t", "nat"}, args: []string{"-i", bridgeIface, "-j", "RETURN"}}
  175. outRule = iptRule{table: iptables.Filter, chain: "FORWARD", args: []string{"-i", bridgeIface, "!", "-o", bridgeIface, "-j", "ACCEPT"}}
  176. natArgs []string
  177. hpNatArgs []string
  178. )
  179. // if hostIP is set use this address as the src-ip during SNAT
  180. if hostIP != nil {
  181. hostAddr := hostIP.String()
  182. natArgs = []string{"-s", address, "!", "-o", bridgeIface, "-j", "SNAT", "--to-source", hostAddr}
  183. hpNatArgs = []string{"-m", "addrtype", "--src-type", "LOCAL", "-o", bridgeIface, "-j", "SNAT", "--to-source", hostAddr}
  184. // Else use MASQUERADE which picks the src-ip based on NH from the route table
  185. } else {
  186. natArgs = []string{"-s", address, "!", "-o", bridgeIface, "-j", "MASQUERADE"}
  187. hpNatArgs = []string{"-m", "addrtype", "--src-type", "LOCAL", "-o", bridgeIface, "-j", "MASQUERADE"}
  188. }
  189. natRule := iptRule{table: iptables.Nat, chain: "POSTROUTING", preArgs: []string{"-t", "nat"}, args: natArgs}
  190. hpNatRule := iptRule{table: iptables.Nat, chain: "POSTROUTING", preArgs: []string{"-t", "nat"}, args: hpNatArgs}
  191. ipVer := iptables.IPv4
  192. if addr.IP.To4() == nil {
  193. ipVer = iptables.IPv6
  194. }
  195. // Set NAT.
  196. if ipmasq {
  197. if err := programChainRule(ipVer, natRule, "NAT", enable); err != nil {
  198. return err
  199. }
  200. }
  201. if ipmasq && !hairpin {
  202. if err := programChainRule(ipVer, skipDNAT, "SKIP DNAT", enable); err != nil {
  203. return err
  204. }
  205. }
  206. // In hairpin mode, masquerade traffic from localhost. If hairpin is disabled or if we're tearing down
  207. // that bridge, make sure the iptables rule isn't lying around.
  208. if err := programChainRule(ipVer, hpNatRule, "MASQ LOCAL HOST", enable && hairpin); err != nil {
  209. return err
  210. }
  211. // Set Inter Container Communication.
  212. if err := setIcc(ipVer, bridgeIface, icc, enable); err != nil {
  213. return err
  214. }
  215. // Set Accept on all non-intercontainer outgoing packets.
  216. return programChainRule(ipVer, outRule, "ACCEPT NON_ICC OUTGOING", enable)
  217. }
  218. func programChainRule(version iptables.IPVersion, rule iptRule, ruleDescr string, insert bool) error {
  219. iptable := iptables.GetIptable(version)
  220. var (
  221. prefix []string
  222. operation string
  223. condition bool
  224. doesExist = iptable.Exists(rule.table, rule.chain, rule.args...)
  225. )
  226. if insert {
  227. condition = !doesExist
  228. prefix = []string{"-I", rule.chain}
  229. operation = "enable"
  230. } else {
  231. condition = doesExist
  232. prefix = []string{"-D", rule.chain}
  233. operation = "disable"
  234. }
  235. if rule.preArgs != nil {
  236. prefix = append(rule.preArgs, prefix...)
  237. }
  238. if condition {
  239. if err := iptable.RawCombinedOutput(append(prefix, rule.args...)...); err != nil {
  240. return fmt.Errorf("Unable to %s %s rule: %s", operation, ruleDescr, err.Error())
  241. }
  242. }
  243. return nil
  244. }
  245. func setIcc(version iptables.IPVersion, bridgeIface string, iccEnable, insert bool) error {
  246. iptable := iptables.GetIptable(version)
  247. var (
  248. table = iptables.Filter
  249. chain = "FORWARD"
  250. args = []string{"-i", bridgeIface, "-o", bridgeIface, "-j"}
  251. acceptArgs = append(args, "ACCEPT")
  252. dropArgs = append(args, "DROP")
  253. )
  254. if insert {
  255. if !iccEnable {
  256. iptable.Raw(append([]string{"-D", chain}, acceptArgs...)...)
  257. if !iptable.Exists(table, chain, dropArgs...) {
  258. if err := iptable.RawCombinedOutput(append([]string{"-A", chain}, dropArgs...)...); err != nil {
  259. return fmt.Errorf("Unable to prevent intercontainer communication: %s", err.Error())
  260. }
  261. }
  262. } else {
  263. iptable.Raw(append([]string{"-D", chain}, dropArgs...)...)
  264. if !iptable.Exists(table, chain, acceptArgs...) {
  265. if err := iptable.RawCombinedOutput(append([]string{"-I", chain}, acceptArgs...)...); err != nil {
  266. return fmt.Errorf("Unable to allow intercontainer communication: %s", err.Error())
  267. }
  268. }
  269. }
  270. } else {
  271. // Remove any ICC rule.
  272. if !iccEnable {
  273. if iptable.Exists(table, chain, dropArgs...) {
  274. iptable.Raw(append([]string{"-D", chain}, dropArgs...)...)
  275. }
  276. } else {
  277. if iptable.Exists(table, chain, acceptArgs...) {
  278. iptable.Raw(append([]string{"-D", chain}, acceptArgs...)...)
  279. }
  280. }
  281. }
  282. return nil
  283. }
  284. // Control Inter Network Communication. Install[Remove] only if it is [not] present.
  285. func setINC(version iptables.IPVersion, iface string, enable bool) error {
  286. iptable := iptables.GetIptable(version)
  287. var (
  288. action = iptables.Insert
  289. actionMsg = "add"
  290. chains = []string{IsolationChain1, IsolationChain2}
  291. rules = [][]string{
  292. {"-i", iface, "!", "-o", iface, "-j", IsolationChain2},
  293. {"-o", iface, "-j", "DROP"},
  294. }
  295. )
  296. if !enable {
  297. action = iptables.Delete
  298. actionMsg = "remove"
  299. }
  300. for i, chain := range chains {
  301. if err := iptable.ProgramRule(iptables.Filter, chain, action, rules[i]); err != nil {
  302. msg := fmt.Sprintf("unable to %s inter-network communication rule: %v", actionMsg, err)
  303. if enable {
  304. if i == 1 {
  305. // Rollback the rule installed on first chain
  306. if err2 := iptable.ProgramRule(iptables.Filter, chains[0], iptables.Delete, rules[0]); err2 != nil {
  307. log.G(context.TODO()).Warnf("Failed to rollback iptables rule after failure (%v): %v", err, err2)
  308. }
  309. }
  310. return fmt.Errorf(msg)
  311. }
  312. log.G(context.TODO()).Warn(msg)
  313. }
  314. }
  315. return nil
  316. }
  317. // Obsolete chain from previous docker versions
  318. const oldIsolationChain = "DOCKER-ISOLATION"
  319. func removeIPChains(version iptables.IPVersion) {
  320. ipt := iptables.GetIptable(version)
  321. // Remove obsolete rules from default chains
  322. ipt.ProgramRule(iptables.Filter, "FORWARD", iptables.Delete, []string{"-j", oldIsolationChain})
  323. // Remove chains
  324. for _, chainInfo := range []iptables.ChainInfo{
  325. {Name: DockerChain, Table: iptables.Nat, IPVersion: version},
  326. {Name: DockerChain, Table: iptables.Filter, IPVersion: version},
  327. {Name: IsolationChain1, Table: iptables.Filter, IPVersion: version},
  328. {Name: IsolationChain2, Table: iptables.Filter, IPVersion: version},
  329. {Name: oldIsolationChain, Table: iptables.Filter, IPVersion: version},
  330. } {
  331. if err := chainInfo.Remove(); err != nil {
  332. log.G(context.TODO()).Warnf("Failed to remove existing iptables entries in table %s chain %s : %v", chainInfo.Table, chainInfo.Name, err)
  333. }
  334. }
  335. }
  336. func setupInternalNetworkRules(bridgeIface string, addr *net.IPNet, icc, insert bool) error {
  337. var version iptables.IPVersion
  338. var inDropRule, outDropRule iptRule
  339. if addr.IP.To4() != nil {
  340. version = iptables.IPv4
  341. inDropRule = iptRule{
  342. table: iptables.Filter,
  343. chain: IsolationChain1,
  344. args: []string{"-i", bridgeIface, "!", "-d", addr.String(), "-j", "DROP"},
  345. }
  346. outDropRule = iptRule{
  347. table: iptables.Filter,
  348. chain: IsolationChain1,
  349. args: []string{"-o", bridgeIface, "!", "-s", addr.String(), "-j", "DROP"},
  350. }
  351. } else {
  352. version = iptables.IPv6
  353. inDropRule = iptRule{
  354. table: iptables.Filter,
  355. chain: IsolationChain1,
  356. args: []string{"-i", bridgeIface, "!", "-o", bridgeIface, "!", "-d", addr.String(), "-j", "DROP"},
  357. }
  358. outDropRule = iptRule{
  359. table: iptables.Filter,
  360. chain: IsolationChain1,
  361. args: []string{"!", "-i", bridgeIface, "-o", bridgeIface, "!", "-s", addr.String(), "-j", "DROP"},
  362. }
  363. }
  364. if err := programChainRule(version, inDropRule, "DROP INCOMING", insert); err != nil {
  365. return err
  366. }
  367. if err := programChainRule(version, outDropRule, "DROP OUTGOING", insert); err != nil {
  368. return err
  369. }
  370. // Set Inter Container Communication.
  371. return setIcc(version, bridgeIface, icc, insert)
  372. }
  373. // clearConntrackEntries flushes conntrack entries matching endpoint IP address
  374. // or matching one of the exposed UDP port.
  375. // In the first case, this could happen if packets were received by the host
  376. // between userland proxy startup and iptables setup.
  377. // In the latter case, this could happen if packets were received whereas there
  378. // were nowhere to route them, as netfilter creates entries in such case.
  379. // This is required because iptables NAT rules are evaluated by netfilter only
  380. // when creating a new conntrack entry. When Docker latter adds NAT rules,
  381. // netfilter ignore them for any packet matching a pre-existing conntrack entry.
  382. // As such, we need to flush all those conntrack entries to make sure NAT rules
  383. // are correctly applied to all packets.
  384. // See: #8795, #44688 & #44742.
  385. func clearConntrackEntries(nlh *netlink.Handle, ep *bridgeEndpoint) {
  386. var ipv4List []net.IP
  387. var ipv6List []net.IP
  388. var udpPorts []uint16
  389. if ep.addr != nil {
  390. ipv4List = append(ipv4List, ep.addr.IP)
  391. }
  392. if ep.addrv6 != nil {
  393. ipv6List = append(ipv6List, ep.addrv6.IP)
  394. }
  395. for _, pb := range ep.portMapping {
  396. if pb.Proto == types.UDP {
  397. udpPorts = append(udpPorts, pb.HostPort)
  398. }
  399. }
  400. iptables.DeleteConntrackEntries(nlh, ipv4List, ipv6List)
  401. iptables.DeleteConntrackEntriesByPort(nlh, types.UDP, udpPorts)
  402. }