iptables.go 11 KB

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