connection_manager.go 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635
  1. package nebula
  2. import (
  3. "bytes"
  4. "context"
  5. "encoding/binary"
  6. "fmt"
  7. "log/slog"
  8. "net/netip"
  9. "sync"
  10. "sync/atomic"
  11. "time"
  12. "github.com/slackhq/nebula/cert"
  13. "github.com/slackhq/nebula/config"
  14. "github.com/slackhq/nebula/header"
  15. )
  16. type trafficDecision int
  17. const (
  18. doNothing trafficDecision = 0
  19. deleteTunnel trafficDecision = 1 // delete the hostinfo on our side, do not notify the remote
  20. closeTunnel trafficDecision = 2 // delete the hostinfo and notify the remote
  21. swapPrimary trafficDecision = 3
  22. migrateRelays trafficDecision = 4
  23. tryRehandshake trafficDecision = 5
  24. sendTestPacket trafficDecision = 6
  25. )
  26. type connectionManager struct {
  27. // relayUsed holds which relay localIndexs are in use
  28. relayUsed map[uint32]struct{}
  29. relayUsedLock *sync.RWMutex
  30. hostMap *HostMap
  31. trafficTimer *LockingTimerWheel[uint32]
  32. intf *Interface
  33. punchy *Punchy
  34. // Configuration settings
  35. checkInterval time.Duration
  36. pendingDeletionInterval time.Duration
  37. inactivityTimeout atomic.Int64
  38. dropInactive atomic.Bool
  39. l *slog.Logger
  40. }
  41. func newConnectionManagerFromConfig(l *slog.Logger, c *config.C, hm *HostMap, p *Punchy) *connectionManager {
  42. cm := &connectionManager{
  43. hostMap: hm,
  44. l: l,
  45. punchy: p,
  46. relayUsed: make(map[uint32]struct{}),
  47. relayUsedLock: &sync.RWMutex{},
  48. }
  49. cm.reload(c, true)
  50. c.RegisterReloadCallback(func(c *config.C) {
  51. cm.reload(c, false)
  52. })
  53. return cm
  54. }
  55. func (cm *connectionManager) reload(c *config.C, initial bool) {
  56. if initial {
  57. cm.checkInterval = time.Duration(c.GetInt("timers.connection_alive_interval", 5)) * time.Second
  58. cm.pendingDeletionInterval = time.Duration(c.GetInt("timers.pending_deletion_interval", 10)) * time.Second
  59. // We want at least a minimum resolution of 500ms per tick so that we can hit these intervals
  60. // pretty close to their configured duration.
  61. // The inactivity duration is checked each time a hostinfo ticks through so we don't need the wheel to contain it.
  62. minDuration := min(time.Millisecond*500, cm.checkInterval, cm.pendingDeletionInterval)
  63. maxDuration := max(cm.checkInterval, cm.pendingDeletionInterval)
  64. cm.trafficTimer = NewLockingTimerWheel[uint32](minDuration, maxDuration)
  65. }
  66. if initial || c.HasChanged("tunnels.inactivity_timeout") {
  67. old := cm.getInactivityTimeout()
  68. cm.inactivityTimeout.Store((int64)(c.GetDuration("tunnels.inactivity_timeout", 10*time.Minute)))
  69. if !initial {
  70. cm.l.Info("Inactivity timeout has changed",
  71. "oldDuration", old,
  72. "newDuration", cm.getInactivityTimeout(),
  73. )
  74. }
  75. }
  76. if initial || c.HasChanged("tunnels.drop_inactive") {
  77. old := cm.dropInactive.Load()
  78. cm.dropInactive.Store(c.GetBool("tunnels.drop_inactive", false))
  79. if !initial {
  80. cm.l.Info("Drop inactive setting has changed",
  81. "oldBool", old,
  82. "newBool", cm.dropInactive.Load(),
  83. )
  84. }
  85. }
  86. }
  87. func (cm *connectionManager) getInactivityTimeout() time.Duration {
  88. return (time.Duration)(cm.inactivityTimeout.Load())
  89. }
  90. func (cm *connectionManager) In(h *HostInfo) {
  91. h.in.Store(true)
  92. }
  93. func (cm *connectionManager) Out(h *HostInfo) {
  94. h.out.Store(true)
  95. }
  96. func (cm *connectionManager) RelayUsed(localIndex uint32) {
  97. cm.relayUsedLock.RLock()
  98. // If this already exists, return
  99. if _, ok := cm.relayUsed[localIndex]; ok {
  100. cm.relayUsedLock.RUnlock()
  101. return
  102. }
  103. cm.relayUsedLock.RUnlock()
  104. cm.relayUsedLock.Lock()
  105. cm.relayUsed[localIndex] = struct{}{}
  106. cm.relayUsedLock.Unlock()
  107. }
  108. // getAndResetTrafficCheck returns if there was any inbound or outbound traffic within the last tick and
  109. // resets the state for this local index
  110. func (cm *connectionManager) getAndResetTrafficCheck(h *HostInfo, now time.Time) (bool, bool) {
  111. in := h.in.Swap(false)
  112. out := h.out.Swap(false)
  113. if in || out {
  114. h.lastUsed = now
  115. }
  116. return in, out
  117. }
  118. func (cm *connectionManager) Start(ctx context.Context) {
  119. clockSource := time.NewTicker(cm.trafficTimer.t.tickDuration)
  120. defer clockSource.Stop()
  121. p := []byte("")
  122. nb := make([]byte, 12, 12)
  123. out := make([]byte, mtu)
  124. for {
  125. select {
  126. case <-ctx.Done():
  127. return
  128. case now := <-clockSource.C:
  129. cm.trafficTimer.Advance(now)
  130. for {
  131. localIndex, has := cm.trafficTimer.Purge()
  132. if !has {
  133. break
  134. }
  135. cm.doTrafficCheck(localIndex, p, nb, out, now)
  136. }
  137. }
  138. }
  139. }
  140. func (cm *connectionManager) doTrafficCheck(localIndex uint32, p, nb, out []byte, now time.Time) {
  141. decision, hostinfo, primary := cm.makeTrafficDecision(localIndex, now)
  142. switch decision {
  143. case deleteTunnel:
  144. if cm.hostMap.DeleteHostInfo(hostinfo) {
  145. // Only clearing the lighthouse cache if this is the last hostinfo for this vpn ip in the hostmap
  146. cm.intf.lightHouse.DeleteVpnAddrs(hostinfo.vpnAddrs)
  147. }
  148. case closeTunnel:
  149. cm.intf.sendCloseTunnel(hostinfo)
  150. cm.intf.closeTunnel(hostinfo)
  151. case swapPrimary:
  152. cm.swapPrimary(hostinfo, primary)
  153. case migrateRelays:
  154. cm.migrateRelayUsed(hostinfo, primary)
  155. case tryRehandshake:
  156. cm.tryRehandshake(hostinfo)
  157. case sendTestPacket:
  158. cm.intf.SendMessageToHostInfo(header.Test, header.TestRequest, hostinfo, p, nb, out)
  159. }
  160. cm.resetRelayTrafficCheck(hostinfo)
  161. cm.ensureLanes(localIndex, decision, hostinfo)
  162. }
  163. // ensureLanes piggybacks lane re-establishment on the per-tunnel traffic
  164. // tick: any live base with lane state gets its empty slots retried (subject to
  165. // the per-slot backoff). makeTrafficDecision returns a nil hostinfo on some
  166. // keep-alive paths, so re-resolve the index in that case — an idle base must
  167. // still restart lanes that died while it was quiet.
  168. func (cm *connectionManager) ensureLanes(localIndex uint32, decision trafficDecision, hostinfo *HostInfo) {
  169. if decision == deleteTunnel || decision == closeTunnel {
  170. return
  171. }
  172. if hostinfo == nil {
  173. hostinfo = cm.hostMap.QueryIndex(localIndex)
  174. if hostinfo == nil {
  175. return
  176. }
  177. }
  178. if hostinfo.isLane() || hostinfo.lanes == nil {
  179. return
  180. }
  181. cm.intf.handshakeManager.EnsureLanes(hostinfo)
  182. }
  183. func (cm *connectionManager) resetRelayTrafficCheck(hostinfo *HostInfo) {
  184. if hostinfo != nil {
  185. cm.relayUsedLock.Lock()
  186. defer cm.relayUsedLock.Unlock()
  187. // No need to migrate any relays, delete usage info now.
  188. for _, idx := range hostinfo.relayState.CopyRelayForIdxs() {
  189. delete(cm.relayUsed, idx)
  190. }
  191. }
  192. }
  193. func (cm *connectionManager) migrateRelayUsed(oldhostinfo, newhostinfo *HostInfo) {
  194. relayFor := oldhostinfo.relayState.CopyAllRelayFor()
  195. for _, r := range relayFor {
  196. existing, ok := newhostinfo.relayState.QueryRelayForByIp(r.PeerAddr)
  197. var index uint32
  198. var relayFrom netip.Addr
  199. var relayTo netip.Addr
  200. switch {
  201. case ok:
  202. switch existing.State {
  203. case Established, PeerRequested, Disestablished:
  204. // This relay already exists in newhostinfo, then do nothing.
  205. continue
  206. case Requested:
  207. // The relay exists in a Requested state; re-send the request
  208. index = existing.LocalIndex
  209. switch r.Type {
  210. case TerminalType:
  211. relayFrom = cm.intf.myVpnAddrs[0]
  212. relayTo = existing.PeerAddr
  213. case ForwardingType:
  214. relayFrom = existing.PeerAddr
  215. relayTo = newhostinfo.vpnAddrs[0]
  216. default:
  217. // should never happen
  218. panic(fmt.Sprintf("Migrating unknown relay type: %v", r.Type))
  219. }
  220. }
  221. case !ok:
  222. cm.relayUsedLock.RLock()
  223. if _, relayUsed := cm.relayUsed[r.LocalIndex]; !relayUsed {
  224. // The relay hasn't been used; don't migrate it.
  225. cm.relayUsedLock.RUnlock()
  226. continue
  227. }
  228. cm.relayUsedLock.RUnlock()
  229. // The relay doesn't exist at all; create some relay state and send the request.
  230. var err error
  231. index, err = AddRelay(cm.l, newhostinfo, cm.hostMap, r.PeerAddr, nil, r.Type, Requested)
  232. if err != nil {
  233. cm.l.Error("failed to migrate relay to new hostinfo", "error", err)
  234. continue
  235. }
  236. switch r.Type {
  237. case TerminalType:
  238. relayFrom = cm.intf.myVpnAddrs[0]
  239. relayTo = r.PeerAddr
  240. case ForwardingType:
  241. relayFrom = r.PeerAddr
  242. relayTo = newhostinfo.vpnAddrs[0]
  243. default:
  244. // should never happen
  245. panic(fmt.Sprintf("Migrating unknown relay type: %v", r.Type))
  246. }
  247. }
  248. // Send a CreateRelayRequest to the peer.
  249. req := NebulaControl{
  250. Type: NebulaControl_CreateRelayRequest,
  251. InitiatorRelayIndex: index,
  252. }
  253. switch newhostinfo.GetCert().Certificate.Version() {
  254. case cert.Version1:
  255. if !relayFrom.Is4() {
  256. cm.l.Error("can not migrate v1 relay with a v6 network because the relay is not running a current nebula version")
  257. continue
  258. }
  259. if !relayTo.Is4() {
  260. cm.l.Error("can not migrate v1 relay with a v6 remote network because the relay is not running a current nebula version")
  261. continue
  262. }
  263. b := relayFrom.As4()
  264. req.OldRelayFromAddr = binary.BigEndian.Uint32(b[:])
  265. b = relayTo.As4()
  266. req.OldRelayToAddr = binary.BigEndian.Uint32(b[:])
  267. case cert.Version2:
  268. req.RelayFromAddr = netAddrToProtoAddr(relayFrom)
  269. req.RelayToAddr = netAddrToProtoAddr(relayTo)
  270. default:
  271. newhostinfo.logger(cm.l).Error("Unknown certificate version found while attempting to migrate relay")
  272. continue
  273. }
  274. msg, err := req.Marshal()
  275. if err != nil {
  276. cm.l.Error("failed to marshal Control message to migrate relay", "error", err)
  277. } else {
  278. cm.intf.SendMessageToHostInfo(header.Control, 0, newhostinfo, msg, make([]byte, 12), make([]byte, mtu))
  279. cm.l.Info("send CreateRelayRequest",
  280. "relayFrom", relayFrom,
  281. "relayTo", relayTo,
  282. "initiatorRelayIndex", req.InitiatorRelayIndex,
  283. "responderRelayIndex", req.ResponderRelayIndex,
  284. "vpnAddrs", newhostinfo.vpnAddrs,
  285. )
  286. }
  287. }
  288. }
  289. func (cm *connectionManager) makeTrafficDecision(localIndex uint32, now time.Time) (trafficDecision, *HostInfo, *HostInfo) {
  290. // Read lock the main hostmap to order decisions based on tunnels being the primary tunnel
  291. cm.hostMap.RLock()
  292. defer cm.hostMap.RUnlock()
  293. hostinfo := cm.hostMap.Indexes[localIndex]
  294. if hostinfo == nil {
  295. cm.l.Debug("Not found in hostmap", "localIndex", localIndex)
  296. return doNothing, nil, nil
  297. }
  298. if cm.isInvalidCertificate(now, hostinfo) {
  299. return closeTunnel, hostinfo, nil
  300. }
  301. if hostinfo.isLane() {
  302. return cm.makeLaneTrafficDecision(hostinfo, now)
  303. }
  304. primary := cm.hostMap.Hosts[hostinfo.vpnAddrs[0]]
  305. mainHostInfo := true
  306. if primary != nil && primary != hostinfo {
  307. mainHostInfo = false
  308. }
  309. // Check for traffic on this hostinfo
  310. inTraffic, outTraffic := cm.getAndResetTrafficCheck(hostinfo, now)
  311. // A hostinfo is determined alive if there is incoming traffic
  312. if inTraffic {
  313. decision := doNothing
  314. if cm.l.Enabled(context.Background(), slog.LevelDebug) {
  315. hostinfo.logger(cm.l).Debug("Tunnel status",
  316. "tunnelCheck", m{"state": "alive", "method": "passive"},
  317. )
  318. }
  319. hostinfo.pendingDeletion.Store(false)
  320. if mainHostInfo {
  321. decision = tryRehandshake
  322. } else {
  323. if cm.shouldSwapPrimary(hostinfo) {
  324. decision = swapPrimary
  325. } else {
  326. // migrate the relays to the primary, if in use.
  327. decision = migrateRelays
  328. }
  329. }
  330. cm.trafficTimer.Add(hostinfo.localIndexId, cm.checkInterval)
  331. if !outTraffic {
  332. // Send a punch packet to keep the NAT state alive
  333. cm.punchy.SendPunch(hostinfo)
  334. }
  335. return decision, hostinfo, primary
  336. }
  337. if hostinfo.pendingDeletion.Load() {
  338. // We have already sent a test packet and nothing was returned, this hostinfo is dead
  339. hostinfo.logger(cm.l).Info("Tunnel status",
  340. "tunnelCheck", m{"state": "dead", "method": "active"},
  341. )
  342. return deleteTunnel, hostinfo, nil
  343. }
  344. decision := doNothing
  345. if hostinfo != nil && hostinfo.ConnectionState != nil && mainHostInfo {
  346. if !outTraffic {
  347. inactiveFor, isInactive := cm.isInactive(hostinfo, now)
  348. if isInactive {
  349. // Tunnel is inactive, tear it down
  350. hostinfo.logger(cm.l).Info("Dropping tunnel due to inactivity",
  351. "inactiveDuration", inactiveFor,
  352. "primary", mainHostInfo,
  353. )
  354. return closeTunnel, hostinfo, primary
  355. }
  356. // If we aren't sending or receiving traffic then its an unused tunnel and we don't to test the tunnel.
  357. // Just maintain NAT state if configured to do so.
  358. cm.punchy.SendPunch(hostinfo)
  359. cm.trafficTimer.Add(hostinfo.localIndexId, cm.checkInterval)
  360. return doNothing, nil, nil
  361. }
  362. // We aren't receiving traffic but we are sending it. The outbound
  363. // traffic itself refreshes the primary remote's NAT state; this
  364. // fans out to non-primary remotes, but only if target_all_remotes
  365. // is configured.
  366. cm.punchy.SendPunchToAll(hostinfo)
  367. if cm.l.Enabled(context.Background(), slog.LevelDebug) {
  368. hostinfo.logger(cm.l).Debug("Tunnel status",
  369. "tunnelCheck", m{"state": "testing", "method": "active"},
  370. )
  371. }
  372. // Send a test packet to trigger an authenticated tunnel test, this should suss out any lingering tunnel issues
  373. decision = sendTestPacket
  374. } else {
  375. if cm.l.Enabled(context.Background(), slog.LevelDebug) {
  376. hostinfo.logger(cm.l).Debug("Hostinfo sadness")
  377. }
  378. }
  379. hostinfo.pendingDeletion.Store(true)
  380. cm.trafficTimer.Add(hostinfo.localIndexId, cm.pendingDeletionInterval)
  381. return decision, hostinfo, nil
  382. }
  383. // makeLaneTrafficDecision is the lane-tunnel subset of makeTrafficDecision:
  384. // no primary/swap/rehandshake logic (lanes are never primary), no punches
  385. // (lane keepalives egress the lane's own socket and are its NAT keepalive),
  386. // just alive / test / dead. A dead lane's DeleteHostInfo clears its base slot
  387. // with backoff, and ensureLanes re-establishes it.
  388. func (cm *connectionManager) makeLaneTrafficDecision(hostinfo *HostInfo, now time.Time) (trafficDecision, *HostInfo, *HostInfo) {
  389. inTraffic, _ := cm.getAndResetTrafficCheck(hostinfo, now)
  390. if inTraffic {
  391. if cm.l.Enabled(context.Background(), slog.LevelDebug) {
  392. hostinfo.logger(cm.l).Debug("Tunnel status",
  393. "tunnelCheck", m{"state": "alive", "method": "passive"},
  394. "laneIndex", hostinfo.laneIndex,
  395. )
  396. }
  397. hostinfo.pendingDeletion.Store(false)
  398. cm.trafficTimer.Add(hostinfo.localIndexId, cm.checkInterval)
  399. return doNothing, hostinfo, nil
  400. }
  401. if hostinfo.pendingDeletion.Load() {
  402. hostinfo.logger(cm.l).Info("Tunnel status",
  403. "tunnelCheck", m{"state": "dead", "method": "active"},
  404. "laneIndex", hostinfo.laneIndex,
  405. )
  406. return deleteTunnel, hostinfo, nil
  407. }
  408. // Idle lanes are actively kept alive (unlike idle base tunnels, which
  409. // just get punches): a lane is datapath infrastructure and its keepalive
  410. // doubles as the per-path death detector.
  411. decision := doNothing
  412. if hostinfo.ConnectionState != nil {
  413. decision = sendTestPacket
  414. }
  415. hostinfo.pendingDeletion.Store(true)
  416. cm.trafficTimer.Add(hostinfo.localIndexId, cm.pendingDeletionInterval)
  417. return decision, hostinfo, nil
  418. }
  419. func (cm *connectionManager) isInactive(hostinfo *HostInfo, now time.Time) (time.Duration, bool) {
  420. if cm.dropInactive.Load() == false {
  421. // We aren't configured to drop inactive tunnels
  422. return 0, false
  423. }
  424. // With multiport the data rides the lanes and the base may look idle;
  425. // a base is only inactive if its whole lane family is. lastUsed is only
  426. // written by this ticker goroutine, so these reads are safe.
  427. lastUsed := hostinfo.lastUsed
  428. if ls := hostinfo.lanes; ls != nil {
  429. for i := range ls.txLanes {
  430. if lane := ls.txLanes[i].Load(); lane != nil && lane.lastUsed.After(lastUsed) {
  431. lastUsed = lane.lastUsed
  432. }
  433. }
  434. ls.Lock()
  435. for _, lane := range ls.peerLanes {
  436. if lane.lastUsed.After(lastUsed) {
  437. lastUsed = lane.lastUsed
  438. }
  439. }
  440. ls.Unlock()
  441. }
  442. inactiveDuration := now.Sub(lastUsed)
  443. if inactiveDuration < cm.getInactivityTimeout() {
  444. // It's not considered inactive
  445. return inactiveDuration, false
  446. }
  447. // The tunnel is inactive
  448. return inactiveDuration, true
  449. }
  450. func (cm *connectionManager) shouldSwapPrimary(current *HostInfo) bool {
  451. // The primary tunnel is the most recent handshake to complete locally and should work entirely fine.
  452. // If we are here then we have multiple tunnels for a host pair and neither side believes the same tunnel is primary.
  453. // Let's sort this out.
  454. // Only one side should swap because if both swap then we may never resolve to a single tunnel.
  455. // vpn addr is static across all tunnels for this host pair so lets
  456. // use that to determine if we should consider swapping.
  457. if current.vpnAddrs[0].Compare(cm.intf.myVpnAddrs[0]) < 0 {
  458. // Their primary vpn addr is less than mine. Do not swap.
  459. return false
  460. }
  461. crt := cm.intf.pki.getCertState().getCertificate(current.ConnectionState.myCert.Version())
  462. if crt == nil {
  463. //my cert was reloaded away. We should definitely swap from this tunnel
  464. return true
  465. }
  466. // If this tunnel is using the latest certificate then we should swap it to primary for a bit and see if things
  467. // settle down.
  468. return bytes.Equal(current.ConnectionState.myCert.Signature(), crt.Signature())
  469. }
  470. func (cm *connectionManager) swapPrimary(current, primary *HostInfo) {
  471. cm.hostMap.Lock()
  472. // Make sure the primary is still the same after the write lock. This avoids a race with a rehandshake.
  473. if cm.hostMap.Hosts[current.vpnAddrs[0]] == primary {
  474. cm.hostMap.unlockedMakePrimary(current)
  475. }
  476. cm.hostMap.Unlock()
  477. }
  478. // isInvalidCertificate decides if we should destroy a tunnel.
  479. // returns true if pki.disconnect_invalid is true and the certificate is no longer valid.
  480. // Blocklisted certificates will skip the pki.disconnect_invalid check and return true.
  481. func (cm *connectionManager) isInvalidCertificate(now time.Time, hostinfo *HostInfo) bool {
  482. remoteCert := hostinfo.GetCert()
  483. if remoteCert == nil {
  484. return false //don't tear down tunnels for handshakes in progress
  485. }
  486. caPool := cm.intf.pki.GetCAPool()
  487. err := caPool.VerifyCachedCertificate(now, remoteCert)
  488. if err == nil {
  489. return false //cert is still valid! yay!
  490. } else if err == cert.ErrBlockListed { //avoiding errors.Is for speed
  491. // Block listed certificates should always be disconnected
  492. hostinfo.logger(cm.l).Info("Remote certificate is blocked, tearing down the tunnel",
  493. "error", err,
  494. "fingerprint", remoteCert.Fingerprint,
  495. )
  496. return true
  497. } else if cm.intf.disconnectInvalid.Load() {
  498. hostinfo.logger(cm.l).Info("Remote certificate is no longer valid, tearing down the tunnel",
  499. "error", err,
  500. "fingerprint", remoteCert.Fingerprint,
  501. )
  502. return true
  503. } else {
  504. //if we reach here, the cert is no longer valid, but we're configured to keep tunnels from now-invalid certs open
  505. return false
  506. }
  507. }
  508. func (cm *connectionManager) tryRehandshake(hostinfo *HostInfo) {
  509. cs := cm.intf.pki.getCertState()
  510. curCrt := hostinfo.ConnectionState.myCert
  511. curCrtVersion := curCrt.Version()
  512. myCrt := cs.getCertificate(curCrtVersion)
  513. if myCrt == nil {
  514. cm.l.Info("Re-handshaking with remote",
  515. "vpnAddrs", hostinfo.vpnAddrs,
  516. "version", curCrtVersion,
  517. "reason", "local certificate removed",
  518. )
  519. cm.intf.handshakeManager.StartHandshake(hostinfo.vpnAddrs[0], nil)
  520. return
  521. }
  522. peerCrt := hostinfo.ConnectionState.peerCert
  523. if peerCrt != nil && curCrtVersion < peerCrt.Certificate.Version() {
  524. // if our certificate version is less than theirs, and we have a matching version available, rehandshake?
  525. if cs.getCertificate(peerCrt.Certificate.Version()) != nil {
  526. cm.l.Info("Re-handshaking with remote",
  527. "vpnAddrs", hostinfo.vpnAddrs,
  528. "version", curCrtVersion,
  529. "peerVersion", peerCrt.Certificate.Version(),
  530. "reason", "local certificate version lower than peer, attempting to correct",
  531. )
  532. cm.intf.handshakeManager.StartHandshake(hostinfo.vpnAddrs[0], func(hh *HandshakeHostInfo) {
  533. hh.initiatingVersionOverride = peerCrt.Certificate.Version()
  534. })
  535. return
  536. }
  537. }
  538. if !bytes.Equal(curCrt.Signature(), myCrt.Signature()) {
  539. cm.l.Info("Re-handshaking with remote",
  540. "vpnAddrs", hostinfo.vpnAddrs,
  541. "reason", "local certificate is not current",
  542. )
  543. cm.intf.handshakeManager.StartHandshake(hostinfo.vpnAddrs[0], nil)
  544. return
  545. }
  546. if curCrtVersion < cs.initiatingVersion {
  547. cm.l.Info("Re-handshaking with remote",
  548. "vpnAddrs", hostinfo.vpnAddrs,
  549. "reason", "current cert version < pki.initiatingVersion",
  550. )
  551. cm.intf.handshakeManager.StartHandshake(hostinfo.vpnAddrs[0], nil)
  552. return
  553. }
  554. }