iptables.go 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281
  1. // Copyright 2019 the Kilo authors
  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. "fmt"
  17. "net"
  18. "strings"
  19. "sync"
  20. "time"
  21. "github.com/coreos/go-iptables/iptables"
  22. )
  23. // Client represents any type that can administer iptables rules.
  24. type Client interface {
  25. AppendUnique(table string, chain string, rule ...string) error
  26. Delete(table string, chain string, rule ...string) error
  27. Exists(table string, chain string, rule ...string) (bool, error)
  28. ClearChain(table string, chain string) error
  29. DeleteChain(table string, chain string) error
  30. NewChain(table string, chain string) error
  31. }
  32. // Rule is an interface for interacting with iptables objects.
  33. type Rule interface {
  34. Add(Client) error
  35. Delete(Client) error
  36. Exists(Client) (bool, error)
  37. String() string
  38. }
  39. // rule represents an iptables rule.
  40. type rule struct {
  41. table string
  42. chain string
  43. spec []string
  44. }
  45. // NewRule creates a new iptables rule in the given table and chain.
  46. func NewRule(table, chain string, spec ...string) Rule {
  47. return &rule{table, chain, spec}
  48. }
  49. func (r *rule) Add(client Client) error {
  50. if err := client.AppendUnique(r.table, r.chain, r.spec...); err != nil {
  51. return fmt.Errorf("failed to add iptables rule: %v", err)
  52. }
  53. return nil
  54. }
  55. func (r *rule) Delete(client Client) error {
  56. // Ignore the returned error as an error likely means
  57. // that the rule doesn't exist, which is fine.
  58. client.Delete(r.table, r.chain, r.spec...)
  59. return nil
  60. }
  61. func (r *rule) Exists(client Client) (bool, error) {
  62. return client.Exists(r.table, r.chain, r.spec...)
  63. }
  64. func (r *rule) String() string {
  65. if r == nil {
  66. return ""
  67. }
  68. return fmt.Sprintf("%s_%s_%s", r.table, r.chain, strings.Join(r.spec, "_"))
  69. }
  70. // chain represents an iptables chain.
  71. type chain struct {
  72. table string
  73. chain string
  74. }
  75. // NewChain creates a new iptables chain in the given table.
  76. func NewChain(table, name string) Rule {
  77. return &chain{table, name}
  78. }
  79. func (c *chain) Add(client Client) error {
  80. if err := client.ClearChain(c.table, c.chain); err != nil {
  81. return fmt.Errorf("failed to add iptables chain: %v", err)
  82. }
  83. return nil
  84. }
  85. func (c *chain) Delete(client Client) error {
  86. // The chain must be empty before it can be deleted.
  87. if err := client.ClearChain(c.table, c.chain); err != nil {
  88. return fmt.Errorf("failed to clear iptables chain: %v", err)
  89. }
  90. // Ignore the returned error as an error likely means
  91. // that the chain doesn't exist, which is fine.
  92. client.DeleteChain(c.table, c.chain)
  93. return nil
  94. }
  95. func (c *chain) Exists(client Client) (bool, error) {
  96. // The code for "chain already exists".
  97. existsErr := 1
  98. err := client.NewChain(c.table, c.chain)
  99. se, ok := err.(statusExiter)
  100. switch {
  101. case err == nil:
  102. // If there was no error adding a new chain, then it did not exist.
  103. // Delete it and return false.
  104. client.DeleteChain(c.table, c.chain)
  105. return false, nil
  106. case ok && se.ExitStatus() == existsErr:
  107. return true, nil
  108. default:
  109. return false, err
  110. }
  111. }
  112. func (c *chain) String() string {
  113. if c == nil {
  114. return ""
  115. }
  116. return fmt.Sprintf("%s_%s", c.table, c.chain)
  117. }
  118. // Controller is able to reconcile a given set of iptables rules.
  119. type Controller struct {
  120. client Client
  121. errors chan error
  122. sync.Mutex
  123. rules []Rule
  124. subscribed bool
  125. }
  126. // New generates a new iptables rules controller.
  127. // It expects an IP address length to determine
  128. // whether to operate in IPv4 or IPv6 mode.
  129. func New(ipLength int) (*Controller, error) {
  130. p := iptables.ProtocolIPv4
  131. if ipLength == net.IPv6len {
  132. p = iptables.ProtocolIPv6
  133. }
  134. client, err := iptables.NewWithProtocol(p)
  135. if err != nil {
  136. return nil, fmt.Errorf("failed to create iptables client: %v", err)
  137. }
  138. return &Controller{
  139. client: client,
  140. errors: make(chan error),
  141. }, nil
  142. }
  143. // Run watches for changes to iptables rules and reconciles
  144. // the rules against the desired state.
  145. func (c *Controller) Run(stop <-chan struct{}) (<-chan error, error) {
  146. c.Lock()
  147. if c.subscribed {
  148. c.Unlock()
  149. return c.errors, nil
  150. }
  151. // Ensure a given instance only subscribes once.
  152. c.subscribed = true
  153. c.Unlock()
  154. go func() {
  155. defer close(c.errors)
  156. for {
  157. select {
  158. case <-time.After(5 * time.Second):
  159. case <-stop:
  160. return
  161. }
  162. if err := c.reconcile(); err != nil {
  163. nonBlockingSend(c.errors, fmt.Errorf("failed to reconcile rules: %v", err))
  164. }
  165. }
  166. }()
  167. return c.errors, nil
  168. }
  169. // reconcile makes sure that every rule is still in the backend.
  170. // It does not ensure that the order in the backend is correct.
  171. // If any rule is missing, that rule and all following rules are
  172. // re-added.
  173. func (c *Controller) reconcile() error {
  174. c.Lock()
  175. defer c.Unlock()
  176. for i, r := range c.rules {
  177. ok, err := r.Exists(c.client)
  178. if err != nil {
  179. return fmt.Errorf("failed to check if rule exists: %v", err)
  180. }
  181. if !ok {
  182. if err := c.resetFromIndex(i, c.rules); err != nil {
  183. return fmt.Errorf("failed to add rule: %v", err)
  184. }
  185. break
  186. }
  187. }
  188. return nil
  189. }
  190. // resetFromIndex re-adds all rules starting from the given index.
  191. func (c *Controller) resetFromIndex(i int, rules []Rule) error {
  192. if i >= len(rules) {
  193. return nil
  194. }
  195. for j := i; j < len(rules); j++ {
  196. if err := rules[j].Delete(c.client); err != nil {
  197. return fmt.Errorf("failed to delete rule: %v", err)
  198. }
  199. if err := rules[j].Add(c.client); err != nil {
  200. return fmt.Errorf("failed to add rule: %v", err)
  201. }
  202. }
  203. return nil
  204. }
  205. // deleteFromIndex deletes all rules starting from the given index.
  206. func (c *Controller) deleteFromIndex(i int, rules *[]Rule) error {
  207. if i >= len(*rules) {
  208. return nil
  209. }
  210. for j := i; j < len(*rules); j++ {
  211. if err := (*rules)[j].Delete(c.client); err != nil {
  212. return fmt.Errorf("failed to delete rule: %v", err)
  213. }
  214. (*rules)[j] = nil
  215. }
  216. *rules = (*rules)[:i]
  217. return nil
  218. }
  219. // Set idempotently overwrites any iptables rules previously defined
  220. // for the controller with the given set of rules.
  221. func (c *Controller) Set(rules []Rule) error {
  222. c.Lock()
  223. defer c.Unlock()
  224. var i int
  225. for ; i < len(rules); i++ {
  226. if i < len(c.rules) {
  227. if rules[i].String() != c.rules[i].String() {
  228. if err := c.deleteFromIndex(i, &c.rules); err != nil {
  229. return err
  230. }
  231. }
  232. }
  233. if i >= len(c.rules) {
  234. if err := rules[i].Add(c.client); err != nil {
  235. return fmt.Errorf("failed to add rule: %v", err)
  236. }
  237. c.rules = append(c.rules, rules[i])
  238. }
  239. }
  240. return c.deleteFromIndex(i, &c.rules)
  241. }
  242. // CleanUp will clean up any rules created by the controller.
  243. func (c *Controller) CleanUp() error {
  244. c.Lock()
  245. defer c.Unlock()
  246. return c.deleteFromIndex(0, &c.rules)
  247. }
  248. func nonBlockingSend(errors chan<- error, err error) {
  249. select {
  250. case errors <- err:
  251. default:
  252. }
  253. }