setup_ip_tables.go 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259
  1. package bridge
  2. import (
  3. "fmt"
  4. "net"
  5. "github.com/Sirupsen/logrus"
  6. "github.com/docker/libnetwork/iptables"
  7. "github.com/docker/libnetwork/netutils"
  8. )
  9. // DockerChain: DOCKER iptable chain name
  10. const (
  11. DockerChain = "DOCKER"
  12. )
  13. func setupIPChains(config *configuration) (*iptables.ChainInfo, *iptables.ChainInfo, error) {
  14. // Sanity check.
  15. if config.EnableIPTables == false {
  16. return nil, nil, fmt.Errorf("Cannot create new chains, EnableIPTable is disabled")
  17. }
  18. hairpinMode := !config.EnableUserlandProxy
  19. natChain, err := iptables.NewChain(DockerChain, iptables.Nat, hairpinMode)
  20. if err != nil {
  21. return nil, nil, fmt.Errorf("Failed to create NAT chain: %s", err.Error())
  22. }
  23. defer func() {
  24. if err != nil {
  25. if err := iptables.RemoveExistingChain(DockerChain, iptables.Nat); err != nil {
  26. logrus.Warnf("Failed on removing iptables NAT chain on cleanup: %v", err)
  27. }
  28. }
  29. }()
  30. filterChain, err := iptables.NewChain(DockerChain, iptables.Filter, hairpinMode)
  31. if err != nil {
  32. return nil, nil, fmt.Errorf("Failed to create FILTER chain: %s", err.Error())
  33. }
  34. return natChain, filterChain, nil
  35. }
  36. func (n *bridgeNetwork) setupIPTables(config *networkConfiguration, i *bridgeInterface) error {
  37. d := n.driver
  38. d.Lock()
  39. driverConfig := d.config
  40. d.Unlock()
  41. // Sanity check.
  42. if driverConfig.EnableIPTables == false {
  43. return fmt.Errorf("Cannot program chains, EnableIPTable is disabled")
  44. }
  45. // Pickup this configuraton option from driver
  46. hairpinMode := !driverConfig.EnableUserlandProxy
  47. addrv4, _, err := netutils.GetIfaceAddr(config.BridgeName)
  48. if err != nil {
  49. return fmt.Errorf("Failed to setup IP tables, cannot acquire Interface address: %s", err.Error())
  50. }
  51. ipnet := addrv4.(*net.IPNet)
  52. maskedAddrv4 := &net.IPNet{
  53. IP: ipnet.IP.Mask(ipnet.Mask),
  54. Mask: ipnet.Mask,
  55. }
  56. if err = setupIPTablesInternal(config.BridgeName, maskedAddrv4, config.EnableICC, config.EnableIPMasquerade, hairpinMode, true); err != nil {
  57. return fmt.Errorf("Failed to Setup IP tables: %s", err.Error())
  58. }
  59. n.registerIptCleanFunc(func() error {
  60. return setupIPTablesInternal(config.BridgeName, maskedAddrv4, config.EnableICC, config.EnableIPMasquerade, hairpinMode, false)
  61. })
  62. natChain, filterChain, err := n.getDriverChains()
  63. if err != nil {
  64. return fmt.Errorf("Failed to setup IP tables, cannot acquire chain info %s", err.Error())
  65. }
  66. err = iptables.ProgramChain(natChain, config.BridgeName, hairpinMode, true)
  67. if err != nil {
  68. return fmt.Errorf("Failed to program NAT chain: %s", err.Error())
  69. }
  70. err = iptables.ProgramChain(filterChain, config.BridgeName, hairpinMode, true)
  71. if err != nil {
  72. return fmt.Errorf("Failed to program FILTER chain: %s", err.Error())
  73. }
  74. n.registerIptCleanFunc(func() error {
  75. return iptables.ProgramChain(filterChain, config.BridgeName, hairpinMode, false)
  76. })
  77. n.portMapper.SetIptablesChain(filterChain, n.getNetworkBridgeName())
  78. return nil
  79. }
  80. type iptRule struct {
  81. table iptables.Table
  82. chain string
  83. preArgs []string
  84. args []string
  85. }
  86. func setupIPTablesInternal(bridgeIface string, addr net.Addr, icc, ipmasq, hairpin, enable bool) error {
  87. var (
  88. address = addr.String()
  89. natRule = iptRule{table: iptables.Nat, chain: "POSTROUTING", preArgs: []string{"-t", "nat"}, args: []string{"-s", address, "!", "-o", bridgeIface, "-j", "MASQUERADE"}}
  90. hpNatRule = iptRule{table: iptables.Nat, chain: "POSTROUTING", preArgs: []string{"-t", "nat"}, args: []string{"-m", "addrtype", "--src-type", "LOCAL", "-o", bridgeIface, "-j", "MASQUERADE"}}
  91. outRule = iptRule{table: iptables.Filter, chain: "FORWARD", args: []string{"-i", bridgeIface, "!", "-o", bridgeIface, "-j", "ACCEPT"}}
  92. inRule = iptRule{table: iptables.Filter, chain: "FORWARD", args: []string{"-o", bridgeIface, "-m", "conntrack", "--ctstate", "RELATED,ESTABLISHED", "-j", "ACCEPT"}}
  93. )
  94. // Set NAT.
  95. if ipmasq {
  96. if err := programChainRule(natRule, "NAT", enable); err != nil {
  97. return err
  98. }
  99. }
  100. // In hairpin mode, masquerade traffic from localhost
  101. if hairpin {
  102. if err := programChainRule(hpNatRule, "MASQ LOCAL HOST", enable); err != nil {
  103. return err
  104. }
  105. }
  106. // Set Inter Container Communication.
  107. if err := setIcc(bridgeIface, icc, enable); err != nil {
  108. return err
  109. }
  110. // Set Accept on all non-intercontainer outgoing packets.
  111. if err := programChainRule(outRule, "ACCEPT NON_ICC OUTGOING", enable); err != nil {
  112. return err
  113. }
  114. // Set Accept on incoming packets for existing connections.
  115. if err := programChainRule(inRule, "ACCEPT INCOMING", enable); err != nil {
  116. return err
  117. }
  118. return nil
  119. }
  120. func programChainRule(rule iptRule, ruleDescr string, insert bool) error {
  121. var (
  122. prefix []string
  123. operation string
  124. condition bool
  125. doesExist = iptables.Exists(rule.table, rule.chain, rule.args...)
  126. )
  127. if insert {
  128. condition = !doesExist
  129. prefix = []string{"-I", rule.chain}
  130. operation = "enable"
  131. } else {
  132. condition = doesExist
  133. prefix = []string{"-D", rule.chain}
  134. operation = "disable"
  135. }
  136. if rule.preArgs != nil {
  137. prefix = append(rule.preArgs, prefix...)
  138. }
  139. if condition {
  140. if output, err := iptables.Raw(append(prefix, rule.args...)...); err != nil {
  141. return fmt.Errorf("Unable to %s %s rule: %s", operation, ruleDescr, err.Error())
  142. } else if len(output) != 0 {
  143. return &iptables.ChainError{Chain: rule.chain, Output: output}
  144. }
  145. }
  146. return nil
  147. }
  148. func setIcc(bridgeIface string, iccEnable, insert bool) error {
  149. var (
  150. table = iptables.Filter
  151. chain = "FORWARD"
  152. args = []string{"-i", bridgeIface, "-o", bridgeIface, "-j"}
  153. acceptArgs = append(args, "ACCEPT")
  154. dropArgs = append(args, "DROP")
  155. )
  156. if insert {
  157. if !iccEnable {
  158. iptables.Raw(append([]string{"-D", chain}, acceptArgs...)...)
  159. if !iptables.Exists(table, chain, dropArgs...) {
  160. if output, err := iptables.Raw(append([]string{"-A", chain}, dropArgs...)...); err != nil {
  161. return fmt.Errorf("Unable to prevent intercontainer communication: %s", err.Error())
  162. } else if len(output) != 0 {
  163. return fmt.Errorf("Error disabling intercontainer communication: %s", output)
  164. }
  165. }
  166. } else {
  167. iptables.Raw(append([]string{"-D", chain}, dropArgs...)...)
  168. if !iptables.Exists(table, chain, acceptArgs...) {
  169. if output, err := iptables.Raw(append([]string{"-I", chain}, acceptArgs...)...); err != nil {
  170. return fmt.Errorf("Unable to allow intercontainer communication: %s", err.Error())
  171. } else if len(output) != 0 {
  172. return fmt.Errorf("Error enabling intercontainer communication: %s", output)
  173. }
  174. }
  175. }
  176. } else {
  177. // Remove any ICC rule.
  178. if !iccEnable {
  179. if iptables.Exists(table, chain, dropArgs...) {
  180. iptables.Raw(append([]string{"-D", chain}, dropArgs...)...)
  181. }
  182. } else {
  183. if iptables.Exists(table, chain, acceptArgs...) {
  184. iptables.Raw(append([]string{"-D", chain}, acceptArgs...)...)
  185. }
  186. }
  187. }
  188. return nil
  189. }
  190. // Control Inter Network Communication. Install/remove only if it is not/is present.
  191. func setINC(network1, network2 string, enable bool) error {
  192. var (
  193. table = iptables.Filter
  194. chain = "FORWARD"
  195. args = [2][]string{{"-s", network1, "-d", network2, "-j", "DROP"}, {"-s", network2, "-d", network1, "-j", "DROP"}}
  196. )
  197. if enable {
  198. for i := 0; i < 2; i++ {
  199. if iptables.Exists(table, chain, args[i]...) {
  200. continue
  201. }
  202. if output, err := iptables.Raw(append([]string{"-I", chain}, args[i]...)...); err != nil {
  203. return fmt.Errorf("unable to add inter-network communication rule: %s", err.Error())
  204. } else if len(output) != 0 {
  205. return fmt.Errorf("error adding inter-network communication rule: %s", string(output))
  206. }
  207. }
  208. } else {
  209. for i := 0; i < 2; i++ {
  210. if !iptables.Exists(table, chain, args[i]...) {
  211. continue
  212. }
  213. if output, err := iptables.Raw(append([]string{"-D", chain}, args[i]...)...); err != nil {
  214. return fmt.Errorf("unable to remove inter-network communication rule: %s", err.Error())
  215. } else if len(output) != 0 {
  216. return fmt.Errorf("error removing inter-network communication rule: %s", string(output))
  217. }
  218. }
  219. }
  220. return nil
  221. }