iptables.go 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295
  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. "log"
  20. "os/exec"
  21. "regexp"
  22. "strconv"
  23. "strings"
  24. "syscall"
  25. )
  26. // Adds the output of stderr to exec.ExitError
  27. type Error struct {
  28. exec.ExitError
  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("exit status %v: %v", e.ExitStatus(), e.msg)
  36. }
  37. type IPTables struct {
  38. path string
  39. hasCheck bool
  40. hasWait bool
  41. fmu *fileLock
  42. }
  43. func New() (*IPTables, error) {
  44. path, err := exec.LookPath("iptables")
  45. if err != nil {
  46. return nil, err
  47. }
  48. checkPresent, waitPresent, err := getIptablesCommandSupport()
  49. if err != nil {
  50. log.Printf("Error checking iptables version, assuming version at least 1.4.20: %v", err)
  51. checkPresent = true
  52. waitPresent = true
  53. }
  54. ipt := IPTables{
  55. path: path,
  56. hasCheck: checkPresent,
  57. hasWait: waitPresent,
  58. }
  59. if !waitPresent {
  60. ipt.fmu, err = newXtablesFileLock()
  61. if err != nil {
  62. return nil, err
  63. }
  64. }
  65. return &ipt, nil
  66. }
  67. // Exists checks if given rulespec in specified table/chain exists
  68. func (ipt *IPTables) Exists(table, chain string, rulespec ...string) (bool, error) {
  69. if !ipt.hasCheck {
  70. return ipt.existsForOldIptables(table, chain, rulespec)
  71. }
  72. cmd := append([]string{"-t", table, "-C", chain}, rulespec...)
  73. err := ipt.run(cmd...)
  74. switch {
  75. case err == nil:
  76. return true, nil
  77. case err.(*Error).ExitStatus() == 1:
  78. return false, nil
  79. default:
  80. return false, err
  81. }
  82. }
  83. // Insert inserts rulespec to specified table/chain (in specified pos)
  84. func (ipt *IPTables) Insert(table, chain string, pos int, rulespec ...string) error {
  85. cmd := append([]string{"-t", table, "-I", chain, strconv.Itoa(pos)}, rulespec...)
  86. return ipt.run(cmd...)
  87. }
  88. // Append appends rulespec to specified table/chain
  89. func (ipt *IPTables) Append(table, chain string, rulespec ...string) error {
  90. cmd := append([]string{"-t", table, "-A", chain}, rulespec...)
  91. return ipt.run(cmd...)
  92. }
  93. // AppendUnique acts like Append except that it won't add a duplicate
  94. func (ipt *IPTables) AppendUnique(table, chain string, rulespec ...string) error {
  95. exists, err := ipt.Exists(table, chain, rulespec...)
  96. if err != nil {
  97. return err
  98. }
  99. if !exists {
  100. return ipt.Append(table, chain, rulespec...)
  101. }
  102. return nil
  103. }
  104. // Delete removes rulespec in specified table/chain
  105. func (ipt *IPTables) Delete(table, chain string, rulespec ...string) error {
  106. cmd := append([]string{"-t", table, "-D", chain}, rulespec...)
  107. return ipt.run(cmd...)
  108. }
  109. // List rules in specified table/chain
  110. func (ipt *IPTables) List(table, chain string) ([]string, error) {
  111. args := []string{"-t", table, "-S", chain}
  112. var stdout bytes.Buffer
  113. if err := ipt.runWithOutput(args, &stdout); err != nil {
  114. return nil, err
  115. }
  116. rules := strings.Split(stdout.String(), "\n")
  117. if len(rules) > 0 && rules[len(rules)-1] == "" {
  118. rules = rules[:len(rules)-1]
  119. }
  120. return rules, nil
  121. }
  122. func (ipt *IPTables) NewChain(table, chain string) error {
  123. return ipt.run("-t", table, "-N", chain)
  124. }
  125. // ClearChain flushed (deletes all rules) in the specified table/chain.
  126. // If the chain does not exist, a new one will be created
  127. func (ipt *IPTables) ClearChain(table, chain string) error {
  128. err := ipt.NewChain(table, chain)
  129. switch {
  130. case err == nil:
  131. return nil
  132. case err.(*Error).ExitStatus() == 1:
  133. // chain already exists. Flush (clear) it.
  134. return ipt.run("-t", table, "-F", chain)
  135. default:
  136. return err
  137. }
  138. }
  139. // DeleteChain deletes the chain in the specified table.
  140. // The chain must be empty
  141. func (ipt *IPTables) DeleteChain(table, chain string) error {
  142. return ipt.run("-t", table, "-X", chain)
  143. }
  144. // run runs an iptables command with the given arguments, ignoring
  145. // any stdout output
  146. func (ipt *IPTables) run(args ...string) error {
  147. return ipt.runWithOutput(args, nil)
  148. }
  149. // runWithOutput runs an iptables command with the given arguments,
  150. // writing any stdout output to the given writer
  151. func (ipt *IPTables) runWithOutput(args []string, stdout io.Writer) error {
  152. args = append([]string{ipt.path}, args...)
  153. if ipt.hasWait {
  154. args = append(args, "--wait")
  155. } else {
  156. ul, err := ipt.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. }