ipmasq.go 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  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 sent it to FLANNEL chain
  37. {"POSTROUTING", "-s", ipn.String(), "-j", "FLANNEL"},
  38. }
  39. for _, rule := range rules {
  40. log.Info("Adding iptables rule: ", strings.Join(rule, " "))
  41. chain := rule[0]
  42. args := rule[1:len(rule)]
  43. err = ipt.AppendUnique("nat", chain, args...)
  44. if err != nil {
  45. return fmt.Errorf("Failed to insert IP masquerade rule: %v", err)
  46. }
  47. }
  48. return nil
  49. }