ipmasq.go 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. // Copyright 2015 CNI 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 ip
  15. import (
  16. "fmt"
  17. "net"
  18. "github.com/coreos/go-iptables/iptables"
  19. )
  20. // SetupIPMasq installs iptables rules to masquerade traffic
  21. // coming from ipn and going outside of it
  22. func SetupIPMasq(ipn *net.IPNet, chain string, comment string) error {
  23. ipt, err := iptables.New()
  24. if err != nil {
  25. return fmt.Errorf("failed to locate iptables: %v", err)
  26. }
  27. if err = ipt.NewChain("nat", chain); err != nil {
  28. if err.(*iptables.Error).ExitStatus() != 1 {
  29. // TODO(eyakubovich): assumes exit status 1 implies chain exists
  30. return err
  31. }
  32. }
  33. if err = ipt.AppendUnique("nat", chain, "-d", ipn.String(), "-j", "ACCEPT", "-m", "comment", "--comment", comment); err != nil {
  34. return err
  35. }
  36. if err = ipt.AppendUnique("nat", chain, "!", "-d", "224.0.0.0/4", "-j", "MASQUERADE", "-m", "comment", "--comment", comment); err != nil {
  37. return err
  38. }
  39. return ipt.AppendUnique("nat", "POSTROUTING", "-s", ipn.String(), "-j", chain, "-m", "comment", "--comment", comment)
  40. }
  41. // TeardownIPMasq undoes the effects of SetupIPMasq
  42. func TeardownIPMasq(ipn *net.IPNet, chain string, comment string) error {
  43. ipt, err := iptables.New()
  44. if err != nil {
  45. return fmt.Errorf("failed to locate iptables: %v", err)
  46. }
  47. if err = ipt.Delete("nat", "POSTROUTING", "-s", ipn.String(), "-j", chain, "-m", "comment", "--comment", comment); err != nil {
  48. return err
  49. }
  50. if err = ipt.ClearChain("nat", chain); err != nil {
  51. return err
  52. }
  53. return ipt.DeleteChain("nat", chain)
  54. }