connection_manager.go 20 KB

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