iptables.go 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358
  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. return ipt.executeList(args)
  123. }
  124. // ListChains returns a slice containing the name of each chain in the specified table.
  125. func (ipt *IPTables) ListChains(table string) ([]string, error) {
  126. args := []string{"-t", table, "-S"}
  127. result, err := ipt.executeList(args)
  128. if err != nil {
  129. return nil, err
  130. }
  131. // Iterate over rules to find all default (-P) and user-specified (-N) chains.
  132. // Chains definition always come before rules.
  133. // Format is the following:
  134. // -P OUTPUT ACCEPT
  135. // -N Custom
  136. var chains []string
  137. for _, val := range result {
  138. if strings.HasPrefix(val, "-P") || strings.HasPrefix(val, "-N") {
  139. chains = append(chains, strings.Fields(val)[1])
  140. } else {
  141. break
  142. }
  143. }
  144. return chains, nil
  145. }
  146. func (ipt *IPTables) executeList(args []string) ([]string, error) {
  147. var stdout bytes.Buffer
  148. if err := ipt.runWithOutput(args, &stdout); err != nil {
  149. return nil, err
  150. }
  151. rules := strings.Split(stdout.String(), "\n")
  152. if len(rules) > 0 && rules[len(rules)-1] == "" {
  153. rules = rules[:len(rules)-1]
  154. }
  155. return rules, nil
  156. }
  157. // NewChain creates a new chain in the specified table.
  158. // If the chain already exists, it will result in an error.
  159. func (ipt *IPTables) NewChain(table, chain string) error {
  160. return ipt.run("-t", table, "-N", chain)
  161. }
  162. // ClearChain flushed (deletes all rules) in the specified table/chain.
  163. // If the chain does not exist, a new one will be created
  164. func (ipt *IPTables) ClearChain(table, chain string) error {
  165. err := ipt.NewChain(table, chain)
  166. eerr, eok := err.(*Error)
  167. switch {
  168. case err == nil:
  169. return nil
  170. case eok && eerr.ExitStatus() == 1:
  171. // chain already exists. Flush (clear) it.
  172. return ipt.run("-t", table, "-F", chain)
  173. default:
  174. return err
  175. }
  176. }
  177. // RenameChain renames the old chain to the new one.
  178. func (ipt *IPTables) RenameChain(table, oldChain, newChain string) error {
  179. return ipt.run("-t", table, "-E", oldChain, newChain)
  180. }
  181. // DeleteChain deletes the chain in the specified table.
  182. // The chain must be empty
  183. func (ipt *IPTables) DeleteChain(table, chain string) error {
  184. return ipt.run("-t", table, "-X", chain)
  185. }
  186. // run runs an iptables command with the given arguments, ignoring
  187. // any stdout output
  188. func (ipt *IPTables) run(args ...string) error {
  189. return ipt.runWithOutput(args, nil)
  190. }
  191. // runWithOutput runs an iptables command with the given arguments,
  192. // writing any stdout output to the given writer
  193. func (ipt *IPTables) runWithOutput(args []string, stdout io.Writer) error {
  194. args = append([]string{ipt.path}, args...)
  195. if ipt.hasWait {
  196. args = append(args, "--wait")
  197. } else {
  198. fmu, err := newXtablesFileLock()
  199. if err != nil {
  200. return err
  201. }
  202. ul, err := fmu.tryLock()
  203. if err != nil {
  204. return err
  205. }
  206. defer ul.Unlock()
  207. }
  208. var stderr bytes.Buffer
  209. cmd := exec.Cmd{
  210. Path: ipt.path,
  211. Args: args,
  212. Stdout: stdout,
  213. Stderr: &stderr,
  214. }
  215. if err := cmd.Run(); err != nil {
  216. return &Error{*(err.(*exec.ExitError)), stderr.String()}
  217. }
  218. return nil
  219. }
  220. // getIptablesCommand returns the correct command for the given protocol, either "iptables" or "ip6tables".
  221. func getIptablesCommand(proto Protocol) string {
  222. if proto == ProtocolIPv6 {
  223. return "ip6tables"
  224. } else {
  225. return "iptables"
  226. }
  227. }
  228. // Checks if iptables has the "-C" and "--wait" flag
  229. func getIptablesCommandSupport(path string) (bool, bool, error) {
  230. vstring, err := getIptablesVersionString(path)
  231. if err != nil {
  232. return false, false, err
  233. }
  234. v1, v2, v3, err := extractIptablesVersion(vstring)
  235. if err != nil {
  236. return false, false, err
  237. }
  238. return iptablesHasCheckCommand(v1, v2, v3), iptablesHasWaitCommand(v1, v2, v3), nil
  239. }
  240. // getIptablesVersion returns the first three components of the iptables version.
  241. // e.g. "iptables v1.3.66" would return (1, 3, 66, nil)
  242. func extractIptablesVersion(str string) (int, int, int, error) {
  243. versionMatcher := regexp.MustCompile("v([0-9]+)\\.([0-9]+)\\.([0-9]+)")
  244. result := versionMatcher.FindStringSubmatch(str)
  245. if result == nil {
  246. return 0, 0, 0, fmt.Errorf("no iptables version found in string: %s", str)
  247. }
  248. v1, err := strconv.Atoi(result[1])
  249. if err != nil {
  250. return 0, 0, 0, err
  251. }
  252. v2, err := strconv.Atoi(result[2])
  253. if err != nil {
  254. return 0, 0, 0, err
  255. }
  256. v3, err := strconv.Atoi(result[3])
  257. if err != nil {
  258. return 0, 0, 0, err
  259. }
  260. return v1, v2, v3, nil
  261. }
  262. // Runs "iptables --version" to get the version string
  263. func getIptablesVersionString(path string) (string, error) {
  264. cmd := exec.Command(path, "--version")
  265. var out bytes.Buffer
  266. cmd.Stdout = &out
  267. err := cmd.Run()
  268. if err != nil {
  269. return "", err
  270. }
  271. return out.String(), nil
  272. }
  273. // Checks if an iptables version is after 1.4.11, when --check was added
  274. func iptablesHasCheckCommand(v1 int, v2 int, v3 int) bool {
  275. if v1 > 1 {
  276. return true
  277. }
  278. if v1 == 1 && v2 > 4 {
  279. return true
  280. }
  281. if v1 == 1 && v2 == 4 && v3 >= 11 {
  282. return true
  283. }
  284. return false
  285. }
  286. // Checks if an iptables version is after 1.4.20, when --wait was added
  287. func iptablesHasWaitCommand(v1 int, v2 int, v3 int) bool {
  288. if v1 > 1 {
  289. return true
  290. }
  291. if v1 == 1 && v2 > 4 {
  292. return true
  293. }
  294. if v1 == 1 && v2 == 4 && v3 >= 20 {
  295. return true
  296. }
  297. return false
  298. }
  299. // Checks if a rule specification exists for a table
  300. func (ipt *IPTables) existsForOldIptables(table, chain string, rulespec []string) (bool, error) {
  301. rs := strings.Join(append([]string{"-A", chain}, rulespec...), " ")
  302. args := []string{"-t", table, "-S"}
  303. var stdout bytes.Buffer
  304. err := ipt.runWithOutput(args, &stdout)
  305. if err != nil {
  306. return false, err
  307. }
  308. return strings.Contains(stdout.String(), rs), nil
  309. }