iptables.go 11 KB

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