iptables.go 18 KB

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