iptables.go 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251
  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. "log"
  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. }
  39. func New() (*IPTables, error) {
  40. path, err := exec.LookPath("iptables")
  41. if err != nil {
  42. return nil, err
  43. }
  44. return &IPTables{path}, nil
  45. }
  46. // Exists checks if given rulespec in specified table/chain exists
  47. func (ipt *IPTables) Exists(table, chain string, rulespec...string) (bool, error) {
  48. checkPresent, err := getIptablesHasCheckCommand()
  49. if err != nil {
  50. log.Printf("Error checking iptables version, assuming version at least 1.4.11: %v", err)
  51. checkPresent = true
  52. }
  53. if !checkPresent {
  54. cmd := append([]string{"-A", chain}, rulespec...)
  55. return existsForOldIpTables(table, strings.Join(cmd, " "))
  56. } else {
  57. cmd := append([]string{"-t", table, "-C", chain}, rulespec...)
  58. err := ipt.run(cmd...)
  59. switch {
  60. case err == nil:
  61. return true, nil
  62. case err.(*Error).ExitStatus() == 1:
  63. return false, nil
  64. default:
  65. return false, err
  66. }
  67. }
  68. }
  69. // Insert inserts rulespec to specified table/chain (in specified pos)
  70. func (ipt *IPTables) Insert(table, chain string, pos int, rulespec ...string) error {
  71. cmd := append([]string{"-t", table, "-I", chain, strconv.Itoa(pos)}, rulespec...)
  72. return ipt.run(cmd...)
  73. }
  74. // Append appends rulespec to specified table/chain
  75. func (ipt *IPTables) Append(table, chain string, rulespec ...string) error {
  76. cmd := append([]string{"-t", table, "-A", chain}, rulespec...)
  77. return ipt.run(cmd...)
  78. }
  79. // AppendUnique acts like Append except that it won't add a duplicate
  80. func (ipt *IPTables) AppendUnique(table, chain string, rulespec ...string) error {
  81. exists, err := ipt.Exists(table, chain, rulespec...)
  82. if err != nil {
  83. return err
  84. }
  85. if !exists {
  86. return ipt.Append(table, chain, rulespec...)
  87. }
  88. return nil
  89. }
  90. // Delete removes rulespec in specified table/chain
  91. func (ipt *IPTables) Delete(table, chain string, rulespec ...string) error {
  92. cmd := append([]string{"-t", table, "-D", chain}, rulespec...)
  93. return ipt.run(cmd...)
  94. }
  95. // List rules in specified table/chain
  96. func (ipt *IPTables) List(table, chain string) ([]string, error) {
  97. var stdout, stderr bytes.Buffer
  98. cmd := exec.Cmd{
  99. Path: ipt.path,
  100. Args: []string{ipt.path, "-t", table, "-S", chain},
  101. Stdout: &stdout,
  102. Stderr: &stderr,
  103. }
  104. if err := cmd.Run(); err != nil {
  105. return nil, &Error{*(err.(*exec.ExitError)), stderr.String()}
  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. // ClearChain flushed (deletes all rules) in the specifed table/chain.
  114. // If the chain does not exist, new one will be created
  115. func (ipt *IPTables) ClearChain(table, chain string) error {
  116. err := ipt.run("-t", table, "-N", chain)
  117. switch {
  118. case err == nil:
  119. return nil
  120. case err.(*Error).ExitStatus() == 1:
  121. // chain already exists. Flush (clear) it.
  122. return ipt.run("-t", table, "-F", chain)
  123. default:
  124. return err
  125. }
  126. }
  127. // DeleteChain deletes the chain in the specified table.
  128. // The chain must be empty
  129. func (ipt *IPTables) DeleteChain(table, chain string) error {
  130. return ipt.run("-t", table, "-X", chain)
  131. }
  132. func (ipt *IPTables) run(args... string) error {
  133. var stderr bytes.Buffer
  134. cmd := exec.Cmd{
  135. Path: ipt.path,
  136. Args: append([]string{ipt.path}, args...),
  137. Stderr: &stderr,
  138. }
  139. if err := cmd.Run(); err != nil {
  140. return &Error{*(err.(*exec.ExitError)), stderr.String()}
  141. }
  142. return nil
  143. }
  144. // Checks if iptables has the "-C" flag
  145. func getIptablesHasCheckCommand() (bool, error) {
  146. vstring, err := getIptablesVersionString()
  147. if err != nil {
  148. return false, err
  149. }
  150. v1, v2, v3, err := extractIptablesVersion(vstring)
  151. if err != nil {
  152. return false, err
  153. }
  154. return iptablesHasCheckCommand(v1, v2, v3), nil
  155. }
  156. // getIptablesVersion returns the first three components of the iptables version.
  157. // e.g. "iptables v1.3.66" would return (1, 3, 66, nil)
  158. func extractIptablesVersion(str string) (int, int, int, error) {
  159. versionMatcher := regexp.MustCompile("v([0-9]+)\\.([0-9]+)\\.([0-9]+)")
  160. result := versionMatcher.FindStringSubmatch(str)
  161. if result == nil {
  162. return 0, 0, 0, fmt.Errorf("no iptables version found in string: %s", str)
  163. }
  164. v1, err := strconv.Atoi(result[1])
  165. if err != nil {
  166. return 0, 0, 0, err
  167. }
  168. v2, err := strconv.Atoi(result[2])
  169. if err != nil {
  170. return 0, 0, 0, err
  171. }
  172. v3, err := strconv.Atoi(result[3])
  173. if err != nil {
  174. return 0, 0, 0, err
  175. }
  176. return v1, v2, v3, nil
  177. }
  178. // Runs "iptables --version" to get the version string
  179. func getIptablesVersionString() (string, error) {
  180. cmd := exec.Command("iptables", "--version")
  181. var out bytes.Buffer
  182. cmd.Stdout = &out
  183. err := cmd.Run()
  184. if err != nil {
  185. return "", err
  186. }
  187. return out.String(), nil
  188. }
  189. // Checks if an iptables version is after 1.4.11, when --check was added
  190. func iptablesHasCheckCommand(v1 int, v2 int, v3 int) bool {
  191. if v1 > 1 {
  192. return true
  193. }
  194. if v1 == 1 && v2 > 4 {
  195. return true
  196. }
  197. if v1 == 1 && v2 == 4 && v3 >= 11 {
  198. return true
  199. }
  200. return false
  201. }
  202. // Checks if a rule specification exists for a table
  203. func existsForOldIpTables(table string, ruleSpec string) (bool, error) {
  204. cmd := exec.Command("iptables", "-t", table, "-S")
  205. var out bytes.Buffer
  206. cmd.Stdout = &out
  207. err := cmd.Run()
  208. if err != nil {
  209. return false, err
  210. }
  211. rules := out.String()
  212. return strings.Contains(rules, ruleSpec), nil
  213. }