iptables.go 16 KB

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