iptables.go 9.1 KB

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