iptables.go 12 KB

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