setup_ip_tables_linux.go 15 KB

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