setup_ip_tables_linux.go 15 KB

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