iptables.go 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328
  1. package iptables
  2. import (
  3. "errors"
  4. "fmt"
  5. "net"
  6. "os/exec"
  7. "strconv"
  8. "strings"
  9. "sync"
  10. "github.com/Sirupsen/logrus"
  11. )
  12. // Action signifies the iptable action.
  13. type Action string
  14. // Table refers to Nat, Filter or Mangle.
  15. type Table string
  16. const (
  17. // Append appends the rule at the end of the chain.
  18. Append Action = "-A"
  19. // Delete deletes the rule from the chain.
  20. Delete Action = "-D"
  21. // Insert inserts the rule at the top of the chain.
  22. Insert Action = "-I"
  23. // Nat table is used for nat translation rules.
  24. Nat Table = "nat"
  25. // Filter table is used for filter rules.
  26. Filter Table = "filter"
  27. // Mangle table is used for mangling the packet.
  28. Mangle Table = "mangle"
  29. )
  30. var (
  31. iptablesPath string
  32. supportsXlock = false
  33. // used to lock iptables commands if xtables lock is not supported
  34. bestEffortLock sync.Mutex
  35. // ErrIptablesNotFound is returned when the rule is not found.
  36. ErrIptablesNotFound = errors.New("Iptables not found")
  37. )
  38. // Chain defines the iptables chain.
  39. type Chain struct {
  40. Name string
  41. Bridge string
  42. Table Table
  43. HairpinMode bool
  44. }
  45. // ChainError is returned to represent errors during ip table operation.
  46. type ChainError struct {
  47. Chain string
  48. Output []byte
  49. }
  50. func (e ChainError) Error() string {
  51. return fmt.Sprintf("Error iptables %s: %s", e.Chain, string(e.Output))
  52. }
  53. func initCheck() error {
  54. if iptablesPath == "" {
  55. path, err := exec.LookPath("iptables")
  56. if err != nil {
  57. return ErrIptablesNotFound
  58. }
  59. iptablesPath = path
  60. supportsXlock = exec.Command(iptablesPath, "--wait", "-L", "-n").Run() == nil
  61. }
  62. return nil
  63. }
  64. // NewChain adds a new chain to ip table.
  65. func NewChain(name, bridge string, table Table, hairpinMode bool) (*Chain, error) {
  66. c := &Chain{
  67. Name: name,
  68. Bridge: bridge,
  69. Table: table,
  70. HairpinMode: hairpinMode,
  71. }
  72. if string(c.Table) == "" {
  73. c.Table = Filter
  74. }
  75. // Add chain if it doesn't exist
  76. if _, err := Raw("-t", string(c.Table), "-n", "-L", c.Name); err != nil {
  77. if output, err := Raw("-t", string(c.Table), "-N", c.Name); err != nil {
  78. return nil, err
  79. } else if len(output) != 0 {
  80. return nil, fmt.Errorf("Could not create %s/%s chain: %s", c.Table, c.Name, output)
  81. }
  82. }
  83. switch table {
  84. case Nat:
  85. preroute := []string{
  86. "-m", "addrtype",
  87. "--dst-type", "LOCAL",
  88. "-j", c.Name}
  89. if !Exists(Nat, "PREROUTING", preroute...) {
  90. if err := c.Prerouting(Append, preroute...); err != nil {
  91. return nil, fmt.Errorf("Failed to inject docker in PREROUTING chain: %s", err)
  92. }
  93. }
  94. output := []string{
  95. "-m", "addrtype",
  96. "--dst-type", "LOCAL",
  97. "-j", c.Name}
  98. if !hairpinMode {
  99. output = append(output, "!", "--dst", "127.0.0.0/8")
  100. }
  101. if !Exists(Nat, "OUTPUT", output...) {
  102. if err := c.Output(Append, output...); err != nil {
  103. return nil, fmt.Errorf("Failed to inject docker in OUTPUT chain: %s", err)
  104. }
  105. }
  106. case Filter:
  107. link := []string{
  108. "-o", c.Bridge,
  109. "-j", c.Name}
  110. if !Exists(Filter, "FORWARD", link...) {
  111. insert := append([]string{string(Insert), "FORWARD"}, link...)
  112. if output, err := Raw(insert...); err != nil {
  113. return nil, err
  114. } else if len(output) != 0 {
  115. return nil, fmt.Errorf("Could not create linking rule to %s/%s: %s", c.Table, c.Name, output)
  116. }
  117. }
  118. }
  119. return c, nil
  120. }
  121. // RemoveExistingChain removes existing chain from the table.
  122. func RemoveExistingChain(name string, table Table) error {
  123. c := &Chain{
  124. Name: name,
  125. Table: table,
  126. }
  127. if string(c.Table) == "" {
  128. c.Table = Filter
  129. }
  130. return c.Remove()
  131. }
  132. // Forward adds forwarding rule to 'filter' table and corresponding nat rule to 'nat' table.
  133. func (c *Chain) Forward(action Action, ip net.IP, port int, proto, destAddr string, destPort int) error {
  134. daddr := ip.String()
  135. if ip.IsUnspecified() {
  136. // iptables interprets "0.0.0.0" as "0.0.0.0/32", whereas we
  137. // want "0.0.0.0/0". "0/0" is correctly interpreted as "any
  138. // value" by both iptables and ip6tables.
  139. daddr = "0/0"
  140. }
  141. args := []string{"-t", string(Nat), string(action), c.Name,
  142. "-p", proto,
  143. "-d", daddr,
  144. "--dport", strconv.Itoa(port),
  145. "-j", "DNAT",
  146. "--to-destination", net.JoinHostPort(destAddr, strconv.Itoa(destPort))}
  147. if !c.HairpinMode {
  148. args = append(args, "!", "-i", c.Bridge)
  149. }
  150. if output, err := Raw(args...); err != nil {
  151. return err
  152. } else if len(output) != 0 {
  153. return ChainError{Chain: "FORWARD", Output: output}
  154. }
  155. if output, err := Raw("-t", string(Filter), string(action), c.Name,
  156. "!", "-i", c.Bridge,
  157. "-o", c.Bridge,
  158. "-p", proto,
  159. "-d", destAddr,
  160. "--dport", strconv.Itoa(destPort),
  161. "-j", "ACCEPT"); err != nil {
  162. return err
  163. } else if len(output) != 0 {
  164. return ChainError{Chain: "FORWARD", Output: output}
  165. }
  166. if output, err := Raw("-t", string(Nat), string(action), "POSTROUTING",
  167. "-p", proto,
  168. "-s", destAddr,
  169. "-d", destAddr,
  170. "--dport", strconv.Itoa(destPort),
  171. "-j", "MASQUERADE"); err != nil {
  172. return err
  173. } else if len(output) != 0 {
  174. return ChainError{Chain: "FORWARD", Output: output}
  175. }
  176. return nil
  177. }
  178. // Link adds reciprocal ACCEPT rule for two supplied IP addresses.
  179. // Traffic is allowed from ip1 to ip2 and vice-versa
  180. func (c *Chain) Link(action Action, ip1, ip2 net.IP, port int, proto string) error {
  181. if output, err := Raw("-t", string(Filter), string(action), c.Name,
  182. "-i", c.Bridge, "-o", c.Bridge,
  183. "-p", proto,
  184. "-s", ip1.String(),
  185. "-d", ip2.String(),
  186. "--dport", strconv.Itoa(port),
  187. "-j", "ACCEPT"); err != nil {
  188. return err
  189. } else if len(output) != 0 {
  190. return fmt.Errorf("Error iptables forward: %s", output)
  191. }
  192. if output, err := Raw("-t", string(Filter), string(action), c.Name,
  193. "-i", c.Bridge, "-o", c.Bridge,
  194. "-p", proto,
  195. "-s", ip2.String(),
  196. "-d", ip1.String(),
  197. "--sport", strconv.Itoa(port),
  198. "-j", "ACCEPT"); err != nil {
  199. return err
  200. } else if len(output) != 0 {
  201. return fmt.Errorf("Error iptables forward: %s", output)
  202. }
  203. return nil
  204. }
  205. // Prerouting adds linking rule to nat/PREROUTING chain.
  206. func (c *Chain) Prerouting(action Action, args ...string) error {
  207. a := []string{"-t", string(Nat), string(action), "PREROUTING"}
  208. if len(args) > 0 {
  209. a = append(a, args...)
  210. }
  211. if output, err := Raw(a...); err != nil {
  212. return err
  213. } else if len(output) != 0 {
  214. return ChainError{Chain: "PREROUTING", Output: output}
  215. }
  216. return nil
  217. }
  218. // Output adds linking rule to an OUTPUT chain.
  219. func (c *Chain) Output(action Action, args ...string) error {
  220. a := []string{"-t", string(c.Table), string(action), "OUTPUT"}
  221. if len(args) > 0 {
  222. a = append(a, args...)
  223. }
  224. if output, err := Raw(a...); err != nil {
  225. return err
  226. } else if len(output) != 0 {
  227. return ChainError{Chain: "OUTPUT", Output: output}
  228. }
  229. return nil
  230. }
  231. // Remove removes the chain.
  232. func (c *Chain) Remove() error {
  233. // Ignore errors - This could mean the chains were never set up
  234. if c.Table == Nat {
  235. c.Prerouting(Delete, "-m", "addrtype", "--dst-type", "LOCAL", "-j", c.Name)
  236. c.Output(Delete, "-m", "addrtype", "--dst-type", "LOCAL", "!", "--dst", "127.0.0.0/8", "-j", c.Name)
  237. c.Output(Delete, "-m", "addrtype", "--dst-type", "LOCAL", "-j", c.Name) // Created in versions <= 0.1.6
  238. c.Prerouting(Delete)
  239. c.Output(Delete)
  240. }
  241. Raw("-t", string(c.Table), "-F", c.Name)
  242. Raw("-t", string(c.Table), "-X", c.Name)
  243. return nil
  244. }
  245. // Exists checks if a rule exists
  246. func Exists(table Table, chain string, rule ...string) bool {
  247. if string(table) == "" {
  248. table = Filter
  249. }
  250. // iptables -C, --check option was added in v.1.4.11
  251. // http://ftp.netfilter.org/pub/iptables/changes-iptables-1.4.11.txt
  252. // try -C
  253. // if exit status is 0 then return true, the rule exists
  254. if _, err := Raw(append([]string{
  255. "-t", string(table), "-C", chain}, rule...)...); err == nil {
  256. return true
  257. }
  258. // parse "iptables -S" for the rule (this checks rules in a specific chain
  259. // in a specific table)
  260. ruleString := strings.Join(rule, " ")
  261. existingRules, _ := exec.Command(iptablesPath, "-t", string(table), "-S", chain).Output()
  262. return strings.Contains(string(existingRules), ruleString)
  263. }
  264. // Raw calls 'iptables' system command, passing supplied arguments.
  265. func Raw(args ...string) ([]byte, error) {
  266. if firewalldRunning {
  267. output, err := Passthrough(Iptables, args...)
  268. if err == nil || !strings.Contains(err.Error(), "was not provided by any .service files") {
  269. return output, err
  270. }
  271. }
  272. if err := initCheck(); err != nil {
  273. return nil, err
  274. }
  275. if supportsXlock {
  276. args = append([]string{"--wait"}, args...)
  277. } else {
  278. bestEffortLock.Lock()
  279. defer bestEffortLock.Unlock()
  280. }
  281. logrus.Debugf("%s, %v", iptablesPath, args)
  282. output, err := exec.Command(iptablesPath, args...).CombinedOutput()
  283. if err != nil {
  284. return nil, fmt.Errorf("iptables failed: iptables %v: %s (%s)", strings.Join(args, " "), output, err)
  285. }
  286. // ignore iptables' message about xtables lock
  287. if strings.Contains(string(output), "waiting for it to exit") {
  288. output = []byte("")
  289. }
  290. return output, err
  291. }