ipmasq.go 1.7 KB

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