iptables.go 9.0 KB

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