iptables.go 7.3 KB

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