setup_ip_tables_linux.go 16 KB

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