iptables.go 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296
  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. type IPTables struct {
  37. path string
  38. hasCheck bool
  39. hasWait bool
  40. }
  41. func New() (*IPTables, error) {
  42. path, err := exec.LookPath("iptables")
  43. if err != nil {
  44. return nil, err
  45. }
  46. checkPresent, waitPresent, err := getIptablesCommandSupport()
  47. if err != nil {
  48. return nil, fmt.Errorf("error checking iptables version: %v", err)
  49. }
  50. ipt := IPTables{
  51. path: path,
  52. hasCheck: checkPresent,
  53. hasWait: waitPresent,
  54. }
  55. return &ipt, nil
  56. }
  57. // Exists checks if given rulespec in specified table/chain exists
  58. func (ipt *IPTables) Exists(table, chain string, rulespec ...string) (bool, error) {
  59. if !ipt.hasCheck {
  60. return ipt.existsForOldIptables(table, chain, rulespec)
  61. }
  62. cmd := append([]string{"-t", table, "-C", chain}, rulespec...)
  63. err := ipt.run(cmd...)
  64. eerr, eok := err.(*Error)
  65. switch {
  66. case err == nil:
  67. return true, nil
  68. case eok && eerr.ExitStatus() == 1:
  69. return false, nil
  70. default:
  71. return false, err
  72. }
  73. }
  74. // Insert inserts rulespec to specified table/chain (in specified pos)
  75. func (ipt *IPTables) Insert(table, chain string, pos int, rulespec ...string) error {
  76. cmd := append([]string{"-t", table, "-I", chain, strconv.Itoa(pos)}, rulespec...)
  77. return ipt.run(cmd...)
  78. }
  79. // Append appends rulespec to specified table/chain
  80. func (ipt *IPTables) Append(table, chain string, rulespec ...string) error {
  81. cmd := append([]string{"-t", table, "-A", chain}, rulespec...)
  82. return ipt.run(cmd...)
  83. }
  84. // AppendUnique acts like Append except that it won't add a duplicate
  85. func (ipt *IPTables) AppendUnique(table, chain string, rulespec ...string) error {
  86. exists, err := ipt.Exists(table, chain, rulespec...)
  87. if err != nil {
  88. return err
  89. }
  90. if !exists {
  91. return ipt.Append(table, chain, rulespec...)
  92. }
  93. return nil
  94. }
  95. // Delete removes rulespec in specified table/chain
  96. func (ipt *IPTables) Delete(table, chain string, rulespec ...string) error {
  97. cmd := append([]string{"-t", table, "-D", chain}, rulespec...)
  98. return ipt.run(cmd...)
  99. }
  100. // List rules in specified table/chain
  101. func (ipt *IPTables) List(table, chain string) ([]string, error) {
  102. args := []string{"-t", table, "-S", chain}
  103. var stdout bytes.Buffer
  104. if err := ipt.runWithOutput(args, &stdout); err != nil {
  105. return nil, err
  106. }
  107. rules := strings.Split(stdout.String(), "\n")
  108. if len(rules) > 0 && rules[len(rules)-1] == "" {
  109. rules = rules[:len(rules)-1]
  110. }
  111. return rules, nil
  112. }
  113. func (ipt *IPTables) NewChain(table, chain string) error {
  114. return ipt.run("-t", table, "-N", chain)
  115. }
  116. // ClearChain flushed (deletes all rules) in the specified table/chain.
  117. // If the chain does not exist, a new one will be created
  118. func (ipt *IPTables) ClearChain(table, chain string) error {
  119. err := ipt.NewChain(table, chain)
  120. eerr, eok := err.(*Error)
  121. switch {
  122. case err == nil:
  123. return nil
  124. case eok && eerr.ExitStatus() == 1:
  125. // chain already exists. Flush (clear) it.
  126. return ipt.run("-t", table, "-F", chain)
  127. default:
  128. return err
  129. }
  130. }
  131. // RenameChain renames the old chain to the new one.
  132. func (ipt *IPTables) RenameChain(table, oldChain, newChain string) error {
  133. return ipt.run("-t", table, "-E", oldChain, newChain)
  134. }
  135. // DeleteChain deletes the chain in the specified table.
  136. // The chain must be empty
  137. func (ipt *IPTables) DeleteChain(table, chain string) error {
  138. return ipt.run("-t", table, "-X", chain)
  139. }
  140. // run runs an iptables command with the given arguments, ignoring
  141. // any stdout output
  142. func (ipt *IPTables) run(args ...string) error {
  143. return ipt.runWithOutput(args, nil)
  144. }
  145. // runWithOutput runs an iptables command with the given arguments,
  146. // writing any stdout output to the given writer
  147. func (ipt *IPTables) runWithOutput(args []string, stdout io.Writer) error {
  148. args = append([]string{ipt.path}, args...)
  149. if ipt.hasWait {
  150. args = append(args, "--wait")
  151. } else {
  152. fmu, err := newXtablesFileLock()
  153. if err != nil {
  154. return err
  155. }
  156. ul, err := fmu.tryLock()
  157. if err != nil {
  158. return err
  159. }
  160. defer ul.Unlock()
  161. }
  162. var stderr bytes.Buffer
  163. cmd := exec.Cmd{
  164. Path: ipt.path,
  165. Args: args,
  166. Stdout: stdout,
  167. Stderr: &stderr,
  168. }
  169. if err := cmd.Run(); err != nil {
  170. return &Error{*(err.(*exec.ExitError)), stderr.String()}
  171. }
  172. return nil
  173. }
  174. // Checks if iptables has the "-C" and "--wait" flag
  175. func getIptablesCommandSupport() (bool, bool, error) {
  176. vstring, err := getIptablesVersionString()
  177. if err != nil {
  178. return false, false, err
  179. }
  180. v1, v2, v3, err := extractIptablesVersion(vstring)
  181. if err != nil {
  182. return false, false, err
  183. }
  184. return iptablesHasCheckCommand(v1, v2, v3), iptablesHasWaitCommand(v1, v2, v3), nil
  185. }
  186. // getIptablesVersion returns the first three components of the iptables version.
  187. // e.g. "iptables v1.3.66" would return (1, 3, 66, nil)
  188. func extractIptablesVersion(str string) (int, int, int, error) {
  189. versionMatcher := regexp.MustCompile("v([0-9]+)\\.([0-9]+)\\.([0-9]+)")
  190. result := versionMatcher.FindStringSubmatch(str)
  191. if result == nil {
  192. return 0, 0, 0, fmt.Errorf("no iptables version found in string: %s", str)
  193. }
  194. v1, err := strconv.Atoi(result[1])
  195. if err != nil {
  196. return 0, 0, 0, err
  197. }
  198. v2, err := strconv.Atoi(result[2])
  199. if err != nil {
  200. return 0, 0, 0, err
  201. }
  202. v3, err := strconv.Atoi(result[3])
  203. if err != nil {
  204. return 0, 0, 0, err
  205. }
  206. return v1, v2, v3, nil
  207. }
  208. // Runs "iptables --version" to get the version string
  209. func getIptablesVersionString() (string, error) {
  210. cmd := exec.Command("iptables", "--version")
  211. var out bytes.Buffer
  212. cmd.Stdout = &out
  213. err := cmd.Run()
  214. if err != nil {
  215. return "", err
  216. }
  217. return out.String(), nil
  218. }
  219. // Checks if an iptables version is after 1.4.11, when --check was added
  220. func iptablesHasCheckCommand(v1 int, v2 int, v3 int) bool {
  221. if v1 > 1 {
  222. return true
  223. }
  224. if v1 == 1 && v2 > 4 {
  225. return true
  226. }
  227. if v1 == 1 && v2 == 4 && v3 >= 11 {
  228. return true
  229. }
  230. return false
  231. }
  232. // Checks if an iptables version is after 1.4.20, when --wait was added
  233. func iptablesHasWaitCommand(v1 int, v2 int, v3 int) bool {
  234. if v1 > 1 {
  235. return true
  236. }
  237. if v1 == 1 && v2 > 4 {
  238. return true
  239. }
  240. if v1 == 1 && v2 == 4 && v3 >= 20 {
  241. return true
  242. }
  243. return false
  244. }
  245. // Checks if a rule specification exists for a table
  246. func (ipt *IPTables) existsForOldIptables(table, chain string, rulespec []string) (bool, error) {
  247. rs := strings.Join(append([]string{"-A", chain}, rulespec...), " ")
  248. args := []string{"-t", table, "-S"}
  249. var stdout bytes.Buffer
  250. err := ipt.runWithOutput(args, &stdout)
  251. if err != nil {
  252. return false, err
  253. }
  254. return strings.Contains(stdout.String(), rs), nil
  255. }