iptables.go 7.4 KB

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