Debian Codegraph @

connection_manager.go

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