iptables.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530
  1. // Copyright 2015 CoreOS, Inc.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package iptables
  15. import (
  16. "bytes"
  17. "fmt"
  18. "io"
  19. "net"
  20. "os/exec"
  21. "regexp"
  22. "strconv"
  23. "strings"
  24. "syscall"
  25. )
  26. // Adds the output of stderr to exec.ExitError
  27. type Error struct {
  28. exec.ExitError
  29. cmd exec.Cmd
  30. msg string
  31. exitStatus *int //for overriding
  32. }
  33. func (e *Error) ExitStatus() int {
  34. if e.exitStatus != nil {
  35. return *e.exitStatus
  36. }
  37. return e.Sys().(syscall.WaitStatus).ExitStatus()
  38. }
  39. func (e *Error) Error() string {
  40. return fmt.Sprintf("running %v: exit status %v: %v", e.cmd.Args, e.ExitStatus(), e.msg)
  41. }
  42. // IsNotExist returns true if the error is due to the chain or rule not existing
  43. func (e *Error) IsNotExist() bool {
  44. return e.ExitStatus() == 1 &&
  45. (e.msg == "iptables: Bad rule (does a matching rule exist in that chain?).\n" ||
  46. e.msg == "iptables: No chain/target/match by that name.\n")
  47. }
  48. // Protocol to differentiate between IPv4 and IPv6
  49. type Protocol byte
  50. const (
  51. ProtocolIPv4 Protocol = iota
  52. ProtocolIPv6
  53. )
  54. type IPTables struct {
  55. path string
  56. proto Protocol
  57. hasCheck bool
  58. hasWait bool
  59. hasRandomFully bool
  60. v1 int
  61. v2 int
  62. v3 int
  63. mode string // the underlying iptables operating mode, e.g. nf_tables
  64. }
  65. // New creates a new IPTables.
  66. // For backwards compatibility, this always uses IPv4, i.e. "iptables".
  67. func New() (*IPTables, error) {
  68. return NewWithProtocol(ProtocolIPv4)
  69. }
  70. // New creates a new IPTables for the given proto.
  71. // The proto will determine which command is used, either "iptables" or "ip6tables".
  72. func NewWithProtocol(proto Protocol) (*IPTables, error) {
  73. path, err := exec.LookPath(getIptablesCommand(proto))
  74. if err != nil {
  75. return nil, err
  76. }
  77. vstring, err := getIptablesVersionString(path)
  78. v1, v2, v3, mode, err := extractIptablesVersion(vstring)
  79. checkPresent, waitPresent, randomFullyPresent := getIptablesCommandSupport(v1, v2, v3)
  80. ipt := IPTables{
  81. path: path,
  82. proto: proto,
  83. hasCheck: checkPresent,
  84. hasWait: waitPresent,
  85. hasRandomFully: randomFullyPresent,
  86. v1: v1,
  87. v2: v2,
  88. v3: v3,
  89. mode: mode,
  90. }
  91. return &ipt, nil
  92. }
  93. // Proto returns the protocol used by this IPTables.
  94. func (ipt *IPTables) Proto() Protocol {
  95. return ipt.proto
  96. }
  97. // Exists checks if given rulespec in specified table/chain exists
  98. func (ipt *IPTables) Exists(table, chain string, rulespec ...string) (bool, error) {
  99. if !ipt.hasCheck {
  100. return ipt.existsForOldIptables(table, chain, rulespec)
  101. }
  102. cmd := append([]string{"-t", table, "-C", chain}, rulespec...)
  103. err := ipt.run(cmd...)
  104. eerr, eok := err.(*Error)
  105. switch {
  106. case err == nil:
  107. return true, nil
  108. case eok && eerr.ExitStatus() == 1:
  109. return false, nil
  110. default:
  111. return false, err
  112. }
  113. }
  114. // Insert inserts rulespec to specified table/chain (in specified pos)
  115. func (ipt *IPTables) Insert(table, chain string, pos int, rulespec ...string) error {
  116. cmd := append([]string{"-t", table, "-I", chain, strconv.Itoa(pos)}, rulespec...)
  117. return ipt.run(cmd...)
  118. }
  119. // Append appends rulespec to specified table/chain
  120. func (ipt *IPTables) Append(table, chain string, rulespec ...string) error {
  121. cmd := append([]string{"-t", table, "-A", chain}, rulespec...)
  122. return ipt.run(cmd...)
  123. }
  124. // AppendUnique acts like Append except that it won't add a duplicate
  125. func (ipt *IPTables) AppendUnique(table, chain string, rulespec ...string) error {
  126. exists, err := ipt.Exists(table, chain, rulespec...)
  127. if err != nil {
  128. return err
  129. }
  130. if !exists {
  131. return ipt.Append(table, chain, rulespec...)
  132. }
  133. return nil
  134. }
  135. // Delete removes rulespec in specified table/chain
  136. func (ipt *IPTables) Delete(table, chain string, rulespec ...string) error {
  137. cmd := append([]string{"-t", table, "-D", chain}, rulespec...)
  138. return ipt.run(cmd...)
  139. }
  140. // List rules in specified table/chain
  141. func (ipt *IPTables) List(table, chain string) ([]string, error) {
  142. args := []string{"-t", table, "-S", chain}
  143. return ipt.executeList(args)
  144. }
  145. // List rules (with counters) in specified table/chain
  146. func (ipt *IPTables) ListWithCounters(table, chain string) ([]string, error) {
  147. args := []string{"-t", table, "-v", "-S", chain}
  148. return ipt.executeList(args)
  149. }
  150. // ListChains returns a slice containing the name of each chain in the specified table.
  151. func (ipt *IPTables) ListChains(table string) ([]string, error) {
  152. args := []string{"-t", table, "-S"}
  153. result, err := ipt.executeList(args)
  154. if err != nil {
  155. return nil, err
  156. }
  157. // Iterate over rules to find all default (-P) and user-specified (-N) chains.
  158. // Chains definition always come before rules.
  159. // Format is the following:
  160. // -P OUTPUT ACCEPT
  161. // -N Custom
  162. var chains []string
  163. for _, val := range result {
  164. if strings.HasPrefix(val, "-P") || strings.HasPrefix(val, "-N") {
  165. chains = append(chains, strings.Fields(val)[1])
  166. } else {
  167. break
  168. }
  169. }
  170. return chains, nil
  171. }
  172. // Stats lists rules including the byte and packet counts
  173. func (ipt *IPTables) Stats(table, chain string) ([][]string, error) {
  174. args := []string{"-t", table, "-L", chain, "-n", "-v", "-x"}
  175. lines, err := ipt.executeList(args)
  176. if err != nil {
  177. return nil, err
  178. }
  179. appendSubnet := func(addr string) string {
  180. if strings.IndexByte(addr, byte('/')) < 0 {
  181. if strings.IndexByte(addr, '.') < 0 {
  182. return addr + "/128"
  183. }
  184. return addr + "/32"
  185. }
  186. return addr
  187. }
  188. ipv6 := ipt.proto == ProtocolIPv6
  189. rows := [][]string{}
  190. for i, line := range lines {
  191. // Skip over chain name and field header
  192. if i < 2 {
  193. continue
  194. }
  195. // Fields:
  196. // 0=pkts 1=bytes 2=target 3=prot 4=opt 5=in 6=out 7=source 8=destination 9=options
  197. line = strings.TrimSpace(line)
  198. fields := strings.Fields(line)
  199. // The ip6tables verbose output cannot be naively split due to the default "opt"
  200. // field containing 2 single spaces.
  201. if ipv6 {
  202. // Check if field 6 is "opt" or "source" address
  203. dest := fields[6]
  204. ip, _, _ := net.ParseCIDR(dest)
  205. if ip == nil {
  206. ip = net.ParseIP(dest)
  207. }
  208. // If we detected a CIDR or IP, the "opt" field is empty.. insert it.
  209. if ip != nil {
  210. f := []string{}
  211. f = append(f, fields[:4]...)
  212. f = append(f, " ") // Empty "opt" field for ip6tables
  213. f = append(f, fields[4:]...)
  214. fields = f
  215. }
  216. }
  217. // Adjust "source" and "destination" to include netmask, to match regular
  218. // List output
  219. fields[7] = appendSubnet(fields[7])
  220. fields[8] = appendSubnet(fields[8])
  221. // Combine "options" fields 9... into a single space-delimited field.
  222. options := fields[9:]
  223. fields = fields[:9]
  224. fields = append(fields, strings.Join(options, " "))
  225. rows = append(rows, fields)
  226. }
  227. return rows, nil
  228. }
  229. func (ipt *IPTables) executeList(args []string) ([]string, error) {
  230. var stdout bytes.Buffer
  231. if err := ipt.runWithOutput(args, &stdout); err != nil {
  232. return nil, err
  233. }
  234. rules := strings.Split(stdout.String(), "\n")
  235. // strip trailing newline
  236. if len(rules) > 0 && rules[len(rules)-1] == "" {
  237. rules = rules[:len(rules)-1]
  238. }
  239. // nftables mode doesn't return an error code when listing a non-existent
  240. // chain. Patch that up.
  241. if len(rules) == 0 && ipt.mode == "nf_tables" {
  242. v := 1
  243. return nil, &Error{
  244. cmd: exec.Cmd{Args: args},
  245. msg: "iptables: No chain/target/match by that name.\n",
  246. exitStatus: &v,
  247. }
  248. }
  249. for i, rule := range rules {
  250. rules[i] = filterRuleOutput(rule)
  251. }
  252. return rules, nil
  253. }
  254. // NewChain creates a new chain in the specified table.
  255. // If the chain already exists, it will result in an error.
  256. func (ipt *IPTables) NewChain(table, chain string) error {
  257. return ipt.run("-t", table, "-N", chain)
  258. }
  259. // ClearChain flushed (deletes all rules) in the specified table/chain.
  260. // If the chain does not exist, a new one will be created
  261. func (ipt *IPTables) ClearChain(table, chain string) error {
  262. err := ipt.NewChain(table, chain)
  263. // the exit code for "this table already exists" is different for
  264. // different iptables modes
  265. existsErr := 1
  266. if ipt.mode == "nf_tables" {
  267. existsErr = 4
  268. }
  269. eerr, eok := err.(*Error)
  270. switch {
  271. case err == nil:
  272. return nil
  273. case eok && eerr.ExitStatus() == existsErr:
  274. // chain already exists. Flush (clear) it.
  275. return ipt.run("-t", table, "-F", chain)
  276. default:
  277. return err
  278. }
  279. }
  280. // RenameChain renames the old chain to the new one.
  281. func (ipt *IPTables) RenameChain(table, oldChain, newChain string) error {
  282. return ipt.run("-t", table, "-E", oldChain, newChain)
  283. }
  284. // DeleteChain deletes the chain in the specified table.
  285. // The chain must be empty
  286. func (ipt *IPTables) DeleteChain(table, chain string) error {
  287. return ipt.run("-t", table, "-X", chain)
  288. }
  289. // ChangePolicy changes policy on chain to target
  290. func (ipt *IPTables) ChangePolicy(table, chain, target string) error {
  291. return ipt.run("-t", table, "-P", chain, target)
  292. }
  293. // Check if the underlying iptables command supports the --random-fully flag
  294. func (ipt *IPTables) HasRandomFully() bool {
  295. return ipt.hasRandomFully
  296. }
  297. // Return version components of the underlying iptables command
  298. func (ipt *IPTables) GetIptablesVersion() (int, int, int) {
  299. return ipt.v1, ipt.v2, ipt.v3
  300. }
  301. // run runs an iptables command with the given arguments, ignoring
  302. // any stdout output
  303. func (ipt *IPTables) run(args ...string) error {
  304. return ipt.runWithOutput(args, nil)
  305. }
  306. // runWithOutput runs an iptables command with the given arguments,
  307. // writing any stdout output to the given writer
  308. func (ipt *IPTables) runWithOutput(args []string, stdout io.Writer) error {
  309. args = append([]string{ipt.path}, args...)
  310. if ipt.hasWait {
  311. args = append(args, "--wait")
  312. } else {
  313. fmu, err := newXtablesFileLock()
  314. if err != nil {
  315. return err
  316. }
  317. ul, err := fmu.tryLock()
  318. if err != nil {
  319. return err
  320. }
  321. defer ul.Unlock()
  322. }
  323. var stderr bytes.Buffer
  324. cmd := exec.Cmd{
  325. Path: ipt.path,
  326. Args: args,
  327. Stdout: stdout,
  328. Stderr: &stderr,
  329. }
  330. if err := cmd.Run(); err != nil {
  331. switch e := err.(type) {
  332. case *exec.ExitError:
  333. return &Error{*e, cmd, stderr.String(), nil}
  334. default:
  335. return err
  336. }
  337. }
  338. return nil
  339. }
  340. // getIptablesCommand returns the correct command for the given protocol, either "iptables" or "ip6tables".
  341. func getIptablesCommand(proto Protocol) string {
  342. if proto == ProtocolIPv6 {
  343. return "ip6tables"
  344. } else {
  345. return "iptables"
  346. }
  347. }
  348. // Checks if iptables has the "-C" and "--wait" flag
  349. func getIptablesCommandSupport(v1 int, v2 int, v3 int) (bool, bool, bool) {
  350. return iptablesHasCheckCommand(v1, v2, v3), iptablesHasWaitCommand(v1, v2, v3), iptablesHasRandomFully(v1, v2, v3)
  351. }
  352. // getIptablesVersion returns the first three components of the iptables version
  353. // and the operating mode (e.g. nf_tables or legacy)
  354. // e.g. "iptables v1.3.66" would return (1, 3, 66, legacy, nil)
  355. func extractIptablesVersion(str string) (int, int, int, string, error) {
  356. versionMatcher := regexp.MustCompile(`v([0-9]+)\.([0-9]+)\.([0-9]+)(?:\s+\((\w+))?`)
  357. result := versionMatcher.FindStringSubmatch(str)
  358. if result == nil {
  359. return 0, 0, 0, "", fmt.Errorf("no iptables version found in string: %s", str)
  360. }
  361. v1, err := strconv.Atoi(result[1])
  362. if err != nil {
  363. return 0, 0, 0, "", err
  364. }
  365. v2, err := strconv.Atoi(result[2])
  366. if err != nil {
  367. return 0, 0, 0, "", err
  368. }
  369. v3, err := strconv.Atoi(result[3])
  370. if err != nil {
  371. return 0, 0, 0, "", err
  372. }
  373. mode := "legacy"
  374. if result[4] != "" {
  375. mode = result[4]
  376. }
  377. return v1, v2, v3, mode, nil
  378. }
  379. // Runs "iptables --version" to get the version string
  380. func getIptablesVersionString(path string) (string, error) {
  381. cmd := exec.Command(path, "--version")
  382. var out bytes.Buffer
  383. cmd.Stdout = &out
  384. err := cmd.Run()
  385. if err != nil {
  386. return "", err
  387. }
  388. return out.String(), nil
  389. }
  390. // Checks if an iptables version is after 1.4.11, when --check was added
  391. func iptablesHasCheckCommand(v1 int, v2 int, v3 int) bool {
  392. if v1 > 1 {
  393. return true
  394. }
  395. if v1 == 1 && v2 > 4 {
  396. return true
  397. }
  398. if v1 == 1 && v2 == 4 && v3 >= 11 {
  399. return true
  400. }
  401. return false
  402. }
  403. // Checks if an iptables version is after 1.4.20, when --wait was added
  404. func iptablesHasWaitCommand(v1 int, v2 int, v3 int) bool {
  405. if v1 > 1 {
  406. return true
  407. }
  408. if v1 == 1 && v2 > 4 {
  409. return true
  410. }
  411. if v1 == 1 && v2 == 4 && v3 >= 20 {
  412. return true
  413. }
  414. return false
  415. }
  416. // Checks if an iptables version is after 1.6.2, when --random-fully was added
  417. func iptablesHasRandomFully(v1 int, v2 int, v3 int) bool {
  418. if v1 > 1 {
  419. return true
  420. }
  421. if v1 == 1 && v2 > 6 {
  422. return true
  423. }
  424. if v1 == 1 && v2 == 6 && v3 >= 2 {
  425. return true
  426. }
  427. return false
  428. }
  429. // Checks if a rule specification exists for a table
  430. func (ipt *IPTables) existsForOldIptables(table, chain string, rulespec []string) (bool, error) {
  431. rs := strings.Join(append([]string{"-A", chain}, rulespec...), " ")
  432. args := []string{"-t", table, "-S"}
  433. var stdout bytes.Buffer
  434. err := ipt.runWithOutput(args, &stdout)
  435. if err != nil {
  436. return false, err
  437. }
  438. return strings.Contains(stdout.String(), rs), nil
  439. }
  440. // counterRegex is the regex used to detect nftables counter format
  441. var counterRegex = regexp.MustCompile(`^\[([0-9]+):([0-9]+)\] `)
  442. // filterRuleOutput works around some inconsistencies in output.
  443. // For example, when iptables is in legacy vs. nftables mode, it produces
  444. // different results.
  445. func filterRuleOutput(rule string) string {
  446. out := rule
  447. // work around an output difference in nftables mode where counters
  448. // are output in iptables-save format, rather than iptables -S format
  449. // The string begins with "[0:0]"
  450. //
  451. // Fixes #49
  452. if groups := counterRegex.FindStringSubmatch(out); groups != nil {
  453. // drop the brackets
  454. out = out[len(groups[0]):]
  455. out = fmt.Sprintf("%s -c %s %s", out, groups[1], groups[2])
  456. }
  457. return out
  458. }