iptables.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558
  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 %s in PREROUTING chain: %s", c.Name, 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 %s in PREROUTING chain: %s", c.Name, 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 %s in OUTPUT chain: %s", c.Name, 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 %s in OUTPUT chain: %s", c.Name, 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. if proto == "sctp" {
  257. // Linux kernel v4.9 and below enables NETIF_F_SCTP_CRC for veth by
  258. // the following commit.
  259. // This introduces a problem when conbined with a physical NIC without
  260. // NETIF_F_SCTP_CRC. As for a workaround, here we add an iptables entry
  261. // to fill the checksum.
  262. //
  263. // https://github.com/torvalds/linux/commit/c80fafbbb59ef9924962f83aac85531039395b18
  264. args = []string{
  265. "-p", proto,
  266. "--sport", strconv.Itoa(destPort),
  267. "-j", "CHECKSUM",
  268. "--checksum-fill",
  269. }
  270. if err := ProgramRule(Mangle, "POSTROUTING", action, args); err != nil {
  271. return err
  272. }
  273. }
  274. return nil
  275. }
  276. // Link adds reciprocal ACCEPT rule for two supplied IP addresses.
  277. // Traffic is allowed from ip1 to ip2 and vice-versa
  278. func (c *ChainInfo) Link(action Action, ip1, ip2 net.IP, port int, proto string, bridgeName string) error {
  279. // forward
  280. args := []string{
  281. "-i", bridgeName, "-o", bridgeName,
  282. "-p", proto,
  283. "-s", ip1.String(),
  284. "-d", ip2.String(),
  285. "--dport", strconv.Itoa(port),
  286. "-j", "ACCEPT",
  287. }
  288. if err := ProgramRule(Filter, c.Name, action, args); err != nil {
  289. return err
  290. }
  291. // reverse
  292. args[7], args[9] = args[9], args[7]
  293. args[10] = "--sport"
  294. return ProgramRule(Filter, c.Name, action, args)
  295. }
  296. // ProgramRule adds the rule specified by args only if the
  297. // rule is not already present in the chain. Reciprocally,
  298. // it removes the rule only if present.
  299. func ProgramRule(table Table, chain string, action Action, args []string) error {
  300. if Exists(table, chain, args...) != (action == Delete) {
  301. return nil
  302. }
  303. return RawCombinedOutput(append([]string{"-t", string(table), string(action), chain}, args...)...)
  304. }
  305. // Prerouting adds linking rule to nat/PREROUTING chain.
  306. func (c *ChainInfo) Prerouting(action Action, args ...string) error {
  307. a := []string{"-t", string(Nat), string(action), "PREROUTING"}
  308. if len(args) > 0 {
  309. a = append(a, args...)
  310. }
  311. if output, err := Raw(a...); err != nil {
  312. return err
  313. } else if len(output) != 0 {
  314. return ChainError{Chain: "PREROUTING", Output: output}
  315. }
  316. return nil
  317. }
  318. // Output adds linking rule to an OUTPUT chain.
  319. func (c *ChainInfo) Output(action Action, args ...string) error {
  320. a := []string{"-t", string(c.Table), string(action), "OUTPUT"}
  321. if len(args) > 0 {
  322. a = append(a, args...)
  323. }
  324. if output, err := Raw(a...); err != nil {
  325. return err
  326. } else if len(output) != 0 {
  327. return ChainError{Chain: "OUTPUT", Output: output}
  328. }
  329. return nil
  330. }
  331. // Remove removes the chain.
  332. func (c *ChainInfo) Remove() error {
  333. // Ignore errors - This could mean the chains were never set up
  334. if c.Table == Nat {
  335. c.Prerouting(Delete, "-m", "addrtype", "--dst-type", "LOCAL", "-j", c.Name)
  336. c.Output(Delete, "-m", "addrtype", "--dst-type", "LOCAL", "!", "--dst", "127.0.0.0/8", "-j", c.Name)
  337. c.Output(Delete, "-m", "addrtype", "--dst-type", "LOCAL", "-j", c.Name) // Created in versions <= 0.1.6
  338. c.Prerouting(Delete)
  339. c.Output(Delete)
  340. }
  341. Raw("-t", string(c.Table), "-F", c.Name)
  342. Raw("-t", string(c.Table), "-X", c.Name)
  343. return nil
  344. }
  345. // Exists checks if a rule exists
  346. func Exists(table Table, chain string, rule ...string) bool {
  347. return exists(false, table, chain, rule...)
  348. }
  349. // ExistsNative behaves as Exists with the difference it
  350. // will always invoke `iptables` binary.
  351. func ExistsNative(table Table, chain string, rule ...string) bool {
  352. return exists(true, table, chain, rule...)
  353. }
  354. func exists(native bool, table Table, chain string, rule ...string) bool {
  355. f := Raw
  356. if native {
  357. f = raw
  358. }
  359. if string(table) == "" {
  360. table = Filter
  361. }
  362. if err := initCheck(); err != nil {
  363. // The exists() signature does not allow us to return an error, but at least
  364. // we can skip the (likely invalid) exec invocation.
  365. return false
  366. }
  367. if supportsCOpt {
  368. // if exit status is 0 then return true, the rule exists
  369. _, err := f(append([]string{"-t", string(table), "-C", chain}, rule...)...)
  370. return err == nil
  371. }
  372. // parse "iptables -S" for the rule (it checks rules in a specific chain
  373. // in a specific table and it is very unreliable)
  374. return existsRaw(table, chain, rule...)
  375. }
  376. func existsRaw(table Table, chain string, rule ...string) bool {
  377. ruleString := fmt.Sprintf("%s %s\n", chain, strings.Join(rule, " "))
  378. existingRules, _ := exec.Command(iptablesPath, "-t", string(table), "-S", chain).Output()
  379. return strings.Contains(string(existingRules), ruleString)
  380. }
  381. // Raw calls 'iptables' system command, passing supplied arguments.
  382. func Raw(args ...string) ([]byte, error) {
  383. if firewalldRunning {
  384. output, err := Passthrough(Iptables, args...)
  385. if err == nil || !strings.Contains(err.Error(), "was not provided by any .service files") {
  386. return output, err
  387. }
  388. }
  389. return raw(args...)
  390. }
  391. func raw(args ...string) ([]byte, error) {
  392. if err := initCheck(); err != nil {
  393. return nil, err
  394. }
  395. if supportsXlock {
  396. args = append([]string{"--wait"}, args...)
  397. } else {
  398. bestEffortLock.Lock()
  399. defer bestEffortLock.Unlock()
  400. }
  401. logrus.Debugf("%s, %v", iptablesPath, args)
  402. output, err := exec.Command(iptablesPath, args...).CombinedOutput()
  403. if err != nil {
  404. return nil, fmt.Errorf("iptables failed: iptables %v: %s (%s)", strings.Join(args, " "), output, err)
  405. }
  406. // ignore iptables' message about xtables lock
  407. if strings.Contains(string(output), xLockWaitMsg) {
  408. output = []byte("")
  409. }
  410. return output, err
  411. }
  412. // RawCombinedOutput inernally calls the Raw function and returns a non nil
  413. // error if Raw returned a non nil error or a non empty output
  414. func RawCombinedOutput(args ...string) error {
  415. if output, err := Raw(args...); err != nil || len(output) != 0 {
  416. return fmt.Errorf("%s (%v)", string(output), err)
  417. }
  418. return nil
  419. }
  420. // RawCombinedOutputNative behave as RawCombinedOutput with the difference it
  421. // will always invoke `iptables` binary
  422. func RawCombinedOutputNative(args ...string) error {
  423. if output, err := raw(args...); err != nil || len(output) != 0 {
  424. return fmt.Errorf("%s (%v)", string(output), err)
  425. }
  426. return nil
  427. }
  428. // ExistChain checks if a chain exists
  429. func ExistChain(chain string, table Table) bool {
  430. if _, err := Raw("-t", string(table), "-nL", chain); err == nil {
  431. return true
  432. }
  433. return false
  434. }
  435. // GetVersion reads the iptables version numbers during initialization
  436. func GetVersion() (major, minor, micro int, err error) {
  437. out, err := exec.Command(iptablesPath, "--version").CombinedOutput()
  438. if err == nil {
  439. major, minor, micro = parseVersionNumbers(string(out))
  440. }
  441. return
  442. }
  443. // SetDefaultPolicy sets the passed default policy for the table/chain
  444. func SetDefaultPolicy(table Table, chain string, policy Policy) error {
  445. if err := RawCombinedOutput("-t", string(table), "-P", chain, string(policy)); err != nil {
  446. return fmt.Errorf("setting default policy to %v in %v chain failed: %v", policy, chain, err)
  447. }
  448. return nil
  449. }
  450. func parseVersionNumbers(input string) (major, minor, micro int) {
  451. re := regexp.MustCompile(`v\d*.\d*.\d*`)
  452. line := re.FindString(input)
  453. fmt.Sscanf(line, "v%d.%d.%d", &major, &minor, &micro)
  454. return
  455. }
  456. // iptables -C, --check option was added in v.1.4.11
  457. // http://ftp.netfilter.org/pub/iptables/changes-iptables-1.4.11.txt
  458. func supportsCOption(mj, mn, mc int) bool {
  459. return mj > 1 || (mj == 1 && (mn > 4 || (mn == 4 && mc >= 11)))
  460. }
  461. // AddReturnRule adds a return rule for the chain in the filter table
  462. func AddReturnRule(chain string) error {
  463. var (
  464. table = Filter
  465. args = []string{"-j", "RETURN"}
  466. )
  467. if Exists(table, chain, args...) {
  468. return nil
  469. }
  470. err := RawCombinedOutput(append([]string{"-A", chain}, args...)...)
  471. if err != nil {
  472. return fmt.Errorf("unable to add return rule in %s chain: %s", chain, err.Error())
  473. }
  474. return nil
  475. }
  476. // EnsureJumpRule ensures the jump rule is on top
  477. func EnsureJumpRule(fromChain, toChain string) error {
  478. var (
  479. table = Filter
  480. args = []string{"-j", toChain}
  481. )
  482. if Exists(table, fromChain, args...) {
  483. err := RawCombinedOutput(append([]string{"-D", fromChain}, args...)...)
  484. if err != nil {
  485. return fmt.Errorf("unable to remove jump to %s rule in %s chain: %s", toChain, fromChain, err.Error())
  486. }
  487. }
  488. err := RawCombinedOutput(append([]string{"-I", fromChain}, args...)...)
  489. if err != nil {
  490. return fmt.Errorf("unable to insert jump to %s rule in %s chain: %s", toChain, fromChain, err.Error())
  491. }
  492. return nil
  493. }