iptables.go 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172
  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. log "github.com/golang/glog"
  20. "time"
  21. "github.com/coreos/flannel/pkg/ip"
  22. "github.com/coreos/flannel/subnet"
  23. "github.com/coreos/go-iptables/iptables"
  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 IPTablesRule struct {
  31. table string
  32. chain string
  33. rulespec []string
  34. }
  35. func MasqRules(ipn ip.IP4Net, lease *subnet.Lease) []IPTablesRule {
  36. n := ipn.String()
  37. sn := lease.Subnet.String()
  38. supports_random_fully := false
  39. ipt, err := iptables.New()
  40. if err == nil {
  41. supports_random_fully = ipt.HasRandomFully()
  42. }
  43. if supports_random_fully {
  44. return []IPTablesRule{
  45. // This rule makes sure we don't NAT traffic within overlay network (e.g. coming out of docker0)
  46. {"nat", "POSTROUTING", []string{"-s", n, "-d", n, "-j", "RETURN"}},
  47. // NAT if it's not multicast traffic
  48. {"nat", "POSTROUTING", []string{"-s", n, "!", "-d", "224.0.0.0/4", "-j", "MASQUERADE", "--random-fully"}},
  49. // Prevent performing Masquerade on external traffic which arrives from a Node that owns the container/pod IP address
  50. {"nat", "POSTROUTING", []string{"!", "-s", n, "-d", sn, "-j", "RETURN"}},
  51. // Masquerade anything headed towards flannel from the host
  52. {"nat", "POSTROUTING", []string{"!", "-s", n, "-d", n, "-j", "MASQUERADE", "--random-fully"}},
  53. }
  54. } else {
  55. return []IPTablesRule{
  56. // This rule makes sure we don't NAT traffic within overlay network (e.g. coming out of docker0)
  57. {"nat", "POSTROUTING", []string{"-s", n, "-d", n, "-j", "RETURN"}},
  58. // NAT if it's not multicast traffic
  59. {"nat", "POSTROUTING", []string{"-s", n, "!", "-d", "224.0.0.0/4", "-j", "MASQUERADE"}},
  60. // Prevent performing Masquerade on external traffic which arrives from a Node that owns the container/pod IP address
  61. {"nat", "POSTROUTING", []string{"!", "-s", n, "-d", sn, "-j", "RETURN"}},
  62. // Masquerade anything headed towards flannel from the host
  63. {"nat", "POSTROUTING", []string{"!", "-s", n, "-d", n, "-j", "MASQUERADE"}},
  64. }
  65. }
  66. }
  67. func ForwardRules(flannelNetwork string) []IPTablesRule {
  68. return []IPTablesRule{
  69. // These rules allow traffic to be forwarded if it is to or from the flannel network range.
  70. {"filter", "FORWARD", []string{"-s", flannelNetwork, "-j", "ACCEPT"}},
  71. {"filter", "FORWARD", []string{"-d", flannelNetwork, "-j", "ACCEPT"}},
  72. }
  73. }
  74. func ipTablesRulesExist(ipt IPTables, rules []IPTablesRule) (bool, error) {
  75. for _, rule := range rules {
  76. exists, err := ipt.Exists(rule.table, rule.chain, rule.rulespec...)
  77. if err != nil {
  78. // this shouldn't ever happen
  79. return false, fmt.Errorf("failed to check rule existence: %v", err)
  80. }
  81. if !exists {
  82. return false, nil
  83. }
  84. }
  85. return true, nil
  86. }
  87. func SetupAndEnsureIPTables(rules []IPTablesRule, resyncPeriod int) {
  88. ipt, err := iptables.New()
  89. if err != nil {
  90. // if we can't find iptables, give up and return
  91. log.Errorf("Failed to setup IPTables. iptables binary was not found: %v", err)
  92. return
  93. }
  94. defer func() {
  95. teardownIPTables(ipt, rules)
  96. }()
  97. for {
  98. // Ensure that all the iptables rules exist every 5 seconds
  99. if err := ensureIPTables(ipt, rules); err != nil {
  100. log.Errorf("Failed to ensure iptables rules: %v", err)
  101. }
  102. time.Sleep(time.Duration(resyncPeriod) * time.Second)
  103. }
  104. }
  105. // DeleteIPTables delete specified iptables rules
  106. func DeleteIPTables(rules []IPTablesRule) error {
  107. ipt, err := iptables.New()
  108. if err != nil {
  109. // if we can't find iptables, give up and return
  110. log.Errorf("Failed to setup IPTables. iptables binary was not found: %v", err)
  111. return err
  112. }
  113. teardownIPTables(ipt, rules)
  114. return nil
  115. }
  116. func ensureIPTables(ipt IPTables, rules []IPTablesRule) error {
  117. exists, err := ipTablesRulesExist(ipt, rules)
  118. if err != nil {
  119. return fmt.Errorf("Error checking rule existence: %v", err)
  120. }
  121. if exists {
  122. // if all the rules already exist, no need to do anything
  123. return nil
  124. }
  125. // Otherwise, teardown all the rules and set them up again
  126. // We do this because the order of the rules is important
  127. log.Info("Some iptables rules are missing; deleting and recreating rules")
  128. teardownIPTables(ipt, rules)
  129. if err = setupIPTables(ipt, rules); err != nil {
  130. return fmt.Errorf("Error setting up rules: %v", err)
  131. }
  132. return nil
  133. }
  134. func setupIPTables(ipt IPTables, rules []IPTablesRule) error {
  135. for _, rule := range rules {
  136. log.Info("Adding iptables rule: ", strings.Join(rule.rulespec, " "))
  137. err := ipt.AppendUnique(rule.table, rule.chain, rule.rulespec...)
  138. if err != nil {
  139. return fmt.Errorf("failed to insert IPTables rule: %v", err)
  140. }
  141. }
  142. return nil
  143. }
  144. func teardownIPTables(ipt IPTables, rules []IPTablesRule) {
  145. for _, rule := range rules {
  146. log.Info("Deleting iptables rule: ", strings.Join(rule.rulespec, " "))
  147. // We ignore errors here because if there's an error it's almost certainly because the rule
  148. // doesn't exist, which is fine (we don't need to delete rules that don't exist)
  149. ipt.Delete(rule.table, rule.chain, rule.rulespec...)
  150. }
  151. }