iptables.go 10 KB

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