connection_manager.go 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665
  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.markIn()
  92. }
  93. // OutNoRebind records outbound traffic without consuming the rebind epoch, for relayed sends: the direct path
  94. // to the relay consumes the edge, the via send must not.
  95. func (cm *connectionManager) OutNoRebind(h *HostInfo) {
  96. h.markOutOnly()
  97. }
  98. // Out records outbound traffic and reports whether we rebound since this tunnel last sent
  99. func (cm *connectionManager) Out(h *HostInfo) bool {
  100. return h.markOut(cm.intf.rebindEpoch.Load())
  101. }
  102. func (cm *connectionManager) RelayUsed(localIndex uint32) {
  103. cm.relayUsedLock.RLock()
  104. // If this already exists, return
  105. if _, ok := cm.relayUsed[localIndex]; ok {
  106. cm.relayUsedLock.RUnlock()
  107. return
  108. }
  109. cm.relayUsedLock.RUnlock()
  110. cm.relayUsedLock.Lock()
  111. cm.relayUsed[localIndex] = struct{}{}
  112. cm.relayUsedLock.Unlock()
  113. }
  114. // getAndResetTrafficCheck returns if there was any inbound or outbound traffic within the last tick and
  115. // resets the state for this local index
  116. func (cm *connectionManager) getAndResetTrafficCheck(h *HostInfo, now time.Time) (bool, bool) {
  117. in, out := h.takeTraffic()
  118. if in || out {
  119. h.lastUsed = now
  120. }
  121. return in, out
  122. }
  123. func (cm *connectionManager) Start(ctx context.Context) {
  124. clockSource := time.NewTicker(cm.trafficTimer.t.tickDuration)
  125. defer clockSource.Stop()
  126. p := []byte("")
  127. nb := make([]byte, 12, 12)
  128. out := make([]byte, mtu)
  129. for {
  130. select {
  131. case <-ctx.Done():
  132. return
  133. case now := <-clockSource.C:
  134. cm.trafficTimer.Advance(now)
  135. for {
  136. localIndex, has := cm.trafficTimer.Purge()
  137. if !has {
  138. break
  139. }
  140. cm.doTrafficCheck(localIndex, p, nb, out, now)
  141. }
  142. }
  143. }
  144. }
  145. func (cm *connectionManager) doTrafficCheck(localIndex uint32, p, nb, out []byte, now time.Time) {
  146. decision, hostinfo, primary := cm.makeTrafficDecision(localIndex, now)
  147. switch decision {
  148. case deleteTunnel:
  149. if cm.hostMap.DeleteHostInfo(hostinfo) {
  150. // Only clearing the lighthouse cache if this is the last hostinfo for this vpn ip in the hostmap
  151. cm.intf.lightHouse.DeleteVpnAddrs(hostinfo.vpnAddrs)
  152. }
  153. case closeTunnel:
  154. cm.intf.sendCloseTunnel(hostinfo)
  155. cm.intf.closeTunnel(hostinfo)
  156. case swapPrimary:
  157. cm.swapPrimary(hostinfo, primary)
  158. case migrateRelays:
  159. cm.migrateRelayUsed(hostinfo, primary)
  160. case tryRehandshake:
  161. cm.tryRehandshake(hostinfo)
  162. case sendTestPacket:
  163. cm.intf.SendMessageToHostInfo(header.Test, header.TestRequest, hostinfo, p, nb, out)
  164. }
  165. cm.resetRelayTrafficCheck(hostinfo)
  166. cm.ensureLanes(localIndex, decision, hostinfo)
  167. }
  168. // ensureLanes piggybacks lane establishment on the per-tunnel traffic tick:
  169. // any live base with lane state gets the slots its data plane asked for
  170. // started (subject to the per-slot backoff). This tick is the right place for
  171. // it precisely because lanes are demand-driven — a base only lands here when
  172. // it has traffic, which is the same condition that raises lane demand.
  173. // makeTrafficDecision returns a nil hostinfo on some keep-alive paths, so
  174. // re-resolve the index in that case.
  175. func (cm *connectionManager) ensureLanes(localIndex uint32, decision trafficDecision, hostinfo *HostInfo) {
  176. if decision == deleteTunnel || decision == closeTunnel {
  177. return
  178. }
  179. if hostinfo == nil {
  180. hostinfo = cm.hostMap.QueryIndex(localIndex)
  181. if hostinfo == nil {
  182. return
  183. }
  184. }
  185. if hostinfo.isLane() || hostinfo.lanes == nil {
  186. return
  187. }
  188. cm.intf.handshakeManager.EnsureLanes(hostinfo)
  189. }
  190. func (cm *connectionManager) resetRelayTrafficCheck(hostinfo *HostInfo) {
  191. if hostinfo != nil {
  192. cm.relayUsedLock.Lock()
  193. defer cm.relayUsedLock.Unlock()
  194. // No need to migrate any relays, delete usage info now.
  195. for _, idx := range hostinfo.relayState.CopyRelayForIdxs() {
  196. delete(cm.relayUsed, idx)
  197. }
  198. }
  199. }
  200. func (cm *connectionManager) migrateRelayUsed(oldhostinfo, newhostinfo *HostInfo) {
  201. relayFor := oldhostinfo.relayState.CopyAllRelayFor()
  202. for _, r := range relayFor {
  203. existing, ok := newhostinfo.relayState.QueryRelayForByIp(r.PeerAddr)
  204. var index uint32
  205. var relayFrom netip.Addr
  206. var relayTo netip.Addr
  207. switch {
  208. case ok:
  209. switch existing.State {
  210. case Established, PeerRequested, Disestablished:
  211. // This relay already exists in newhostinfo, then do nothing.
  212. continue
  213. case Requested:
  214. // The relay exists in a Requested state; re-send the request
  215. index = existing.LocalIndex
  216. switch r.Type {
  217. case TerminalType:
  218. relayFrom = cm.intf.myVpnAddrs[0]
  219. relayTo = existing.PeerAddr
  220. case ForwardingType:
  221. relayFrom = existing.PeerAddr
  222. relayTo = newhostinfo.vpnAddrs[0]
  223. default:
  224. // should never happen
  225. panic(fmt.Sprintf("Migrating unknown relay type: %v", r.Type))
  226. }
  227. }
  228. case !ok:
  229. cm.relayUsedLock.RLock()
  230. if _, relayUsed := cm.relayUsed[r.LocalIndex]; !relayUsed {
  231. // The relay hasn't been used; don't migrate it.
  232. cm.relayUsedLock.RUnlock()
  233. continue
  234. }
  235. cm.relayUsedLock.RUnlock()
  236. // The relay doesn't exist at all; create some relay state and send the request.
  237. var err error
  238. index, err = AddRelay(cm.l, newhostinfo, cm.hostMap, r.PeerAddr, nil, r.Type, Requested)
  239. if err != nil {
  240. cm.l.Error("failed to migrate relay to new hostinfo", "error", err)
  241. continue
  242. }
  243. switch r.Type {
  244. case TerminalType:
  245. relayFrom = cm.intf.myVpnAddrs[0]
  246. relayTo = r.PeerAddr
  247. case ForwardingType:
  248. relayFrom = r.PeerAddr
  249. relayTo = newhostinfo.vpnAddrs[0]
  250. default:
  251. // should never happen
  252. panic(fmt.Sprintf("Migrating unknown relay type: %v", r.Type))
  253. }
  254. }
  255. // Send a CreateRelayRequest to the peer.
  256. req := NebulaControl{
  257. Type: NebulaControl_CreateRelayRequest,
  258. InitiatorRelayIndex: index,
  259. }
  260. switch newhostinfo.GetCert().Certificate.Version() {
  261. case cert.Version1:
  262. if !relayFrom.Is4() {
  263. cm.l.Error("can not migrate v1 relay with a v6 network because the relay is not running a current nebula version")
  264. continue
  265. }
  266. if !relayTo.Is4() {
  267. cm.l.Error("can not migrate v1 relay with a v6 remote network because the relay is not running a current nebula version")
  268. continue
  269. }
  270. b := relayFrom.As4()
  271. req.OldRelayFromAddr = binary.BigEndian.Uint32(b[:])
  272. b = relayTo.As4()
  273. req.OldRelayToAddr = binary.BigEndian.Uint32(b[:])
  274. case cert.Version2:
  275. req.RelayFromAddr = netAddrToProtoAddr(relayFrom)
  276. req.RelayToAddr = netAddrToProtoAddr(relayTo)
  277. default:
  278. newhostinfo.logger(cm.l).Error("Unknown certificate version found while attempting to migrate relay")
  279. continue
  280. }
  281. msg, err := req.Marshal()
  282. if err != nil {
  283. cm.l.Error("failed to marshal Control message to migrate relay", "error", err)
  284. } else {
  285. cm.intf.SendMessageToHostInfo(header.Control, 0, newhostinfo, msg, make([]byte, 12), make([]byte, mtu))
  286. cm.l.Info("send CreateRelayRequest",
  287. "relayFrom", relayFrom,
  288. "relayTo", relayTo,
  289. "initiatorRelayIndex", req.InitiatorRelayIndex,
  290. "responderRelayIndex", req.ResponderRelayIndex,
  291. "vpnAddrs", newhostinfo.vpnAddrs,
  292. )
  293. }
  294. }
  295. }
  296. func (cm *connectionManager) makeTrafficDecision(localIndex uint32, now time.Time) (trafficDecision, *HostInfo, *HostInfo) {
  297. // Read lock the main hostmap to order decisions based on tunnels being the primary tunnel
  298. cm.hostMap.RLock()
  299. defer cm.hostMap.RUnlock()
  300. hostinfo := cm.hostMap.Indexes[localIndex]
  301. if hostinfo == nil {
  302. cm.l.Debug("Not found in hostmap", "localIndex", localIndex)
  303. return doNothing, nil, nil
  304. }
  305. if cm.isInvalidCertificate(now, hostinfo) {
  306. return closeTunnel, hostinfo, nil
  307. }
  308. // Checked ahead of the lane branch: an exhausted counter is fatal for lanes too, and makeLaneTrafficDecision
  309. // only reasons about liveness.
  310. if hostinfo.ConnectionState != nil && hostinfo.ConnectionState.messageCounter.Load() >= RejectAfterMessages {
  311. // Send path can't encrypt a CloseTunnel notify, so just delete locally; the peer recovers via recv_error.
  312. hostinfo.logger(cm.l).Error("Dropping tunnel, message counter is exhausted")
  313. return deleteTunnel, hostinfo, nil
  314. }
  315. if hostinfo.isLane() {
  316. return cm.makeLaneTrafficDecision(hostinfo, now)
  317. }
  318. primary := cm.hostMap.Hosts[hostinfo.vpnAddrs[0]]
  319. mainHostInfo := true
  320. if primary != nil && primary != hostinfo {
  321. mainHostInfo = false
  322. }
  323. // Check for traffic on this hostinfo
  324. inTraffic, outTraffic := cm.getAndResetTrafficCheck(hostinfo, now)
  325. // A hostinfo is determined alive if there is incoming traffic
  326. if inTraffic {
  327. decision := doNothing
  328. if cm.l.Enabled(context.Background(), slog.LevelDebug) {
  329. hostinfo.logger(cm.l).Debug("Tunnel status",
  330. "tunnelCheck", m{"state": "alive", "method": "passive"},
  331. )
  332. }
  333. hostinfo.setPendingDeletion(false)
  334. if mainHostInfo {
  335. decision = tryRehandshake
  336. } else {
  337. if cm.shouldSwapPrimary(hostinfo) {
  338. decision = swapPrimary
  339. } else {
  340. // migrate the relays to the primary, if in use.
  341. decision = migrateRelays
  342. }
  343. }
  344. cm.trafficTimer.Add(hostinfo.localIndexId, cm.checkInterval)
  345. if !outTraffic {
  346. // Send a punch packet to keep the NAT state alive
  347. cm.punchy.SendPunch(hostinfo)
  348. }
  349. return decision, hostinfo, primary
  350. }
  351. if hostinfo.isPendingDeletion() {
  352. // We have already sent a test packet and nothing was returned, this hostinfo is dead
  353. hostinfo.logger(cm.l).Info("Tunnel status",
  354. "tunnelCheck", m{"state": "dead", "method": "active"},
  355. )
  356. return deleteTunnel, hostinfo, nil
  357. }
  358. decision := doNothing
  359. if hostinfo != nil && hostinfo.ConnectionState != nil && mainHostInfo {
  360. if !outTraffic {
  361. inactiveFor, isInactive := cm.isInactive(hostinfo, now)
  362. if isInactive {
  363. // Tunnel is inactive, tear it down
  364. hostinfo.logger(cm.l).Info("Dropping tunnel due to inactivity",
  365. "inactiveDuration", inactiveFor,
  366. "primary", mainHostInfo,
  367. )
  368. return closeTunnel, hostinfo, primary
  369. }
  370. // If we aren't sending or receiving traffic then its an unused tunnel and we don't to test the tunnel.
  371. // Just maintain NAT state if configured to do so.
  372. cm.punchy.SendPunch(hostinfo)
  373. cm.trafficTimer.Add(hostinfo.localIndexId, cm.checkInterval)
  374. return doNothing, nil, nil
  375. }
  376. // We aren't receiving traffic but we are sending it. The outbound
  377. // traffic itself refreshes the primary remote's NAT state; this
  378. // fans out to non-primary remotes, but only if target_all_remotes
  379. // is configured.
  380. cm.punchy.SendPunchToAll(hostinfo)
  381. if cm.l.Enabled(context.Background(), slog.LevelDebug) {
  382. hostinfo.logger(cm.l).Debug("Tunnel status",
  383. "tunnelCheck", m{"state": "testing", "method": "active"},
  384. )
  385. }
  386. // Send a test packet to trigger an authenticated tunnel test, this should suss out any lingering tunnel issues
  387. decision = sendTestPacket
  388. } else {
  389. if cm.l.Enabled(context.Background(), slog.LevelDebug) {
  390. hostinfo.logger(cm.l).Debug("Hostinfo sadness")
  391. }
  392. }
  393. hostinfo.setPendingDeletion(true)
  394. cm.trafficTimer.Add(hostinfo.localIndexId, cm.pendingDeletionInterval)
  395. return decision, hostinfo, nil
  396. }
  397. // makeLaneTrafficDecision is the lane-tunnel subset of makeTrafficDecision:
  398. // no primary/swap/rehandshake logic (lanes are never primary), no punches
  399. // (lane keepalives egress the lane's own socket and are its NAT keepalive),
  400. // just alive / test / dead. A dead lane's DeleteHostInfo clears its base slot
  401. // with backoff, and ensureLanes re-establishes it.
  402. func (cm *connectionManager) makeLaneTrafficDecision(hostinfo *HostInfo, now time.Time) (trafficDecision, *HostInfo, *HostInfo) {
  403. inTraffic, _ := cm.getAndResetTrafficCheck(hostinfo, now)
  404. if inTraffic {
  405. if cm.l.Enabled(context.Background(), slog.LevelDebug) {
  406. hostinfo.logger(cm.l).Debug("Tunnel status",
  407. "tunnelCheck", m{"state": "alive", "method": "passive"},
  408. "laneIndex", hostinfo.laneIndex,
  409. )
  410. }
  411. hostinfo.setPendingDeletion(false)
  412. cm.trafficTimer.Add(hostinfo.localIndexId, cm.checkInterval)
  413. return doNothing, hostinfo, nil
  414. }
  415. if hostinfo.isPendingDeletion() {
  416. hostinfo.logger(cm.l).Info("Tunnel status",
  417. "tunnelCheck", m{"state": "dead", "method": "active"},
  418. "laneIndex", hostinfo.laneIndex,
  419. )
  420. return deleteTunnel, hostinfo, nil
  421. }
  422. // Idle lanes are actively kept alive (unlike idle base tunnels, which
  423. // just get punches): a lane is datapath infrastructure and its keepalive
  424. // doubles as the per-path death detector.
  425. decision := doNothing
  426. if hostinfo.ConnectionState != nil {
  427. decision = sendTestPacket
  428. }
  429. hostinfo.setPendingDeletion(true)
  430. cm.trafficTimer.Add(hostinfo.localIndexId, cm.pendingDeletionInterval)
  431. return decision, hostinfo, nil
  432. }
  433. func (cm *connectionManager) isInactive(hostinfo *HostInfo, now time.Time) (time.Duration, bool) {
  434. if cm.dropInactive.Load() == false {
  435. // We aren't configured to drop inactive tunnels
  436. return 0, false
  437. }
  438. // With multiport the data rides the lanes and the base may look idle;
  439. // a base is only inactive if its whole lane family is. lastUsed is only
  440. // written by this ticker goroutine, so these reads are safe.
  441. lastUsed := hostinfo.lastUsed
  442. if ls := hostinfo.lanes; ls != nil {
  443. for i := range ls.txLanes {
  444. if lane := ls.txLanes[i].Load(); lane != nil && lane.lastUsed.After(lastUsed) {
  445. lastUsed = lane.lastUsed
  446. }
  447. }
  448. ls.Lock()
  449. for _, lane := range ls.peerLanes {
  450. if lane.lastUsed.After(lastUsed) {
  451. lastUsed = lane.lastUsed
  452. }
  453. }
  454. ls.Unlock()
  455. }
  456. inactiveDuration := now.Sub(lastUsed)
  457. if inactiveDuration < cm.getInactivityTimeout() {
  458. // It's not considered inactive
  459. return inactiveDuration, false
  460. }
  461. // The tunnel is inactive
  462. return inactiveDuration, true
  463. }
  464. func (cm *connectionManager) shouldSwapPrimary(current *HostInfo) bool {
  465. // The primary tunnel is the most recent handshake to complete locally and should work entirely fine.
  466. // If we are here then we have multiple tunnels for a host pair and neither side believes the same tunnel is primary.
  467. // Let's sort this out.
  468. // Only one side should swap because if both swap then we may never resolve to a single tunnel.
  469. // vpn addr is static across all tunnels for this host pair so lets
  470. // use that to determine if we should consider swapping.
  471. if current.vpnAddrs[0].Compare(cm.intf.myVpnAddrs[0]) < 0 {
  472. // Their primary vpn addr is less than mine. Do not swap.
  473. return false
  474. }
  475. if current.ConnectionState.messageCounter.Load() >= RehandshakeAfterMessages {
  476. // This tunnel is being rolled for counter exhaustion, never swap back onto its spent key.
  477. return false
  478. }
  479. crt := cm.intf.pki.getCertState().getCertificate(current.ConnectionState.myCert.Version())
  480. if crt == nil {
  481. //my cert was reloaded away. We should definitely swap from this tunnel
  482. return true
  483. }
  484. // If this tunnel is using the latest certificate then we should swap it to primary for a bit and see if things
  485. // settle down.
  486. return bytes.Equal(current.ConnectionState.myCert.Signature(), crt.Signature())
  487. }
  488. func (cm *connectionManager) swapPrimary(current, primary *HostInfo) {
  489. cm.hostMap.Lock()
  490. // Make sure the primary is still the same after the write lock. This avoids a race with a rehandshake.
  491. if cm.hostMap.Hosts[current.vpnAddrs[0]] == primary {
  492. cm.hostMap.unlockedMakePrimary(current)
  493. }
  494. cm.hostMap.Unlock()
  495. }
  496. // isInvalidCertificate decides if we should destroy a tunnel.
  497. // returns true if pki.disconnect_invalid is true and the certificate is no longer valid.
  498. // Blocklisted certificates will skip the pki.disconnect_invalid check and return true.
  499. func (cm *connectionManager) isInvalidCertificate(now time.Time, hostinfo *HostInfo) bool {
  500. remoteCert := hostinfo.GetCert()
  501. if remoteCert == nil {
  502. return false //don't tear down tunnels for handshakes in progress
  503. }
  504. caPool := cm.intf.pki.GetCAPool()
  505. err := caPool.VerifyCachedCertificate(now, remoteCert)
  506. if err == nil {
  507. return false //cert is still valid! yay!
  508. } else if err == cert.ErrBlockListed { //avoiding errors.Is for speed
  509. // Block listed certificates should always be disconnected
  510. hostinfo.logger(cm.l).Info("Remote certificate is blocked, tearing down the tunnel",
  511. "error", err,
  512. "fingerprint", remoteCert.Fingerprint,
  513. )
  514. return true
  515. } else if cm.intf.disconnectInvalid.Load() {
  516. hostinfo.logger(cm.l).Info("Remote certificate is no longer valid, tearing down the tunnel",
  517. "error", err,
  518. "fingerprint", remoteCert.Fingerprint,
  519. )
  520. return true
  521. } else {
  522. //if we reach here, the cert is no longer valid, but we're configured to keep tunnels from now-invalid certs open
  523. return false
  524. }
  525. }
  526. func (cm *connectionManager) tryRehandshake(hostinfo *HostInfo) {
  527. cs := cm.intf.pki.getCertState()
  528. curCrt := hostinfo.ConnectionState.myCert
  529. curCrtVersion := curCrt.Version()
  530. myCrt := cs.getCertificate(curCrtVersion)
  531. if myCrt == nil {
  532. cm.l.Info("Re-handshaking with remote",
  533. "vpnAddrs", hostinfo.vpnAddrs,
  534. "version", curCrtVersion,
  535. "reason", "local certificate removed",
  536. )
  537. cm.intf.handshakeManager.StartHandshake(hostinfo.vpnAddrs[0], nil)
  538. return
  539. }
  540. peerCrt := hostinfo.ConnectionState.peerCert
  541. if peerCrt != nil && curCrtVersion < peerCrt.Certificate.Version() {
  542. // if our certificate version is less than theirs, and we have a matching version available, rehandshake?
  543. if cs.getCertificate(peerCrt.Certificate.Version()) != nil {
  544. cm.l.Info("Re-handshaking with remote",
  545. "vpnAddrs", hostinfo.vpnAddrs,
  546. "version", curCrtVersion,
  547. "peerVersion", peerCrt.Certificate.Version(),
  548. "reason", "local certificate version lower than peer, attempting to correct",
  549. )
  550. cm.intf.handshakeManager.StartHandshake(hostinfo.vpnAddrs[0], func(hh *HandshakeHostInfo) {
  551. hh.initiatingVersionOverride = peerCrt.Certificate.Version()
  552. })
  553. return
  554. }
  555. }
  556. if !bytes.Equal(curCrt.Signature(), myCrt.Signature()) {
  557. cm.l.Info("Re-handshaking with remote",
  558. "vpnAddrs", hostinfo.vpnAddrs,
  559. "reason", "local certificate is not current",
  560. )
  561. cm.intf.handshakeManager.StartHandshake(hostinfo.vpnAddrs[0], nil)
  562. return
  563. }
  564. if curCrtVersion < cs.initiatingVersion {
  565. cm.l.Info("Re-handshaking with remote",
  566. "vpnAddrs", hostinfo.vpnAddrs,
  567. "reason", "current cert version < pki.initiatingVersion",
  568. )
  569. cm.intf.handshakeManager.StartHandshake(hostinfo.vpnAddrs[0], nil)
  570. return
  571. }
  572. if hostinfo.ConnectionState.messageCounter.Load() >= RehandshakeAfterMessages {
  573. cm.l.Info("Re-handshaking with remote",
  574. "vpnAddrs", hostinfo.vpnAddrs,
  575. "reason", "message counter rehandshake threshold reached",
  576. )
  577. cm.intf.handshakeManager.StartHandshake(hostinfo.vpnAddrs[0], nil)
  578. return
  579. }
  580. }