setup_ip_tables.go 15 KB

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