1
0

handshake_manager.go 38 KB

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