iptables.go 11 KB

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