iptables.go 16 KB

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