iptables.go 16 KB

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