Debian Codegraph @

handshake_manager.go

raw
1 package nebula
2
3 import (
4 "bytes"
5 "context"
6 "crypto/rand"
7 "encoding/binary"
8 "errors"
9 "log/slog"
10 "net/netip"
11 "slices"
12 "sync"
13 "time"
14
15 "github.com/rcrowley/go-metrics"
16 "github.com/slackhq/nebula/cert"
17 "github.com/slackhq/nebula/handshake"
18 "github.com/slackhq/nebula/header"
19 "github.com/slackhq/nebula/udp"
20 )
21
22 const (
23 DefaultHandshakeTryInterval = time.Millisecond * 100
24 DefaultHandshakeRetries = 10
25 DefaultHandshakeTriggerBuffer = 64
26
27 // maxCachedPackets is how many unsent packets we'll buffer per pending
28 // handshake before dropping further ones.
29 maxCachedPackets = 100
30
31 // HandshakePacket map keys mirror the IX protocol stage convention:
32 // stage 0 = the initiator's first message (and what the responder
33 // receives, stripped of header)
34 // stage 2 = the responder's reply
35 // Other handshake patterns will need new keys when added.
36 handshakePacketStage0 uint8 = 0
37 handshakePacketStage2 uint8 = 2
38 )
39
40 var (
41 defaultHandshakeConfig = HandshakeConfig{
42 tryInterval: DefaultHandshakeTryInterval,
43 retries: DefaultHandshakeRetries,
44 triggerBuffer: DefaultHandshakeTriggerBuffer,
45 }
46 )
47
48 type HandshakeConfig struct {
49 tryInterval time.Duration
50 retries int64
51 triggerBuffer int
52
53 messageMetrics *MessageMetrics
54 }
55
56 type HandshakeManager struct {
57 // Mutex for interacting with the vpnIps and indexes maps
58 sync.RWMutex
59
60 vpnIps map[netip.Addr]*HandshakeHostInfo
61 indexes map[uint32]*HandshakeHostInfo
62
63 mainHostMap *HostMap
64 lightHouse *LightHouse
65 outside udp.Conn
66 config HandshakeConfig
67 OutboundHandshakeTimer *LockingTimerWheel[netip.Addr]
68 messageMetrics *MessageMetrics
69 metricInitiated metrics.Counter
70 metricTimedOut metrics.Counter
71 f *Interface
72 l *slog.Logger
73
74 // can be used to trigger outbound handshake for the given vpnIp
75 trigger chan netip.Addr
76 }
77
78 type HandshakeHostInfo struct {
79 sync.Mutex
80
81 startTime time.Time // Time that we first started trying with this handshake
82 ready bool // Is the handshake ready
83 initiatingVersionOverride cert.Version // Should we use a non-default cert version for this handshake?
84 counter int64 // How many attempts have we made so far
85 lastRemotes []netip.AddrPort // Remotes that we sent to during the previous attempt
86 lastRelays []netip.Addr // Relays we attempted to use during the previous attempt
87 packetStore []*cachedPacket // A set of packets to be transmitted once the handshake completes
88
89 hostinfo *HostInfo
90 machine *handshake.Machine // The handshake state machine, set during stage 0 (initiator) or beginHandshake (responder multi-message)
91 }
92
93 func (hh *HandshakeHostInfo) cachePacket(l *slog.Logger, t header.MessageType, st header.MessageSubType, packet []byte, f packetCallback, m *cachedPacketMetrics) {
94 if len(hh.packetStore) < maxCachedPackets {
95 tempPacket := make([]byte, len(packet))
96 copy(tempPacket, packet)
97
98 hh.packetStore = append(hh.packetStore, &cachedPacket{t, st, f, tempPacket})
99 if l.Enabled(context.Background(), slog.LevelDebug) {
100 hh.hostinfo.logger(l).Debug("Packet store",
101 "length", len(hh.packetStore),
102 "stored", true,
103 )
104 }
105
106 } else {
107 m.dropped.Inc(1)
108
109 if l.Enabled(context.Background(), slog.LevelDebug) {
110 hh.hostinfo.logger(l).Debug("Packet store",
111 "length", len(hh.packetStore),
112 "stored", false,
113 )
114 }
115 }
116 }
117
118 func NewHandshakeManager(l *slog.Logger, mainHostMap *HostMap, lightHouse *LightHouse, outside udp.Conn, config HandshakeConfig) *HandshakeManager {
119 return &HandshakeManager{
120 vpnIps: map[netip.Addr]*HandshakeHostInfo{},
121 indexes: map[uint32]*HandshakeHostInfo{},
122 mainHostMap: mainHostMap,
123 lightHouse: lightHouse,
124 outside: outside,
125 config: config,
126 trigger: make(chan netip.Addr, config.triggerBuffer),
127 OutboundHandshakeTimer: NewLockingTimerWheel[netip.Addr](config.tryInterval, hsTimeout(config.retries, config.tryInterval)),
128 messageMetrics: config.messageMetrics,
129 metricInitiated: metrics.GetOrRegisterCounter("handshake_manager.initiated", nil),
130 metricTimedOut: metrics.GetOrRegisterCounter("handshake_manager.timed_out", nil),
131 l: l,
132 }
133 }
134
135 func (hm *HandshakeManager) Run(ctx context.Context) {
136 clockSource := time.NewTicker(hm.config.tryInterval)
137 defer clockSource.Stop()
138
139 for {
140 select {
141 case <-ctx.Done():
142 return
143 case vpnIP := <-hm.trigger:
144 hm.handleOutbound(vpnIP, true)
145 case now := <-clockSource.C:
146 hm.NextOutboundHandshakeTimerTick(now)
147 }
148 }
149 }
150
151 func (hm *HandshakeManager) HandleIncoming(via ViaSender, packet []byte, h *header.H) {
152 // Gate on known handshake subtypes. Unknown subtypes (or future ones we
153 // don't yet support) are dropped here rather than silently routed through
154 // the IX path. Add a case when introducing a new pattern.
155 switch h.Subtype {
156 case header.HandshakeIXPSK0:
157 // supported
158 default:
159 hm.l.Debug("dropping handshake with unsupported subtype",
160 "from", via, "subtype", h.Subtype)
161 return
162 }
163
164 // First remote allow list check before we know the vpnIp
165 if !via.IsRelayed {
166 if !hm.lightHouse.GetRemoteAllowList().AllowUnknownVpnAddr(via.UdpAddr.Addr()) {
167 hm.l.Debug("lighthouse.remote_allow_list denied incoming handshake", "from", via)
168 return
169 }
170 }
171
172 // First message of a new handshake. The wire format requires RemoteIndex
173 // to be zero here (the initiator has no responder index to fill in yet),
174 // and generateIndex never allocates 0, so any non-zero RemoteIndex on a
175 // stage-1 packet is malformed or someone probing for an index collision.
176 // Drop without paying the cost of running noise on a pending Machine.
177 if h.MessageCounter == 1 {
178 if h.RemoteIndex != 0 {
179 hm.l.Debug("dropping stage-1 handshake with non-zero RemoteIndex",
180 "from", via, "remoteIndex", h.RemoteIndex)
181 return
182 }
183 hm.beginHandshake(via, packet, h)
184 return
185 }
186
187 // Continuation message must match a pending handshake by index.
188 // Anything else is an orphaned packet (e.g., late retransmit after
189 // timeout) and is dropped.
190 if hh := hm.queryIndex(h.RemoteIndex); hh != nil {
191 hm.continueHandshake(via, hh, packet)
192 return
193 }
194 }
195
196 func (hm *HandshakeManager) NextOutboundHandshakeTimerTick(now time.Time) {
197 hm.OutboundHandshakeTimer.Advance(now)
198 for {
199 vpnIp, has := hm.OutboundHandshakeTimer.Purge()
200 if !has {
201 break
202 }
203 hm.handleOutbound(vpnIp, false)
204 }
205 }
206
207 func (hm *HandshakeManager) handleOutbound(vpnIp netip.Addr, lighthouseTriggered bool) {
208 hh := hm.queryVpnIp(vpnIp)
209 if hh == nil {
210 return
211 }
212 hh.Lock()
213 defer hh.Unlock()
214
215 hostinfo := hh.hostinfo
216 // If we are out of time, clean up
217 if hh.counter >= hm.config.retries {
218 fields := []any{
219 "udpAddrs", hh.hostinfo.remotes.CopyAddrs(hm.mainHostMap.GetPreferredRanges()),
220 "initiatorIndex", hh.hostinfo.localIndexId,
221 "durationNs", time.Since(hh.startTime).Nanoseconds(),
222 }
223 // hh.machine can be nil here if buildStage0Packet never succeeded
224 // (e.g., no certificate available). In that case there's no useful
225 // handshake metadata to log.
226 if hh.machine != nil {
227 fields = append(fields, "handshake", m{
228 "stage": uint64(hh.machine.MessageIndex()),
229 "style": header.SubTypeName(header.Handshake, hh.machine.Subtype()),
230 })
231 }
232 hh.hostinfo.logger(hm.l).Info("Handshake timed out", fields...)
233 hm.metricTimedOut.Inc(1)
234 hm.DeleteHostInfo(hostinfo)
235 return
236 }
237
238 // Increment the counter to increase our delay, linear backoff
239 hh.counter++
240
241 // Check if we have a handshake packet to transmit yet
242 if !hh.ready {
243 if !hm.buildStage0Packet(hh) {
244 hm.OutboundHandshakeTimer.Add(vpnIp, hm.config.tryInterval*time.Duration(hh.counter))
245 return
246 }
247 }
248
249 // TODO: this hardcodes "always retransmit stage 0", which is correct for
250 // IX (the initiator only ever sends one packet, msg1) but wrong the
251 // moment a 3+ message pattern lands. The retry loop should resend the
252 // most recent outgoing message, not always stage 0. That implies
253 // HandshakeHostInfo tracking a single "currentOutbound" packet (bytes +
254 // header metadata) that gets replaced as the handshake progresses,
255 // instead of indexing into HandshakePacket.
256 stage0 := hostinfo.HandshakePacket[handshakePacketStage0]
257 hsFields := m{
258 "stage": uint64(hh.machine.MessageIndex()),
259 "style": header.SubTypeName(header.Handshake, hh.machine.Subtype()),
260 }
261
262 // Get a remotes object if we don't already have one.
263 // This is mainly to protect us as this should never be the case
264 // NB ^ This comment doesn't jive. It's how the thing gets initialized.
265 // It's the common path. Should it update every time, in case a future LH query/queries give us more info?
266 if hostinfo.remotes == nil {
267 hostinfo.remotes = hm.lightHouse.QueryCache([]netip.Addr{vpnIp})
268 }
269
270 remotes := hostinfo.remotes.CopyAddrs(hm.mainHostMap.GetPreferredRanges())
271 remotesHaveChanged := !slices.Equal(remotes, hh.lastRemotes)
272
273 // We only care about a lighthouse trigger if we have new remotes to send to.
274 // This is a very specific optimization for a fast lighthouse reply.
275 if lighthouseTriggered && !remotesHaveChanged {
276 // If we didn't return here a lighthouse could cause us to aggressively send handshakes
277 return
278 }
279
280 hh.lastRemotes = remotes
281
282 // This will generate a load of queries for hosts with only 1 ip
283 // (such as ones registered to the lighthouse with only a private IP)
284 // So we only do it one time after attempting 5 handshakes already.
285 if len(remotes) <= 1 && hh.counter == 5 {
286 // If we only have 1 remote it is highly likely our query raced with the other host registered within the lighthouse
287 // Our vpnIp here has a tunnel with a lighthouse but has yet to send a host update packet there so we only know about
288 // the learned public ip for them. Query again to short circuit the promotion counter
289 hm.lightHouse.QueryServer(vpnIp)
290 }
291
292 // Send the handshake to all known ips, stage 2 takes care of assigning the hostinfo.remote based on the first to reply
293 var sentTo []netip.AddrPort
294 hostinfo.remotes.ForEach(hm.mainHostMap.GetPreferredRanges(), func(addr netip.AddrPort, _ bool) {
295 hm.messageMetrics.Tx(header.Handshake, hh.machine.Subtype(), 1)
296 err := hm.outside.WriteTo(stage0, addr)
297 if err != nil {
298 // These repeat every attempt, so match the success log below and only shout when the remotes changed
299 level := slog.LevelDebug
300 if remotesHaveChanged {
301 level = slog.LevelError
302 }
303
304 hostinfo.logger(hm.l).Log(context.Background(), level, "Failed to send handshake message",
305 "udpAddr", addr,
306 "initiatorIndex", hostinfo.localIndexId,
307 "handshake", hsFields,
308 "error", err,
309 )
310
311 } else {
312 sentTo = append(sentTo, addr)
313 }
314 })
315
316 // Don't be too noisy or confusing if we fail to send a handshake - if we don't get through we'll eventually log a timeout,
317 // so only log when the list of remotes has changed
318 if remotesHaveChanged {
319 hostinfo.logger(hm.l).Info("Handshake message sent",
320 "udpAddrs", sentTo,
321 "initiatorIndex", hostinfo.localIndexId,
322 "handshake", hsFields,
323 )
324 } else if hm.l.Enabled(context.Background(), slog.LevelDebug) {
325 hostinfo.logger(hm.l).Debug("Handshake message sent",
326 "udpAddrs", sentTo,
327 "initiatorIndex", hostinfo.localIndexId,
328 "handshake", hsFields,
329 )
330 }
331
332 hm.f.relayManager.StartRelays(hm.f, vpnIp, hh, stage0)
333
334 // If a lighthouse triggered this attempt then we are still in the timer wheel and do not need to re-add
335 if !lighthouseTriggered {
336 hm.OutboundHandshakeTimer.Add(vpnIp, hm.config.tryInterval*time.Duration(hh.counter))
337 }
338 }
339
340 // GetOrHandshake will try to find a hostinfo with a fully formed tunnel or start a new handshake if one is not present
341 // The 2nd argument will be true if the hostinfo is ready to transmit traffic
342 func (hm *HandshakeManager) GetOrHandshake(vpnIp netip.Addr, cacheCb func(*HandshakeHostInfo)) (*HostInfo, bool) {
343 hm.mainHostMap.RLock()
344 h, ok := hm.mainHostMap.Hosts[vpnIp]
345 hm.mainHostMap.RUnlock()
346
347 if ok {
348 // Do not attempt promotion if you are a lighthouse
349 if !hm.lightHouse.amLighthouse {
350 h.TryPromoteBest(hm.mainHostMap.GetPreferredRanges(), hm.f)
351 }
352 return h, true
353 }
354
355 return hm.StartHandshake(vpnIp, cacheCb), false
356 }
357
358 // StartHandshake will ensure a handshake is currently being attempted for the provided vpn ip
359 func (hm *HandshakeManager) StartHandshake(vpnAddr netip.Addr, cacheCb func(*HandshakeHostInfo)) *HostInfo {
360 hm.Lock()
361
362 if hh, ok := hm.vpnIps[vpnAddr]; ok {
363 // We are already trying to handshake with this vpn ip
364 if cacheCb != nil {
365 cacheCb(hh)
366 }
367 hm.Unlock()
368 return hh.hostinfo
369 }
370
371 hostinfo := &HostInfo{
372 vpnAddrs: []netip.Addr{vpnAddr},
373 HandshakePacket: make(map[uint8][]byte, 0),
374 relayState: RelayState{
375 relays: nil,
376 relayForByAddr: map[netip.Addr]*Relay{},
377 relayForByIdx: map[uint32]*Relay{},
378 },
379 }
380
381 hh := &HandshakeHostInfo{
382 hostinfo: hostinfo,
383 startTime: time.Now(),
384 }
385 hm.vpnIps[vpnAddr] = hh
386 hm.metricInitiated.Inc(1)
387 hm.OutboundHandshakeTimer.Add(vpnAddr, hm.config.tryInterval)
388
389 if cacheCb != nil {
390 cacheCb(hh)
391 }
392
393 // If this is a static host, we don't need to wait for the HostQueryReply
394 // We can trigger the handshake right now
395 _, doTrigger := hm.lightHouse.GetStaticHostList()[vpnAddr]
396 if !doTrigger {
397 // Add any calculated remotes, and trigger early handshake if one found
398 doTrigger = hm.lightHouse.addCalculatedRemotes(vpnAddr)
399 }
400
401 if doTrigger {
402 select {
403 case hm.trigger <- vpnAddr:
404 default:
405 }
406 }
407
408 hm.Unlock()
409 hm.lightHouse.QueryServer(vpnAddr)
410 return hostinfo
411 }
412
413 var (
414 ErrExistingHostInfo = errors.New("existing hostinfo")
415 ErrAlreadySeen = errors.New("already seen")
416 ErrLocalIndexCollision = errors.New("local index collision")
417 )
418
419 // CheckAndComplete checks for any conflicts in the main and pending hostmap
420 // before adding hostinfo to main. If err is nil, it was added. Otherwise err will be:
421 //
422 // ErrAlreadySeen if we already have an entry in the hostmap that has seen the
423 // exact same handshake packet
424 //
425 // ErrExistingHostInfo if we already have an entry in the hostmap for this
426 // VpnIp and the new handshake was older than the one we currently have
427 //
428 // ErrLocalIndexCollision if we already have an entry in the main or pending
429 // hostmap for the hostinfo.localIndexId.
430 func (hm *HandshakeManager) CheckAndComplete(hostinfo *HostInfo, handshakePacket uint8, f *Interface) (*HostInfo, error) {
431 hm.mainHostMap.Lock()
432 defer hm.mainHostMap.Unlock()
433 hm.Lock()
434 defer hm.Unlock()
435
436 // Check if we already have a tunnel with this vpn ip
437 existingHostInfo, found := hm.mainHostMap.Hosts[hostinfo.vpnAddrs[0]]
438 if found && existingHostInfo != nil {
439 // Is it just a delayed handshake packet? Check every hostinfo we hold for this address.
440 for _, testHostInfo := range hm.mainHostMap.unlockedGetHostList(hostinfo.vpnAddrs[0]) {
441 if bytes.Equal(hostinfo.HandshakePacket[handshakePacket], testHostInfo.HandshakePacket[handshakePacket]) {
442 return testHostInfo, ErrAlreadySeen
443 }
444 }
445
446 // Is this a newer handshake?
447 if existingHostInfo.lastHandshakeTime >= hostinfo.lastHandshakeTime && !existingHostInfo.ConnectionState.initiator {
448 return existingHostInfo, ErrExistingHostInfo
449 }
450
451 existingHostInfo.logger(hm.l).Info("Taking new handshake")
452 }
453
454 existingIndex, found := hm.mainHostMap.Indexes[hostinfo.localIndexId]
455 if found {
456 // We have a collision, but for a different hostinfo
457 return existingIndex, ErrLocalIndexCollision
458 }
459
460 existingPendingIndex, found := hm.indexes[hostinfo.localIndexId]
461 if found && existingPendingIndex.hostinfo != hostinfo {
462 // We have a collision, but for a different hostinfo
463 return existingPendingIndex.hostinfo, ErrLocalIndexCollision
464 }
465
466 existingRemoteIndex, found := hm.mainHostMap.RemoteIndexes[hostinfo.remoteIndexId]
467 if found && existingRemoteIndex != nil && existingRemoteIndex.vpnAddrs[0] != hostinfo.vpnAddrs[0] {
468 // We have a collision, but this can happen since we can't control
469 // the remote ID. Just log about the situation as a note.
470 hostinfo.logger(hm.l).Info("New host shadows existing host remoteIndex",
471 "collision", existingRemoteIndex.vpnAddrs,
472 )
473 }
474
475 hm.mainHostMap.unlockedAddHostInfo(hostinfo, f)
476 return existingHostInfo, nil
477 }
478
479 // Complete is a simpler version of CheckAndComplete when we already know we
480 // won't have a localIndexId collision because we already have an entry in the
481 // pendingHostMap. An existing hostinfo is returned if there was one.
482 func (hm *HandshakeManager) Complete(hostinfo *HostInfo, f *Interface) {
483 hm.mainHostMap.Lock()
484 defer hm.mainHostMap.Unlock()
485 hm.Lock()
486 defer hm.Unlock()
487
488 existingRemoteIndex, found := hm.mainHostMap.RemoteIndexes[hostinfo.remoteIndexId]
489 if found && existingRemoteIndex != nil {
490 // We have a collision, but this can happen since we can't control
491 // the remote ID. Just log about the situation as a note.
492 hostinfo.logger(hm.l).Info("New host shadows existing host remoteIndex",
493 "collision", existingRemoteIndex.vpnAddrs,
494 )
495 }
496
497 // We need to remove from the pending hostmap first to avoid undoing work when after to the main hostmap.
498 hm.unlockedDeleteHostInfo(hostinfo)
499 hm.mainHostMap.unlockedAddHostInfo(hostinfo, f)
500 }
501
502 // allocateIndex generates a unique localIndexId for this HostInfo
503 // and adds it to the pendingHostMap. Will error if we are unable to generate
504 // a unique localIndexId
505 func (hm *HandshakeManager) allocateIndex(hh *HandshakeHostInfo) (uint32, error) {
506 hm.mainHostMap.RLock()
507 defer hm.mainHostMap.RUnlock()
508 hm.Lock()
509 defer hm.Unlock()
510
511 for range 32 {
512 index, err := generateIndex(hm.l)
513 if err != nil {
514 return 0, err
515 }
516
517 _, inPending := hm.indexes[index]
518 _, inMain := hm.mainHostMap.Indexes[index]
519
520 if !inMain && !inPending {
521 hh.hostinfo.localIndexId = index
522 hm.indexes[index] = hh
523 return index, nil
524 }
525 }
526
527 return 0, errors.New("failed to generate unique localIndexId")
528 }
529
530 func (hm *HandshakeManager) DeleteHostInfo(hostinfo *HostInfo) {
531 hm.Lock()
532 defer hm.Unlock()
533 hm.unlockedDeleteHostInfo(hostinfo)
534 }
535
536 func (hm *HandshakeManager) unlockedDeleteHostInfo(hostinfo *HostInfo) {
537 for _, addr := range hostinfo.vpnAddrs {
538 if cur, ok := hm.vpnIps[addr]; ok && cur.hostinfo == hostinfo {
539 delete(hm.vpnIps, addr)
540 }
541 }
542
543 if len(hm.vpnIps) == 0 {
544 hm.vpnIps = map[netip.Addr]*HandshakeHostInfo{}
545 }
546
547 delete(hm.indexes, hostinfo.localIndexId)
548 if len(hm.indexes) == 0 {
549 hm.indexes = map[uint32]*HandshakeHostInfo{}
550 }
551
552 if hm.l.Enabled(context.Background(), slog.LevelDebug) {
553 hm.l.Debug("Pending hostmap hostInfo deleted",
554 "hostMap", m{"mapTotalSize": len(hm.vpnIps),
555 "vpnAddrs": hostinfo.vpnAddrs, "indexNumber": hostinfo.localIndexId, "remoteIndexNumber": hostinfo.remoteIndexId},
556 )
557 }
558 }
559
560 func (hm *HandshakeManager) QueryVpnAddr(vpnIp netip.Addr) *HostInfo {
561 hh := hm.queryVpnIp(vpnIp)
562 if hh != nil {
563 return hh.hostinfo
564 }
565 return nil
566
567 }
568
569 func (hm *HandshakeManager) queryVpnIp(vpnIp netip.Addr) *HandshakeHostInfo {
570 hm.RLock()
571 defer hm.RUnlock()
572 return hm.vpnIps[vpnIp]
573 }
574
575 func (hm *HandshakeManager) QueryIndex(index uint32) *HostInfo {
576 hh := hm.queryIndex(index)
577 if hh != nil {
578 return hh.hostinfo
579 }
580 return nil
581 }
582
583 func (hm *HandshakeManager) queryIndex(index uint32) *HandshakeHostInfo {
584 hm.RLock()
585 defer hm.RUnlock()
586 return hm.indexes[index]
587 }
588
589 func (hm *HandshakeManager) GetPreferredRanges() []netip.Prefix {
590 return hm.mainHostMap.GetPreferredRanges()
591 }
592
593 func (hm *HandshakeManager) ForEachVpnAddr(f controlEach) {
594 hm.RLock()
595 defer hm.RUnlock()
596
597 for _, v := range hm.vpnIps {
598 f(v.hostinfo)
599 }
600 }
601
602 func (hm *HandshakeManager) ForEachIndex(f controlEach) {
603 hm.RLock()
604 defer hm.RUnlock()
605
606 for _, v := range hm.indexes {
607 f(v.hostinfo)
608 }
609 }
610
611 func (hm *HandshakeManager) EmitStats() {
612 hm.RLock()
613 hostLen := len(hm.vpnIps)
614 indexLen := len(hm.indexes)
615 hm.RUnlock()
616
617 metrics.GetOrRegisterGauge("hostmap.pending.hosts", nil).Update(int64(hostLen))
618 metrics.GetOrRegisterGauge("hostmap.pending.indexes", nil).Update(int64(indexLen))
619 hm.mainHostMap.EmitStats()
620 }
621
622 // Utility functions below
623
624 func generateIndex(l *slog.Logger) (uint32, error) {
625 b := make([]byte, 4)
626
627 // Let zero mean we don't know the ID, so don't generate zero
628 var index uint32
629 for index == 0 {
630 _, err := rand.Read(b)
631 if err != nil {
632 l.Error("Failed to generate index", "error", err)
633 return 0, err
634 }
635
636 index = binary.BigEndian.Uint32(b)
637 }
638
639 if l.Enabled(context.Background(), slog.LevelDebug) {
640 l.Debug("Generated index", "index", index)
641 }
642 return index, nil
643 }
644
645 func hsTimeout(tries int64, interval time.Duration) time.Duration {
646 return time.Duration(tries / 2 * ((2 * int64(interval)) + (tries-1)*int64(interval)))
647 }
648
649 // buildStage0Packet creates the initial handshake packet for the initiator.
650 func (hm *HandshakeManager) buildStage0Packet(hh *HandshakeHostInfo) bool {
651 cs := hm.f.pki.getCertState()
652 v := cs.DefaultVersion()
653 if hh.initiatingVersionOverride != cert.VersionPre1 {
654 v = hh.initiatingVersionOverride
655 } else if v < cert.Version2 {
656 for _, a := range hh.hostinfo.vpnAddrs {
657 if a.Is6() {
658 v = cert.Version2
659 break
660 }
661 }
662 }
663
664 cred := cs.GetCredential(v)
665 if cred == nil {
666 hm.f.l.Error("Unable to handshake with host because no certificate is available",
667 "vpnAddrs", hh.hostinfo.vpnAddrs, "certVersion", v)
668 return false
669 }
670
671 machine, err := handshake.NewMachine(
672 v, cs.GetCredential,
673 hm.certVerifier(), func() (uint32, error) { return hm.allocateIndex(hh) },
674 true, header.HandshakeIXPSK0,
675 )
676 if err != nil {
677 hm.f.l.Error("Failed to create handshake machine",
678 "vpnAddrs", hh.hostinfo.vpnAddrs, "error", err)
679 return false
680 }
681
682 msg, err := machine.Initiate(nil)
683 if err != nil {
684 hm.f.l.Error("Failed to initiate handshake",
685 "vpnAddrs", hh.hostinfo.vpnAddrs, "error", err)
686 return false
687 }
688
689 // hostinfo.ConnectionState stays nil until the handshake completes in
690 // continueHandshake. Pre-completion control surfaces guard with nil
691 // checks; the data plane never observes a pending hostinfo.
692 hh.hostinfo.HandshakePacket[handshakePacketStage0] = msg
693 hh.machine = machine
694 hh.ready = true
695 return true
696 }
697
698 // beginHandshake handles an incoming handshake packet that doesn't match any
699 // existing pending handshake. It creates a new responder Machine and processes
700 // the first message.
701 func (hm *HandshakeManager) beginHandshake(via ViaSender, packet []byte, h *header.H) {
702 f := hm.f
703 cs := f.pki.getCertState()
704
705 v := cs.DefaultVersion()
706 if cs.GetCredential(v) == nil {
707 f.l.Error("Unable to handshake with host because no certificate is available",
708 "from", via, "certVersion", v)
709 return
710 }
711
712 machine, err := handshake.NewMachine(
713 v, cs.GetCredential,
714 hm.certVerifier(), func() (uint32, error) { return generateIndex(f.l) },
715 false, header.HandshakeIXPSK0,
716 )
717 if err != nil {
718 f.l.Error("Failed to create handshake machine", "from", via, "error", err)
719 return
720 }
721
722 response, result, err := machine.ProcessPacket(nil, packet)
723 if err != nil {
724 f.l.Error("Failed to process handshake packet", "from", via, "error", err)
725 return
726 }
727
728 if result == nil {
729 // Multi-message pattern: the responder Machine would need to be
730 // registered in hm.indexes so a future inbound packet finds it via
731 // continueHandshake. The current manager doesn't do that yet, so
732 // fail loudly rather than silently dropping the in-flight handshake.
733 // TODO: support multi-message responder flows (XX, pqIX, etc.).
734 // See also the IX-shaped cipher key assignment in handshake.Machine.
735 f.l.Error("multi-message handshake responder is not supported",
736 "from", via, "error", handshake.ErrMultiMessageUnsupported)
737 return
738 }
739
740 remoteCert := result.RemoteCert
741 if remoteCert == nil {
742 f.l.Error("Handshake did not produce a peer certificate", "from", via)
743 return
744 }
745
746 // Validate peer identity
747 vpnAddrs, anyVpnAddrsInCommon, ok := hm.validatePeerCert(via, remoteCert)
748 if !ok {
749 return
750 }
751
752 hostinfo := &HostInfo{
753 ConnectionState: newConnectionStateFromResult(result),
754 localIndexId: result.LocalIndex,
755 remoteIndexId: result.RemoteIndex,
756 vpnAddrs: vpnAddrs,
757 HandshakePacket: make(map[uint8][]byte, 0),
758 lastHandshakeTime: result.HandshakeTime,
759 relayState: RelayState{
760 relays: nil,
761 relayForByAddr: map[netip.Addr]*Relay{},
762 relayForByIdx: map[uint32]*Relay{},
763 },
764 }
765
766 msg := "Handshake message received"
767 if !anyVpnAddrsInCommon {
768 msg = "Handshake message received, but no vpnNetworks in common."
769 }
770 f.l.Info(msg,
771 "vpnAddrs", vpnAddrs,
772 "from", via,
773 "certName", remoteCert.Certificate.Name(),
774 "certVersion", remoteCert.Certificate.Version(),
775 "fingerprint", remoteCert.Fingerprint,
776 "issuer", remoteCert.Certificate.Issuer(),
777 "initiatorIndex", result.RemoteIndex,
778 "responderIndex", result.LocalIndex,
779 "handshake", m{"stage": uint64(machine.MessageIndex()), "style": header.SubTypeName(header.Handshake, machine.Subtype())},
780 )
781
782 // packet aliases the listener's incoming buffer, so this copy must stay.
783 hostinfo.HandshakePacket[handshakePacketStage0] = make([]byte, len(packet[header.Len:]))
784 copy(hostinfo.HandshakePacket[handshakePacketStage0], packet[header.Len:])
785
786 // response was freshly allocated by ProcessPacket; safe to retain directly.
787 if response != nil {
788 hostinfo.HandshakePacket[handshakePacketStage2] = response
789 }
790
791 hostinfo.remotes = f.lightHouse.QueryCache(vpnAddrs)
792 if !via.IsRelayed {
793 hostinfo.SetRemote(via.UdpAddr)
794 }
795 hostinfo.buildNetworks(f.myVpnNetworksTable, remoteCert.Certificate)
796
797 existing, err := hm.CheckAndComplete(hostinfo, handshakePacketStage0, f)
798 if err != nil {
799 hm.handleCheckAndCompleteError(err, existing, hostinfo, via)
800 return
801 }
802
803 hm.sendHandshakeResponse(via, response, hostinfo, false)
804 hostinfo.remotes.RefreshFromHandshake(vpnAddrs)
805
806 // Don't wait for UpdateWorker
807 if f.lightHouse.IsAnyLighthouseAddr(vpnAddrs) {
808 f.lightHouse.TriggerUpdate()
809 }
810 }
811
812 // continueHandshake feeds an incoming packet to an existing pending handshake Machine.
813 func (hm *HandshakeManager) continueHandshake(via ViaSender, hh *HandshakeHostInfo, packet []byte) {
814 f := hm.f
815
816 hh.Lock()
817 defer hh.Unlock()
818
819 // Re-verify hh is still tracked. Between queryIndex returning and us taking
820 // hh.Lock, handleOutbound may have timed out and deleted it. Once we hold
821 // hh.Lock no other deleter can race our index: handleOutbound also takes
822 // hh.Lock first, and handleRecvError targets a main-hostmap entry with a
823 // different localIndexId.
824 hm.RLock()
825 cur, ok := hm.indexes[hh.hostinfo.localIndexId]
826 hm.RUnlock()
827 if !ok || cur != hh {
828 return
829 }
830
831 hostinfo := hh.hostinfo
832 if !via.IsRelayed {
833 if !f.lightHouse.GetRemoteAllowList().AllowAll(hostinfo.vpnAddrs, via.UdpAddr.Addr()) {
834 f.l.Debug("lighthouse.remote_allow_list denied incoming handshake",
835 "vpnAddrs", hostinfo.vpnAddrs, "from", via)
836 return
837 }
838 }
839
840 machine := hh.machine
841 if machine == nil {
842 f.l.Error("No handshake machine available for continuation",
843 "vpnAddrs", hostinfo.vpnAddrs, "from", via)
844 hm.DeleteHostInfo(hostinfo)
845 return
846 }
847
848 response, result, err := machine.ProcessPacket(nil, packet)
849 if err != nil {
850 // Recoverable errors are routine noise, log at Debug. Fatal errors get a Warn.
851 if machine.Failed() {
852 f.l.Warn("Failed to process handshake packet, abandoning",
853 "vpnAddrs", hostinfo.vpnAddrs, "from", via, "error", err)
854 hm.DeleteHostInfo(hostinfo)
855 } else {
856 f.l.Debug("Failed to process handshake packet",
857 "vpnAddrs", hostinfo.vpnAddrs, "from", via, "error", err)
858 }
859 return
860 }
861
862 if response != nil {
863 hm.sendHandshakeResponse(via, response, hostinfo, false)
864 }
865
866 if result == nil {
867 return
868 }
869
870 // Handshake complete; build the ConnectionState now that we have keys and a verified peer cert.
871 hostinfo.ConnectionState = newConnectionStateFromResult(result)
872
873 remoteCert := result.RemoteCert
874 if remoteCert == nil {
875 f.l.Error("Handshake completed without peer certificate",
876 "vpnAddrs", hostinfo.vpnAddrs, "from", via)
877 hm.DeleteHostInfo(hostinfo)
878 return
879 }
880
881 vpnNetworks := remoteCert.Certificate.Networks()
882 hostinfo.remoteIndexId = result.RemoteIndex
883 hostinfo.lastHandshakeTime = result.HandshakeTime
884
885 if !via.IsRelayed {
886 hostinfo.SetRemote(via.UdpAddr)
887 } else {
888 hostinfo.relayState.InsertRelayTo(via.relayHI.vpnAddrs[0])
889 }
890
891 // Verify correct host responded (initiator check)
892 vpnAddrs := make([]netip.Addr, len(vpnNetworks))
893 correctHostResponded := false
894 anyVpnAddrsInCommon := false
895 for i, network := range vpnNetworks {
896 // inside.go drops self-routed packets at the firewall stage, but we'd
897 // rather not let a self-handshake complete in the first place: it
898 // wastes a hostmap slot, suppresses no log, and obscures routing
899 // misconfig. Explicit refusal here mirrors the responder-side check
900 // in validatePeerCert.
901 if f.myVpnAddrsTable.Contains(network.Addr()) {
902 f.l.Error("Refusing to handshake with myself",
903 "vpnNetworks", vpnNetworks,
904 "from", via,
905 "certName", remoteCert.Certificate.Name(),
906 "certVersion", remoteCert.Certificate.Version(),
907 "fingerprint", remoteCert.Fingerprint,
908 "issuer", remoteCert.Certificate.Issuer(),
909 "handshake", m{"stage": uint64(machine.MessageIndex()), "style": header.SubTypeName(header.Handshake, machine.Subtype())},
910 )
911 hm.DeleteHostInfo(hostinfo)
912 return
913 }
914 vpnAddrs[i] = network.Addr()
915 if hostinfo.vpnAddrs[0] == network.Addr() {
916 correctHostResponded = true
917 }
918 if f.myVpnNetworksTable.Contains(network.Addr()) {
919 anyVpnAddrsInCommon = true
920 }
921 }
922
923 if !correctHostResponded {
924 f.l.Info("Incorrect host responded to handshake",
925 "intendedVpnAddrs", hostinfo.vpnAddrs,
926 "haveVpnNetworks", vpnNetworks,
927 "from", via,
928 "certName", remoteCert.Certificate.Name(),
929 "certVersion", remoteCert.Certificate.Version(),
930 "fingerprint", remoteCert.Fingerprint,
931 "issuer", remoteCert.Certificate.Issuer(),
932 "handshake", m{"stage": uint64(machine.MessageIndex()), "style": header.SubTypeName(header.Handshake, machine.Subtype())},
933 )
934
935 hm.DeleteHostInfo(hostinfo)
936 hm.StartHandshake(hostinfo.vpnAddrs[0], func(newHH *HandshakeHostInfo) {
937 newHH.hostinfo.remotes = hostinfo.remotes
938 newHH.hostinfo.remotes.BlockRemote(via)
939 newHH.packetStore = hh.packetStore
940 hh.packetStore = []*cachedPacket{}
941 hostinfo.vpnAddrs = vpnAddrs
942 f.sendCloseTunnel(hostinfo)
943 })
944 return
945 }
946
947 duration := time.Since(hh.startTime).Nanoseconds()
948 msg := "Handshake message received"
949 if !anyVpnAddrsInCommon {
950 msg = "Handshake message received, but no vpnNetworks in common."
951 }
952 f.l.Info(msg,
953 "vpnAddrs", vpnAddrs,
954 "from", via,
955 "certName", remoteCert.Certificate.Name(),
956 "certVersion", remoteCert.Certificate.Version(),
957 "fingerprint", remoteCert.Fingerprint,
958 "issuer", remoteCert.Certificate.Issuer(),
959 "initiatorIndex", result.LocalIndex,
960 "responderIndex", result.RemoteIndex,
961 "handshake", m{"stage": uint64(machine.MessageIndex()), "style": header.SubTypeName(header.Handshake, machine.Subtype())},
962 "durationNs", duration,
963 "sentCachedPackets", len(hh.packetStore),
964 )
965
966 hostinfo.vpnAddrs = vpnAddrs
967 hostinfo.buildNetworks(f.myVpnNetworksTable, remoteCert.Certificate)
968
969 hm.Complete(hostinfo, f)
970
971 if len(hh.packetStore) > 0 {
972 if f.l.Enabled(context.Background(), slog.LevelDebug) {
973 hostinfo.logger(f.l).Debug("Sending stored packets", "count", len(hh.packetStore))
974 }
975 nb := make([]byte, 12, 12)
976 out := make([]byte, mtu)
977 for _, cp := range hh.packetStore {
978 cp.callback(cp.messageType, cp.messageSubType, hostinfo, cp.packet, nb, out)
979 }
980 f.cachedPacketMetrics.sent.Inc(int64(len(hh.packetStore)))
981 }
982
983 hostinfo.remotes.RefreshFromHandshake(vpnAddrs)
984 f.metricHandshakes.Update(duration)
985
986 // Don't wait for UpdateWorker
987 if f.lightHouse.IsAnyLighthouseAddr(vpnAddrs) {
988 f.lightHouse.TriggerUpdate()
989 }
990 }
991
992 // validatePeerCert checks the peer certificate for self-connection and remote allow list.
993 // Returns the VPN addrs, whether any of them fall within one of our own VPN
994 // networks, and true if valid; false if rejected.
995 func (hm *HandshakeManager) validatePeerCert(via ViaSender, remoteCert *cert.CachedCertificate) ([]netip.Addr, bool, bool) {
996 f := hm.f
997 vpnNetworks := remoteCert.Certificate.Networks()
998
999 // The cert package rejects host certs with no networks at parse time, so
1000 // reaching this state would mean an invariant was bypassed elsewhere.
1001 // Refuse explicitly so downstream code (which indexes vpnAddrs[0]) can't
1002 // panic if that invariant ever changes.
1003 if len(vpnNetworks) == 0 {
1004 f.l.Info("No networks in certificate",
1005 "from", via, "cert", remoteCert)
1006 return nil, false, false
1007 }
1008
1009 vpnAddrs := make([]netip.Addr, len(vpnNetworks))
1010 anyVpnAddrsInCommon := false
1011
1012 for i, network := range vpnNetworks {
1013 if f.myVpnAddrsTable.Contains(network.Addr()) {
1014 f.l.Error("Refusing to handshake with myself",
1015 "vpnNetworks", vpnNetworks,
1016 "from", via,
1017 "certName", remoteCert.Certificate.Name(),
1018 "certVersion", remoteCert.Certificate.Version(),
1019 "fingerprint", remoteCert.Fingerprint,
1020 "issuer", remoteCert.Certificate.Issuer(),
1021 )
1022 return nil, false, false
1023 }
1024 vpnAddrs[i] = network.Addr()
1025 if f.myVpnNetworksTable.Contains(network.Addr()) {
1026 anyVpnAddrsInCommon = true
1027 }
1028 }
1029
1030 if !via.IsRelayed {
1031 if !f.lightHouse.GetRemoteAllowList().AllowAll(vpnAddrs, via.UdpAddr.Addr()) {
1032 f.l.Debug("lighthouse.remote_allow_list denied incoming handshake",
1033 "vpnAddrs", vpnAddrs, "from", via)
1034 return nil, false, false
1035 }
1036 }
1037
1038 return vpnAddrs, anyVpnAddrsInCommon, true
1039 }
1040
1041 // sendHandshakeResponse sends a handshake response via the appropriate transport.
1042 // cached is true when msg is a stored response being retransmitted because
1043 // the peer's stage-1 retransmit landed (the ErrAlreadySeen path); false on a
1044 // fresh response.
1045 func (hm *HandshakeManager) sendHandshakeResponse(via ViaSender, msg []byte, hostinfo *HostInfo, cached bool) {
1046 if msg == nil {
1047 return
1048 }
1049
1050 f := hm.f
1051 f.messageMetrics.Tx(header.Handshake, header.MessageSubType(msg[1]), 1)
1052
1053 // Common log fields. peerCert may be nil during intermediate
1054 // multi-message flows (handshake hasn't completed yet); skip the cert
1055 // block if so.
1056 logFields := []any{
1057 "vpnAddrs", hostinfo.vpnAddrs,
1058 "handshake", m{"stage": uint64(2), "style": header.SubTypeName(header.Handshake, header.HandshakeIXPSK0)},
1059 "cached", cached,
1060 "initiatorIndex", hostinfo.remoteIndexId,
1061 "responderIndex", hostinfo.localIndexId,
1062 }
1063 if peerCert := hostinfo.ConnectionState.peerCert; peerCert != nil {
1064 logFields = append(logFields,
1065 "certName", peerCert.Certificate.Name(),
1066 "certVersion", peerCert.Certificate.Version(),
1067 "fingerprint", peerCert.Fingerprint,
1068 "issuer", peerCert.Certificate.Issuer(),
1069 )
1070 }
1071
1072 if !via.IsRelayed {
1073 fields := append(logFields, "from", via)
1074 err := f.outside.WriteTo(msg, via.UdpAddr)
1075 if err != nil {
1076 f.l.Error("Failed to send handshake message", append(fields, "error", err)...)
1077 } else {
1078 f.l.Info("Handshake message sent", fields...)
1079 }
1080 } else {
1081 if via.relay == nil {
1082 f.l.Error("Handshake send failed: both addr and via.relay are nil.")
1083 return
1084 }
1085 hostinfo.relayState.InsertRelayTo(via.relayHI.vpnAddrs[0])
1086 // We received a valid handshake on this relay, so make sure the relay
1087 // state reflects that, in case it had been marked Disestablished.
1088 via.relayHI.relayState.UpdateRelayForByIdxState(via.relay.LocalIndex, Established)
1089 f.SendVia(via.relayHI, via.relay, msg, make([]byte, 12), make([]byte, mtu), false)
1090 f.l.Info("Handshake message sent", append(logFields, "relay", via.relayHI.vpnAddrs[0])...)
1091 }
1092 }
1093
1094 // handleCheckAndCompleteError handles errors from CheckAndComplete.
1095 // This only fires from the responder-side beginHandshake path, after the
1096 // peer cert has been validated and ConnectionState populated, so peerCert
1097 // is always non-nil for the cases that log it.
1098 func (hm *HandshakeManager) handleCheckAndCompleteError(err error, existing, hostinfo *HostInfo, via ViaSender) {
1099 f := hm.f
1100 peerCert := hostinfo.ConnectionState.peerCert
1101 hsFields := m{"stage": uint64(1), "style": header.SubTypeName(header.Handshake, header.HandshakeIXPSK0)}
1102
1103 switch err {
1104 case ErrAlreadySeen:
1105 if existing.SetRemoteIfPreferred(f.hostMap, via) {
1106 f.SendMessageToVpnAddr(header.Test, header.TestRequest, hostinfo.vpnAddrs[0], []byte(""), make([]byte, 12, 12), make([]byte, mtu))
1107 }
1108 // Resend the original response. The peer is committed to that response's
1109 // ephemeral keys; a freshly-built one would have different keys and break
1110 // the tunnel even though both sides "completed" the handshake.
1111 if msg := existing.HandshakePacket[handshakePacketStage2]; msg != nil {
1112 hm.sendHandshakeResponse(via, msg, existing, true)
1113 }
1114
1115 case ErrExistingHostInfo:
1116 f.l.Info("Handshake too old",
1117 "vpnAddrs", hostinfo.vpnAddrs,
1118 "from", via,
1119 "certName", peerCert.Certificate.Name(),
1120 "certVersion", peerCert.Certificate.Version(),
1121 "fingerprint", peerCert.Fingerprint,
1122 "issuer", peerCert.Certificate.Issuer(),
1123 "oldHandshakeTime", existing.lastHandshakeTime,
1124 "newHandshakeTime", hostinfo.lastHandshakeTime,
1125 "initiatorIndex", hostinfo.remoteIndexId,
1126 "responderIndex", hostinfo.localIndexId,
1127 "handshake", hsFields,
1128 )
1129 f.SendMessageToVpnAddr(header.Test, header.TestRequest, hostinfo.vpnAddrs[0], []byte(""), make([]byte, 12, 12), make([]byte, mtu))
1130
1131 case ErrLocalIndexCollision:
1132 f.l.Error("Failed to add HostInfo due to localIndex collision",
1133 "vpnAddrs", hostinfo.vpnAddrs,
1134 "from", via,
1135 "certName", peerCert.Certificate.Name(),
1136 "certVersion", peerCert.Certificate.Version(),
1137 "fingerprint", peerCert.Fingerprint,
1138 "issuer", peerCert.Certificate.Issuer(),
1139 "localIndex", hostinfo.localIndexId,
1140 "initiatorIndex", hostinfo.remoteIndexId,
1141 "responderIndex", hostinfo.localIndexId,
1142 "handshake", hsFields,
1143 )
1144
1145 default:
1146 f.l.Error("Failed to add HostInfo to HostMap",
1147 "vpnAddrs", hostinfo.vpnAddrs,
1148 "from", via,
1149 "error", err,
1150 "certName", peerCert.Certificate.Name(),
1151 "certVersion", peerCert.Certificate.Version(),
1152 "fingerprint", peerCert.Fingerprint,
1153 "issuer", peerCert.Certificate.Issuer(),
1154 "initiatorIndex", hostinfo.remoteIndexId,
1155 "responderIndex", hostinfo.localIndexId,
1156 "handshake", hsFields,
1157 )
1158 }
1159 }
1160
1161 // certVerifier returns a CertVerifier that validates certs against the current CA pool.
1162 func (hm *HandshakeManager) certVerifier() handshake.CertVerifier {
1163 return func(c cert.Certificate) (*cert.CachedCertificate, error) {
1164 return hm.f.pki.GetCAPool().VerifyCertificate(time.Now(), c)
1165 }
1166 }