iptables.go 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189
  1. // Copyright 2015 flannel 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. // +build !windows
  15. package network
  16. import (
  17. "fmt"
  18. "strings"
  19. "time"
  20. "github.com/flannel-io/flannel/pkg/ip"
  21. "github.com/flannel-io/flannel/subnet"
  22. "github.com/coreos/go-iptables/iptables"
  23. log "k8s.io/klog"
  24. )
  25. type IPTables interface {
  26. AppendUnique(table string, chain string, rulespec ...string) error
  27. Delete(table string, chain string, rulespec ...string) error
  28. Exists(table string, chain string, rulespec ...string) (bool, error)
  29. }
  30. type IPTablesError interface {
  31. IsNotExist() bool
  32. Error() string
  33. }
  34. type IPTablesRule struct {
  35. table string
  36. chain string
  37. rulespec []string
  38. }
  39. func MasqRules(ipn ip.IP4Net, lease *subnet.Lease) []IPTablesRule {
  40. n := ipn.String()
  41. sn := lease.Subnet.String()
  42. supports_random_fully := false
  43. ipt, err := iptables.New()
  44. if err == nil {
  45. supports_random_fully = ipt.HasRandomFully()
  46. }
  47. if supports_random_fully {
  48. return []IPTablesRule{
  49. // This rule makes sure we don't NAT traffic within overlay network (e.g. coming out of docker0)
  50. {"nat", "POSTROUTING", []string{"-s", n, "-d", n, "-j", "RETURN"}},
  51. // NAT if it's not multicast traffic
  52. {"nat", "POSTROUTING", []string{"-s", n, "!", "-d", "224.0.0.0/4", "-j", "MASQUERADE", "--random-fully"}},
  53. // Prevent performing Masquerade on external traffic which arrives from a Node that owns the container/pod IP address
  54. {"nat", "POSTROUTING", []string{"!", "-s", n, "-d", sn, "-j", "RETURN"}},
  55. // Masquerade anything headed towards flannel from the host
  56. {"nat", "POSTROUTING", []string{"!", "-s", n, "-d", n, "-j", "MASQUERADE", "--random-fully"}},
  57. }
  58. } else {
  59. return []IPTablesRule{
  60. // This rule makes sure we don't NAT traffic within overlay network (e.g. coming out of docker0)
  61. {"nat", "POSTROUTING", []string{"-s", n, "-d", n, "-j", "RETURN"}},
  62. // NAT if it's not multicast traffic
  63. {"nat", "POSTROUTING", []string{"-s", n, "!", "-d", "224.0.0.0/4", "-j", "MASQUERADE"}},
  64. // Prevent performing Masquerade on external traffic which arrives from a Node that owns the container/pod IP address
  65. {"nat", "POSTROUTING", []string{"!", "-s", n, "-d", sn, "-j", "RETURN"}},
  66. // Masquerade anything headed towards flannel from the host
  67. {"nat", "POSTROUTING", []string{"!", "-s", n, "-d", n, "-j", "MASQUERADE"}},
  68. }
  69. }
  70. }
  71. func ForwardRules(flannelNetwork string) []IPTablesRule {
  72. return []IPTablesRule{
  73. // These rules allow traffic to be forwarded if it is to or from the flannel network range.
  74. {"filter", "FORWARD", []string{"-s", flannelNetwork, "-j", "ACCEPT"}},
  75. {"filter", "FORWARD", []string{"-d", flannelNetwork, "-j", "ACCEPT"}},
  76. }
  77. }
  78. func ipTablesRulesExist(ipt IPTables, rules []IPTablesRule) (bool, error) {
  79. for _, rule := range rules {
  80. exists, err := ipt.Exists(rule.table, rule.chain, rule.rulespec...)
  81. if err != nil {
  82. // this shouldn't ever happen
  83. return false, fmt.Errorf("failed to check rule existence: %v", err)
  84. }
  85. if !exists {
  86. return false, nil
  87. }
  88. }
  89. return true, nil
  90. }
  91. func SetupAndEnsureIPTables(rules []IPTablesRule, resyncPeriod int) {
  92. ipt, err := iptables.New()
  93. if err != nil {
  94. // if we can't find iptables, give up and return
  95. log.Errorf("Failed to setup IPTables. iptables binary was not found: %v", err)
  96. return
  97. }
  98. defer func() {
  99. teardownIPTables(ipt, rules)
  100. }()
  101. for {
  102. // Ensure that all the iptables rules exist every 5 seconds
  103. if err := ensureIPTables(ipt, rules); err != nil {
  104. log.Errorf("Failed to ensure iptables rules: %v", err)
  105. }
  106. time.Sleep(time.Duration(resyncPeriod) * time.Second)
  107. }
  108. }
  109. // DeleteIPTables delete specified iptables rules
  110. func DeleteIPTables(rules []IPTablesRule) error {
  111. ipt, err := iptables.New()
  112. if err != nil {
  113. // if we can't find iptables, give up and return
  114. log.Errorf("Failed to setup IPTables. iptables binary was not found: %v", err)
  115. return err
  116. }
  117. teardownIPTables(ipt, rules)
  118. return nil
  119. }
  120. func ensureIPTables(ipt IPTables, rules []IPTablesRule) error {
  121. exists, err := ipTablesRulesExist(ipt, rules)
  122. if err != nil {
  123. return fmt.Errorf("Error checking rule existence: %v", err)
  124. }
  125. if exists {
  126. // if all the rules already exist, no need to do anything
  127. return nil
  128. }
  129. // Otherwise, teardown all the rules and set them up again
  130. // We do this because the order of the rules is important
  131. log.Info("Some iptables rules are missing; deleting and recreating rules")
  132. if err = teardownIPTables(ipt, rules); err != nil {
  133. return fmt.Errorf("Error tearing down rules: %v", err)
  134. }
  135. if err = setupIPTables(ipt, rules); err != nil {
  136. return fmt.Errorf("Error setting up rules: %v", err)
  137. }
  138. return nil
  139. }
  140. func setupIPTables(ipt IPTables, rules []IPTablesRule) error {
  141. for _, rule := range rules {
  142. log.Info("Adding iptables rule: ", strings.Join(rule.rulespec, " "))
  143. err := ipt.AppendUnique(rule.table, rule.chain, rule.rulespec...)
  144. if err != nil {
  145. return fmt.Errorf("failed to insert IPTables rule: %v", err)
  146. }
  147. }
  148. return nil
  149. }
  150. func teardownIPTables(ipt IPTables, rules []IPTablesRule) error {
  151. for _, rule := range rules {
  152. log.Info("Deleting iptables rule: ", strings.Join(rule.rulespec, " "))
  153. err := ipt.Delete(rule.table, rule.chain, rule.rulespec...)
  154. if err != nil {
  155. e := err.(IPTablesError)
  156. // If this error is because the rule is already deleted, the message from iptables will be
  157. // "Bad rule (does a matching rule exist in that chain?)". These are safe to ignore.
  158. // However other errors (like EAGAIN caused by other things not respecting the xtables.lock)
  159. // should halt the ensure process. Otherwise rules can get out of order when a rule we think
  160. // is deleted is actually still in the chain.
  161. // This will leave the rules incomplete until the next successful reconciliation loop.
  162. if !e.IsNotExist() {
  163. return err
  164. }
  165. }
  166. }
  167. return nil
  168. }