iptables.go 11 KB

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