iptables.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398
  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. resyncPeriod time.Duration
  179. sync.Mutex
  180. rules []Rule
  181. subscribed bool
  182. }
  183. // ControllerOption modifies the controller's configuration.
  184. type ControllerOption func(h *Controller)
  185. // WithLogger adds a logger to the controller.
  186. func WithLogger(logger log.Logger) ControllerOption {
  187. return func(c *Controller) {
  188. c.logger = logger
  189. }
  190. }
  191. // WithResyncPeriod modifies how often the controller reconciles.
  192. func WithResyncPeriod(resyncPeriod time.Duration) ControllerOption {
  193. return func(c *Controller) {
  194. c.resyncPeriod = resyncPeriod
  195. }
  196. }
  197. // WithClients adds iptables clients to the controller.
  198. func WithClients(v4, v6 Client) ControllerOption {
  199. return func(c *Controller) {
  200. c.v4 = v4
  201. c.v6 = v6
  202. }
  203. }
  204. // New generates a new iptables rules controller.
  205. // If no options are given, IPv4 and IPv6 clients
  206. // will be instantiated using the regular iptables backend.
  207. func New(opts ...ControllerOption) (*Controller, error) {
  208. c := &Controller{
  209. errors: make(chan error),
  210. logger: log.NewNopLogger(),
  211. }
  212. for _, o := range opts {
  213. o(c)
  214. }
  215. if c.v4 == nil {
  216. v4, err := iptables.NewWithProtocol(iptables.ProtocolIPv4)
  217. if err != nil {
  218. return nil, fmt.Errorf("failed to create iptables IPv4 client: %v", err)
  219. }
  220. c.v4 = v4
  221. }
  222. if c.v6 == nil {
  223. v6, err := iptables.NewWithProtocol(iptables.ProtocolIPv6)
  224. if err != nil {
  225. return nil, fmt.Errorf("failed to create iptables IPv6 client: %v", err)
  226. }
  227. c.v6 = v6
  228. }
  229. return c, nil
  230. }
  231. // Run watches for changes to iptables rules and reconciles
  232. // the rules against the desired state.
  233. func (c *Controller) Run(stop <-chan struct{}) (<-chan error, error) {
  234. c.Lock()
  235. if c.subscribed {
  236. c.Unlock()
  237. return c.errors, nil
  238. }
  239. // Ensure a given instance only subscribes once.
  240. c.subscribed = true
  241. c.Unlock()
  242. go func() {
  243. t := time.NewTimer(c.resyncPeriod)
  244. defer close(c.errors)
  245. for {
  246. select {
  247. case <-t.C:
  248. if err := c.reconcile(); err != nil {
  249. nonBlockingSend(c.errors, fmt.Errorf("failed to reconcile rules: %v", err))
  250. }
  251. t.Reset(c.resyncPeriod)
  252. case <-stop:
  253. return
  254. }
  255. }
  256. }()
  257. return c.errors, nil
  258. }
  259. // reconcile makes sure that every rule is still in the backend.
  260. // It does not ensure that the order in the backend is correct.
  261. // If any rule is missing, that rule and all following rules are
  262. // re-added.
  263. func (c *Controller) reconcile() error {
  264. c.Lock()
  265. defer c.Unlock()
  266. var rc ruleCache
  267. for i, r := range c.rules {
  268. ok, err := rc.exists(c.client(r.Proto()), r)
  269. if err != nil {
  270. return fmt.Errorf("failed to check if rule exists: %v", err)
  271. }
  272. if !ok {
  273. level.Info(c.logger).Log("msg", fmt.Sprintf("applying %d iptables rules", len(c.rules)-i))
  274. if err := c.resetFromIndex(i, c.rules); err != nil {
  275. return fmt.Errorf("failed to add rule: %v", err)
  276. }
  277. break
  278. }
  279. }
  280. return nil
  281. }
  282. // resetFromIndex re-adds all rules starting from the given index.
  283. func (c *Controller) resetFromIndex(i int, rules []Rule) error {
  284. if i >= len(rules) {
  285. return nil
  286. }
  287. for j := i; j < len(rules); j++ {
  288. if err := rules[j].Delete(c.client(rules[j].Proto())); err != nil {
  289. return fmt.Errorf("failed to delete rule: %v", err)
  290. }
  291. if err := rules[j].Add(c.client(rules[j].Proto())); err != nil {
  292. return fmt.Errorf("failed to add rule: %v", err)
  293. }
  294. }
  295. return nil
  296. }
  297. // deleteFromIndex deletes all rules starting from the given index.
  298. func (c *Controller) deleteFromIndex(i int, rules *[]Rule) error {
  299. if i >= len(*rules) {
  300. return nil
  301. }
  302. for j := i; j < len(*rules); j++ {
  303. if err := (*rules)[j].Delete(c.client((*rules)[j].Proto())); err != nil {
  304. *rules = append((*rules)[:i], (*rules)[j:]...)
  305. return fmt.Errorf("failed to delete rule: %v", err)
  306. }
  307. (*rules)[j] = nil
  308. }
  309. *rules = (*rules)[:i]
  310. return nil
  311. }
  312. // Set idempotently overwrites any iptables rules previously defined
  313. // for the controller with the given set of rules.
  314. func (c *Controller) Set(rules []Rule) error {
  315. c.Lock()
  316. defer c.Unlock()
  317. var i int
  318. for ; i < len(rules); i++ {
  319. if i < len(c.rules) {
  320. if rules[i].String() != c.rules[i].String() {
  321. if err := c.deleteFromIndex(i, &c.rules); err != nil {
  322. return err
  323. }
  324. }
  325. }
  326. if i >= len(c.rules) {
  327. if err := rules[i].Add(c.client(rules[i].Proto())); err != nil {
  328. return fmt.Errorf("failed to add rule: %v", err)
  329. }
  330. c.rules = append(c.rules, rules[i])
  331. }
  332. }
  333. return c.deleteFromIndex(i, &c.rules)
  334. }
  335. // CleanUp will clean up any rules created by the controller.
  336. func (c *Controller) CleanUp() error {
  337. c.Lock()
  338. defer c.Unlock()
  339. return c.deleteFromIndex(0, &c.rules)
  340. }
  341. func (c *Controller) client(p Protocol) Client {
  342. switch p {
  343. case ProtocolIPv4:
  344. return c.v4
  345. case ProtocolIPv6:
  346. return c.v6
  347. default:
  348. panic("unknown protocol")
  349. }
  350. }
  351. func nonBlockingSend(errors chan<- error, err error) {
  352. select {
  353. case errors <- err:
  354. default:
  355. }
  356. }