iptables.go 16 KB

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