setup_ip_tables.go 15 KB

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