iptables.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575
  1. package iptables
  2. import (
  3. "errors"
  4. "fmt"
  5. "net"
  6. "os/exec"
  7. "regexp"
  8. "strconv"
  9. "strings"
  10. "sync"
  11. "time"
  12. "github.com/sirupsen/logrus"
  13. )
  14. // Action signifies the iptable action.
  15. type Action string
  16. // Policy is the default iptable policies
  17. type Policy string
  18. // Table refers to Nat, Filter or Mangle.
  19. type Table string
  20. const (
  21. // Append appends the rule at the end of the chain.
  22. Append Action = "-A"
  23. // Delete deletes the rule from the chain.
  24. Delete Action = "-D"
  25. // Insert inserts the rule at the top of the chain.
  26. Insert Action = "-I"
  27. // Nat table is used for nat translation rules.
  28. Nat Table = "nat"
  29. // Filter table is used for filter rules.
  30. Filter Table = "filter"
  31. // Mangle table is used for mangling the packet.
  32. Mangle Table = "mangle"
  33. // Drop is the default iptables DROP policy
  34. Drop Policy = "DROP"
  35. // Accept is the default iptables ACCEPT policy
  36. Accept Policy = "ACCEPT"
  37. )
  38. var (
  39. iptablesPath string
  40. supportsXlock = false
  41. supportsCOpt = false
  42. xLockWaitMsg = "Another app is currently holding the xtables lock"
  43. // used to lock iptables commands if xtables lock is not supported
  44. bestEffortLock sync.Mutex
  45. // ErrIptablesNotFound is returned when the rule is not found.
  46. ErrIptablesNotFound = errors.New("Iptables not found")
  47. initOnce 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 detectIptables() {
  77. path, err := exec.LookPath("iptables")
  78. if err != nil {
  79. return
  80. }
  81. iptablesPath = path
  82. supportsXlock = exec.Command(iptablesPath, "--wait", "-L", "-n").Run() == nil
  83. mj, mn, mc, err := GetVersion()
  84. if err != nil {
  85. logrus.Warnf("Failed to read iptables version: %v", err)
  86. return
  87. }
  88. supportsCOpt = supportsCOption(mj, mn, mc)
  89. }
  90. func initDependencies() {
  91. probe()
  92. initFirewalld()
  93. detectIptables()
  94. }
  95. func initCheck() error {
  96. initOnce.Do(initDependencies)
  97. if iptablesPath == "" {
  98. return ErrIptablesNotFound
  99. }
  100. return nil
  101. }
  102. // NewChain adds a new chain to ip table.
  103. func NewChain(name string, table Table, hairpinMode bool) (*ChainInfo, error) {
  104. c := &ChainInfo{
  105. Name: name,
  106. Table: table,
  107. HairpinMode: hairpinMode,
  108. }
  109. if string(c.Table) == "" {
  110. c.Table = Filter
  111. }
  112. // Add chain if it doesn't exist
  113. if _, err := Raw("-t", string(c.Table), "-n", "-L", c.Name); err != nil {
  114. if output, err := Raw("-t", string(c.Table), "-N", c.Name); err != nil {
  115. return nil, err
  116. } else if len(output) != 0 {
  117. return nil, fmt.Errorf("Could not create %s/%s chain: %s", c.Table, c.Name, output)
  118. }
  119. }
  120. return c, nil
  121. }
  122. // ProgramChain is used to add rules to a chain
  123. func ProgramChain(c *ChainInfo, bridgeName string, hairpinMode, enable bool) error {
  124. if c.Name == "" {
  125. return errors.New("Could not program chain, missing chain name")
  126. }
  127. switch c.Table {
  128. case Nat:
  129. preroute := []string{
  130. "-m", "addrtype",
  131. "--dst-type", "LOCAL",
  132. "-j", c.Name}
  133. if !Exists(Nat, "PREROUTING", preroute...) && enable {
  134. if err := c.Prerouting(Append, preroute...); err != nil {
  135. return fmt.Errorf("Failed to inject %s in PREROUTING chain: %s", c.Name, err)
  136. }
  137. } else if Exists(Nat, "PREROUTING", preroute...) && !enable {
  138. if err := c.Prerouting(Delete, preroute...); err != nil {
  139. return fmt.Errorf("Failed to remove %s in PREROUTING chain: %s", c.Name, err)
  140. }
  141. }
  142. output := []string{
  143. "-m", "addrtype",
  144. "--dst-type", "LOCAL",
  145. "-j", c.Name}
  146. if !hairpinMode {
  147. output = append(output, "!", "--dst", "127.0.0.0/8")
  148. }
  149. if !Exists(Nat, "OUTPUT", output...) && enable {
  150. if err := c.Output(Append, output...); err != nil {
  151. return fmt.Errorf("Failed to inject %s in OUTPUT chain: %s", c.Name, err)
  152. }
  153. } else if Exists(Nat, "OUTPUT", output...) && !enable {
  154. if err := c.Output(Delete, output...); err != nil {
  155. return fmt.Errorf("Failed to inject %s in OUTPUT chain: %s", c.Name, err)
  156. }
  157. }
  158. case Filter:
  159. if bridgeName == "" {
  160. return fmt.Errorf("Could not program chain %s/%s, missing bridge name",
  161. c.Table, c.Name)
  162. }
  163. link := []string{
  164. "-o", bridgeName,
  165. "-j", c.Name}
  166. if !Exists(Filter, "FORWARD", link...) && enable {
  167. insert := append([]string{string(Insert), "FORWARD"}, link...)
  168. if output, err := Raw(insert...); err != nil {
  169. return err
  170. } else if len(output) != 0 {
  171. return fmt.Errorf("Could not create linking rule to %s/%s: %s", c.Table, c.Name, output)
  172. }
  173. } else if Exists(Filter, "FORWARD", link...) && !enable {
  174. del := append([]string{string(Delete), "FORWARD"}, link...)
  175. if output, err := Raw(del...); err != nil {
  176. return err
  177. } else if len(output) != 0 {
  178. return fmt.Errorf("Could not delete linking rule from %s/%s: %s", c.Table, c.Name, output)
  179. }
  180. }
  181. establish := []string{
  182. "-o", bridgeName,
  183. "-m", "conntrack",
  184. "--ctstate", "RELATED,ESTABLISHED",
  185. "-j", "ACCEPT"}
  186. if !Exists(Filter, "FORWARD", establish...) && enable {
  187. insert := append([]string{string(Insert), "FORWARD"}, establish...)
  188. if output, err := Raw(insert...); err != nil {
  189. return err
  190. } else if len(output) != 0 {
  191. return fmt.Errorf("Could not create establish rule to %s: %s", c.Table, output)
  192. }
  193. } else if Exists(Filter, "FORWARD", establish...) && !enable {
  194. del := append([]string{string(Delete), "FORWARD"}, establish...)
  195. if output, err := Raw(del...); err != nil {
  196. return err
  197. } else if len(output) != 0 {
  198. return fmt.Errorf("Could not delete establish rule from %s: %s", c.Table, output)
  199. }
  200. }
  201. }
  202. return nil
  203. }
  204. // RemoveExistingChain removes existing chain from the table.
  205. func RemoveExistingChain(name string, table Table) error {
  206. c := &ChainInfo{
  207. Name: name,
  208. Table: table,
  209. }
  210. if string(c.Table) == "" {
  211. c.Table = Filter
  212. }
  213. return c.Remove()
  214. }
  215. // Forward adds forwarding rule to 'filter' table and corresponding nat rule to 'nat' table.
  216. func (c *ChainInfo) Forward(action Action, ip net.IP, port int, proto, destAddr string, destPort int, bridgeName string) error {
  217. daddr := ip.String()
  218. if ip.IsUnspecified() {
  219. // iptables interprets "0.0.0.0" as "0.0.0.0/32", whereas we
  220. // want "0.0.0.0/0". "0/0" is correctly interpreted as "any
  221. // value" by both iptables and ip6tables.
  222. daddr = "0/0"
  223. }
  224. args := []string{
  225. "-p", proto,
  226. "-d", daddr,
  227. "--dport", strconv.Itoa(port),
  228. "-j", "DNAT",
  229. "--to-destination", net.JoinHostPort(destAddr, strconv.Itoa(destPort))}
  230. if !c.HairpinMode {
  231. args = append(args, "!", "-i", bridgeName)
  232. }
  233. if err := ProgramRule(Nat, c.Name, action, args); err != nil {
  234. return err
  235. }
  236. args = []string{
  237. "!", "-i", bridgeName,
  238. "-o", bridgeName,
  239. "-p", proto,
  240. "-d", destAddr,
  241. "--dport", strconv.Itoa(destPort),
  242. "-j", "ACCEPT",
  243. }
  244. if err := ProgramRule(Filter, c.Name, action, args); err != nil {
  245. return err
  246. }
  247. args = []string{
  248. "-p", proto,
  249. "-s", destAddr,
  250. "-d", destAddr,
  251. "--dport", strconv.Itoa(destPort),
  252. "-j", "MASQUERADE",
  253. }
  254. if err := ProgramRule(Nat, "POSTROUTING", action, args); err != nil {
  255. return err
  256. }
  257. if proto == "sctp" {
  258. // Linux kernel v4.9 and below enables NETIF_F_SCTP_CRC for veth by
  259. // the following commit.
  260. // This introduces a problem when conbined with a physical NIC without
  261. // NETIF_F_SCTP_CRC. As for a workaround, here we add an iptables entry
  262. // to fill the checksum.
  263. //
  264. // https://github.com/torvalds/linux/commit/c80fafbbb59ef9924962f83aac85531039395b18
  265. args = []string{
  266. "-p", proto,
  267. "--sport", strconv.Itoa(destPort),
  268. "-j", "CHECKSUM",
  269. "--checksum-fill",
  270. }
  271. if err := ProgramRule(Mangle, "POSTROUTING", action, args); err != nil {
  272. return err
  273. }
  274. }
  275. return nil
  276. }
  277. // Link adds reciprocal ACCEPT rule for two supplied IP addresses.
  278. // Traffic is allowed from ip1 to ip2 and vice-versa
  279. func (c *ChainInfo) Link(action Action, ip1, ip2 net.IP, port int, proto string, bridgeName string) error {
  280. // forward
  281. args := []string{
  282. "-i", bridgeName, "-o", bridgeName,
  283. "-p", proto,
  284. "-s", ip1.String(),
  285. "-d", ip2.String(),
  286. "--dport", strconv.Itoa(port),
  287. "-j", "ACCEPT",
  288. }
  289. if err := ProgramRule(Filter, c.Name, action, args); err != nil {
  290. return err
  291. }
  292. // reverse
  293. args[7], args[9] = args[9], args[7]
  294. args[10] = "--sport"
  295. return ProgramRule(Filter, c.Name, action, args)
  296. }
  297. // ProgramRule adds the rule specified by args only if the
  298. // rule is not already present in the chain. Reciprocally,
  299. // it removes the rule only if present.
  300. func ProgramRule(table Table, chain string, action Action, args []string) error {
  301. if Exists(table, chain, args...) != (action == Delete) {
  302. return nil
  303. }
  304. return RawCombinedOutput(append([]string{"-t", string(table), string(action), chain}, args...)...)
  305. }
  306. // Prerouting adds linking rule to nat/PREROUTING chain.
  307. func (c *ChainInfo) Prerouting(action Action, args ...string) error {
  308. a := []string{"-t", string(Nat), string(action), "PREROUTING"}
  309. if len(args) > 0 {
  310. a = append(a, args...)
  311. }
  312. if output, err := Raw(a...); err != nil {
  313. return err
  314. } else if len(output) != 0 {
  315. return ChainError{Chain: "PREROUTING", Output: output}
  316. }
  317. return nil
  318. }
  319. // Output adds linking rule to an OUTPUT chain.
  320. func (c *ChainInfo) Output(action Action, args ...string) error {
  321. a := []string{"-t", string(c.Table), string(action), "OUTPUT"}
  322. if len(args) > 0 {
  323. a = append(a, args...)
  324. }
  325. if output, err := Raw(a...); err != nil {
  326. return err
  327. } else if len(output) != 0 {
  328. return ChainError{Chain: "OUTPUT", Output: output}
  329. }
  330. return nil
  331. }
  332. // Remove removes the chain.
  333. func (c *ChainInfo) Remove() error {
  334. // Ignore errors - This could mean the chains were never set up
  335. if c.Table == Nat {
  336. c.Prerouting(Delete, "-m", "addrtype", "--dst-type", "LOCAL", "-j", c.Name)
  337. c.Output(Delete, "-m", "addrtype", "--dst-type", "LOCAL", "!", "--dst", "127.0.0.0/8", "-j", c.Name)
  338. c.Output(Delete, "-m", "addrtype", "--dst-type", "LOCAL", "-j", c.Name) // Created in versions <= 0.1.6
  339. c.Prerouting(Delete)
  340. c.Output(Delete)
  341. }
  342. Raw("-t", string(c.Table), "-F", c.Name)
  343. Raw("-t", string(c.Table), "-X", c.Name)
  344. return nil
  345. }
  346. // Exists checks if a rule exists
  347. func Exists(table Table, chain string, rule ...string) bool {
  348. return exists(false, table, chain, rule...)
  349. }
  350. // ExistsNative behaves as Exists with the difference it
  351. // will always invoke `iptables` binary.
  352. func ExistsNative(table Table, chain string, rule ...string) bool {
  353. return exists(true, table, chain, rule...)
  354. }
  355. func exists(native bool, table Table, chain string, rule ...string) bool {
  356. f := Raw
  357. if native {
  358. f = raw
  359. }
  360. if string(table) == "" {
  361. table = Filter
  362. }
  363. if err := initCheck(); err != nil {
  364. // The exists() signature does not allow us to return an error, but at least
  365. // we can skip the (likely invalid) exec invocation.
  366. return false
  367. }
  368. if supportsCOpt {
  369. // if exit status is 0 then return true, the rule exists
  370. _, err := f(append([]string{"-t", string(table), "-C", chain}, rule...)...)
  371. return err == nil
  372. }
  373. // parse "iptables -S" for the rule (it checks rules in a specific chain
  374. // in a specific table and it is very unreliable)
  375. return existsRaw(table, chain, rule...)
  376. }
  377. func existsRaw(table Table, chain string, rule ...string) bool {
  378. ruleString := fmt.Sprintf("%s %s\n", chain, strings.Join(rule, " "))
  379. existingRules, _ := exec.Command(iptablesPath, "-t", string(table), "-S", chain).Output()
  380. return strings.Contains(string(existingRules), ruleString)
  381. }
  382. // Maximum duration that an iptables operation can take
  383. // before flagging a warning.
  384. const opWarnTime = 2 * time.Second
  385. func filterOutput(start time.Time, output []byte, args ...string) []byte {
  386. // Flag operations that have taken a long time to complete
  387. opTime := time.Since(start)
  388. if opTime > opWarnTime {
  389. logrus.Warnf("xtables contention detected while running [%s]: Waited for %.2f seconds and received %q", strings.Join(args, " "), float64(opTime)/float64(time.Second), string(output))
  390. }
  391. // ignore iptables' message about xtables lock:
  392. // it is a warning, not an error.
  393. if strings.Contains(string(output), xLockWaitMsg) {
  394. output = []byte("")
  395. }
  396. // Put further filters here if desired
  397. return output
  398. }
  399. // Raw calls 'iptables' system command, passing supplied arguments.
  400. func Raw(args ...string) ([]byte, error) {
  401. if firewalldRunning {
  402. startTime := time.Now()
  403. output, err := Passthrough(Iptables, args...)
  404. if err == nil || !strings.Contains(err.Error(), "was not provided by any .service files") {
  405. return filterOutput(startTime, output, args...), err
  406. }
  407. }
  408. return raw(args...)
  409. }
  410. func raw(args ...string) ([]byte, error) {
  411. if err := initCheck(); err != nil {
  412. return nil, err
  413. }
  414. if supportsXlock {
  415. args = append([]string{"--wait"}, args...)
  416. } else {
  417. bestEffortLock.Lock()
  418. defer bestEffortLock.Unlock()
  419. }
  420. logrus.Debugf("%s, %v", iptablesPath, args)
  421. startTime := time.Now()
  422. output, err := exec.Command(iptablesPath, args...).CombinedOutput()
  423. if err != nil {
  424. return nil, fmt.Errorf("iptables failed: iptables %v: %s (%s)", strings.Join(args, " "), output, err)
  425. }
  426. return filterOutput(startTime, output, args...), err
  427. }
  428. // RawCombinedOutput internally calls the Raw function and returns a non nil
  429. // error if Raw returned a non nil error or a non empty output
  430. func RawCombinedOutput(args ...string) error {
  431. if output, err := Raw(args...); err != nil || len(output) != 0 {
  432. return fmt.Errorf("%s (%v)", string(output), err)
  433. }
  434. return nil
  435. }
  436. // RawCombinedOutputNative behave as RawCombinedOutput with the difference it
  437. // will always invoke `iptables` binary
  438. func RawCombinedOutputNative(args ...string) error {
  439. if output, err := raw(args...); err != nil || len(output) != 0 {
  440. return fmt.Errorf("%s (%v)", string(output), err)
  441. }
  442. return nil
  443. }
  444. // ExistChain checks if a chain exists
  445. func ExistChain(chain string, table Table) bool {
  446. if _, err := Raw("-t", string(table), "-nL", chain); err == nil {
  447. return true
  448. }
  449. return false
  450. }
  451. // GetVersion reads the iptables version numbers during initialization
  452. func GetVersion() (major, minor, micro int, err error) {
  453. out, err := exec.Command(iptablesPath, "--version").CombinedOutput()
  454. if err == nil {
  455. major, minor, micro = parseVersionNumbers(string(out))
  456. }
  457. return
  458. }
  459. // SetDefaultPolicy sets the passed default policy for the table/chain
  460. func SetDefaultPolicy(table Table, chain string, policy Policy) error {
  461. if err := RawCombinedOutput("-t", string(table), "-P", chain, string(policy)); err != nil {
  462. return fmt.Errorf("setting default policy to %v in %v chain failed: %v", policy, chain, err)
  463. }
  464. return nil
  465. }
  466. func parseVersionNumbers(input string) (major, minor, micro int) {
  467. re := regexp.MustCompile(`v\d*.\d*.\d*`)
  468. line := re.FindString(input)
  469. fmt.Sscanf(line, "v%d.%d.%d", &major, &minor, &micro)
  470. return
  471. }
  472. // iptables -C, --check option was added in v.1.4.11
  473. // http://ftp.netfilter.org/pub/iptables/changes-iptables-1.4.11.txt
  474. func supportsCOption(mj, mn, mc int) bool {
  475. return mj > 1 || (mj == 1 && (mn > 4 || (mn == 4 && mc >= 11)))
  476. }
  477. // AddReturnRule adds a return rule for the chain in the filter table
  478. func AddReturnRule(chain string) error {
  479. var (
  480. table = Filter
  481. args = []string{"-j", "RETURN"}
  482. )
  483. if Exists(table, chain, args...) {
  484. return nil
  485. }
  486. err := RawCombinedOutput(append([]string{"-A", chain}, args...)...)
  487. if err != nil {
  488. return fmt.Errorf("unable to add return rule in %s chain: %s", chain, err.Error())
  489. }
  490. return nil
  491. }
  492. // EnsureJumpRule ensures the jump rule is on top
  493. func EnsureJumpRule(fromChain, toChain string) error {
  494. var (
  495. table = Filter
  496. args = []string{"-j", toChain}
  497. )
  498. if Exists(table, fromChain, args...) {
  499. err := RawCombinedOutput(append([]string{"-D", fromChain}, args...)...)
  500. if err != nil {
  501. return fmt.Errorf("unable to remove jump to %s rule in %s chain: %s", toChain, fromChain, err.Error())
  502. }
  503. }
  504. err := RawCombinedOutput(append([]string{"-I", fromChain}, args...)...)
  505. if err != nil {
  506. return fmt.Errorf("unable to insert jump to %s rule in %s chain: %s", toChain, fromChain, err.Error())
  507. }
  508. return nil
  509. }