iptables.go 12 KB

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