iptables.go 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253
  1. /*
  2. Copyright 2015 CoreOS Inc.
  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. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package iptables
  14. import (
  15. "bytes"
  16. "fmt"
  17. "log"
  18. "os/exec"
  19. "regexp"
  20. "strconv"
  21. "strings"
  22. "syscall"
  23. )
  24. // Adds the output of stderr to exec.ExitError
  25. type Error struct {
  26. exec.ExitError
  27. msg string
  28. }
  29. func (e *Error) ExitStatus() int {
  30. return e.Sys().(syscall.WaitStatus).ExitStatus()
  31. }
  32. func (e *Error) Error() string {
  33. return fmt.Sprintf("exit status %v: %v", e.ExitStatus(), e.msg)
  34. }
  35. type IPTables struct {
  36. path string
  37. }
  38. func New() (*IPTables, error) {
  39. path, err := exec.LookPath("iptables")
  40. if err != nil {
  41. return nil, err
  42. }
  43. return &IPTables{path}, nil
  44. }
  45. // Exists checks if given rulespec in specified table/chain exists
  46. func (ipt *IPTables) Exists(table, chain string, rulespec...string) (bool, error) {
  47. checkPresent, err := getIptablesHasCheckCommand()
  48. if err != nil {
  49. log.Printf("Error checking iptables version, assuming version at least 1.4.11: %v", err)
  50. checkPresent = true
  51. }
  52. if !checkPresent {
  53. cmd := append([]string{"-A", chain}, rulespec...)
  54. return existsForOldIpTables(table, strings.Join(cmd, " "))
  55. } else {
  56. cmd := append([]string{"-t", table, "-C", chain}, rulespec...)
  57. err := ipt.run(cmd...)
  58. switch {
  59. case err == nil:
  60. return true, nil
  61. case err.(*Error).ExitStatus() == 1:
  62. return false, nil
  63. default:
  64. return false, err
  65. }
  66. }
  67. }
  68. // Insert inserts rulespec to specified table/chain (in specified pos)
  69. func (ipt *IPTables) Insert(table, chain string, pos int, rulespec ...string) error {
  70. cmd := append([]string{"-t", table, "-I", chain, strconv.Itoa(pos)}, rulespec...)
  71. return ipt.run(cmd...)
  72. }
  73. // Append appends rulespec to specified table/chain
  74. func (ipt *IPTables) Append(table, chain string, rulespec ...string) error {
  75. cmd := append([]string{"-t", table, "-A", chain}, rulespec...)
  76. return ipt.run(cmd...)
  77. }
  78. // AppendUnique acts like Append except that it won't add a duplicate
  79. func (ipt *IPTables) AppendUnique(table, chain string, rulespec ...string) error {
  80. exists, err := ipt.Exists(table, chain, rulespec...)
  81. if err != nil {
  82. return err
  83. }
  84. if !exists {
  85. return ipt.Append(table, chain, rulespec...)
  86. }
  87. return nil
  88. }
  89. // Delete removes rulespec in specified table/chain
  90. func (ipt *IPTables) Delete(table, chain string, rulespec ...string) error {
  91. cmd := append([]string{"-t", table, "-D", chain}, rulespec...)
  92. return ipt.run(cmd...)
  93. }
  94. // List rules in specified table/chain
  95. func (ipt *IPTables) List(table, chain string) ([]string, error) {
  96. var stdout, stderr bytes.Buffer
  97. cmd := exec.Cmd{
  98. Path: ipt.path,
  99. Args: []string{ipt.path, "-t", table, "-S", chain},
  100. Stdout: &stdout,
  101. Stderr: &stderr,
  102. }
  103. if err := cmd.Run(); err != nil {
  104. return nil, &Error{*(err.(*exec.ExitError)), stderr.String()}
  105. }
  106. rules := strings.Split(stdout.String(), "\n")
  107. if len(rules) > 0 && rules[len(rules)-1] == "" {
  108. rules = rules[:len(rules)-1]
  109. }
  110. return rules, nil
  111. }
  112. // ClearChain flushed (deletes all rules) in the specifed table/chain.
  113. // If the chain does not exist, new one will be created
  114. func (ipt *IPTables) ClearChain(table, chain string) error {
  115. err := ipt.run("-t", table, "-N", chain)
  116. switch {
  117. case err == nil:
  118. return nil
  119. case err.(*Error).ExitStatus() == 1:
  120. // chain already exists. Flush (clear) it.
  121. return ipt.run("-t", table, "-F", chain)
  122. default:
  123. return err
  124. }
  125. }
  126. // DeleteChain deletes the chain in the specified table.
  127. // The chain must be empty
  128. func (ipt *IPTables) DeleteChain(table, chain string) error {
  129. return ipt.run("-t", table, "-X", chain)
  130. }
  131. func (ipt *IPTables) run(args... string) error {
  132. var stderr bytes.Buffer
  133. cmd := exec.Cmd{
  134. Path: ipt.path,
  135. Args: append([]string{ipt.path}, args...),
  136. Stderr: &stderr,
  137. }
  138. if err := cmd.Run(); err != nil {
  139. return &Error{*(err.(*exec.ExitError)), stderr.String()}
  140. }
  141. return nil
  142. }
  143. // Checks if iptables has the "-C" flag
  144. func getIptablesHasCheckCommand() (bool, error) {
  145. vstring, err := getIptablesVersionString()
  146. if err != nil {
  147. return false, err
  148. }
  149. v1, v2, v3, err := extractIptablesVersion(vstring)
  150. if err != nil {
  151. return false, err
  152. }
  153. return iptablesHasCheckCommand(v1, v2, v3), nil
  154. }
  155. // getIptablesVersion returns the first three components of the iptables version.
  156. // e.g. "iptables v1.3.66" would return (1, 3, 66, nil)
  157. func extractIptablesVersion(str string) (int, int, int, error) {
  158. versionMatcher := regexp.MustCompile("v([0-9]+)\\.([0-9]+)\\.([0-9]+)")
  159. result := versionMatcher.FindStringSubmatch(str)
  160. if result == nil {
  161. return 0, 0, 0, fmt.Errorf("no iptables version found in string: %s", str)
  162. }
  163. v1, err := strconv.Atoi(result[1])
  164. if err != nil {
  165. return 0, 0, 0, err
  166. }
  167. v2, err := strconv.Atoi(result[2])
  168. if err != nil {
  169. return 0, 0, 0, err
  170. }
  171. v3, err := strconv.Atoi(result[3])
  172. if err != nil {
  173. return 0, 0, 0, err
  174. }
  175. return v1, v2, v3, nil
  176. }
  177. // Runs "iptables --version" to get the version string
  178. func getIptablesVersionString() (string, error) {
  179. cmd := exec.Command("iptables", "--version")
  180. var out bytes.Buffer
  181. cmd.Stdout = &out
  182. err := cmd.Run()
  183. if err != nil {
  184. return "", err
  185. }
  186. return out.String(), nil
  187. }
  188. // Checks if an iptables version is after 1.4.11, when --check was added
  189. func iptablesHasCheckCommand(v1 int, v2 int, v3 int) bool {
  190. if v1 > 1 {
  191. return true
  192. }
  193. if v1 == 1 && v2 > 4 {
  194. return true
  195. }
  196. if v1 == 1 && v2 == 4 && v3 >= 11 {
  197. return true
  198. }
  199. return false
  200. }
  201. // Checks if a rule specification exists for a table
  202. func existsForOldIpTables(table string, ruleSpec string) (bool, error) {
  203. cmd := exec.Command("iptables", "-t", table, "-S")
  204. var out bytes.Buffer
  205. cmd.Stdout = &out
  206. err := cmd.Run()
  207. if err != nil {
  208. return false, err
  209. }
  210. rules := out.String()
  211. return strings.Contains(rules, ruleSpec), nil
  212. }