ipmasq.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  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. package network
  15. import (
  16. "fmt"
  17. "strings"
  18. "github.com/coreos/go-iptables/iptables"
  19. log "github.com/golang/glog"
  20. "github.com/coreos/flannel/pkg/ip"
  21. )
  22. func rules(ipn ip.IP4Net) [][]string {
  23. n := ipn.String()
  24. return [][]string{
  25. // This rule makes sure we don't NAT traffic within overlay network (e.g. coming out of docker0)
  26. {"-s", n, "-d", n, "-j", "RETURN"},
  27. // NAT if it's not multicast traffic
  28. {"-s", n, "!", "-d", "224.0.0.0/4", "-j", "MASQUERADE"},
  29. // Masquerade anything headed towards flannel from the host
  30. {"!", "-s", n, "-d", n, "-j", "MASQUERADE"},
  31. }
  32. }
  33. func setupIPMasq(ipn ip.IP4Net) error {
  34. ipt, err := iptables.New()
  35. if err != nil {
  36. return fmt.Errorf("failed to set up IP Masquerade. iptables was not found")
  37. }
  38. for _, rule := range rules(ipn) {
  39. log.Info("Adding iptables rule: ", strings.Join(rule, " "))
  40. err = ipt.AppendUnique("nat", "POSTROUTING", rule...)
  41. if err != nil {
  42. return fmt.Errorf("failed to insert IP masquerade rule: %v", err)
  43. }
  44. }
  45. return nil
  46. }
  47. func teardownIPMasq(ipn ip.IP4Net) error {
  48. ipt, err := iptables.New()
  49. if err != nil {
  50. return fmt.Errorf("failed to teardown IP Masquerade. iptables was not found")
  51. }
  52. for _, rule := range rules(ipn) {
  53. log.Info("Deleting iptables rule: ", strings.Join(rule, " "))
  54. err = ipt.Delete("nat", "POSTROUTING", rule...)
  55. if err != nil {
  56. return fmt.Errorf("failed to delete IP masquerade rule: %v", err)
  57. }
  58. }
  59. return nil
  60. }