iptables.go 14 KB

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