iptables.go 16 KB

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