iptables.go 12 KB

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