iptables.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467
  1. package iptables
  2. import (
  3. "errors"
  4. "fmt"
  5. "net"
  6. "os/exec"
  7. "regexp"
  8. "strconv"
  9. "strings"
  10. "sync"
  11. "github.com/Sirupsen/logrus"
  12. )
  13. // Action signifies the iptable action.
  14. type Action string
  15. // Policy is the default iptable policies
  16. type Policy string
  17. // Table refers to Nat, Filter or Mangle.
  18. type Table string
  19. const (
  20. // Append appends the rule at the end of the chain.
  21. Append Action = "-A"
  22. // Delete deletes the rule from the chain.
  23. Delete Action = "-D"
  24. // Insert inserts the rule at the top of the chain.
  25. Insert Action = "-I"
  26. // Nat table is used for nat translation rules.
  27. Nat Table = "nat"
  28. // Filter table is used for filter rules.
  29. Filter Table = "filter"
  30. // Mangle table is used for mangling the packet.
  31. Mangle Table = "mangle"
  32. // Drop is the default iptables DROP policy
  33. Drop Policy = "DROP"
  34. // Accept is the default iptables ACCEPT policy
  35. Accept Policy = "ACCEPT"
  36. )
  37. var (
  38. iptablesPath string
  39. supportsXlock = false
  40. supportsCOpt = false
  41. xLockWaitMsg = "Another app is currently holding the xtables lock; waiting"
  42. // used to lock iptables commands if xtables lock is not supported
  43. bestEffortLock sync.Mutex
  44. // ErrIptablesNotFound is returned when the rule is not found.
  45. ErrIptablesNotFound = errors.New("Iptables not found")
  46. probeOnce sync.Once
  47. firewalldOnce sync.Once
  48. )
  49. // ChainInfo defines the iptables chain.
  50. type ChainInfo struct {
  51. Name string
  52. Table Table
  53. HairpinMode bool
  54. }
  55. // ChainError is returned to represent errors during ip table operation.
  56. type ChainError struct {
  57. Chain string
  58. Output []byte
  59. }
  60. func (e ChainError) Error() string {
  61. return fmt.Sprintf("Error iptables %s: %s", e.Chain, string(e.Output))
  62. }
  63. func probe() {
  64. if out, err := exec.Command("modprobe", "-va", "nf_nat").CombinedOutput(); err != nil {
  65. logrus.Warnf("Running modprobe nf_nat failed with message: `%s`, error: %v", strings.TrimSpace(string(out)), err)
  66. }
  67. if out, err := exec.Command("modprobe", "-va", "xt_conntrack").CombinedOutput(); err != nil {
  68. logrus.Warnf("Running modprobe xt_conntrack failed with message: `%s`, error: %v", strings.TrimSpace(string(out)), err)
  69. }
  70. }
  71. func initFirewalld() {
  72. if err := FirewalldInit(); err != nil {
  73. logrus.Debugf("Fail to initialize firewalld: %v, using raw iptables instead", err)
  74. }
  75. }
  76. func initCheck() error {
  77. if iptablesPath == "" {
  78. probeOnce.Do(probe)
  79. firewalldOnce.Do(initFirewalld)
  80. path, err := exec.LookPath("iptables")
  81. if err != nil {
  82. return ErrIptablesNotFound
  83. }
  84. iptablesPath = path
  85. supportsXlock = exec.Command(iptablesPath, "--wait", "-L", "-n").Run() == nil
  86. mj, mn, mc, err := GetVersion()
  87. if err != nil {
  88. logrus.Warnf("Failed to read iptables version: %v", err)
  89. return nil
  90. }
  91. supportsCOpt = supportsCOption(mj, mn, mc)
  92. }
  93. return nil
  94. }
  95. // NewChain adds a new chain to ip table.
  96. func NewChain(name string, table Table, hairpinMode bool) (*ChainInfo, error) {
  97. c := &ChainInfo{
  98. Name: name,
  99. Table: table,
  100. HairpinMode: hairpinMode,
  101. }
  102. if string(c.Table) == "" {
  103. c.Table = Filter
  104. }
  105. // Add chain if it doesn't exist
  106. if _, err := Raw("-t", string(c.Table), "-n", "-L", c.Name); err != nil {
  107. if output, err := Raw("-t", string(c.Table), "-N", c.Name); err != nil {
  108. return nil, err
  109. } else if len(output) != 0 {
  110. return nil, fmt.Errorf("Could not create %s/%s chain: %s", c.Table, c.Name, output)
  111. }
  112. }
  113. return c, nil
  114. }
  115. // ProgramChain is used to add rules to a chain
  116. func ProgramChain(c *ChainInfo, bridgeName string, hairpinMode, enable bool) error {
  117. if c.Name == "" {
  118. return errors.New("Could not program chain, missing chain name")
  119. }
  120. switch c.Table {
  121. case Nat:
  122. preroute := []string{
  123. "-m", "addrtype",
  124. "--dst-type", "LOCAL",
  125. "-j", c.Name}
  126. if !Exists(Nat, "PREROUTING", preroute...) && enable {
  127. if err := c.Prerouting(Append, preroute...); err != nil {
  128. return fmt.Errorf("Failed to inject docker in PREROUTING chain: %s", err)
  129. }
  130. } else if Exists(Nat, "PREROUTING", preroute...) && !enable {
  131. if err := c.Prerouting(Delete, preroute...); err != nil {
  132. return fmt.Errorf("Failed to remove docker in PREROUTING chain: %s", err)
  133. }
  134. }
  135. output := []string{
  136. "-m", "addrtype",
  137. "--dst-type", "LOCAL",
  138. "-j", c.Name}
  139. if !hairpinMode {
  140. output = append(output, "!", "--dst", "127.0.0.0/8")
  141. }
  142. if !Exists(Nat, "OUTPUT", output...) && enable {
  143. if err := c.Output(Append, output...); err != nil {
  144. return fmt.Errorf("Failed to inject docker in OUTPUT chain: %s", err)
  145. }
  146. } else if Exists(Nat, "OUTPUT", output...) && !enable {
  147. if err := c.Output(Delete, output...); err != nil {
  148. return fmt.Errorf("Failed to inject docker in OUTPUT chain: %s", err)
  149. }
  150. }
  151. case Filter:
  152. if bridgeName == "" {
  153. return fmt.Errorf("Could not program chain %s/%s, missing bridge name",
  154. c.Table, c.Name)
  155. }
  156. link := []string{
  157. "-o", bridgeName,
  158. "-j", c.Name}
  159. if !Exists(Filter, "FORWARD", link...) && enable {
  160. insert := append([]string{string(Insert), "FORWARD"}, link...)
  161. if output, err := Raw(insert...); err != nil {
  162. return err
  163. } else if len(output) != 0 {
  164. return fmt.Errorf("Could not create linking rule to %s/%s: %s", c.Table, c.Name, output)
  165. }
  166. } else if Exists(Filter, "FORWARD", link...) && !enable {
  167. del := append([]string{string(Delete), "FORWARD"}, link...)
  168. if output, err := Raw(del...); err != nil {
  169. return err
  170. } else if len(output) != 0 {
  171. return fmt.Errorf("Could not delete linking rule from %s/%s: %s", c.Table, c.Name, output)
  172. }
  173. }
  174. }
  175. return nil
  176. }
  177. // RemoveExistingChain removes existing chain from the table.
  178. func RemoveExistingChain(name string, table Table) error {
  179. c := &ChainInfo{
  180. Name: name,
  181. Table: table,
  182. }
  183. if string(c.Table) == "" {
  184. c.Table = Filter
  185. }
  186. return c.Remove()
  187. }
  188. // Forward adds forwarding rule to 'filter' table and corresponding nat rule to 'nat' table.
  189. func (c *ChainInfo) Forward(action Action, ip net.IP, port int, proto, destAddr string, destPort int, bridgeName string) error {
  190. daddr := ip.String()
  191. if ip.IsUnspecified() {
  192. // iptables interprets "0.0.0.0" as "0.0.0.0/32", whereas we
  193. // want "0.0.0.0/0". "0/0" is correctly interpreted as "any
  194. // value" by both iptables and ip6tables.
  195. daddr = "0/0"
  196. }
  197. args := []string{
  198. "-p", proto,
  199. "-d", daddr,
  200. "--dport", strconv.Itoa(port),
  201. "-j", "DNAT",
  202. "--to-destination", net.JoinHostPort(destAddr, strconv.Itoa(destPort))}
  203. if !c.HairpinMode {
  204. args = append(args, "!", "-i", bridgeName)
  205. }
  206. if err := ProgramRule(Nat, c.Name, action, args); err != nil {
  207. return err
  208. }
  209. args = []string{
  210. "!", "-i", bridgeName,
  211. "-o", bridgeName,
  212. "-p", proto,
  213. "-d", destAddr,
  214. "--dport", strconv.Itoa(destPort),
  215. "-j", "ACCEPT",
  216. }
  217. if err := ProgramRule(Filter, c.Name, action, args); err != nil {
  218. return err
  219. }
  220. args = []string{
  221. "-p", proto,
  222. "-s", destAddr,
  223. "-d", destAddr,
  224. "--dport", strconv.Itoa(destPort),
  225. "-j", "MASQUERADE",
  226. }
  227. if err := ProgramRule(Nat, "POSTROUTING", action, args); err != nil {
  228. return err
  229. }
  230. return nil
  231. }
  232. // Link adds reciprocal ACCEPT rule for two supplied IP addresses.
  233. // Traffic is allowed from ip1 to ip2 and vice-versa
  234. func (c *ChainInfo) Link(action Action, ip1, ip2 net.IP, port int, proto string, bridgeName string) error {
  235. // forward
  236. args := []string{
  237. "-i", bridgeName, "-o", bridgeName,
  238. "-p", proto,
  239. "-s", ip1.String(),
  240. "-d", ip2.String(),
  241. "--dport", strconv.Itoa(port),
  242. "-j", "ACCEPT",
  243. }
  244. if err := ProgramRule(Filter, c.Name, action, args); err != nil {
  245. return err
  246. }
  247. // reverse
  248. args[7], args[9] = args[9], args[7]
  249. args[10] = "--sport"
  250. if err := ProgramRule(Filter, c.Name, action, args); err != nil {
  251. return err
  252. }
  253. return nil
  254. }
  255. // ProgramRule adds the rule specified by args only if the
  256. // rule is not already present in the chain. Reciprocally,
  257. // it removes the rule only if present.
  258. func ProgramRule(table Table, chain string, action Action, args []string) error {
  259. if Exists(table, chain, args...) != (action == Delete) {
  260. return nil
  261. }
  262. return RawCombinedOutput(append([]string{"-t", string(table), string(action), chain}, args...)...)
  263. }
  264. // Prerouting adds linking rule to nat/PREROUTING chain.
  265. func (c *ChainInfo) Prerouting(action Action, args ...string) error {
  266. a := []string{"-t", string(Nat), string(action), "PREROUTING"}
  267. if len(args) > 0 {
  268. a = append(a, args...)
  269. }
  270. if output, err := Raw(a...); err != nil {
  271. return err
  272. } else if len(output) != 0 {
  273. return ChainError{Chain: "PREROUTING", Output: output}
  274. }
  275. return nil
  276. }
  277. // Output adds linking rule to an OUTPUT chain.
  278. func (c *ChainInfo) Output(action Action, args ...string) error {
  279. a := []string{"-t", string(c.Table), string(action), "OUTPUT"}
  280. if len(args) > 0 {
  281. a = append(a, args...)
  282. }
  283. if output, err := Raw(a...); err != nil {
  284. return err
  285. } else if len(output) != 0 {
  286. return ChainError{Chain: "OUTPUT", Output: output}
  287. }
  288. return nil
  289. }
  290. // Remove removes the chain.
  291. func (c *ChainInfo) Remove() error {
  292. // Ignore errors - This could mean the chains were never set up
  293. if c.Table == Nat {
  294. c.Prerouting(Delete, "-m", "addrtype", "--dst-type", "LOCAL", "-j", c.Name)
  295. c.Output(Delete, "-m", "addrtype", "--dst-type", "LOCAL", "!", "--dst", "127.0.0.0/8", "-j", c.Name)
  296. c.Output(Delete, "-m", "addrtype", "--dst-type", "LOCAL", "-j", c.Name) // Created in versions <= 0.1.6
  297. c.Prerouting(Delete)
  298. c.Output(Delete)
  299. }
  300. Raw("-t", string(c.Table), "-F", c.Name)
  301. Raw("-t", string(c.Table), "-X", c.Name)
  302. return nil
  303. }
  304. // Exists checks if a rule exists
  305. func Exists(table Table, chain string, rule ...string) bool {
  306. return exists(false, table, chain, rule...)
  307. }
  308. // ExistsNative behaves as Exists with the difference it
  309. // will always invoke `iptables` binary.
  310. func ExistsNative(table Table, chain string, rule ...string) bool {
  311. return exists(true, table, chain, rule...)
  312. }
  313. func exists(native bool, table Table, chain string, rule ...string) bool {
  314. f := Raw
  315. if native {
  316. f = raw
  317. }
  318. if string(table) == "" {
  319. table = Filter
  320. }
  321. initCheck()
  322. if supportsCOpt {
  323. // if exit status is 0 then return true, the rule exists
  324. _, err := f(append([]string{"-t", string(table), "-C", chain}, rule...)...)
  325. return err == nil
  326. }
  327. // parse "iptables -S" for the rule (it checks rules in a specific chain
  328. // in a specific table and it is very unreliable)
  329. return existsRaw(table, chain, rule...)
  330. }
  331. func existsRaw(table Table, chain string, rule ...string) bool {
  332. ruleString := fmt.Sprintf("%s %s\n", chain, strings.Join(rule, " "))
  333. existingRules, _ := exec.Command(iptablesPath, "-t", string(table), "-S", chain).Output()
  334. return strings.Contains(string(existingRules), ruleString)
  335. }
  336. // Raw calls 'iptables' system command, passing supplied arguments.
  337. func Raw(args ...string) ([]byte, error) {
  338. if firewalldRunning {
  339. output, err := Passthrough(Iptables, args...)
  340. if err == nil || !strings.Contains(err.Error(), "was not provided by any .service files") {
  341. return output, err
  342. }
  343. }
  344. return raw(args...)
  345. }
  346. func raw(args ...string) ([]byte, error) {
  347. if err := initCheck(); err != nil {
  348. return nil, err
  349. }
  350. if supportsXlock {
  351. args = append([]string{"--wait"}, args...)
  352. } else {
  353. bestEffortLock.Lock()
  354. defer bestEffortLock.Unlock()
  355. }
  356. logrus.Debugf("%s, %v", iptablesPath, args)
  357. output, err := exec.Command(iptablesPath, args...).CombinedOutput()
  358. if err != nil {
  359. return nil, fmt.Errorf("iptables failed: iptables %v: %s (%s)", strings.Join(args, " "), output, err)
  360. }
  361. // ignore iptables' message about xtables lock
  362. if strings.Contains(string(output), xLockWaitMsg) {
  363. output = []byte("")
  364. }
  365. return output, err
  366. }
  367. // RawCombinedOutput inernally calls the Raw function and returns a non nil
  368. // error if Raw returned a non nil error or a non empty output
  369. func RawCombinedOutput(args ...string) error {
  370. if output, err := Raw(args...); err != nil || len(output) != 0 {
  371. return fmt.Errorf("%s (%v)", string(output), err)
  372. }
  373. return nil
  374. }
  375. // RawCombinedOutputNative behave as RawCombinedOutput with the difference it
  376. // will always invoke `iptables` binary
  377. func RawCombinedOutputNative(args ...string) error {
  378. if output, err := raw(args...); err != nil || len(output) != 0 {
  379. return fmt.Errorf("%s (%v)", string(output), err)
  380. }
  381. return nil
  382. }
  383. // ExistChain checks if a chain exists
  384. func ExistChain(chain string, table Table) bool {
  385. if _, err := Raw("-t", string(table), "-L", chain); err == nil {
  386. return true
  387. }
  388. return false
  389. }
  390. // GetVersion reads the iptables version numbers
  391. func GetVersion() (major, minor, micro int, err error) {
  392. out, err := Raw("--version")
  393. if err == nil {
  394. major, minor, micro = parseVersionNumbers(string(out))
  395. }
  396. return
  397. }
  398. // SetDefaultPolicy sets the passed default policy for the table/chain
  399. func SetDefaultPolicy(table Table, chain string, policy Policy) error {
  400. if err := RawCombinedOutput("-t", string(table), "-P", chain, string(policy)); err != nil {
  401. return fmt.Errorf("setting default policy to %v in %v chain failed: %v", policy, chain, err)
  402. }
  403. return nil
  404. }
  405. func parseVersionNumbers(input string) (major, minor, micro int) {
  406. re := regexp.MustCompile(`v\d*.\d*.\d*`)
  407. line := re.FindString(input)
  408. fmt.Sscanf(line, "v%d.%d.%d", &major, &minor, &micro)
  409. return
  410. }
  411. // iptables -C, --check option was added in v.1.4.11
  412. // http://ftp.netfilter.org/pub/iptables/changes-iptables-1.4.11.txt
  413. func supportsCOption(mj, mn, mc int) bool {
  414. return mj > 1 || (mj == 1 && (mn > 4 || (mn == 4 && mc >= 11)))
  415. }