encryption.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693
  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. ipsecVxlan = append([]string{"-m", "policy", "--dir", "in", "--pol", "ipsec"}, plainVxlan...)
  240. block = append(plainVxlan, "-j", "DROP")
  241. accept = append(ipsecVxlan, "-j", "ACCEPT")
  242. chain = "INPUT"
  243. action = iptables.Append
  244. msg = "add"
  245. )
  246. // TODO IPv6 support
  247. iptable := iptables.GetIptable(iptables.IPv4)
  248. if !add {
  249. action = iptables.Delete
  250. msg = "remove"
  251. }
  252. // Accept incoming VXLAN datagrams for the VNI which were subjected to IPSec processing.
  253. if err := iptable.ProgramRule(iptables.Filter, chain, action, accept); err != nil {
  254. return fmt.Errorf("could not %s input accept rule: %w", msg, err)
  255. }
  256. // Drop incoming VXLAN datagrams for the VNI which were received in cleartext.
  257. if err := iptable.ProgramRule(iptables.Filter, chain, action, block); err != nil {
  258. return fmt.Errorf("could not %s input drop rule: %w", msg, err)
  259. }
  260. return nil
  261. })
  262. func programSA(localIP, remoteIP net.IP, spi *spi, k *key, dir int, add bool) (fSA *netlink.XfrmState, rSA *netlink.XfrmState, err error) {
  263. var (
  264. action = "Removing"
  265. xfrmProgram = ns.NlHandle().XfrmStateDel
  266. )
  267. if add {
  268. action = "Adding"
  269. xfrmProgram = ns.NlHandle().XfrmStateAdd
  270. }
  271. if dir&reverse > 0 {
  272. rSA = &netlink.XfrmState{
  273. Src: remoteIP,
  274. Dst: localIP,
  275. Proto: netlink.XFRM_PROTO_ESP,
  276. Spi: spi.reverse,
  277. Mode: netlink.XFRM_MODE_TRANSPORT,
  278. Reqid: mark,
  279. }
  280. if add {
  281. rSA.Aead = buildAeadAlgo(k, spi.reverse)
  282. }
  283. exists, err := saExists(rSA)
  284. if err != nil {
  285. exists = !add
  286. }
  287. if add != exists {
  288. logrus.Debugf("%s: rSA{%s}", action, rSA)
  289. if err := xfrmProgram(rSA); err != nil {
  290. logrus.Warnf("Failed %s rSA{%s}: %v", action, rSA, err)
  291. }
  292. }
  293. }
  294. if dir&forward > 0 {
  295. fSA = &netlink.XfrmState{
  296. Src: localIP,
  297. Dst: remoteIP,
  298. Proto: netlink.XFRM_PROTO_ESP,
  299. Spi: spi.forward,
  300. Mode: netlink.XFRM_MODE_TRANSPORT,
  301. Reqid: mark,
  302. }
  303. if add {
  304. fSA.Aead = buildAeadAlgo(k, spi.forward)
  305. }
  306. exists, err := saExists(fSA)
  307. if err != nil {
  308. exists = !add
  309. }
  310. if add != exists {
  311. logrus.Debugf("%s fSA{%s}", action, fSA)
  312. if err := xfrmProgram(fSA); err != nil {
  313. logrus.Warnf("Failed %s fSA{%s}: %v.", action, fSA, err)
  314. }
  315. }
  316. }
  317. return
  318. }
  319. func programSP(fSA *netlink.XfrmState, rSA *netlink.XfrmState, add bool) error {
  320. action := "Removing"
  321. xfrmProgram := ns.NlHandle().XfrmPolicyDel
  322. if add {
  323. action = "Adding"
  324. xfrmProgram = ns.NlHandle().XfrmPolicyAdd
  325. }
  326. // Create a congruent cidr
  327. s := types.GetMinimalIP(fSA.Src)
  328. d := types.GetMinimalIP(fSA.Dst)
  329. fullMask := net.CIDRMask(8*len(s), 8*len(s))
  330. fPol := &netlink.XfrmPolicy{
  331. Src: &net.IPNet{IP: s, Mask: fullMask},
  332. Dst: &net.IPNet{IP: d, Mask: fullMask},
  333. Dir: netlink.XFRM_DIR_OUT,
  334. Proto: 17,
  335. DstPort: 4789,
  336. Mark: &spMark,
  337. Tmpls: []netlink.XfrmPolicyTmpl{
  338. {
  339. Src: fSA.Src,
  340. Dst: fSA.Dst,
  341. Proto: netlink.XFRM_PROTO_ESP,
  342. Mode: netlink.XFRM_MODE_TRANSPORT,
  343. Spi: fSA.Spi,
  344. Reqid: mark,
  345. },
  346. },
  347. }
  348. exists, err := spExists(fPol)
  349. if err != nil {
  350. exists = !add
  351. }
  352. if add != exists {
  353. logrus.Debugf("%s fSP{%s}", action, fPol)
  354. if err := xfrmProgram(fPol); err != nil {
  355. logrus.Warnf("%s fSP{%s}: %v", action, fPol, err)
  356. }
  357. }
  358. return nil
  359. }
  360. func saExists(sa *netlink.XfrmState) (bool, error) {
  361. _, err := ns.NlHandle().XfrmStateGet(sa)
  362. switch err {
  363. case nil:
  364. return true, nil
  365. case syscall.ESRCH:
  366. return false, nil
  367. default:
  368. err = fmt.Errorf("Error while checking for SA existence: %v", err)
  369. logrus.Warn(err)
  370. return false, err
  371. }
  372. }
  373. func spExists(sp *netlink.XfrmPolicy) (bool, error) {
  374. _, err := ns.NlHandle().XfrmPolicyGet(sp)
  375. switch err {
  376. case nil:
  377. return true, nil
  378. case syscall.ENOENT:
  379. return false, nil
  380. default:
  381. err = fmt.Errorf("Error while checking for SP existence: %v", err)
  382. logrus.Warn(err)
  383. return false, err
  384. }
  385. }
  386. func buildSPI(src, dst net.IP, st uint32) int {
  387. b := make([]byte, 4)
  388. binary.BigEndian.PutUint32(b, st)
  389. h := fnv.New32a()
  390. h.Write(src)
  391. h.Write(b)
  392. h.Write(dst)
  393. return int(binary.BigEndian.Uint32(h.Sum(nil)))
  394. }
  395. func buildAeadAlgo(k *key, s int) *netlink.XfrmStateAlgo {
  396. salt := make([]byte, 4)
  397. binary.BigEndian.PutUint32(salt, uint32(s))
  398. return &netlink.XfrmStateAlgo{
  399. Name: "rfc4106(gcm(aes))",
  400. Key: append(k.value, salt...),
  401. ICVLen: 64,
  402. }
  403. }
  404. func (d *driver) secMapWalk(f func(string, []*spi) ([]*spi, bool)) error {
  405. d.secMap.Lock()
  406. for node, indices := range d.secMap.nodes {
  407. idxs, stop := f(node, indices)
  408. if idxs != nil {
  409. d.secMap.nodes[node] = idxs
  410. }
  411. if stop {
  412. break
  413. }
  414. }
  415. d.secMap.Unlock()
  416. return nil
  417. }
  418. func (d *driver) setKeys(keys []*key) error {
  419. // Remove any stale policy, state
  420. clearEncryptionStates()
  421. // Accept the encryption keys and clear any stale encryption map
  422. d.Lock()
  423. d.keys = keys
  424. d.secMap = &encrMap{nodes: map[string][]*spi{}}
  425. d.Unlock()
  426. logrus.Debugf("Initial encryption keys: %v", keys)
  427. return nil
  428. }
  429. // updateKeys allows to add a new key and/or change the primary key and/or prune an existing key
  430. // The primary key is the key used in transmission and will go in first position in the list.
  431. func (d *driver) updateKeys(newKey, primary, pruneKey *key) error {
  432. logrus.Debugf("Updating Keys. New: %v, Primary: %v, Pruned: %v", newKey, primary, pruneKey)
  433. logrus.Debugf("Current: %v", d.keys)
  434. var (
  435. newIdx = -1
  436. priIdx = -1
  437. delIdx = -1
  438. lIP = net.ParseIP(d.bindAddress)
  439. aIP = net.ParseIP(d.advertiseAddress)
  440. )
  441. d.Lock()
  442. defer d.Unlock()
  443. // add new
  444. if newKey != nil {
  445. d.keys = append(d.keys, newKey)
  446. newIdx += len(d.keys)
  447. }
  448. for i, k := range d.keys {
  449. if primary != nil && k.tag == primary.tag {
  450. priIdx = i
  451. }
  452. if pruneKey != nil && k.tag == pruneKey.tag {
  453. delIdx = i
  454. }
  455. }
  456. if (newKey != nil && newIdx == -1) ||
  457. (primary != nil && priIdx == -1) ||
  458. (pruneKey != nil && delIdx == -1) {
  459. return types.BadRequestErrorf("cannot find proper key indices while processing key update:"+
  460. "(newIdx,priIdx,delIdx):(%d, %d, %d)", newIdx, priIdx, delIdx)
  461. }
  462. if priIdx != -1 && priIdx == delIdx {
  463. return types.BadRequestErrorf("attempting to both make a key (index %d) primary and delete it", priIdx)
  464. }
  465. d.secMapWalk(func(rIPs string, spis []*spi) ([]*spi, bool) {
  466. rIP := net.ParseIP(rIPs)
  467. return updateNodeKey(lIP, aIP, rIP, spis, d.keys, newIdx, priIdx, delIdx), false
  468. })
  469. // swap primary
  470. if priIdx != -1 {
  471. d.keys[0], d.keys[priIdx] = d.keys[priIdx], d.keys[0]
  472. }
  473. // prune
  474. if delIdx != -1 {
  475. if delIdx == 0 {
  476. delIdx = priIdx
  477. }
  478. d.keys = append(d.keys[:delIdx], d.keys[delIdx+1:]...)
  479. }
  480. logrus.Debugf("Updated: %v", d.keys)
  481. return nil
  482. }
  483. /********************************************************
  484. * Steady state: rSA0, rSA1, rSA2, fSA1, fSP1
  485. * Rotation --> -rSA0, +rSA3, +fSA2, +fSP2/-fSP1, -fSA1
  486. * Steady state: rSA1, rSA2, rSA3, fSA2, fSP2
  487. *********************************************************/
  488. // Spis and keys are sorted in such away the one in position 0 is the primary
  489. func updateNodeKey(lIP, aIP, rIP net.IP, idxs []*spi, curKeys []*key, newIdx, priIdx, delIdx int) []*spi {
  490. logrus.Debugf("Updating keys for node: %s (%d,%d,%d)", rIP, newIdx, priIdx, delIdx)
  491. spis := idxs
  492. logrus.Debugf("Current: %v", spis)
  493. // add new
  494. if newIdx != -1 {
  495. spis = append(spis, &spi{
  496. forward: buildSPI(aIP, rIP, curKeys[newIdx].tag),
  497. reverse: buildSPI(rIP, aIP, curKeys[newIdx].tag),
  498. })
  499. }
  500. if delIdx != -1 {
  501. // -rSA0
  502. programSA(lIP, rIP, spis[delIdx], nil, reverse, false)
  503. }
  504. if newIdx > -1 {
  505. // +rSA2
  506. programSA(lIP, rIP, spis[newIdx], curKeys[newIdx], reverse, true)
  507. }
  508. if priIdx > 0 {
  509. // +fSA2
  510. fSA2, _, _ := programSA(lIP, rIP, spis[priIdx], curKeys[priIdx], forward, true)
  511. // +fSP2, -fSP1
  512. s := types.GetMinimalIP(fSA2.Src)
  513. d := types.GetMinimalIP(fSA2.Dst)
  514. fullMask := net.CIDRMask(8*len(s), 8*len(s))
  515. fSP1 := &netlink.XfrmPolicy{
  516. Src: &net.IPNet{IP: s, Mask: fullMask},
  517. Dst: &net.IPNet{IP: d, Mask: fullMask},
  518. Dir: netlink.XFRM_DIR_OUT,
  519. Proto: 17,
  520. DstPort: 4789,
  521. Mark: &spMark,
  522. Tmpls: []netlink.XfrmPolicyTmpl{
  523. {
  524. Src: fSA2.Src,
  525. Dst: fSA2.Dst,
  526. Proto: netlink.XFRM_PROTO_ESP,
  527. Mode: netlink.XFRM_MODE_TRANSPORT,
  528. Spi: fSA2.Spi,
  529. Reqid: mark,
  530. },
  531. },
  532. }
  533. logrus.Debugf("Updating fSP{%s}", fSP1)
  534. if err := ns.NlHandle().XfrmPolicyUpdate(fSP1); err != nil {
  535. logrus.Warnf("Failed to update fSP{%s}: %v", fSP1, err)
  536. }
  537. // -fSA1
  538. programSA(lIP, rIP, spis[0], nil, forward, false)
  539. }
  540. // swap
  541. if priIdx > 0 {
  542. swp := spis[0]
  543. spis[0] = spis[priIdx]
  544. spis[priIdx] = swp
  545. }
  546. // prune
  547. if delIdx != -1 {
  548. if delIdx == 0 {
  549. delIdx = priIdx
  550. }
  551. spis = append(spis[:delIdx], spis[delIdx+1:]...)
  552. }
  553. logrus.Debugf("Updated: %v", spis)
  554. return spis
  555. }
  556. func (n *network) maxMTU() int {
  557. mtu := 1500
  558. if n.mtu != 0 {
  559. mtu = n.mtu
  560. }
  561. mtu -= vxlanEncap
  562. if n.secure {
  563. // In case of encryption account for the
  564. // esp packet expansion and padding
  565. mtu -= pktExpansion
  566. mtu -= (mtu % 4)
  567. }
  568. return mtu
  569. }
  570. func clearEncryptionStates() {
  571. nlh := ns.NlHandle()
  572. spList, err := nlh.XfrmPolicyList(netlink.FAMILY_ALL)
  573. if err != nil {
  574. logrus.Warnf("Failed to retrieve SP list for cleanup: %v", err)
  575. }
  576. saList, err := nlh.XfrmStateList(netlink.FAMILY_ALL)
  577. if err != nil {
  578. logrus.Warnf("Failed to retrieve SA list for cleanup: %v", err)
  579. }
  580. for _, sp := range spList {
  581. sp := sp
  582. if sp.Mark != nil && sp.Mark.Value == spMark.Value {
  583. if err := nlh.XfrmPolicyDel(&sp); err != nil {
  584. logrus.Warnf("Failed to delete stale SP %s: %v", sp, err)
  585. continue
  586. }
  587. logrus.Debugf("Removed stale SP: %s", sp)
  588. }
  589. }
  590. for _, sa := range saList {
  591. sa := sa
  592. if sa.Reqid == mark {
  593. if err := nlh.XfrmStateDel(&sa); err != nil {
  594. logrus.Warnf("Failed to delete stale SA %s: %v", sa, err)
  595. continue
  596. }
  597. logrus.Debugf("Removed stale SA: %s", sa)
  598. }
  599. }
  600. }