iptables.go 8.3 KB

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