iptables.go 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256
  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, "--wait", "-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. func (ipt *IPTables) NewChain(table, chain string) error {
  114. return ipt.run("-t", table, "-N", chain)
  115. }
  116. // ClearChain flushed (deletes all rules) in the specifed table/chain.
  117. // If the chain does not exist, new one will be created
  118. func (ipt *IPTables) ClearChain(table, chain string) error {
  119. err := ipt.NewChain(table, chain)
  120. switch {
  121. case err == nil:
  122. return nil
  123. case err.(*Error).ExitStatus() == 1:
  124. // chain already exists. Flush (clear) it.
  125. return ipt.run("-t", table, "-F", chain)
  126. default:
  127. return err
  128. }
  129. }
  130. // DeleteChain deletes the chain in the specified table.
  131. // The chain must be empty
  132. func (ipt *IPTables) DeleteChain(table, chain string) error {
  133. return ipt.run("-t", table, "-X", chain)
  134. }
  135. func (ipt *IPTables) run(args ...string) error {
  136. var stderr bytes.Buffer
  137. args = append([]string{"--wait"}, args...)
  138. cmd := exec.Cmd{
  139. Path: ipt.path,
  140. Args: append([]string{ipt.path}, args...),
  141. Stderr: &stderr,
  142. }
  143. if err := cmd.Run(); err != nil {
  144. return &Error{*(err.(*exec.ExitError)), stderr.String()}
  145. }
  146. return nil
  147. }
  148. // Checks if iptables has the "-C" flag
  149. func getIptablesHasCheckCommand() (bool, error) {
  150. vstring, err := getIptablesVersionString()
  151. if err != nil {
  152. return false, err
  153. }
  154. v1, v2, v3, err := extractIptablesVersion(vstring)
  155. if err != nil {
  156. return false, err
  157. }
  158. return iptablesHasCheckCommand(v1, v2, v3), nil
  159. }
  160. // getIptablesVersion returns the first three components of the iptables version.
  161. // e.g. "iptables v1.3.66" would return (1, 3, 66, nil)
  162. func extractIptablesVersion(str string) (int, int, int, error) {
  163. versionMatcher := regexp.MustCompile("v([0-9]+)\\.([0-9]+)\\.([0-9]+)")
  164. result := versionMatcher.FindStringSubmatch(str)
  165. if result == nil {
  166. return 0, 0, 0, fmt.Errorf("no iptables version found in string: %s", str)
  167. }
  168. v1, err := strconv.Atoi(result[1])
  169. if err != nil {
  170. return 0, 0, 0, err
  171. }
  172. v2, err := strconv.Atoi(result[2])
  173. if err != nil {
  174. return 0, 0, 0, err
  175. }
  176. v3, err := strconv.Atoi(result[3])
  177. if err != nil {
  178. return 0, 0, 0, err
  179. }
  180. return v1, v2, v3, nil
  181. }
  182. // Runs "iptables --version" to get the version string
  183. func getIptablesVersionString() (string, error) {
  184. cmd := exec.Command("iptables", "--version")
  185. var out bytes.Buffer
  186. cmd.Stdout = &out
  187. err := cmd.Run()
  188. if err != nil {
  189. return "", err
  190. }
  191. return out.String(), nil
  192. }
  193. // Checks if an iptables version is after 1.4.11, when --check was added
  194. func iptablesHasCheckCommand(v1 int, v2 int, v3 int) bool {
  195. if v1 > 1 {
  196. return true
  197. }
  198. if v1 == 1 && v2 > 4 {
  199. return true
  200. }
  201. if v1 == 1 && v2 == 4 && v3 >= 11 {
  202. return true
  203. }
  204. return false
  205. }
  206. // Checks if a rule specification exists for a table
  207. func existsForOldIpTables(table string, ruleSpec string) (bool, error) {
  208. cmd := exec.Command("iptables", "-t", table, "-S")
  209. var out bytes.Buffer
  210. cmd.Stdout = &out
  211. err := cmd.Run()
  212. if err != nil {
  213. return false, err
  214. }
  215. rules := out.String()
  216. return strings.Contains(rules, ruleSpec), nil
  217. }