ipmasq.go 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. // Copyright 2015 CoreOS, Inc.
  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/flannel/Godeps/_workspace/src/github.com/coreos/go-iptables/iptables"
  19. log "github.com/coreos/flannel/Godeps/_workspace/src/github.com/golang/glog"
  20. "github.com/coreos/flannel/pkg/ip"
  21. )
  22. func setupIPMasq(ipn ip.IP4Net) error {
  23. ipt, err := iptables.New()
  24. if err != nil {
  25. return fmt.Errorf("failed to setup IP Masquerade. iptables was not found")
  26. }
  27. err = ipt.ClearChain("nat", "FLANNEL")
  28. if err != nil {
  29. return fmt.Errorf("Failed to create/clear FLANNEL chain in NAT table: %v", err)
  30. }
  31. rules := [][]string{
  32. // This rule makes sure we don't NAT traffic within overlay network (e.g. coming out of docker0)
  33. {"FLANNEL", "-d", ipn.String(), "-j", "ACCEPT"},
  34. // NAT if it's not multicast traffic
  35. {"FLANNEL", "!", "-d", "224.0.0.0/4", "-j", "MASQUERADE"},
  36. // This rule will take everything coming from overlay and send it to FLANNEL chain
  37. {"POSTROUTING", "-s", ipn.String(), "-j", "FLANNEL"},
  38. // Masquerade anything headed towards flannel from the host
  39. {"POSTROUTING", "!", "-s", ipn.String(), "-d", ipn.String(), "-j", "MASQUERADE"},
  40. }
  41. for _, rule := range rules {
  42. log.Info("Adding iptables rule: ", strings.Join(rule, " "))
  43. chain := rule[0]
  44. args := rule[1:len(rule)]
  45. err = ipt.AppendUnique("nat", chain, args...)
  46. if err != nil {
  47. return fmt.Errorf("Failed to insert IP masquerade rule: %v", err)
  48. }
  49. }
  50. return nil
  51. }