1
0

connection_manager.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550
  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. }
  162. func (cm *connectionManager) resetRelayTrafficCheck(hostinfo *HostInfo) {
  163. if hostinfo != nil {
  164. cm.relayUsedLock.Lock()
  165. defer cm.relayUsedLock.Unlock()
  166. // No need to migrate any relays, delete usage info now.
  167. for _, idx := range hostinfo.relayState.CopyRelayForIdxs() {
  168. delete(cm.relayUsed, idx)
  169. }
  170. }
  171. }
  172. func (cm *connectionManager) migrateRelayUsed(oldhostinfo, newhostinfo *HostInfo) {
  173. relayFor := oldhostinfo.relayState.CopyAllRelayFor()
  174. for _, r := range relayFor {
  175. existing, ok := newhostinfo.relayState.QueryRelayForByIp(r.PeerAddr)
  176. var index uint32
  177. var relayFrom netip.Addr
  178. var relayTo netip.Addr
  179. switch {
  180. case ok:
  181. switch existing.State {
  182. case Established, PeerRequested, Disestablished:
  183. // This relay already exists in newhostinfo, then do nothing.
  184. continue
  185. case Requested:
  186. // The relay exists in a Requested state; re-send the request
  187. index = existing.LocalIndex
  188. switch r.Type {
  189. case TerminalType:
  190. relayFrom = cm.intf.myVpnAddrs[0]
  191. relayTo = existing.PeerAddr
  192. case ForwardingType:
  193. relayFrom = existing.PeerAddr
  194. relayTo = newhostinfo.vpnAddrs[0]
  195. default:
  196. // should never happen
  197. panic(fmt.Sprintf("Migrating unknown relay type: %v", r.Type))
  198. }
  199. }
  200. case !ok:
  201. cm.relayUsedLock.RLock()
  202. if _, relayUsed := cm.relayUsed[r.LocalIndex]; !relayUsed {
  203. // The relay hasn't been used; don't migrate it.
  204. cm.relayUsedLock.RUnlock()
  205. continue
  206. }
  207. cm.relayUsedLock.RUnlock()
  208. // The relay doesn't exist at all; create some relay state and send the request.
  209. var err error
  210. index, err = AddRelay(cm.l, newhostinfo, cm.hostMap, r.PeerAddr, nil, r.Type, Requested)
  211. if err != nil {
  212. cm.l.Error("failed to migrate relay to new hostinfo", "error", err)
  213. continue
  214. }
  215. switch r.Type {
  216. case TerminalType:
  217. relayFrom = cm.intf.myVpnAddrs[0]
  218. relayTo = r.PeerAddr
  219. case ForwardingType:
  220. relayFrom = r.PeerAddr
  221. relayTo = newhostinfo.vpnAddrs[0]
  222. default:
  223. // should never happen
  224. panic(fmt.Sprintf("Migrating unknown relay type: %v", r.Type))
  225. }
  226. }
  227. // Send a CreateRelayRequest to the peer.
  228. req := NebulaControl{
  229. Type: NebulaControl_CreateRelayRequest,
  230. InitiatorRelayIndex: index,
  231. }
  232. switch newhostinfo.GetCert().Certificate.Version() {
  233. case cert.Version1:
  234. if !relayFrom.Is4() {
  235. cm.l.Error("can not migrate v1 relay with a v6 network because the relay is not running a current nebula version")
  236. continue
  237. }
  238. if !relayTo.Is4() {
  239. cm.l.Error("can not migrate v1 relay with a v6 remote network because the relay is not running a current nebula version")
  240. continue
  241. }
  242. b := relayFrom.As4()
  243. req.OldRelayFromAddr = binary.BigEndian.Uint32(b[:])
  244. b = relayTo.As4()
  245. req.OldRelayToAddr = binary.BigEndian.Uint32(b[:])
  246. case cert.Version2:
  247. req.RelayFromAddr = netAddrToProtoAddr(relayFrom)
  248. req.RelayToAddr = netAddrToProtoAddr(relayTo)
  249. default:
  250. newhostinfo.logger(cm.l).Error("Unknown certificate version found while attempting to migrate relay")
  251. continue
  252. }
  253. msg, err := req.Marshal()
  254. if err != nil {
  255. cm.l.Error("failed to marshal Control message to migrate relay", "error", err)
  256. } else {
  257. cm.intf.SendMessageToHostInfo(header.Control, 0, newhostinfo, msg, make([]byte, 12), make([]byte, mtu))
  258. cm.l.Info("send CreateRelayRequest",
  259. "relayFrom", relayFrom,
  260. "relayTo", relayTo,
  261. "initiatorRelayIndex", req.InitiatorRelayIndex,
  262. "responderRelayIndex", req.ResponderRelayIndex,
  263. "vpnAddrs", newhostinfo.vpnAddrs,
  264. )
  265. }
  266. }
  267. }
  268. func (cm *connectionManager) makeTrafficDecision(localIndex uint32, now time.Time) (trafficDecision, *HostInfo, *HostInfo) {
  269. // Read lock the main hostmap to order decisions based on tunnels being the primary tunnel
  270. cm.hostMap.RLock()
  271. defer cm.hostMap.RUnlock()
  272. hostinfo := cm.hostMap.Indexes[localIndex]
  273. if hostinfo == nil {
  274. cm.l.Debug("Not found in hostmap", "localIndex", localIndex)
  275. return doNothing, nil, nil
  276. }
  277. if cm.isInvalidCertificate(now, hostinfo) {
  278. return closeTunnel, hostinfo, nil
  279. }
  280. primary := cm.hostMap.Hosts[hostinfo.vpnAddrs[0]]
  281. mainHostInfo := true
  282. if primary != nil && primary != hostinfo {
  283. mainHostInfo = false
  284. }
  285. // Check for traffic on this hostinfo
  286. inTraffic, outTraffic := cm.getAndResetTrafficCheck(hostinfo, now)
  287. // A hostinfo is determined alive if there is incoming traffic
  288. if inTraffic {
  289. decision := doNothing
  290. if cm.l.Enabled(context.Background(), slog.LevelDebug) {
  291. hostinfo.logger(cm.l).Debug("Tunnel status",
  292. "tunnelCheck", m{"state": "alive", "method": "passive"},
  293. )
  294. }
  295. hostinfo.pendingDeletion.Store(false)
  296. if mainHostInfo {
  297. decision = tryRehandshake
  298. } else {
  299. if cm.shouldSwapPrimary(hostinfo) {
  300. decision = swapPrimary
  301. } else {
  302. // migrate the relays to the primary, if in use.
  303. decision = migrateRelays
  304. }
  305. }
  306. cm.trafficTimer.Add(hostinfo.localIndexId, cm.checkInterval)
  307. if !outTraffic {
  308. // Send a punch packet to keep the NAT state alive
  309. cm.punchy.SendPunch(hostinfo)
  310. }
  311. return decision, hostinfo, primary
  312. }
  313. if hostinfo.pendingDeletion.Load() {
  314. // We have already sent a test packet and nothing was returned, this hostinfo is dead
  315. hostinfo.logger(cm.l).Info("Tunnel status",
  316. "tunnelCheck", m{"state": "dead", "method": "active"},
  317. )
  318. return deleteTunnel, hostinfo, nil
  319. }
  320. decision := doNothing
  321. if hostinfo != nil && hostinfo.ConnectionState != nil && mainHostInfo {
  322. if !outTraffic {
  323. inactiveFor, isInactive := cm.isInactive(hostinfo, now)
  324. if isInactive {
  325. // Tunnel is inactive, tear it down
  326. hostinfo.logger(cm.l).Info("Dropping tunnel due to inactivity",
  327. "inactiveDuration", inactiveFor,
  328. "primary", mainHostInfo,
  329. )
  330. return closeTunnel, hostinfo, primary
  331. }
  332. // If we aren't sending or receiving traffic then its an unused tunnel and we don't to test the tunnel.
  333. // Just maintain NAT state if configured to do so.
  334. cm.punchy.SendPunch(hostinfo)
  335. cm.trafficTimer.Add(hostinfo.localIndexId, cm.checkInterval)
  336. return doNothing, nil, nil
  337. }
  338. // We aren't receiving traffic but we are sending it. The outbound
  339. // traffic itself refreshes the primary remote's NAT state; this
  340. // fans out to non-primary remotes, but only if target_all_remotes
  341. // is configured.
  342. cm.punchy.SendPunchToAll(hostinfo)
  343. if cm.l.Enabled(context.Background(), slog.LevelDebug) {
  344. hostinfo.logger(cm.l).Debug("Tunnel status",
  345. "tunnelCheck", m{"state": "testing", "method": "active"},
  346. )
  347. }
  348. // Send a test packet to trigger an authenticated tunnel test, this should suss out any lingering tunnel issues
  349. decision = sendTestPacket
  350. } else {
  351. if cm.l.Enabled(context.Background(), slog.LevelDebug) {
  352. hostinfo.logger(cm.l).Debug("Hostinfo sadness")
  353. }
  354. }
  355. hostinfo.pendingDeletion.Store(true)
  356. cm.trafficTimer.Add(hostinfo.localIndexId, cm.pendingDeletionInterval)
  357. return decision, hostinfo, nil
  358. }
  359. func (cm *connectionManager) isInactive(hostinfo *HostInfo, now time.Time) (time.Duration, bool) {
  360. if cm.dropInactive.Load() == false {
  361. // We aren't configured to drop inactive tunnels
  362. return 0, false
  363. }
  364. inactiveDuration := now.Sub(hostinfo.lastUsed)
  365. if inactiveDuration < cm.getInactivityTimeout() {
  366. // It's not considered inactive
  367. return inactiveDuration, false
  368. }
  369. // The tunnel is inactive
  370. return inactiveDuration, true
  371. }
  372. func (cm *connectionManager) shouldSwapPrimary(current *HostInfo) bool {
  373. // The primary tunnel is the most recent handshake to complete locally and should work entirely fine.
  374. // If we are here then we have multiple tunnels for a host pair and neither side believes the same tunnel is primary.
  375. // Let's sort this out.
  376. // Only one side should swap because if both swap then we may never resolve to a single tunnel.
  377. // vpn addr is static across all tunnels for this host pair so lets
  378. // use that to determine if we should consider swapping.
  379. if current.vpnAddrs[0].Compare(cm.intf.myVpnAddrs[0]) < 0 {
  380. // Their primary vpn addr is less than mine. Do not swap.
  381. return false
  382. }
  383. crt := cm.intf.pki.getCertState().getCertificate(current.ConnectionState.myCert.Version())
  384. if crt == nil {
  385. //my cert was reloaded away. We should definitely swap from this tunnel
  386. return true
  387. }
  388. // If this tunnel is using the latest certificate then we should swap it to primary for a bit and see if things
  389. // settle down.
  390. return bytes.Equal(current.ConnectionState.myCert.Signature(), crt.Signature())
  391. }
  392. func (cm *connectionManager) swapPrimary(current, primary *HostInfo) {
  393. cm.hostMap.Lock()
  394. // Make sure the primary is still the same after the write lock. This avoids a race with a rehandshake.
  395. if cm.hostMap.Hosts[current.vpnAddrs[0]] == primary {
  396. cm.hostMap.unlockedMakePrimary(current)
  397. }
  398. cm.hostMap.Unlock()
  399. }
  400. // isInvalidCertificate decides if we should destroy a tunnel.
  401. // returns true if pki.disconnect_invalid is true and the certificate is no longer valid.
  402. // Blocklisted certificates will skip the pki.disconnect_invalid check and return true.
  403. func (cm *connectionManager) isInvalidCertificate(now time.Time, hostinfo *HostInfo) bool {
  404. remoteCert := hostinfo.GetCert()
  405. if remoteCert == nil {
  406. return false //don't tear down tunnels for handshakes in progress
  407. }
  408. caPool := cm.intf.pki.GetCAPool()
  409. err := caPool.VerifyCachedCertificate(now, remoteCert)
  410. if err == nil {
  411. return false //cert is still valid! yay!
  412. } else if err == cert.ErrBlockListed { //avoiding errors.Is for speed
  413. // Block listed certificates should always be disconnected
  414. hostinfo.logger(cm.l).Info("Remote certificate is blocked, tearing down the tunnel",
  415. "error", err,
  416. "fingerprint", remoteCert.Fingerprint,
  417. )
  418. return true
  419. } else if cm.intf.disconnectInvalid.Load() {
  420. hostinfo.logger(cm.l).Info("Remote certificate is no longer valid, tearing down the tunnel",
  421. "error", err,
  422. "fingerprint", remoteCert.Fingerprint,
  423. )
  424. return true
  425. } else {
  426. //if we reach here, the cert is no longer valid, but we're configured to keep tunnels from now-invalid certs open
  427. return false
  428. }
  429. }
  430. func (cm *connectionManager) tryRehandshake(hostinfo *HostInfo) {
  431. cs := cm.intf.pki.getCertState()
  432. curCrt := hostinfo.ConnectionState.myCert
  433. curCrtVersion := curCrt.Version()
  434. myCrt := cs.getCertificate(curCrtVersion)
  435. if myCrt == nil {
  436. cm.l.Info("Re-handshaking with remote",
  437. "vpnAddrs", hostinfo.vpnAddrs,
  438. "version", curCrtVersion,
  439. "reason", "local certificate removed",
  440. )
  441. cm.intf.handshakeManager.StartHandshake(hostinfo.vpnAddrs[0], nil)
  442. return
  443. }
  444. peerCrt := hostinfo.ConnectionState.peerCert
  445. if peerCrt != nil && curCrtVersion < peerCrt.Certificate.Version() {
  446. // if our certificate version is less than theirs, and we have a matching version available, rehandshake?
  447. if cs.getCertificate(peerCrt.Certificate.Version()) != nil {
  448. cm.l.Info("Re-handshaking with remote",
  449. "vpnAddrs", hostinfo.vpnAddrs,
  450. "version", curCrtVersion,
  451. "peerVersion", peerCrt.Certificate.Version(),
  452. "reason", "local certificate version lower than peer, attempting to correct",
  453. )
  454. cm.intf.handshakeManager.StartHandshake(hostinfo.vpnAddrs[0], func(hh *HandshakeHostInfo) {
  455. hh.initiatingVersionOverride = peerCrt.Certificate.Version()
  456. })
  457. return
  458. }
  459. }
  460. if !bytes.Equal(curCrt.Signature(), myCrt.Signature()) {
  461. cm.l.Info("Re-handshaking with remote",
  462. "vpnAddrs", hostinfo.vpnAddrs,
  463. "reason", "local certificate is not current",
  464. )
  465. cm.intf.handshakeManager.StartHandshake(hostinfo.vpnAddrs[0], nil)
  466. return
  467. }
  468. if curCrtVersion < cs.initiatingVersion {
  469. cm.l.Info("Re-handshaking with remote",
  470. "vpnAddrs", hostinfo.vpnAddrs,
  471. "reason", "current cert version < pki.initiatingVersion",
  472. )
  473. cm.intf.handshakeManager.StartHandshake(hostinfo.vpnAddrs[0], nil)
  474. return
  475. }
  476. }