ipmasq.go 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  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. "github.com/coreos/flannel/subnet"
  22. )
  23. func rules(ipn ip.IP4Net, lease *subnet.Lease) [][]string {
  24. n := ipn.String()
  25. sn := lease.Subnet.String()
  26. return [][]string{
  27. // This rule makes sure we don't NAT traffic within overlay network (e.g. coming out of docker0)
  28. {"-s", n, "-d", n, "-j", "RETURN"},
  29. // NAT if it's not multicast traffic
  30. {"-s", n, "!", "-d", "224.0.0.0/4", "-j", "MASQUERADE"},
  31. // Prevent performing Masquerade on external traffic which arrives from a Node that owns the container/pod IP address
  32. {"!", "-s", n, "-d", sn, "-j", "RETURN"},
  33. // Masquerade anything headed towards flannel from the host
  34. {"!", "-s", n, "-d", n, "-j", "MASQUERADE"},
  35. }
  36. }
  37. func SetupIPMasq(ipn ip.IP4Net, lease *subnet.Lease) error {
  38. ipt, err := iptables.New()
  39. if err != nil {
  40. return fmt.Errorf("failed to set up IP Masquerade. iptables was not found")
  41. }
  42. for _, rule := range rules(ipn, lease) {
  43. log.Info("Adding iptables rule: ", strings.Join(rule, " "))
  44. err = ipt.AppendUnique("nat", "POSTROUTING", rule...)
  45. if err != nil {
  46. return fmt.Errorf("failed to insert IP masquerade rule: %v", err)
  47. }
  48. }
  49. return nil
  50. }
  51. func TeardownIPMasq(ipn ip.IP4Net, lease *subnet.Lease) error {
  52. ipt, err := iptables.New()
  53. if err != nil {
  54. return fmt.Errorf("failed to teardown IP Masquerade. iptables was not found")
  55. }
  56. for _, rule := range rules(ipn, lease) {
  57. log.Info("Deleting iptables rule: ", strings.Join(rule, " "))
  58. err = ipt.Delete("nat", "POSTROUTING", rule...)
  59. if err != nil {
  60. return fmt.Errorf("failed to delete IP masquerade rule: %v", err)
  61. }
  62. }
  63. return nil
  64. }