iptables.go 16 KB

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