iptables.go 16 KB

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