iptables.go 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365
  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. "os/exec"
  20. "regexp"
  21. "strconv"
  22. "strings"
  23. "syscall"
  24. )
  25. // Adds the output of stderr to exec.ExitError
  26. type Error struct {
  27. exec.ExitError
  28. cmd exec.Cmd
  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("running %v: exit status %v: %v", e.cmd.Args, 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. // List rules (with counters) in specified table/chain
  126. func (ipt *IPTables) ListWithCounters(table, chain string) ([]string, error) {
  127. args := []string{"-t", table, "-v", "-S", chain}
  128. return ipt.executeList(args)
  129. }
  130. // ListChains returns a slice containing the name of each chain in the specified table.
  131. func (ipt *IPTables) ListChains(table string) ([]string, error) {
  132. args := []string{"-t", table, "-S"}
  133. result, err := ipt.executeList(args)
  134. if err != nil {
  135. return nil, err
  136. }
  137. // Iterate over rules to find all default (-P) and user-specified (-N) chains.
  138. // Chains definition always come before rules.
  139. // Format is the following:
  140. // -P OUTPUT ACCEPT
  141. // -N Custom
  142. var chains []string
  143. for _, val := range result {
  144. if strings.HasPrefix(val, "-P") || strings.HasPrefix(val, "-N") {
  145. chains = append(chains, strings.Fields(val)[1])
  146. } else {
  147. break
  148. }
  149. }
  150. return chains, nil
  151. }
  152. func (ipt *IPTables) executeList(args []string) ([]string, error) {
  153. var stdout bytes.Buffer
  154. if err := ipt.runWithOutput(args, &stdout); err != nil {
  155. return nil, err
  156. }
  157. rules := strings.Split(stdout.String(), "\n")
  158. if len(rules) > 0 && rules[len(rules)-1] == "" {
  159. rules = rules[:len(rules)-1]
  160. }
  161. return rules, nil
  162. }
  163. // NewChain creates a new chain in the specified table.
  164. // If the chain already exists, it will result in an error.
  165. func (ipt *IPTables) NewChain(table, chain string) error {
  166. return ipt.run("-t", table, "-N", chain)
  167. }
  168. // ClearChain flushed (deletes all rules) in the specified table/chain.
  169. // If the chain does not exist, a new one will be created
  170. func (ipt *IPTables) ClearChain(table, chain string) error {
  171. err := ipt.NewChain(table, chain)
  172. eerr, eok := err.(*Error)
  173. switch {
  174. case err == nil:
  175. return nil
  176. case eok && eerr.ExitStatus() == 1:
  177. // chain already exists. Flush (clear) it.
  178. return ipt.run("-t", table, "-F", chain)
  179. default:
  180. return err
  181. }
  182. }
  183. // RenameChain renames the old chain to the new one.
  184. func (ipt *IPTables) RenameChain(table, oldChain, newChain string) error {
  185. return ipt.run("-t", table, "-E", oldChain, newChain)
  186. }
  187. // DeleteChain deletes the chain in the specified table.
  188. // The chain must be empty
  189. func (ipt *IPTables) DeleteChain(table, chain string) error {
  190. return ipt.run("-t", table, "-X", chain)
  191. }
  192. // run runs an iptables command with the given arguments, ignoring
  193. // any stdout output
  194. func (ipt *IPTables) run(args ...string) error {
  195. return ipt.runWithOutput(args, nil)
  196. }
  197. // runWithOutput runs an iptables command with the given arguments,
  198. // writing any stdout output to the given writer
  199. func (ipt *IPTables) runWithOutput(args []string, stdout io.Writer) error {
  200. args = append([]string{ipt.path}, args...)
  201. if ipt.hasWait {
  202. args = append(args, "--wait")
  203. } else {
  204. fmu, err := newXtablesFileLock()
  205. if err != nil {
  206. return err
  207. }
  208. ul, err := fmu.tryLock()
  209. if err != nil {
  210. return err
  211. }
  212. defer ul.Unlock()
  213. }
  214. var stderr bytes.Buffer
  215. cmd := exec.Cmd{
  216. Path: ipt.path,
  217. Args: args,
  218. Stdout: stdout,
  219. Stderr: &stderr,
  220. }
  221. if err := cmd.Run(); err != nil {
  222. return &Error{*(err.(*exec.ExitError)), cmd, stderr.String()}
  223. }
  224. return nil
  225. }
  226. // getIptablesCommand returns the correct command for the given protocol, either "iptables" or "ip6tables".
  227. func getIptablesCommand(proto Protocol) string {
  228. if proto == ProtocolIPv6 {
  229. return "ip6tables"
  230. } else {
  231. return "iptables"
  232. }
  233. }
  234. // Checks if iptables has the "-C" and "--wait" flag
  235. func getIptablesCommandSupport(path string) (bool, bool, error) {
  236. vstring, err := getIptablesVersionString(path)
  237. if err != nil {
  238. return false, false, err
  239. }
  240. v1, v2, v3, err := extractIptablesVersion(vstring)
  241. if err != nil {
  242. return false, false, err
  243. }
  244. return iptablesHasCheckCommand(v1, v2, v3), iptablesHasWaitCommand(v1, v2, v3), nil
  245. }
  246. // getIptablesVersion returns the first three components of the iptables version.
  247. // e.g. "iptables v1.3.66" would return (1, 3, 66, nil)
  248. func extractIptablesVersion(str string) (int, int, int, error) {
  249. versionMatcher := regexp.MustCompile("v([0-9]+)\\.([0-9]+)\\.([0-9]+)")
  250. result := versionMatcher.FindStringSubmatch(str)
  251. if result == nil {
  252. return 0, 0, 0, fmt.Errorf("no iptables version found in string: %s", str)
  253. }
  254. v1, err := strconv.Atoi(result[1])
  255. if err != nil {
  256. return 0, 0, 0, err
  257. }
  258. v2, err := strconv.Atoi(result[2])
  259. if err != nil {
  260. return 0, 0, 0, err
  261. }
  262. v3, err := strconv.Atoi(result[3])
  263. if err != nil {
  264. return 0, 0, 0, err
  265. }
  266. return v1, v2, v3, nil
  267. }
  268. // Runs "iptables --version" to get the version string
  269. func getIptablesVersionString(path string) (string, error) {
  270. cmd := exec.Command(path, "--version")
  271. var out bytes.Buffer
  272. cmd.Stdout = &out
  273. err := cmd.Run()
  274. if err != nil {
  275. return "", err
  276. }
  277. return out.String(), nil
  278. }
  279. // Checks if an iptables version is after 1.4.11, when --check was added
  280. func iptablesHasCheckCommand(v1 int, v2 int, v3 int) bool {
  281. if v1 > 1 {
  282. return true
  283. }
  284. if v1 == 1 && v2 > 4 {
  285. return true
  286. }
  287. if v1 == 1 && v2 == 4 && v3 >= 11 {
  288. return true
  289. }
  290. return false
  291. }
  292. // Checks if an iptables version is after 1.4.20, when --wait was added
  293. func iptablesHasWaitCommand(v1 int, v2 int, v3 int) bool {
  294. if v1 > 1 {
  295. return true
  296. }
  297. if v1 == 1 && v2 > 4 {
  298. return true
  299. }
  300. if v1 == 1 && v2 == 4 && v3 >= 20 {
  301. return true
  302. }
  303. return false
  304. }
  305. // Checks if a rule specification exists for a table
  306. func (ipt *IPTables) existsForOldIptables(table, chain string, rulespec []string) (bool, error) {
  307. rs := strings.Join(append([]string{"-A", chain}, rulespec...), " ")
  308. args := []string{"-t", table, "-S"}
  309. var stdout bytes.Buffer
  310. err := ipt.runWithOutput(args, &stdout)
  311. if err != nil {
  312. return false, err
  313. }
  314. return strings.Contains(stdout.String(), rs), nil
  315. }