iptables.go 14 KB

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