iptables.go 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303
  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. hasCheck bool
  39. hasWait bool
  40. fmu *fileLock
  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. if !waitPresent {
  59. ipt.fmu, err = newXtablesFileLock()
  60. if err != nil {
  61. return nil, err
  62. }
  63. }
  64. return &ipt, nil
  65. }
  66. // Exists checks if given rulespec in specified table/chain exists
  67. func (ipt *IPTables) Exists(table, chain string, rulespec ...string) (bool, error) {
  68. if !ipt.hasCheck {
  69. cmd := append([]string{"-A", chain}, rulespec...)
  70. return existsForOldIpTables(table, strings.Join(cmd, " "))
  71. }
  72. cmd := append([]string{"-t", table, "-C", chain}, rulespec...)
  73. err := ipt.run(cmd...)
  74. switch {
  75. case err == nil:
  76. return true, nil
  77. case err.(*Error).ExitStatus() == 1:
  78. return false, nil
  79. default:
  80. return false, err
  81. }
  82. }
  83. // Insert inserts rulespec to specified table/chain (in specified pos)
  84. func (ipt *IPTables) Insert(table, chain string, pos int, rulespec ...string) error {
  85. cmd := append([]string{"-t", table, "-I", chain, strconv.Itoa(pos)}, rulespec...)
  86. return ipt.run(cmd...)
  87. }
  88. // Append appends rulespec to specified table/chain
  89. func (ipt *IPTables) Append(table, chain string, rulespec ...string) error {
  90. cmd := append([]string{"-t", table, "-A", chain}, rulespec...)
  91. return ipt.run(cmd...)
  92. }
  93. // AppendUnique acts like Append except that it won't add a duplicate
  94. func (ipt *IPTables) AppendUnique(table, chain string, rulespec ...string) error {
  95. exists, err := ipt.Exists(table, chain, rulespec...)
  96. if err != nil {
  97. return err
  98. }
  99. if !exists {
  100. return ipt.Append(table, chain, rulespec...)
  101. }
  102. return nil
  103. }
  104. // Delete removes rulespec in specified table/chain
  105. func (ipt *IPTables) Delete(table, chain string, rulespec ...string) error {
  106. cmd := append([]string{"-t", table, "-D", chain}, rulespec...)
  107. return ipt.run(cmd...)
  108. }
  109. // List rules in specified table/chain
  110. func (ipt *IPTables) List(table, chain string) ([]string, error) {
  111. var stdout, stderr bytes.Buffer
  112. args := []string{ipt.path, "-t", table, "-S", chain}
  113. if ipt.hasWait {
  114. args = append(args, "--wait")
  115. } else {
  116. ul, err := ipt.fmu.tryLock()
  117. if err != nil {
  118. return nil, err
  119. }
  120. defer ul.Unlock()
  121. }
  122. cmd := exec.Cmd{
  123. Path: ipt.path,
  124. Args: args,
  125. Stdout: &stdout,
  126. Stderr: &stderr,
  127. }
  128. if err := cmd.Run(); err != nil {
  129. return nil, &Error{*(err.(*exec.ExitError)), stderr.String()}
  130. }
  131. rules := strings.Split(stdout.String(), "\n")
  132. if len(rules) > 0 && rules[len(rules)-1] == "" {
  133. rules = rules[:len(rules)-1]
  134. }
  135. return rules, nil
  136. }
  137. func (ipt *IPTables) NewChain(table, chain string) error {
  138. return ipt.run("-t", table, "-N", chain)
  139. }
  140. // ClearChain flushed (deletes all rules) in the specified table/chain.
  141. // If the chain does not exist, a new one will be created
  142. func (ipt *IPTables) ClearChain(table, chain string) error {
  143. err := ipt.NewChain(table, chain)
  144. switch {
  145. case err == nil:
  146. return nil
  147. case err.(*Error).ExitStatus() == 1:
  148. // chain already exists. Flush (clear) it.
  149. return ipt.run("-t", table, "-F", chain)
  150. default:
  151. return err
  152. }
  153. }
  154. // DeleteChain deletes the chain in the specified table.
  155. // The chain must be empty
  156. func (ipt *IPTables) DeleteChain(table, chain string) error {
  157. return ipt.run("-t", table, "-X", chain)
  158. }
  159. func (ipt *IPTables) run(args ...string) error {
  160. var stderr bytes.Buffer
  161. if ipt.hasWait {
  162. args = append([]string{"--wait"}, args...)
  163. } else {
  164. ul, err := ipt.fmu.tryLock()
  165. if err != nil {
  166. return err
  167. }
  168. defer ul.Unlock()
  169. }
  170. cmd := exec.Cmd{
  171. Path: ipt.path,
  172. Args: append([]string{ipt.path}, args...),
  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 existsForOldIpTables(table string, ruleSpec string) (bool, error) {
  253. cmd := exec.Command("iptables", "-t", table, "-S")
  254. var out bytes.Buffer
  255. cmd.Stdout = &out
  256. err := cmd.Run()
  257. if err != nil {
  258. return false, err
  259. }
  260. rules := out.String()
  261. return strings.Contains(rules, ruleSpec), nil
  262. }