iptables.go 9.7 KB

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