1
0

connection_manager.go 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575
  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, r *config.Reload) {
  51. r.RestartRequiredIfChanged("timers.connection_alive_interval", "timers.pending_deletion_interval")
  52. cm.reload(c, false)
  53. })
  54. return cm
  55. }
  56. func (cm *connectionManager) reload(c *config.C, initial bool) {
  57. if initial {
  58. cm.checkInterval = time.Duration(c.GetInt("timers.connection_alive_interval", 5)) * time.Second
  59. cm.pendingDeletionInterval = time.Duration(c.GetInt("timers.pending_deletion_interval", 10)) * time.Second
  60. // We want at least a minimum resolution of 500ms per tick so that we can hit these intervals
  61. // pretty close to their configured duration.
  62. // The inactivity duration is checked each time a hostinfo ticks through so we don't need the wheel to contain it.
  63. minDuration := min(time.Millisecond*500, cm.checkInterval, cm.pendingDeletionInterval)
  64. maxDuration := max(cm.checkInterval, cm.pendingDeletionInterval)
  65. cm.trafficTimer = NewLockingTimerWheel[uint32](minDuration, maxDuration)
  66. }
  67. if initial || c.HasChanged("tunnels.inactivity_timeout") {
  68. old := cm.getInactivityTimeout()
  69. cm.inactivityTimeout.Store((int64)(c.GetDuration("tunnels.inactivity_timeout", 10*time.Minute)))
  70. if !initial {
  71. cm.l.Info("Inactivity timeout has changed",
  72. "oldDuration", old,
  73. "newDuration", cm.getInactivityTimeout(),
  74. )
  75. }
  76. }
  77. if initial || c.HasChanged("tunnels.drop_inactive") {
  78. old := cm.dropInactive.Load()
  79. cm.dropInactive.Store(c.GetBool("tunnels.drop_inactive", false))
  80. if !initial {
  81. cm.l.Info("Drop inactive setting has changed",
  82. "oldBool", old,
  83. "newBool", cm.dropInactive.Load(),
  84. )
  85. }
  86. }
  87. }
  88. func (cm *connectionManager) getInactivityTimeout() time.Duration {
  89. return (time.Duration)(cm.inactivityTimeout.Load())
  90. }
  91. func (cm *connectionManager) In(h *HostInfo) {
  92. h.markIn()
  93. }
  94. // OutNoRebind records outbound traffic without consuming the rebind epoch, for relayed sends: the direct path
  95. // to the relay consumes the edge, the via send must not.
  96. func (cm *connectionManager) OutNoRebind(h *HostInfo) {
  97. h.markOutOnly()
  98. }
  99. // Out records outbound traffic and reports whether we rebound since this tunnel last sent
  100. func (cm *connectionManager) Out(h *HostInfo) bool {
  101. return h.markOut(cm.intf.rebindEpoch.Load())
  102. }
  103. func (cm *connectionManager) RelayUsed(localIndex uint32) {
  104. cm.relayUsedLock.RLock()
  105. // If this already exists, return
  106. if _, ok := cm.relayUsed[localIndex]; ok {
  107. cm.relayUsedLock.RUnlock()
  108. return
  109. }
  110. cm.relayUsedLock.RUnlock()
  111. cm.relayUsedLock.Lock()
  112. cm.relayUsed[localIndex] = struct{}{}
  113. cm.relayUsedLock.Unlock()
  114. }
  115. // getAndResetTrafficCheck returns if there was any inbound or outbound traffic within the last tick and
  116. // resets the state for this local index
  117. func (cm *connectionManager) getAndResetTrafficCheck(h *HostInfo, now time.Time) (bool, bool) {
  118. in, out := h.takeTraffic()
  119. if in || out {
  120. h.lastUsed = now
  121. }
  122. return in, out
  123. }
  124. func (cm *connectionManager) Start(ctx context.Context) {
  125. clockSource := time.NewTicker(cm.trafficTimer.t.tickDuration)
  126. defer clockSource.Stop()
  127. p := []byte("")
  128. nb := make([]byte, 12, 12)
  129. out := make([]byte, mtu)
  130. for {
  131. select {
  132. case <-ctx.Done():
  133. return
  134. case now := <-clockSource.C:
  135. cm.trafficTimer.Advance(now)
  136. for {
  137. localIndex, has := cm.trafficTimer.Purge()
  138. if !has {
  139. break
  140. }
  141. cm.doTrafficCheck(localIndex, p, nb, out, now)
  142. }
  143. }
  144. }
  145. }
  146. func (cm *connectionManager) doTrafficCheck(localIndex uint32, p, nb, out []byte, now time.Time) {
  147. decision, hostinfo, primary := cm.makeTrafficDecision(localIndex, now)
  148. switch decision {
  149. case deleteTunnel:
  150. // Local delete only, clearing the lighthouse cache if this was the last hostinfo for the vpn addr
  151. cm.intf.closeTunnel(hostinfo)
  152. case closeTunnel:
  153. cm.intf.sendCloseTunnel(hostinfo)
  154. cm.intf.closeTunnel(hostinfo)
  155. case swapPrimary:
  156. cm.swapPrimary(hostinfo, primary)
  157. case migrateRelays:
  158. cm.migrateRelayUsed(hostinfo, primary)
  159. case tryRehandshake:
  160. cm.tryRehandshake(hostinfo)
  161. case sendTestPacket:
  162. cm.intf.SendMessageToHostInfo(header.Test, header.TestRequest, hostinfo, p, nb, out)
  163. }
  164. cm.resetRelayTrafficCheck(hostinfo)
  165. }
  166. func (cm *connectionManager) resetRelayTrafficCheck(hostinfo *HostInfo) {
  167. if hostinfo != nil {
  168. cm.relayUsedLock.Lock()
  169. defer cm.relayUsedLock.Unlock()
  170. // No need to migrate any relays, delete usage info now.
  171. for _, idx := range hostinfo.relayState.CopyRelayForIdxs() {
  172. delete(cm.relayUsed, idx)
  173. }
  174. }
  175. }
  176. func (cm *connectionManager) migrateRelayUsed(oldhostinfo, newhostinfo *HostInfo) {
  177. relayFor := oldhostinfo.relayState.CopyAllRelayFor()
  178. for _, r := range relayFor {
  179. existing, ok := newhostinfo.relayState.QueryRelayForByIp(r.PeerAddr)
  180. var index uint32
  181. var relayFrom netip.Addr
  182. var relayTo netip.Addr
  183. switch {
  184. case ok:
  185. switch existing.State {
  186. case Established, PeerRequested, Disestablished:
  187. // This relay already exists in newhostinfo, then do nothing.
  188. continue
  189. case Requested:
  190. // The relay exists in a Requested state; re-send the request
  191. index = existing.LocalIndex
  192. switch r.Type {
  193. case TerminalType:
  194. relayFrom = cm.intf.myVpnAddrs[0]
  195. relayTo = existing.PeerAddr
  196. case ForwardingType:
  197. relayFrom = existing.PeerAddr
  198. relayTo = newhostinfo.vpnAddrs[0]
  199. default:
  200. // should never happen
  201. panic(fmt.Sprintf("Migrating unknown relay type: %v", r.Type))
  202. }
  203. }
  204. case !ok:
  205. cm.relayUsedLock.RLock()
  206. if _, relayUsed := cm.relayUsed[r.LocalIndex]; !relayUsed {
  207. // The relay hasn't been used; don't migrate it.
  208. cm.relayUsedLock.RUnlock()
  209. continue
  210. }
  211. cm.relayUsedLock.RUnlock()
  212. // The relay doesn't exist at all; create some relay state and send the request.
  213. var err error
  214. index, err = AddRelay(cm.l, newhostinfo, cm.hostMap, r.PeerAddr, nil, r.Type, Requested)
  215. if err != nil {
  216. cm.l.Error("failed to migrate relay to new hostinfo", "error", err)
  217. continue
  218. }
  219. switch r.Type {
  220. case TerminalType:
  221. relayFrom = cm.intf.myVpnAddrs[0]
  222. relayTo = r.PeerAddr
  223. case ForwardingType:
  224. relayFrom = r.PeerAddr
  225. relayTo = newhostinfo.vpnAddrs[0]
  226. default:
  227. // should never happen
  228. panic(fmt.Sprintf("Migrating unknown relay type: %v", r.Type))
  229. }
  230. }
  231. // Send a CreateRelayRequest to the peer.
  232. req := NebulaControl{
  233. Type: NebulaControl_CreateRelayRequest,
  234. InitiatorRelayIndex: index,
  235. }
  236. switch newhostinfo.GetCert().Certificate.Version() {
  237. case cert.Version1:
  238. if !relayFrom.Is4() {
  239. cm.l.Error("can not migrate v1 relay with a v6 network because the relay is not running a current nebula version")
  240. continue
  241. }
  242. if !relayTo.Is4() {
  243. cm.l.Error("can not migrate v1 relay with a v6 remote network because the relay is not running a current nebula version")
  244. continue
  245. }
  246. b := relayFrom.As4()
  247. req.OldRelayFromAddr = binary.BigEndian.Uint32(b[:])
  248. b = relayTo.As4()
  249. req.OldRelayToAddr = binary.BigEndian.Uint32(b[:])
  250. case cert.Version2:
  251. req.RelayFromAddr = netAddrToProtoAddr(relayFrom)
  252. req.RelayToAddr = netAddrToProtoAddr(relayTo)
  253. default:
  254. newhostinfo.logger(cm.l).Error("Unknown certificate version found while attempting to migrate relay")
  255. continue
  256. }
  257. msg, err := req.Marshal()
  258. if err != nil {
  259. cm.l.Error("failed to marshal Control message to migrate relay", "error", err)
  260. } else {
  261. cm.intf.SendMessageToHostInfo(header.Control, 0, newhostinfo, msg, make([]byte, 12), make([]byte, mtu))
  262. cm.l.Info("send CreateRelayRequest",
  263. "relayFrom", relayFrom,
  264. "relayTo", relayTo,
  265. "initiatorRelayIndex", req.InitiatorRelayIndex,
  266. "responderRelayIndex", req.ResponderRelayIndex,
  267. "vpnAddrs", newhostinfo.vpnAddrs,
  268. )
  269. }
  270. }
  271. }
  272. func (cm *connectionManager) makeTrafficDecision(localIndex uint32, now time.Time) (trafficDecision, *HostInfo, *HostInfo) {
  273. // Read lock the main hostmap to order decisions based on tunnels being the primary tunnel
  274. cm.hostMap.RLock()
  275. defer cm.hostMap.RUnlock()
  276. hostinfo := cm.hostMap.Indexes[localIndex]
  277. if hostinfo == nil {
  278. cm.l.Debug("Not found in hostmap", "localIndex", localIndex)
  279. return doNothing, nil, nil
  280. }
  281. if cm.isInvalidCertificate(now, hostinfo) {
  282. return closeTunnel, hostinfo, nil
  283. }
  284. if hostinfo.ConnectionState != nil && hostinfo.ConnectionState.messageCounter.Load() >= RejectAfterMessages {
  285. // Send path can't encrypt a CloseTunnel notify, so just delete locally; the peer recovers via recv_error.
  286. hostinfo.logger(cm.l).Error("Dropping tunnel, message counter is exhausted")
  287. return deleteTunnel, hostinfo, nil
  288. }
  289. primary := cm.hostMap.Hosts[hostinfo.vpnAddrs[0]]
  290. mainHostInfo := true
  291. if primary != nil && primary != hostinfo {
  292. mainHostInfo = false
  293. }
  294. // Check for traffic on this hostinfo
  295. inTraffic, outTraffic := cm.getAndResetTrafficCheck(hostinfo, now)
  296. // A hostinfo is determined alive if there is incoming traffic
  297. if inTraffic {
  298. decision := doNothing
  299. if cm.l.Enabled(context.Background(), slog.LevelDebug) {
  300. hostinfo.logger(cm.l).Debug("Tunnel status",
  301. "tunnelCheck", m{"state": "alive", "method": "passive"},
  302. )
  303. }
  304. hostinfo.setPendingDeletion(false)
  305. if mainHostInfo {
  306. decision = tryRehandshake
  307. } else {
  308. if cm.shouldSwapPrimary(hostinfo) {
  309. decision = swapPrimary
  310. } else {
  311. // migrate the relays to the primary, if in use.
  312. decision = migrateRelays
  313. }
  314. }
  315. cm.trafficTimer.Add(hostinfo.localIndexId, cm.checkInterval)
  316. if !outTraffic {
  317. // Send a punch packet to keep the NAT state alive
  318. cm.punchy.SendPunch(hostinfo)
  319. }
  320. return decision, hostinfo, primary
  321. }
  322. if hostinfo.isPendingDeletion() {
  323. // We have already sent a test packet and nothing was returned, this hostinfo is dead
  324. hostinfo.logger(cm.l).Info("Tunnel status",
  325. "tunnelCheck", m{"state": "dead", "method": "active"},
  326. )
  327. return deleteTunnel, hostinfo, nil
  328. }
  329. decision := doNothing
  330. if hostinfo != nil && hostinfo.ConnectionState != nil && mainHostInfo {
  331. if !outTraffic {
  332. inactiveFor, isInactive := cm.isInactive(hostinfo, now)
  333. if isInactive {
  334. // Tunnel is inactive, tear it down
  335. hostinfo.logger(cm.l).Info("Dropping tunnel due to inactivity",
  336. "inactiveDuration", inactiveFor,
  337. "primary", mainHostInfo,
  338. )
  339. return closeTunnel, hostinfo, primary
  340. }
  341. // If we aren't sending or receiving traffic then its an unused tunnel and we don't to test the tunnel.
  342. // Just maintain NAT state if configured to do so.
  343. cm.punchy.SendPunch(hostinfo)
  344. cm.trafficTimer.Add(hostinfo.localIndexId, cm.checkInterval)
  345. return doNothing, nil, nil
  346. }
  347. // We aren't receiving traffic but we are sending it. The outbound
  348. // traffic itself refreshes the primary remote's NAT state; this
  349. // fans out to non-primary remotes, but only if target_all_remotes
  350. // is configured.
  351. cm.punchy.SendPunchToAll(hostinfo)
  352. if cm.l.Enabled(context.Background(), slog.LevelDebug) {
  353. hostinfo.logger(cm.l).Debug("Tunnel status",
  354. "tunnelCheck", m{"state": "testing", "method": "active"},
  355. )
  356. }
  357. // Send a test packet to trigger an authenticated tunnel test, this should suss out any lingering tunnel issues
  358. decision = sendTestPacket
  359. } else {
  360. if cm.l.Enabled(context.Background(), slog.LevelDebug) {
  361. hostinfo.logger(cm.l).Debug("Hostinfo sadness")
  362. }
  363. }
  364. hostinfo.setPendingDeletion(true)
  365. cm.trafficTimer.Add(hostinfo.localIndexId, cm.pendingDeletionInterval)
  366. return decision, hostinfo, nil
  367. }
  368. func (cm *connectionManager) isInactive(hostinfo *HostInfo, now time.Time) (time.Duration, bool) {
  369. if cm.dropInactive.Load() == false {
  370. // We aren't configured to drop inactive tunnels
  371. return 0, false
  372. }
  373. inactiveDuration := now.Sub(hostinfo.lastUsed)
  374. if inactiveDuration < cm.getInactivityTimeout() {
  375. // It's not considered inactive
  376. return inactiveDuration, false
  377. }
  378. // The tunnel is inactive
  379. return inactiveDuration, true
  380. }
  381. func (cm *connectionManager) shouldSwapPrimary(current *HostInfo) bool {
  382. // The primary tunnel is the most recent handshake to complete locally and should work entirely fine.
  383. // If we are here then we have multiple tunnels for a host pair and neither side believes the same tunnel is primary.
  384. // Let's sort this out.
  385. // Only one side should swap because if both swap then we may never resolve to a single tunnel.
  386. // vpn addr is static across all tunnels for this host pair so lets
  387. // use that to determine if we should consider swapping.
  388. if current.vpnAddrs[0].Compare(cm.intf.myVpnAddrs[0]) < 0 {
  389. // Their primary vpn addr is less than mine. Do not swap.
  390. return false
  391. }
  392. if current.ConnectionState.messageCounter.Load() >= RehandshakeAfterMessages {
  393. // This tunnel is being rolled for counter exhaustion, never swap back onto its spent key.
  394. return false
  395. }
  396. crt := cm.intf.pki.getCertState().getCertificate(current.ConnectionState.myCert.Version())
  397. if crt == nil {
  398. //my cert was reloaded away. We should definitely swap from this tunnel
  399. return true
  400. }
  401. // If this tunnel is using the latest certificate then we should swap it to primary for a bit and see if things
  402. // settle down.
  403. return bytes.Equal(current.ConnectionState.myCert.Signature(), crt.Signature())
  404. }
  405. func (cm *connectionManager) swapPrimary(current, primary *HostInfo) {
  406. cm.hostMap.Lock()
  407. // Make sure the primary is still the same after the write lock. This avoids a race with a rehandshake.
  408. if cm.hostMap.Hosts[current.vpnAddrs[0]] == primary {
  409. cm.hostMap.unlockedMakePrimary(current)
  410. }
  411. cm.hostMap.Unlock()
  412. }
  413. // isInvalidCertificate decides if we should destroy a tunnel.
  414. // returns true if pki.disconnect_invalid is true and the certificate is no longer valid.
  415. // Blocklisted certificates will skip the pki.disconnect_invalid check and return true.
  416. func (cm *connectionManager) isInvalidCertificate(now time.Time, hostinfo *HostInfo) bool {
  417. remoteCert := hostinfo.GetCert()
  418. if remoteCert == nil {
  419. return false //don't tear down tunnels for handshakes in progress
  420. }
  421. caPool := cm.intf.pki.GetCAPool()
  422. err := caPool.VerifyCachedCertificate(now, remoteCert)
  423. if err == nil {
  424. return false //cert is still valid! yay!
  425. } else if err == cert.ErrBlockListed { //avoiding errors.Is for speed
  426. // Block listed certificates should always be disconnected
  427. hostinfo.logger(cm.l).Info("Remote certificate is blocked, tearing down the tunnel",
  428. "error", err,
  429. "fingerprint", remoteCert.Fingerprint,
  430. )
  431. return true
  432. } else if cm.intf.disconnectInvalid.Load() {
  433. hostinfo.logger(cm.l).Info("Remote certificate is no longer valid, tearing down the tunnel",
  434. "error", err,
  435. "fingerprint", remoteCert.Fingerprint,
  436. )
  437. return true
  438. } else {
  439. //if we reach here, the cert is no longer valid, but we're configured to keep tunnels from now-invalid certs open
  440. return false
  441. }
  442. }
  443. func (cm *connectionManager) tryRehandshake(hostinfo *HostInfo) {
  444. cs := cm.intf.pki.getCertState()
  445. curCrt := hostinfo.ConnectionState.myCert
  446. curCrtVersion := curCrt.Version()
  447. myCrt := cs.getCertificate(curCrtVersion)
  448. if myCrt == nil {
  449. cm.l.Info("Re-handshaking with remote",
  450. "vpnAddrs", hostinfo.vpnAddrs,
  451. "version", curCrtVersion,
  452. "reason", "local certificate removed",
  453. )
  454. cm.intf.handshakeManager.StartHandshake(hostinfo.vpnAddrs[0], nil)
  455. return
  456. }
  457. peerCrt := hostinfo.ConnectionState.peerCert
  458. if peerCrt != nil && curCrtVersion < peerCrt.Certificate.Version() {
  459. // if our certificate version is less than theirs, and we have a matching version available, rehandshake?
  460. if cs.getCertificate(peerCrt.Certificate.Version()) != nil {
  461. cm.l.Info("Re-handshaking with remote",
  462. "vpnAddrs", hostinfo.vpnAddrs,
  463. "version", curCrtVersion,
  464. "peerVersion", peerCrt.Certificate.Version(),
  465. "reason", "local certificate version lower than peer, attempting to correct",
  466. )
  467. cm.intf.handshakeManager.StartHandshake(hostinfo.vpnAddrs[0], func(hh *HandshakeHostInfo) {
  468. hh.initiatingVersionOverride = peerCrt.Certificate.Version()
  469. })
  470. return
  471. }
  472. }
  473. if !bytes.Equal(curCrt.Signature(), myCrt.Signature()) {
  474. cm.l.Info("Re-handshaking with remote",
  475. "vpnAddrs", hostinfo.vpnAddrs,
  476. "reason", "local certificate is not current",
  477. )
  478. cm.intf.handshakeManager.StartHandshake(hostinfo.vpnAddrs[0], nil)
  479. return
  480. }
  481. if curCrtVersion < cs.initiatingVersion {
  482. cm.l.Info("Re-handshaking with remote",
  483. "vpnAddrs", hostinfo.vpnAddrs,
  484. "reason", "current cert version < pki.initiatingVersion",
  485. )
  486. cm.intf.handshakeManager.StartHandshake(hostinfo.vpnAddrs[0], nil)
  487. return
  488. }
  489. if hostinfo.ConnectionState.messageCounter.Load() >= RehandshakeAfterMessages {
  490. cm.l.Info("Re-handshaking with remote",
  491. "vpnAddrs", hostinfo.vpnAddrs,
  492. "reason", "message counter rehandshake threshold reached",
  493. )
  494. cm.intf.handshakeManager.StartHandshake(hostinfo.vpnAddrs[0], nil)
  495. return
  496. }
  497. }