iptables.go 15 KB

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