encryption.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704
  1. //go:build linux
  2. // +build linux
  3. package overlay
  4. import (
  5. "bytes"
  6. "encoding/binary"
  7. "encoding/hex"
  8. "fmt"
  9. "hash/fnv"
  10. "net"
  11. "strconv"
  12. "sync"
  13. "syscall"
  14. "github.com/docker/docker/libnetwork/drivers/overlay/overlayutils"
  15. "github.com/docker/docker/libnetwork/iptables"
  16. "github.com/docker/docker/libnetwork/ns"
  17. "github.com/docker/docker/libnetwork/types"
  18. "github.com/hashicorp/go-multierror"
  19. "github.com/sirupsen/logrus"
  20. "github.com/vishvananda/netlink"
  21. )
  22. /*
  23. Encrypted overlay networks use IPsec in transport mode to encrypt and
  24. authenticate the VXLAN UDP datagrams. This driver implements a bespoke control
  25. plane which negotiates the security parameters for each peer-to-peer tunnel.
  26. IPsec Terminology
  27. - ESP: IPSec Encapsulating Security Payload
  28. - SPI: Security Parameter Index
  29. - ICV: Integrity Check Value
  30. - SA: Security Association https://en.wikipedia.org/wiki/IPsec#Security_association
  31. Developer documentation for Linux IPsec is rather sparse online. The following
  32. slide deck provides a decent overview.
  33. https://libreswan.org/wiki/images/e/e0/Netdev-0x12-ipsec-flow.pdf
  34. The Linux IPsec stack is part of XFRM, the netlink packet transformation
  35. interface.
  36. https://man7.org/linux/man-pages/man8/ip-xfrm.8.html
  37. */
  38. const (
  39. // Value used to mark outgoing packets which should have our IPsec
  40. // processing applied. It is also used as a label to identify XFRM
  41. // states (Security Associations) and policies (Security Policies)
  42. // programmed by us so we know which ones we can clean up without
  43. // disrupting other VPN connections on the system.
  44. mark = 0xD0C4E3
  45. pktExpansion = 26 // SPI(4) + SeqN(4) + IV(8) + PadLength(1) + NextHeader(1) + ICV(8)
  46. )
  47. const (
  48. forward = iota + 1
  49. reverse
  50. bidir
  51. )
  52. // Mark value for matching packets which should have our IPsec security policy
  53. // applied.
  54. var spMark = netlink.XfrmMark{Value: mark, Mask: 0xffffffff}
  55. type key struct {
  56. value []byte
  57. tag uint32
  58. }
  59. func (k *key) String() string {
  60. if k != nil {
  61. return fmt.Sprintf("(key: %s, tag: 0x%x)", hex.EncodeToString(k.value)[0:5], k.tag)
  62. }
  63. return ""
  64. }
  65. // Security Parameter Indices for the IPsec flows between local node and a
  66. // remote peer, which identify the Security Associations (XFRM states) to be
  67. // applied when encrypting and decrypting packets.
  68. type spi struct {
  69. forward int
  70. reverse int
  71. }
  72. func (s *spi) String() string {
  73. return fmt.Sprintf("SPI(FWD: 0x%x, REV: 0x%x)", uint32(s.forward), uint32(s.reverse))
  74. }
  75. type encrMap struct {
  76. nodes map[string][]*spi
  77. sync.Mutex
  78. }
  79. func (e *encrMap) String() string {
  80. e.Lock()
  81. defer e.Unlock()
  82. b := new(bytes.Buffer)
  83. for k, v := range e.nodes {
  84. b.WriteString("\n")
  85. b.WriteString(k)
  86. b.WriteString(":")
  87. b.WriteString("[")
  88. for _, s := range v {
  89. b.WriteString(s.String())
  90. b.WriteString(",")
  91. }
  92. b.WriteString("]")
  93. }
  94. return b.String()
  95. }
  96. func (d *driver) checkEncryption(nid string, rIP net.IP, isLocal, add bool) error {
  97. logrus.Debugf("checkEncryption(%.7s, %v, %t)", nid, rIP, isLocal)
  98. n := d.network(nid)
  99. if n == nil || !n.secure {
  100. return nil
  101. }
  102. if len(d.keys) == 0 {
  103. return types.ForbiddenErrorf("encryption key is not present")
  104. }
  105. lIP := net.ParseIP(d.bindAddress)
  106. aIP := net.ParseIP(d.advertiseAddress)
  107. nodes := map[string]net.IP{}
  108. switch {
  109. case isLocal:
  110. if err := d.peerDbNetworkWalk(nid, func(pKey *peerKey, pEntry *peerEntry) bool {
  111. if !aIP.Equal(pEntry.vtep) {
  112. nodes[pEntry.vtep.String()] = pEntry.vtep
  113. }
  114. return false
  115. }); err != nil {
  116. logrus.Warnf("Failed to retrieve list of participating nodes in overlay network %.5s: %v", nid, err)
  117. }
  118. default:
  119. if len(d.network(nid).endpoints) > 0 {
  120. nodes[rIP.String()] = rIP
  121. }
  122. }
  123. logrus.Debugf("List of nodes: %s", nodes)
  124. if add {
  125. for _, rIP := range nodes {
  126. if err := setupEncryption(lIP, aIP, rIP, d.secMap, d.keys); err != nil {
  127. logrus.Warnf("Failed to program network encryption between %s and %s: %v", lIP, rIP, err)
  128. }
  129. }
  130. } else {
  131. if len(nodes) == 0 {
  132. if err := removeEncryption(lIP, rIP, d.secMap); err != nil {
  133. logrus.Warnf("Failed to remove network encryption between %s and %s: %v", lIP, rIP, err)
  134. }
  135. }
  136. }
  137. return nil
  138. }
  139. // setupEncryption programs the encryption parameters for secure communication
  140. // between the local node and a remote node.
  141. func setupEncryption(localIP, advIP, remoteIP net.IP, em *encrMap, keys []*key) error {
  142. logrus.Debugf("Programming encryption between %s and %s", localIP, remoteIP)
  143. rIPs := remoteIP.String()
  144. indices := make([]*spi, 0, len(keys))
  145. for i, k := range keys {
  146. spis := &spi{buildSPI(advIP, remoteIP, k.tag), buildSPI(remoteIP, advIP, k.tag)}
  147. dir := reverse
  148. if i == 0 {
  149. dir = bidir
  150. }
  151. fSA, rSA, err := programSA(localIP, remoteIP, spis, k, dir, true)
  152. if err != nil {
  153. logrus.Warn(err)
  154. }
  155. indices = append(indices, spis)
  156. if i != 0 {
  157. continue
  158. }
  159. err = programSP(fSA, rSA, true)
  160. if err != nil {
  161. logrus.Warn(err)
  162. }
  163. }
  164. em.Lock()
  165. em.nodes[rIPs] = indices
  166. em.Unlock()
  167. return nil
  168. }
  169. func removeEncryption(localIP, remoteIP net.IP, em *encrMap) error {
  170. em.Lock()
  171. indices, ok := em.nodes[remoteIP.String()]
  172. em.Unlock()
  173. if !ok {
  174. return nil
  175. }
  176. for i, idxs := range indices {
  177. dir := reverse
  178. if i == 0 {
  179. dir = bidir
  180. }
  181. fSA, rSA, err := programSA(localIP, remoteIP, idxs, nil, dir, false)
  182. if err != nil {
  183. logrus.Warn(err)
  184. }
  185. if i != 0 {
  186. continue
  187. }
  188. err = programSP(fSA, rSA, false)
  189. if err != nil {
  190. logrus.Warn(err)
  191. }
  192. }
  193. return nil
  194. }
  195. type matchVXLANFunc func(port, vni uint32) []string
  196. // programVXLANRuleFunc returns a function which tries calling programWithMatch
  197. // with the u32 match, falling back to the BPF match if installing u32 variant
  198. // of the rules fails.
  199. func programVXLANRuleFunc(programWithMatch func(matchVXLAN matchVXLANFunc, vni uint32, add bool) error) func(vni uint32, add bool) error {
  200. return func(vni uint32, add bool) error {
  201. if add {
  202. if err := programWithMatch(matchVXLANWithU32, vni, add); err != nil {
  203. // That didn't work. Maybe the xt_u32 module isn't available? Try again with xt_bpf.
  204. err2 := programWithMatch(matchVXLANWithBPF, vni, add)
  205. if err2 != nil {
  206. return multierror.Append(err, err2)
  207. }
  208. }
  209. return nil
  210. } else {
  211. // Delete both flavours.
  212. err := programWithMatch(matchVXLANWithU32, vni, add)
  213. return multierror.Append(err, programWithMatch(matchVXLANWithBPF, vni, add)).ErrorOrNil()
  214. }
  215. }
  216. }
  217. var programMangle = programVXLANRuleFunc(func(matchVXLAN matchVXLANFunc, vni uint32, add bool) error {
  218. var (
  219. m = strconv.FormatUint(mark, 10)
  220. chain = "OUTPUT"
  221. rule = append(matchVXLAN(overlayutils.VXLANUDPPort(), vni), "-j", "MARK", "--set-mark", m)
  222. a = iptables.Append
  223. action = "install"
  224. )
  225. // TODO IPv6 support
  226. iptable := iptables.GetIptable(iptables.IPv4)
  227. if !add {
  228. a = iptables.Delete
  229. action = "remove"
  230. }
  231. if err := iptable.ProgramRule(iptables.Mangle, chain, a, rule); err != nil {
  232. return fmt.Errorf("could not %s mangle rule: %w", action, err)
  233. }
  234. return nil
  235. })
  236. var programInput = programVXLANRuleFunc(func(matchVXLAN matchVXLANFunc, vni uint32, add bool) error {
  237. var (
  238. plainVxlan = matchVXLAN(overlayutils.VXLANUDPPort(), vni)
  239. chain = "INPUT"
  240. msg = "add"
  241. )
  242. rule := func(policy, jump string) []string {
  243. args := append([]string{"-m", "policy", "--dir", "in", "--pol", policy}, plainVxlan...)
  244. return append(args, "-j", jump)
  245. }
  246. // TODO IPv6 support
  247. iptable := iptables.GetIptable(iptables.IPv4)
  248. if !add {
  249. msg = "remove"
  250. }
  251. action := func(a iptables.Action) iptables.Action {
  252. if !add {
  253. return iptables.Delete
  254. }
  255. return a
  256. }
  257. // Accept incoming VXLAN datagrams for the VNI which were subjected to IPSec processing.
  258. // Append to the bottom of the chain to give administrator-configured rules precedence.
  259. if err := iptable.ProgramRule(iptables.Filter, chain, action(iptables.Append), rule("ipsec", "ACCEPT")); err != nil {
  260. return fmt.Errorf("could not %s input accept rule: %w", msg, err)
  261. }
  262. // Drop incoming VXLAN datagrams for the VNI which were received in cleartext.
  263. // Insert at the top of the chain so the packets are dropped even if an
  264. // administrator-configured rule exists which would otherwise unconditionally
  265. // accept incoming VXLAN traffic.
  266. if err := iptable.ProgramRule(iptables.Filter, chain, action(iptables.Insert), rule("none", "DROP")); err != nil {
  267. return fmt.Errorf("could not %s input drop rule: %w", msg, err)
  268. }
  269. return nil
  270. })
  271. func programSA(localIP, remoteIP net.IP, spi *spi, k *key, dir int, add bool) (fSA *netlink.XfrmState, rSA *netlink.XfrmState, err error) {
  272. var (
  273. action = "Removing"
  274. xfrmProgram = ns.NlHandle().XfrmStateDel
  275. )
  276. if add {
  277. action = "Adding"
  278. xfrmProgram = ns.NlHandle().XfrmStateAdd
  279. }
  280. if dir&reverse > 0 {
  281. rSA = &netlink.XfrmState{
  282. Src: remoteIP,
  283. Dst: localIP,
  284. Proto: netlink.XFRM_PROTO_ESP,
  285. Spi: spi.reverse,
  286. Mode: netlink.XFRM_MODE_TRANSPORT,
  287. Reqid: mark,
  288. }
  289. if add {
  290. rSA.Aead = buildAeadAlgo(k, spi.reverse)
  291. }
  292. exists, err := saExists(rSA)
  293. if err != nil {
  294. exists = !add
  295. }
  296. if add != exists {
  297. logrus.Debugf("%s: rSA{%s}", action, rSA)
  298. if err := xfrmProgram(rSA); err != nil {
  299. logrus.Warnf("Failed %s rSA{%s}: %v", action, rSA, err)
  300. }
  301. }
  302. }
  303. if dir&forward > 0 {
  304. fSA = &netlink.XfrmState{
  305. Src: localIP,
  306. Dst: remoteIP,
  307. Proto: netlink.XFRM_PROTO_ESP,
  308. Spi: spi.forward,
  309. Mode: netlink.XFRM_MODE_TRANSPORT,
  310. Reqid: mark,
  311. }
  312. if add {
  313. fSA.Aead = buildAeadAlgo(k, spi.forward)
  314. }
  315. exists, err := saExists(fSA)
  316. if err != nil {
  317. exists = !add
  318. }
  319. if add != exists {
  320. logrus.Debugf("%s fSA{%s}", action, fSA)
  321. if err := xfrmProgram(fSA); err != nil {
  322. logrus.Warnf("Failed %s fSA{%s}: %v.", action, fSA, err)
  323. }
  324. }
  325. }
  326. return
  327. }
  328. func programSP(fSA *netlink.XfrmState, rSA *netlink.XfrmState, add bool) error {
  329. action := "Removing"
  330. xfrmProgram := ns.NlHandle().XfrmPolicyDel
  331. if add {
  332. action = "Adding"
  333. xfrmProgram = ns.NlHandle().XfrmPolicyAdd
  334. }
  335. // Create a congruent cidr
  336. s := types.GetMinimalIP(fSA.Src)
  337. d := types.GetMinimalIP(fSA.Dst)
  338. fullMask := net.CIDRMask(8*len(s), 8*len(s))
  339. fPol := &netlink.XfrmPolicy{
  340. Src: &net.IPNet{IP: s, Mask: fullMask},
  341. Dst: &net.IPNet{IP: d, Mask: fullMask},
  342. Dir: netlink.XFRM_DIR_OUT,
  343. Proto: 17,
  344. DstPort: 4789,
  345. Mark: &spMark,
  346. Tmpls: []netlink.XfrmPolicyTmpl{
  347. {
  348. Src: fSA.Src,
  349. Dst: fSA.Dst,
  350. Proto: netlink.XFRM_PROTO_ESP,
  351. Mode: netlink.XFRM_MODE_TRANSPORT,
  352. Spi: fSA.Spi,
  353. Reqid: mark,
  354. },
  355. },
  356. }
  357. exists, err := spExists(fPol)
  358. if err != nil {
  359. exists = !add
  360. }
  361. if add != exists {
  362. logrus.Debugf("%s fSP{%s}", action, fPol)
  363. if err := xfrmProgram(fPol); err != nil {
  364. logrus.Warnf("%s fSP{%s}: %v", action, fPol, err)
  365. }
  366. }
  367. return nil
  368. }
  369. func saExists(sa *netlink.XfrmState) (bool, error) {
  370. _, err := ns.NlHandle().XfrmStateGet(sa)
  371. switch err {
  372. case nil:
  373. return true, nil
  374. case syscall.ESRCH:
  375. return false, nil
  376. default:
  377. err = fmt.Errorf("Error while checking for SA existence: %v", err)
  378. logrus.Warn(err)
  379. return false, err
  380. }
  381. }
  382. func spExists(sp *netlink.XfrmPolicy) (bool, error) {
  383. _, err := ns.NlHandle().XfrmPolicyGet(sp)
  384. switch err {
  385. case nil:
  386. return true, nil
  387. case syscall.ENOENT:
  388. return false, nil
  389. default:
  390. err = fmt.Errorf("Error while checking for SP existence: %v", err)
  391. logrus.Warn(err)
  392. return false, err
  393. }
  394. }
  395. func buildSPI(src, dst net.IP, st uint32) int {
  396. b := make([]byte, 4)
  397. binary.BigEndian.PutUint32(b, st)
  398. h := fnv.New32a()
  399. h.Write(src)
  400. h.Write(b)
  401. h.Write(dst)
  402. return int(binary.BigEndian.Uint32(h.Sum(nil)))
  403. }
  404. func buildAeadAlgo(k *key, s int) *netlink.XfrmStateAlgo {
  405. salt := make([]byte, 4)
  406. binary.BigEndian.PutUint32(salt, uint32(s))
  407. return &netlink.XfrmStateAlgo{
  408. Name: "rfc4106(gcm(aes))",
  409. Key: append(k.value, salt...),
  410. ICVLen: 64,
  411. }
  412. }
  413. func (d *driver) secMapWalk(f func(string, []*spi) ([]*spi, bool)) error {
  414. d.secMap.Lock()
  415. for node, indices := range d.secMap.nodes {
  416. idxs, stop := f(node, indices)
  417. if idxs != nil {
  418. d.secMap.nodes[node] = idxs
  419. }
  420. if stop {
  421. break
  422. }
  423. }
  424. d.secMap.Unlock()
  425. return nil
  426. }
  427. func (d *driver) setKeys(keys []*key) error {
  428. // Remove any stale policy, state
  429. clearEncryptionStates()
  430. // Accept the encryption keys and clear any stale encryption map
  431. d.Lock()
  432. d.keys = keys
  433. d.secMap = &encrMap{nodes: map[string][]*spi{}}
  434. d.Unlock()
  435. logrus.Debugf("Initial encryption keys: %v", keys)
  436. return nil
  437. }
  438. // updateKeys allows to add a new key and/or change the primary key and/or prune an existing key
  439. // The primary key is the key used in transmission and will go in first position in the list.
  440. func (d *driver) updateKeys(newKey, primary, pruneKey *key) error {
  441. logrus.Debugf("Updating Keys. New: %v, Primary: %v, Pruned: %v", newKey, primary, pruneKey)
  442. logrus.Debugf("Current: %v", d.keys)
  443. var (
  444. newIdx = -1
  445. priIdx = -1
  446. delIdx = -1
  447. lIP = net.ParseIP(d.bindAddress)
  448. aIP = net.ParseIP(d.advertiseAddress)
  449. )
  450. d.Lock()
  451. defer d.Unlock()
  452. // add new
  453. if newKey != nil {
  454. d.keys = append(d.keys, newKey)
  455. newIdx += len(d.keys)
  456. }
  457. for i, k := range d.keys {
  458. if primary != nil && k.tag == primary.tag {
  459. priIdx = i
  460. }
  461. if pruneKey != nil && k.tag == pruneKey.tag {
  462. delIdx = i
  463. }
  464. }
  465. if (newKey != nil && newIdx == -1) ||
  466. (primary != nil && priIdx == -1) ||
  467. (pruneKey != nil && delIdx == -1) {
  468. return types.BadRequestErrorf("cannot find proper key indices while processing key update:"+
  469. "(newIdx,priIdx,delIdx):(%d, %d, %d)", newIdx, priIdx, delIdx)
  470. }
  471. if priIdx != -1 && priIdx == delIdx {
  472. return types.BadRequestErrorf("attempting to both make a key (index %d) primary and delete it", priIdx)
  473. }
  474. d.secMapWalk(func(rIPs string, spis []*spi) ([]*spi, bool) {
  475. rIP := net.ParseIP(rIPs)
  476. return updateNodeKey(lIP, aIP, rIP, spis, d.keys, newIdx, priIdx, delIdx), false
  477. })
  478. // swap primary
  479. if priIdx != -1 {
  480. d.keys[0], d.keys[priIdx] = d.keys[priIdx], d.keys[0]
  481. }
  482. // prune
  483. if delIdx != -1 {
  484. if delIdx == 0 {
  485. delIdx = priIdx
  486. }
  487. d.keys = append(d.keys[:delIdx], d.keys[delIdx+1:]...)
  488. }
  489. logrus.Debugf("Updated: %v", d.keys)
  490. return nil
  491. }
  492. /********************************************************
  493. * Steady state: rSA0, rSA1, rSA2, fSA1, fSP1
  494. * Rotation --> -rSA0, +rSA3, +fSA2, +fSP2/-fSP1, -fSA1
  495. * Steady state: rSA1, rSA2, rSA3, fSA2, fSP2
  496. *********************************************************/
  497. // Spis and keys are sorted in such away the one in position 0 is the primary
  498. func updateNodeKey(lIP, aIP, rIP net.IP, idxs []*spi, curKeys []*key, newIdx, priIdx, delIdx int) []*spi {
  499. logrus.Debugf("Updating keys for node: %s (%d,%d,%d)", rIP, newIdx, priIdx, delIdx)
  500. spis := idxs
  501. logrus.Debugf("Current: %v", spis)
  502. // add new
  503. if newIdx != -1 {
  504. spis = append(spis, &spi{
  505. forward: buildSPI(aIP, rIP, curKeys[newIdx].tag),
  506. reverse: buildSPI(rIP, aIP, curKeys[newIdx].tag),
  507. })
  508. }
  509. if delIdx != -1 {
  510. // -rSA0
  511. programSA(lIP, rIP, spis[delIdx], nil, reverse, false)
  512. }
  513. if newIdx > -1 {
  514. // +rSA2
  515. programSA(lIP, rIP, spis[newIdx], curKeys[newIdx], reverse, true)
  516. }
  517. if priIdx > 0 {
  518. // +fSA2
  519. fSA2, _, _ := programSA(lIP, rIP, spis[priIdx], curKeys[priIdx], forward, true)
  520. // +fSP2, -fSP1
  521. s := types.GetMinimalIP(fSA2.Src)
  522. d := types.GetMinimalIP(fSA2.Dst)
  523. fullMask := net.CIDRMask(8*len(s), 8*len(s))
  524. fSP1 := &netlink.XfrmPolicy{
  525. Src: &net.IPNet{IP: s, Mask: fullMask},
  526. Dst: &net.IPNet{IP: d, Mask: fullMask},
  527. Dir: netlink.XFRM_DIR_OUT,
  528. Proto: 17,
  529. DstPort: 4789,
  530. Mark: &spMark,
  531. Tmpls: []netlink.XfrmPolicyTmpl{
  532. {
  533. Src: fSA2.Src,
  534. Dst: fSA2.Dst,
  535. Proto: netlink.XFRM_PROTO_ESP,
  536. Mode: netlink.XFRM_MODE_TRANSPORT,
  537. Spi: fSA2.Spi,
  538. Reqid: mark,
  539. },
  540. },
  541. }
  542. logrus.Debugf("Updating fSP{%s}", fSP1)
  543. if err := ns.NlHandle().XfrmPolicyUpdate(fSP1); err != nil {
  544. logrus.Warnf("Failed to update fSP{%s}: %v", fSP1, err)
  545. }
  546. // -fSA1
  547. programSA(lIP, rIP, spis[0], nil, forward, false)
  548. }
  549. // swap
  550. if priIdx > 0 {
  551. swp := spis[0]
  552. spis[0] = spis[priIdx]
  553. spis[priIdx] = swp
  554. }
  555. // prune
  556. if delIdx != -1 {
  557. if delIdx == 0 {
  558. delIdx = priIdx
  559. }
  560. spis = append(spis[:delIdx], spis[delIdx+1:]...)
  561. }
  562. logrus.Debugf("Updated: %v", spis)
  563. return spis
  564. }
  565. func (n *network) maxMTU() int {
  566. mtu := 1500
  567. if n.mtu != 0 {
  568. mtu = n.mtu
  569. }
  570. mtu -= vxlanEncap
  571. if n.secure {
  572. // In case of encryption account for the
  573. // esp packet expansion and padding
  574. mtu -= pktExpansion
  575. mtu -= (mtu % 4)
  576. }
  577. return mtu
  578. }
  579. func clearEncryptionStates() {
  580. nlh := ns.NlHandle()
  581. spList, err := nlh.XfrmPolicyList(netlink.FAMILY_ALL)
  582. if err != nil {
  583. logrus.Warnf("Failed to retrieve SP list for cleanup: %v", err)
  584. }
  585. saList, err := nlh.XfrmStateList(netlink.FAMILY_ALL)
  586. if err != nil {
  587. logrus.Warnf("Failed to retrieve SA list for cleanup: %v", err)
  588. }
  589. for _, sp := range spList {
  590. sp := sp
  591. if sp.Mark != nil && sp.Mark.Value == spMark.Value {
  592. if err := nlh.XfrmPolicyDel(&sp); err != nil {
  593. logrus.Warnf("Failed to delete stale SP %s: %v", sp, err)
  594. continue
  595. }
  596. logrus.Debugf("Removed stale SP: %s", sp)
  597. }
  598. }
  599. for _, sa := range saList {
  600. sa := sa
  601. if sa.Reqid == mark {
  602. if err := nlh.XfrmStateDel(&sa); err != nil {
  603. logrus.Warnf("Failed to delete stale SA %s: %v", sa, err)
  604. continue
  605. }
  606. logrus.Debugf("Removed stale SA: %s", sa)
  607. }
  608. }
  609. }