setup_ip_tables.go 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253
  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. natChain, filterChain, err := n.getDriverChains()
  60. if err != nil {
  61. return fmt.Errorf("Failed to setup IP tables, cannot acquire chain info %s", err.Error())
  62. }
  63. err = iptables.ProgramChain(natChain, config.BridgeName, hairpinMode)
  64. if err != nil {
  65. return fmt.Errorf("Failed to program NAT chain: %s", err.Error())
  66. }
  67. err = iptables.ProgramChain(filterChain, config.BridgeName, hairpinMode)
  68. if err != nil {
  69. return fmt.Errorf("Failed to program FILTER chain: %s", err.Error())
  70. }
  71. n.portMapper.SetIptablesChain(filterChain, n.getNetworkBridgeName())
  72. return nil
  73. }
  74. type iptRule struct {
  75. table iptables.Table
  76. chain string
  77. preArgs []string
  78. args []string
  79. }
  80. func setupIPTablesInternal(bridgeIface string, addr net.Addr, icc, ipmasq, hairpin, enable bool) error {
  81. var (
  82. address = addr.String()
  83. natRule = iptRule{table: iptables.Nat, chain: "POSTROUTING", preArgs: []string{"-t", "nat"}, args: []string{"-s", address, "!", "-o", bridgeIface, "-j", "MASQUERADE"}}
  84. hpNatRule = iptRule{table: iptables.Nat, chain: "POSTROUTING", preArgs: []string{"-t", "nat"}, args: []string{"-m", "addrtype", "--src-type", "LOCAL", "-o", bridgeIface, "-j", "MASQUERADE"}}
  85. outRule = iptRule{table: iptables.Filter, chain: "FORWARD", args: []string{"-i", bridgeIface, "!", "-o", bridgeIface, "-j", "ACCEPT"}}
  86. inRule = iptRule{table: iptables.Filter, chain: "FORWARD", args: []string{"-o", bridgeIface, "-m", "conntrack", "--ctstate", "RELATED,ESTABLISHED", "-j", "ACCEPT"}}
  87. )
  88. // Set NAT.
  89. if ipmasq {
  90. if err := programChainRule(natRule, "NAT", enable); err != nil {
  91. return err
  92. }
  93. }
  94. // In hairpin mode, masquerade traffic from localhost
  95. if hairpin {
  96. if err := programChainRule(hpNatRule, "MASQ LOCAL HOST", enable); err != nil {
  97. return err
  98. }
  99. }
  100. // Set Inter Container Communication.
  101. if err := setIcc(bridgeIface, icc, enable); err != nil {
  102. return err
  103. }
  104. // Set Accept on all non-intercontainer outgoing packets.
  105. if err := programChainRule(outRule, "ACCEPT NON_ICC OUTGOING", enable); err != nil {
  106. return err
  107. }
  108. // Set Accept on incoming packets for existing connections.
  109. if err := programChainRule(inRule, "ACCEPT INCOMING", enable); err != nil {
  110. return err
  111. }
  112. return nil
  113. }
  114. func programChainRule(rule iptRule, ruleDescr string, insert bool) error {
  115. var (
  116. prefix []string
  117. operation string
  118. condition bool
  119. doesExist = iptables.Exists(rule.table, rule.chain, rule.args...)
  120. )
  121. if insert {
  122. condition = !doesExist
  123. prefix = []string{"-I", rule.chain}
  124. operation = "enable"
  125. } else {
  126. condition = doesExist
  127. prefix = []string{"-D", rule.chain}
  128. operation = "disable"
  129. }
  130. if rule.preArgs != nil {
  131. prefix = append(rule.preArgs, prefix...)
  132. }
  133. if condition {
  134. if output, err := iptables.Raw(append(prefix, rule.args...)...); err != nil {
  135. return fmt.Errorf("Unable to %s %s rule: %s", operation, ruleDescr, err.Error())
  136. } else if len(output) != 0 {
  137. return &iptables.ChainError{Chain: rule.chain, Output: output}
  138. }
  139. }
  140. return nil
  141. }
  142. func setIcc(bridgeIface string, iccEnable, insert bool) error {
  143. var (
  144. table = iptables.Filter
  145. chain = "FORWARD"
  146. args = []string{"-i", bridgeIface, "-o", bridgeIface, "-j"}
  147. acceptArgs = append(args, "ACCEPT")
  148. dropArgs = append(args, "DROP")
  149. )
  150. if insert {
  151. if !iccEnable {
  152. iptables.Raw(append([]string{"-D", chain}, acceptArgs...)...)
  153. if !iptables.Exists(table, chain, dropArgs...) {
  154. if output, err := iptables.Raw(append([]string{"-A", chain}, dropArgs...)...); err != nil {
  155. return fmt.Errorf("Unable to prevent intercontainer communication: %s", err.Error())
  156. } else if len(output) != 0 {
  157. return fmt.Errorf("Error disabling intercontainer communication: %s", output)
  158. }
  159. }
  160. } else {
  161. iptables.Raw(append([]string{"-D", chain}, dropArgs...)...)
  162. if !iptables.Exists(table, chain, acceptArgs...) {
  163. if output, err := iptables.Raw(append([]string{"-I", chain}, acceptArgs...)...); err != nil {
  164. return fmt.Errorf("Unable to allow intercontainer communication: %s", err.Error())
  165. } else if len(output) != 0 {
  166. return fmt.Errorf("Error enabling intercontainer communication: %s", output)
  167. }
  168. }
  169. }
  170. } else {
  171. // Remove any ICC rule.
  172. if !iccEnable {
  173. if iptables.Exists(table, chain, dropArgs...) {
  174. iptables.Raw(append([]string{"-D", chain}, dropArgs...)...)
  175. }
  176. } else {
  177. if iptables.Exists(table, chain, acceptArgs...) {
  178. iptables.Raw(append([]string{"-D", chain}, acceptArgs...)...)
  179. }
  180. }
  181. }
  182. return nil
  183. }
  184. // Control Inter Network Communication. Install/remove only if it is not/is present.
  185. func setINC(network1, network2 string, enable bool) error {
  186. var (
  187. table = iptables.Filter
  188. chain = "FORWARD"
  189. args = [2][]string{{"-s", network1, "-d", network2, "-j", "DROP"}, {"-s", network2, "-d", network1, "-j", "DROP"}}
  190. )
  191. if enable {
  192. for i := 0; i < 2; i++ {
  193. if iptables.Exists(table, chain, args[i]...) {
  194. continue
  195. }
  196. if output, err := iptables.Raw(append([]string{"-I", chain}, args[i]...)...); err != nil {
  197. return fmt.Errorf("unable to add inter-network communication rule: %s", err.Error())
  198. } else if len(output) != 0 {
  199. return fmt.Errorf("error adding inter-network communication rule: %s", string(output))
  200. }
  201. }
  202. } else {
  203. for i := 0; i < 2; i++ {
  204. if !iptables.Exists(table, chain, args[i]...) {
  205. continue
  206. }
  207. if output, err := iptables.Raw(append([]string{"-D", chain}, args[i]...)...); err != nil {
  208. return fmt.Errorf("unable to remove inter-network communication rule: %s", err.Error())
  209. } else if len(output) != 0 {
  210. return fmt.Errorf("error removing inter-network communication rule: %s", string(output))
  211. }
  212. }
  213. }
  214. return nil
  215. }