handle_xfrm.go 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  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 ipsec
  15. import (
  16. "fmt"
  17. "net"
  18. "syscall"
  19. log "github.com/golang/glog"
  20. "github.com/vishvananda/netlink"
  21. "github.com/coreos/flannel/subnet"
  22. )
  23. func AddXFRMPolicy(myLease, remoteLease *subnet.Lease, dir netlink.Dir, reqID int) error {
  24. src := myLease.Subnet.ToIPNet()
  25. dst := remoteLease.Subnet.ToIPNet()
  26. policy := netlink.XfrmPolicy{
  27. Src: src,
  28. Dst: dst,
  29. Dir: dir,
  30. }
  31. tunnelLeft := myLease.Attrs.PublicIP.ToIP()
  32. tunnelRight := remoteLease.Attrs.PublicIP.ToIP()
  33. tmpl := netlink.XfrmPolicyTmpl{
  34. Src: tunnelLeft,
  35. Dst: tunnelRight,
  36. Proto: netlink.XFRM_PROTO_ESP,
  37. Mode: netlink.XFRM_MODE_TUNNEL,
  38. Reqid: reqID,
  39. }
  40. log.Infof("Adding ipsec policy: %+v", tmpl)
  41. policy.Tmpls = append(policy.Tmpls, tmpl)
  42. if err := netlink.XfrmPolicyAdd(&policy); err != nil {
  43. return fmt.Errorf("error adding policy: %+v err: %v", policy, err)
  44. }
  45. return nil
  46. }
  47. func DeleteXFRMPolicy(localSubnet, remoteSubnet *net.IPNet, localPublicIP, remotePublicIP net.IP, dir netlink.Dir, reqID int) error {
  48. src := localSubnet
  49. dst := remoteSubnet
  50. policy := netlink.XfrmPolicy{
  51. Src: src,
  52. Dst: dst,
  53. Dir: dir,
  54. }
  55. tunnelLeft := localPublicIP
  56. tunnelRight := remotePublicIP
  57. tmpl := netlink.XfrmPolicyTmpl{
  58. Src: tunnelLeft,
  59. Dst: tunnelRight,
  60. Proto: netlink.XFRM_PROTO_ESP,
  61. Mode: netlink.XFRM_MODE_TUNNEL,
  62. Reqid: reqID,
  63. }
  64. log.Infof("Deleting ipsec policy: %+v", tmpl)
  65. policy.Tmpls = append(policy.Tmpls, tmpl)
  66. if err := netlink.XfrmPolicyDel(&policy); err != nil {
  67. return fmt.Errorf("error deleting policy: %+v err: %v", policy, err)
  68. }
  69. return nil
  70. }
  71. func GetIPSECPolicies() ([]netlink.XfrmPolicy, error) {
  72. return netlink.XfrmPolicyList(syscall.AF_INET)
  73. }