setup_ip_tables.go 10 KB

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