iptables.go 7.4 KB

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