iptables.go 16 KB

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