iptables.go 9.3 KB

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