setup_ip_tables.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363
  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) (*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. natChain, err := iptables.NewChain(DockerChain, iptables.Nat, hairpinMode)
  32. if err != nil {
  33. return nil, nil, nil, nil, fmt.Errorf("failed to create NAT chain %s: %v", DockerChain, err)
  34. }
  35. defer func() {
  36. if err != nil {
  37. if err := iptables.RemoveExistingChain(DockerChain, iptables.Nat); err != nil {
  38. logrus.Warnf("failed on removing iptables NAT chain %s on cleanup: %v", DockerChain, err)
  39. }
  40. }
  41. }()
  42. filterChain, err := iptables.NewChain(DockerChain, iptables.Filter, false)
  43. if err != nil {
  44. return nil, nil, nil, nil, fmt.Errorf("failed to create FILTER chain %s: %v", DockerChain, err)
  45. }
  46. defer func() {
  47. if err != nil {
  48. if err := iptables.RemoveExistingChain(DockerChain, iptables.Filter); err != nil {
  49. logrus.Warnf("failed on removing iptables FILTER chain %s on cleanup: %v", DockerChain, err)
  50. }
  51. }
  52. }()
  53. isolationChain1, err := iptables.NewChain(IsolationChain1, iptables.Filter, false)
  54. if err != nil {
  55. return nil, nil, nil, nil, fmt.Errorf("failed to create FILTER isolation chain: %v", err)
  56. }
  57. defer func() {
  58. if err != nil {
  59. if err := iptables.RemoveExistingChain(IsolationChain1, iptables.Filter); err != nil {
  60. logrus.Warnf("failed on removing iptables FILTER chain %s on cleanup: %v", IsolationChain1, err)
  61. }
  62. }
  63. }()
  64. isolationChain2, err := iptables.NewChain(IsolationChain2, iptables.Filter, false)
  65. if err != nil {
  66. return nil, nil, nil, nil, fmt.Errorf("failed to create FILTER isolation chain: %v", err)
  67. }
  68. defer func() {
  69. if err != nil {
  70. if err := iptables.RemoveExistingChain(IsolationChain2, iptables.Filter); err != nil {
  71. logrus.Warnf("failed on removing iptables FILTER chain %s on cleanup: %v", IsolationChain2, err)
  72. }
  73. }
  74. }()
  75. if err := iptables.AddReturnRule(IsolationChain1); err != nil {
  76. return nil, nil, nil, nil, err
  77. }
  78. if err := iptables.AddReturnRule(IsolationChain2); err != nil {
  79. return nil, nil, nil, nil, err
  80. }
  81. return natChain, filterChain, isolationChain1, isolationChain2, nil
  82. }
  83. func (n *bridgeNetwork) setupIPTables(config *networkConfiguration, i *bridgeInterface) error {
  84. var err error
  85. d := n.driver
  86. d.Lock()
  87. driverConfig := d.config
  88. d.Unlock()
  89. // Sanity check.
  90. if driverConfig.EnableIPTables == false {
  91. return errors.New("Cannot program chains, EnableIPTable is disabled")
  92. }
  93. // Pickup this configuration option from driver
  94. hairpinMode := !driverConfig.EnableUserlandProxy
  95. maskedAddrv4 := &net.IPNet{
  96. IP: i.bridgeIPv4.IP.Mask(i.bridgeIPv4.Mask),
  97. Mask: i.bridgeIPv4.Mask,
  98. }
  99. if config.Internal {
  100. if err = setupInternalNetworkRules(config.BridgeName, maskedAddrv4, config.EnableICC, true); err != nil {
  101. return fmt.Errorf("Failed to Setup IP tables: %s", err.Error())
  102. }
  103. n.registerIptCleanFunc(func() error {
  104. return setupInternalNetworkRules(config.BridgeName, maskedAddrv4, config.EnableICC, false)
  105. })
  106. } else {
  107. if err = setupIPTablesInternal(config.BridgeName, maskedAddrv4, config.EnableICC, config.EnableIPMasquerade, hairpinMode, true); err != nil {
  108. return fmt.Errorf("Failed to Setup IP tables: %s", err.Error())
  109. }
  110. n.registerIptCleanFunc(func() error {
  111. return setupIPTablesInternal(config.BridgeName, maskedAddrv4, config.EnableICC, config.EnableIPMasquerade, hairpinMode, false)
  112. })
  113. natChain, filterChain, _, _, err := n.getDriverChains()
  114. if err != nil {
  115. return fmt.Errorf("Failed to setup IP tables, cannot acquire chain info %s", err.Error())
  116. }
  117. err = iptables.ProgramChain(natChain, config.BridgeName, hairpinMode, true)
  118. if err != nil {
  119. return fmt.Errorf("Failed to program NAT chain: %s", err.Error())
  120. }
  121. err = iptables.ProgramChain(filterChain, config.BridgeName, hairpinMode, true)
  122. if err != nil {
  123. return fmt.Errorf("Failed to program FILTER chain: %s", err.Error())
  124. }
  125. n.registerIptCleanFunc(func() error {
  126. return iptables.ProgramChain(filterChain, config.BridgeName, hairpinMode, false)
  127. })
  128. n.portMapper.SetIptablesChain(natChain, n.getNetworkBridgeName())
  129. }
  130. d.Lock()
  131. err = iptables.EnsureJumpRule("FORWARD", IsolationChain1)
  132. d.Unlock()
  133. if err != nil {
  134. return err
  135. }
  136. return nil
  137. }
  138. type iptRule struct {
  139. table iptables.Table
  140. chain string
  141. preArgs []string
  142. args []string
  143. }
  144. func setupIPTablesInternal(bridgeIface string, addr net.Addr, icc, ipmasq, hairpin, enable bool) error {
  145. var (
  146. address = addr.String()
  147. natRule = iptRule{table: iptables.Nat, chain: "POSTROUTING", preArgs: []string{"-t", "nat"}, args: []string{"-s", address, "!", "-o", bridgeIface, "-j", "MASQUERADE"}}
  148. hpNatRule = iptRule{table: iptables.Nat, chain: "POSTROUTING", preArgs: []string{"-t", "nat"}, args: []string{"-m", "addrtype", "--src-type", "LOCAL", "-o", bridgeIface, "-j", "MASQUERADE"}}
  149. skipDNAT = iptRule{table: iptables.Nat, chain: DockerChain, preArgs: []string{"-t", "nat"}, args: []string{"-i", bridgeIface, "-j", "RETURN"}}
  150. outRule = iptRule{table: iptables.Filter, chain: "FORWARD", args: []string{"-i", bridgeIface, "!", "-o", bridgeIface, "-j", "ACCEPT"}}
  151. )
  152. // Set NAT.
  153. if ipmasq {
  154. if err := programChainRule(natRule, "NAT", enable); err != nil {
  155. return err
  156. }
  157. }
  158. if ipmasq && !hairpin {
  159. if err := programChainRule(skipDNAT, "SKIP DNAT", enable); err != nil {
  160. return err
  161. }
  162. }
  163. // In hairpin mode, masquerade traffic from localhost
  164. if hairpin {
  165. if err := programChainRule(hpNatRule, "MASQ LOCAL HOST", enable); err != nil {
  166. return err
  167. }
  168. }
  169. // Set Inter Container Communication.
  170. if err := setIcc(bridgeIface, icc, enable); err != nil {
  171. return err
  172. }
  173. // Set Accept on all non-intercontainer outgoing packets.
  174. return programChainRule(outRule, "ACCEPT NON_ICC OUTGOING", enable)
  175. }
  176. func programChainRule(rule iptRule, ruleDescr string, insert bool) error {
  177. var (
  178. prefix []string
  179. operation string
  180. condition bool
  181. doesExist = iptables.Exists(rule.table, rule.chain, rule.args...)
  182. )
  183. if insert {
  184. condition = !doesExist
  185. prefix = []string{"-I", rule.chain}
  186. operation = "enable"
  187. } else {
  188. condition = doesExist
  189. prefix = []string{"-D", rule.chain}
  190. operation = "disable"
  191. }
  192. if rule.preArgs != nil {
  193. prefix = append(rule.preArgs, prefix...)
  194. }
  195. if condition {
  196. if err := iptables.RawCombinedOutput(append(prefix, rule.args...)...); err != nil {
  197. return fmt.Errorf("Unable to %s %s rule: %s", operation, ruleDescr, err.Error())
  198. }
  199. }
  200. return nil
  201. }
  202. func setIcc(bridgeIface string, iccEnable, insert bool) error {
  203. var (
  204. table = iptables.Filter
  205. chain = "FORWARD"
  206. args = []string{"-i", bridgeIface, "-o", bridgeIface, "-j"}
  207. acceptArgs = append(args, "ACCEPT")
  208. dropArgs = append(args, "DROP")
  209. )
  210. if insert {
  211. if !iccEnable {
  212. iptables.Raw(append([]string{"-D", chain}, acceptArgs...)...)
  213. if !iptables.Exists(table, chain, dropArgs...) {
  214. if err := iptables.RawCombinedOutput(append([]string{"-A", chain}, dropArgs...)...); err != nil {
  215. return fmt.Errorf("Unable to prevent intercontainer communication: %s", err.Error())
  216. }
  217. }
  218. } else {
  219. iptables.Raw(append([]string{"-D", chain}, dropArgs...)...)
  220. if !iptables.Exists(table, chain, acceptArgs...) {
  221. if err := iptables.RawCombinedOutput(append([]string{"-I", chain}, acceptArgs...)...); err != nil {
  222. return fmt.Errorf("Unable to allow intercontainer communication: %s", err.Error())
  223. }
  224. }
  225. }
  226. } else {
  227. // Remove any ICC rule.
  228. if !iccEnable {
  229. if iptables.Exists(table, chain, dropArgs...) {
  230. iptables.Raw(append([]string{"-D", chain}, dropArgs...)...)
  231. }
  232. } else {
  233. if iptables.Exists(table, chain, acceptArgs...) {
  234. iptables.Raw(append([]string{"-D", chain}, acceptArgs...)...)
  235. }
  236. }
  237. }
  238. return nil
  239. }
  240. // Control Inter Network Communication. Install[Remove] only if it is [not] present.
  241. func setINC(iface string, enable bool) error {
  242. var (
  243. action = iptables.Insert
  244. actionMsg = "add"
  245. chains = []string{IsolationChain1, IsolationChain2}
  246. rules = [][]string{
  247. {"-i", iface, "!", "-o", iface, "-j", IsolationChain2},
  248. {"-o", iface, "-j", "DROP"},
  249. }
  250. )
  251. if !enable {
  252. action = iptables.Delete
  253. actionMsg = "remove"
  254. }
  255. for i, chain := range chains {
  256. if err := iptables.ProgramRule(iptables.Filter, chain, action, rules[i]); err != nil {
  257. msg := fmt.Sprintf("unable to %s inter-network communication rule: %v", actionMsg, err)
  258. if enable {
  259. if i == 1 {
  260. // Rollback the rule installed on first chain
  261. if err2 := iptables.ProgramRule(iptables.Filter, chains[0], iptables.Delete, rules[0]); err2 != nil {
  262. logrus.Warnf("Failed to rollback iptables rule after failure (%v): %v", err, err2)
  263. }
  264. }
  265. return fmt.Errorf(msg)
  266. }
  267. logrus.Warn(msg)
  268. }
  269. }
  270. return nil
  271. }
  272. // Obsolete chain from previous docker versions
  273. const oldIsolationChain = "DOCKER-ISOLATION"
  274. func removeIPChains() {
  275. // Remove obsolete rules from default chains
  276. iptables.ProgramRule(iptables.Filter, "FORWARD", iptables.Delete, []string{"-j", oldIsolationChain})
  277. // Remove chains
  278. for _, chainInfo := range []iptables.ChainInfo{
  279. {Name: DockerChain, Table: iptables.Nat},
  280. {Name: DockerChain, Table: iptables.Filter},
  281. {Name: IsolationChain1, Table: iptables.Filter},
  282. {Name: IsolationChain2, Table: iptables.Filter},
  283. {Name: oldIsolationChain, Table: iptables.Filter},
  284. } {
  285. if err := chainInfo.Remove(); err != nil {
  286. logrus.Warnf("Failed to remove existing iptables entries in table %s chain %s : %v", chainInfo.Table, chainInfo.Name, err)
  287. }
  288. }
  289. }
  290. func setupInternalNetworkRules(bridgeIface string, addr net.Addr, icc, insert bool) error {
  291. var (
  292. inDropRule = iptRule{table: iptables.Filter, chain: IsolationChain1, args: []string{"-i", bridgeIface, "!", "-d", addr.String(), "-j", "DROP"}}
  293. outDropRule = iptRule{table: iptables.Filter, chain: IsolationChain1, args: []string{"-o", bridgeIface, "!", "-s", addr.String(), "-j", "DROP"}}
  294. )
  295. if err := programChainRule(inDropRule, "DROP INCOMING", insert); err != nil {
  296. return err
  297. }
  298. if err := programChainRule(outDropRule, "DROP OUTGOING", insert); err != nil {
  299. return err
  300. }
  301. // Set Inter Container Communication.
  302. return setIcc(bridgeIface, icc, insert)
  303. }
  304. func clearEndpointConnections(nlh *netlink.Handle, ep *bridgeEndpoint) {
  305. var ipv4List []net.IP
  306. var ipv6List []net.IP
  307. if ep.addr != nil {
  308. ipv4List = append(ipv4List, ep.addr.IP)
  309. }
  310. if ep.addrv6 != nil {
  311. ipv6List = append(ipv6List, ep.addrv6.IP)
  312. }
  313. iptables.DeleteConntrackEntries(nlh, ipv4List, ipv6List)
  314. }