handshake_manager.go 38 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166
  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. sync.RWMutex
  50. vpnIps map[netip.Addr]*HandshakeHostInfo
  51. indexes map[uint32]*HandshakeHostInfo
  52. mainHostMap *HostMap
  53. lightHouse *LightHouse
  54. outside udp.Conn
  55. config HandshakeConfig
  56. OutboundHandshakeTimer *LockingTimerWheel[netip.Addr]
  57. messageMetrics *MessageMetrics
  58. metricInitiated metrics.Counter
  59. metricTimedOut metrics.Counter
  60. f *Interface
  61. l *slog.Logger
  62. // can be used to trigger outbound handshake for the given vpnIp
  63. trigger chan netip.Addr
  64. }
  65. type HandshakeHostInfo struct {
  66. sync.Mutex
  67. startTime time.Time // Time that we first started trying with this handshake
  68. ready bool // Is the handshake ready
  69. initiatingVersionOverride cert.Version // Should we use a non-default cert version for this handshake?
  70. counter int64 // How many attempts have we made so far
  71. lastRemotes []netip.AddrPort // Remotes that we sent to during the previous attempt
  72. packetStore []*cachedPacket // A set of packets to be transmitted once the handshake completes
  73. hostinfo *HostInfo
  74. machine *handshake.Machine // The handshake state machine, set during stage 0 (initiator) or beginHandshake (responder multi-message)
  75. }
  76. func (hh *HandshakeHostInfo) cachePacket(l *slog.Logger, t header.MessageType, st header.MessageSubType, packet []byte, f packetCallback, m *cachedPacketMetrics) {
  77. if len(hh.packetStore) < maxCachedPackets {
  78. tempPacket := make([]byte, len(packet))
  79. copy(tempPacket, packet)
  80. hh.packetStore = append(hh.packetStore, &cachedPacket{t, st, f, tempPacket})
  81. if l.Enabled(context.Background(), slog.LevelDebug) {
  82. hh.hostinfo.logger(l).Debug("Packet store",
  83. "length", len(hh.packetStore),
  84. "stored", true,
  85. )
  86. }
  87. } else {
  88. m.dropped.Inc(1)
  89. if l.Enabled(context.Background(), slog.LevelDebug) {
  90. hh.hostinfo.logger(l).Debug("Packet store",
  91. "length", len(hh.packetStore),
  92. "stored", false,
  93. )
  94. }
  95. }
  96. }
  97. func NewHandshakeManager(l *slog.Logger, mainHostMap *HostMap, lightHouse *LightHouse, outside udp.Conn, config HandshakeConfig) *HandshakeManager {
  98. return &HandshakeManager{
  99. vpnIps: map[netip.Addr]*HandshakeHostInfo{},
  100. indexes: map[uint32]*HandshakeHostInfo{},
  101. mainHostMap: mainHostMap,
  102. lightHouse: lightHouse,
  103. outside: outside,
  104. config: config,
  105. trigger: make(chan netip.Addr, config.triggerBuffer),
  106. OutboundHandshakeTimer: NewLockingTimerWheel[netip.Addr](config.tryInterval, hsTimeout(config.retries, config.tryInterval)),
  107. messageMetrics: config.messageMetrics,
  108. metricInitiated: metrics.GetOrRegisterCounter("handshake_manager.initiated", nil),
  109. metricTimedOut: metrics.GetOrRegisterCounter("handshake_manager.timed_out", nil),
  110. l: l,
  111. }
  112. }
  113. func (hm *HandshakeManager) Run(ctx context.Context) {
  114. clockSource := time.NewTicker(hm.config.tryInterval)
  115. defer clockSource.Stop()
  116. for {
  117. select {
  118. case <-ctx.Done():
  119. return
  120. case vpnIP := <-hm.trigger:
  121. hm.handleOutbound(vpnIP, true)
  122. case now := <-clockSource.C:
  123. hm.NextOutboundHandshakeTimerTick(now)
  124. }
  125. }
  126. }
  127. func (hm *HandshakeManager) HandleIncoming(via ViaSender, packet []byte, h *header.H) {
  128. // Gate on known handshake subtypes. Unknown subtypes (or future ones we
  129. // don't yet support) are dropped here rather than silently routed through
  130. // the IX path. Add a case when introducing a new pattern.
  131. switch h.Subtype {
  132. case header.HandshakeIXPSK0:
  133. // supported
  134. default:
  135. hm.l.Debug("dropping handshake with unsupported subtype",
  136. "from", via, "subtype", h.Subtype)
  137. return
  138. }
  139. // First remote allow list check before we know the vpnIp
  140. if !via.IsRelayed {
  141. if !hm.lightHouse.GetRemoteAllowList().AllowUnknownVpnAddr(via.UdpAddr.Addr()) {
  142. hm.l.Debug("lighthouse.remote_allow_list denied incoming handshake", "from", via)
  143. return
  144. }
  145. }
  146. // First message of a new handshake. The wire format requires RemoteIndex
  147. // to be zero here (the initiator has no responder index to fill in yet),
  148. // and generateIndex never allocates 0, so any non-zero RemoteIndex on a
  149. // stage-1 packet is malformed or someone probing for an index collision.
  150. // Drop without paying the cost of running noise on a pending Machine.
  151. if h.MessageCounter == 1 {
  152. if h.RemoteIndex != 0 {
  153. hm.l.Debug("dropping stage-1 handshake with non-zero RemoteIndex",
  154. "from", via, "remoteIndex", h.RemoteIndex)
  155. return
  156. }
  157. hm.beginHandshake(via, packet, h)
  158. return
  159. }
  160. // Continuation message must match a pending handshake by index.
  161. // Anything else is an orphaned packet (e.g., late retransmit after
  162. // timeout) and is dropped.
  163. if hh := hm.queryIndex(h.RemoteIndex); hh != nil {
  164. hm.continueHandshake(via, hh, packet)
  165. return
  166. }
  167. }
  168. func (hm *HandshakeManager) NextOutboundHandshakeTimerTick(now time.Time) {
  169. hm.OutboundHandshakeTimer.Advance(now)
  170. for {
  171. vpnIp, has := hm.OutboundHandshakeTimer.Purge()
  172. if !has {
  173. break
  174. }
  175. hm.handleOutbound(vpnIp, false)
  176. }
  177. }
  178. func (hm *HandshakeManager) handleOutbound(vpnIp netip.Addr, lighthouseTriggered bool) {
  179. hh := hm.queryVpnIp(vpnIp)
  180. if hh == nil {
  181. return
  182. }
  183. hh.Lock()
  184. defer hh.Unlock()
  185. hostinfo := hh.hostinfo
  186. // If we are out of time, clean up
  187. if hh.counter >= hm.config.retries {
  188. fields := []any{
  189. "udpAddrs", hh.hostinfo.remotes.CopyAddrs(hm.mainHostMap.GetPreferredRanges()),
  190. "initiatorIndex", hh.hostinfo.localIndexId,
  191. "remoteIndex", hh.hostinfo.remoteIndexId,
  192. "durationNs", time.Since(hh.startTime).Nanoseconds(),
  193. }
  194. // hh.machine can be nil here if buildStage0Packet never succeeded
  195. // (e.g., no certificate available). In that case there's no useful
  196. // handshake metadata to log.
  197. if hh.machine != nil {
  198. fields = append(fields, "handshake", m{
  199. "stage": uint64(hh.machine.MessageIndex()),
  200. "style": header.SubTypeName(header.Handshake, hh.machine.Subtype()),
  201. })
  202. }
  203. hh.hostinfo.logger(hm.l).Info("Handshake timed out", fields...)
  204. hm.metricTimedOut.Inc(1)
  205. hm.DeleteHostInfo(hostinfo)
  206. return
  207. }
  208. // Increment the counter to increase our delay, linear backoff
  209. hh.counter++
  210. // Check if we have a handshake packet to transmit yet
  211. if !hh.ready {
  212. if !hm.buildStage0Packet(hh) {
  213. hm.OutboundHandshakeTimer.Add(vpnIp, hm.config.tryInterval*time.Duration(hh.counter))
  214. return
  215. }
  216. }
  217. // TODO: this hardcodes "always retransmit stage 0", which is correct for
  218. // IX (the initiator only ever sends one packet, msg1) but wrong the
  219. // moment a 3+ message pattern lands. The retry loop should resend the
  220. // most recent outgoing message, not always stage 0. That implies
  221. // HandshakeHostInfo tracking a single "currentOutbound" packet (bytes +
  222. // header metadata) that gets replaced as the handshake progresses,
  223. // instead of indexing into HandshakePacket.
  224. stage0 := hostinfo.HandshakePacket[handshakePacketStage0]
  225. hsFields := m{
  226. "stage": uint64(hh.machine.MessageIndex()),
  227. "style": header.SubTypeName(header.Handshake, hh.machine.Subtype()),
  228. }
  229. // Get a remotes object if we don't already have one.
  230. // This is mainly to protect us as this should never be the case
  231. // NB ^ This comment doesn't jive. It's how the thing gets initialized.
  232. // It's the common path. Should it update every time, in case a future LH query/queries give us more info?
  233. if hostinfo.remotes == nil {
  234. hostinfo.remotes = hm.lightHouse.QueryCache([]netip.Addr{vpnIp})
  235. }
  236. remotes := hostinfo.remotes.CopyAddrs(hm.mainHostMap.GetPreferredRanges())
  237. remotesHaveChanged := !slices.Equal(remotes, hh.lastRemotes)
  238. // We only care about a lighthouse trigger if we have new remotes to send to.
  239. // This is a very specific optimization for a fast lighthouse reply.
  240. if lighthouseTriggered && !remotesHaveChanged {
  241. // If we didn't return here a lighthouse could cause us to aggressively send handshakes
  242. return
  243. }
  244. hh.lastRemotes = remotes
  245. // This will generate a load of queries for hosts with only 1 ip
  246. // (such as ones registered to the lighthouse with only a private IP)
  247. // So we only do it one time after attempting 5 handshakes already.
  248. if len(remotes) <= 1 && hh.counter == 5 {
  249. // If we only have 1 remote it is highly likely our query raced with the other host registered within the lighthouse
  250. // Our vpnIp here has a tunnel with a lighthouse but has yet to send a host update packet there so we only know about
  251. // the learned public ip for them. Query again to short circuit the promotion counter
  252. hm.lightHouse.QueryServer(vpnIp)
  253. }
  254. // Send the handshake to all known ips, stage 2 takes care of assigning the hostinfo.remote based on the first to reply
  255. var sentTo []netip.AddrPort
  256. hostinfo.remotes.ForEach(hm.mainHostMap.GetPreferredRanges(), func(addr netip.AddrPort, _ bool) {
  257. hm.messageMetrics.Tx(header.Handshake, hh.machine.Subtype(), 1)
  258. err := hm.outside.WriteTo(stage0, addr)
  259. if err != nil {
  260. hostinfo.logger(hm.l).Error("Failed to send handshake message",
  261. "udpAddr", addr,
  262. "initiatorIndex", hostinfo.localIndexId,
  263. "handshake", hsFields,
  264. "error", err,
  265. )
  266. } else {
  267. sentTo = append(sentTo, addr)
  268. }
  269. })
  270. // 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,
  271. // so only log when the list of remotes has changed
  272. if remotesHaveChanged {
  273. hostinfo.logger(hm.l).Info("Handshake message sent",
  274. "udpAddrs", sentTo,
  275. "initiatorIndex", hostinfo.localIndexId,
  276. "handshake", hsFields,
  277. )
  278. } else if hm.l.Enabled(context.Background(), slog.LevelDebug) {
  279. hostinfo.logger(hm.l).Debug("Handshake message sent",
  280. "udpAddrs", sentTo,
  281. "initiatorIndex", hostinfo.localIndexId,
  282. "handshake", hsFields,
  283. )
  284. }
  285. hm.f.relayManager.StartRelays(hm.f, vpnIp, hostinfo, stage0)
  286. // If a lighthouse triggered this attempt then we are still in the timer wheel and do not need to re-add
  287. if !lighthouseTriggered {
  288. hm.OutboundHandshakeTimer.Add(vpnIp, hm.config.tryInterval*time.Duration(hh.counter))
  289. }
  290. }
  291. // GetOrHandshake will try to find a hostinfo with a fully formed tunnel or start a new handshake if one is not present
  292. // The 2nd argument will be true if the hostinfo is ready to transmit traffic
  293. func (hm *HandshakeManager) GetOrHandshake(vpnIp netip.Addr, cacheCb func(*HandshakeHostInfo)) (*HostInfo, bool) {
  294. hm.mainHostMap.RLock()
  295. h, ok := hm.mainHostMap.Hosts[vpnIp]
  296. hm.mainHostMap.RUnlock()
  297. if ok {
  298. // Do not attempt promotion if you are a lighthouse
  299. if !hm.lightHouse.amLighthouse {
  300. h.TryPromoteBest(hm.mainHostMap.GetPreferredRanges(), hm.f)
  301. }
  302. return h, true
  303. }
  304. return hm.StartHandshake(vpnIp, cacheCb), false
  305. }
  306. // StartHandshake will ensure a handshake is currently being attempted for the provided vpn ip
  307. func (hm *HandshakeManager) StartHandshake(vpnAddr netip.Addr, cacheCb func(*HandshakeHostInfo)) *HostInfo {
  308. hm.Lock()
  309. if hh, ok := hm.vpnIps[vpnAddr]; ok {
  310. // We are already trying to handshake with this vpn ip
  311. if cacheCb != nil {
  312. cacheCb(hh)
  313. }
  314. hm.Unlock()
  315. return hh.hostinfo
  316. }
  317. hostinfo := &HostInfo{
  318. vpnAddrs: []netip.Addr{vpnAddr},
  319. HandshakePacket: make(map[uint8][]byte, 0),
  320. relayState: RelayState{
  321. relays: nil,
  322. relayForByAddr: map[netip.Addr]*Relay{},
  323. relayForByIdx: map[uint32]*Relay{},
  324. },
  325. }
  326. hh := &HandshakeHostInfo{
  327. hostinfo: hostinfo,
  328. startTime: time.Now(),
  329. }
  330. hm.vpnIps[vpnAddr] = hh
  331. hm.metricInitiated.Inc(1)
  332. hm.OutboundHandshakeTimer.Add(vpnAddr, hm.config.tryInterval)
  333. if cacheCb != nil {
  334. cacheCb(hh)
  335. }
  336. // If this is a static host, we don't need to wait for the HostQueryReply
  337. // We can trigger the handshake right now
  338. _, doTrigger := hm.lightHouse.GetStaticHostList()[vpnAddr]
  339. if !doTrigger {
  340. // Add any calculated remotes, and trigger early handshake if one found
  341. doTrigger = hm.lightHouse.addCalculatedRemotes(vpnAddr)
  342. }
  343. if doTrigger {
  344. select {
  345. case hm.trigger <- vpnAddr:
  346. default:
  347. }
  348. }
  349. hm.Unlock()
  350. hm.lightHouse.QueryServer(vpnAddr)
  351. return hostinfo
  352. }
  353. var (
  354. ErrExistingHostInfo = errors.New("existing hostinfo")
  355. ErrAlreadySeen = errors.New("already seen")
  356. ErrLocalIndexCollision = errors.New("local index collision")
  357. )
  358. // CheckAndComplete checks for any conflicts in the main and pending hostmap
  359. // before adding hostinfo to main. If err is nil, it was added. Otherwise err will be:
  360. //
  361. // ErrAlreadySeen if we already have an entry in the hostmap that has seen the
  362. // exact same handshake packet
  363. //
  364. // ErrExistingHostInfo if we already have an entry in the hostmap for this
  365. // VpnIp and the new handshake was older than the one we currently have
  366. //
  367. // ErrLocalIndexCollision if we already have an entry in the main or pending
  368. // hostmap for the hostinfo.localIndexId.
  369. func (hm *HandshakeManager) CheckAndComplete(hostinfo *HostInfo, handshakePacket uint8, f *Interface) (*HostInfo, error) {
  370. hm.mainHostMap.Lock()
  371. defer hm.mainHostMap.Unlock()
  372. hm.Lock()
  373. defer hm.Unlock()
  374. // Check if we already have a tunnel with this vpn ip
  375. existingHostInfo, found := hm.mainHostMap.Hosts[hostinfo.vpnAddrs[0]]
  376. if found && existingHostInfo != nil {
  377. testHostInfo := existingHostInfo
  378. for testHostInfo != nil {
  379. // Is it just a delayed handshake packet?
  380. if bytes.Equal(hostinfo.HandshakePacket[handshakePacket], testHostInfo.HandshakePacket[handshakePacket]) {
  381. return testHostInfo, ErrAlreadySeen
  382. }
  383. testHostInfo = testHostInfo.next
  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. "remoteIndex", hostinfo.remoteIndexId,
  407. "collision", existingRemoteIndex.vpnAddrs,
  408. )
  409. }
  410. hm.mainHostMap.unlockedAddHostInfo(hostinfo, f)
  411. return existingHostInfo, nil
  412. }
  413. // Complete is a simpler version of CheckAndComplete when we already know we
  414. // won't have a localIndexId collision because we already have an entry in the
  415. // pendingHostMap. An existing hostinfo is returned if there was one.
  416. func (hm *HandshakeManager) Complete(hostinfo *HostInfo, f *Interface) {
  417. hm.mainHostMap.Lock()
  418. defer hm.mainHostMap.Unlock()
  419. hm.Lock()
  420. defer hm.Unlock()
  421. existingRemoteIndex, found := hm.mainHostMap.RemoteIndexes[hostinfo.remoteIndexId]
  422. if found && existingRemoteIndex != nil {
  423. // We have a collision, but this can happen since we can't control
  424. // the remote ID. Just log about the situation as a note.
  425. hostinfo.logger(hm.l).Info("New host shadows existing host remoteIndex",
  426. "remoteIndex", hostinfo.remoteIndexId,
  427. "collision", existingRemoteIndex.vpnAddrs,
  428. )
  429. }
  430. // We need to remove from the pending hostmap first to avoid undoing work when after to the main hostmap.
  431. hm.unlockedDeleteHostInfo(hostinfo)
  432. hm.mainHostMap.unlockedAddHostInfo(hostinfo, f)
  433. }
  434. // allocateIndex generates a unique localIndexId for this HostInfo
  435. // and adds it to the pendingHostMap. Will error if we are unable to generate
  436. // a unique localIndexId
  437. func (hm *HandshakeManager) allocateIndex(hh *HandshakeHostInfo) (uint32, error) {
  438. hm.mainHostMap.RLock()
  439. defer hm.mainHostMap.RUnlock()
  440. hm.Lock()
  441. defer hm.Unlock()
  442. for range 32 {
  443. index, err := generateIndex(hm.l)
  444. if err != nil {
  445. return 0, err
  446. }
  447. _, inPending := hm.indexes[index]
  448. _, inMain := hm.mainHostMap.Indexes[index]
  449. if !inMain && !inPending {
  450. hh.hostinfo.localIndexId = index
  451. hm.indexes[index] = hh
  452. return index, nil
  453. }
  454. }
  455. return 0, errors.New("failed to generate unique localIndexId")
  456. }
  457. func (hm *HandshakeManager) DeleteHostInfo(hostinfo *HostInfo) {
  458. hm.Lock()
  459. defer hm.Unlock()
  460. hm.unlockedDeleteHostInfo(hostinfo)
  461. }
  462. func (hm *HandshakeManager) unlockedDeleteHostInfo(hostinfo *HostInfo) {
  463. for _, addr := range hostinfo.vpnAddrs {
  464. delete(hm.vpnIps, addr)
  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. hostinfo := &HostInfo{
  643. ConnectionState: newConnectionStateFromResult(result),
  644. localIndexId: result.LocalIndex,
  645. remoteIndexId: result.RemoteIndex,
  646. vpnAddrs: vpnAddrs,
  647. HandshakePacket: make(map[uint8][]byte, 0),
  648. lastHandshakeTime: result.HandshakeTime,
  649. relayState: RelayState{
  650. relays: nil,
  651. relayForByAddr: map[netip.Addr]*Relay{},
  652. relayForByIdx: map[uint32]*Relay{},
  653. },
  654. }
  655. msg := "Handshake message received"
  656. if !anyVpnAddrsInCommon {
  657. msg = "Handshake message received, but no vpnNetworks in common."
  658. }
  659. f.l.Info(msg,
  660. "vpnAddrs", vpnAddrs,
  661. "from", via,
  662. "certName", remoteCert.Certificate.Name(),
  663. "certVersion", remoteCert.Certificate.Version(),
  664. "fingerprint", remoteCert.Fingerprint,
  665. "issuer", remoteCert.Certificate.Issuer(),
  666. "initiatorIndex", result.RemoteIndex,
  667. "responderIndex", result.LocalIndex,
  668. "handshake", m{"stage": uint64(machine.MessageIndex()), "style": header.SubTypeName(header.Handshake, machine.Subtype())},
  669. )
  670. // packet aliases the listener's incoming buffer, so this copy must stay.
  671. hostinfo.HandshakePacket[handshakePacketStage0] = make([]byte, len(packet[header.Len:]))
  672. copy(hostinfo.HandshakePacket[handshakePacketStage0], packet[header.Len:])
  673. // response was freshly allocated by ProcessPacket; safe to retain directly.
  674. if response != nil {
  675. hostinfo.HandshakePacket[handshakePacketStage2] = response
  676. }
  677. hostinfo.remotes = f.lightHouse.QueryCache(vpnAddrs)
  678. if !via.IsRelayed {
  679. hostinfo.SetRemote(via.UdpAddr)
  680. }
  681. hostinfo.buildNetworks(f.myVpnNetworksTable, remoteCert.Certificate)
  682. existing, err := hm.CheckAndComplete(hostinfo, handshakePacketStage0, f)
  683. if err != nil {
  684. hm.handleCheckAndCompleteError(err, existing, hostinfo, via)
  685. return
  686. }
  687. hm.sendHandshakeResponse(via, response, hostinfo, false)
  688. f.connectionManager.AddTrafficWatch(hostinfo)
  689. hostinfo.remotes.RefreshFromHandshake(vpnAddrs)
  690. // Don't wait for UpdateWorker
  691. if f.lightHouse.IsAnyLighthouseAddr(vpnAddrs) {
  692. f.lightHouse.TriggerUpdate()
  693. }
  694. }
  695. // continueHandshake feeds an incoming packet to an existing pending handshake Machine.
  696. func (hm *HandshakeManager) continueHandshake(via ViaSender, hh *HandshakeHostInfo, packet []byte) {
  697. f := hm.f
  698. hh.Lock()
  699. defer hh.Unlock()
  700. // Re-verify hh is still tracked. Between queryIndex returning and us taking
  701. // hh.Lock, handleOutbound may have timed out and deleted it. Once we hold
  702. // hh.Lock no other deleter can race our index: handleOutbound also takes
  703. // hh.Lock first, and handleRecvError targets a main-hostmap entry with a
  704. // different localIndexId.
  705. hm.RLock()
  706. cur, ok := hm.indexes[hh.hostinfo.localIndexId]
  707. hm.RUnlock()
  708. if !ok || cur != hh {
  709. return
  710. }
  711. hostinfo := hh.hostinfo
  712. if !via.IsRelayed {
  713. if !f.lightHouse.GetRemoteAllowList().AllowAll(hostinfo.vpnAddrs, via.UdpAddr.Addr()) {
  714. f.l.Debug("lighthouse.remote_allow_list denied incoming handshake",
  715. "vpnAddrs", hostinfo.vpnAddrs, "from", via)
  716. return
  717. }
  718. }
  719. machine := hh.machine
  720. if machine == nil {
  721. f.l.Error("No handshake machine available for continuation",
  722. "vpnAddrs", hostinfo.vpnAddrs, "from", via)
  723. hm.DeleteHostInfo(hostinfo)
  724. return
  725. }
  726. response, result, err := machine.ProcessPacket(nil, packet)
  727. if err != nil {
  728. // Recoverable errors are routine noise, log at Debug. Fatal errors get a Warn.
  729. if machine.Failed() {
  730. f.l.Warn("Failed to process handshake packet, abandoning",
  731. "vpnAddrs", hostinfo.vpnAddrs, "from", via, "error", err)
  732. hm.DeleteHostInfo(hostinfo)
  733. } else {
  734. f.l.Debug("Failed to process handshake packet",
  735. "vpnAddrs", hostinfo.vpnAddrs, "from", via, "error", err)
  736. }
  737. return
  738. }
  739. if response != nil {
  740. hm.sendHandshakeResponse(via, response, hostinfo, false)
  741. }
  742. if result == nil {
  743. return
  744. }
  745. // Handshake complete; build the ConnectionState now that we have keys and a verified peer cert.
  746. hostinfo.ConnectionState = newConnectionStateFromResult(result)
  747. remoteCert := result.RemoteCert
  748. if remoteCert == nil {
  749. f.l.Error("Handshake completed without peer certificate",
  750. "vpnAddrs", hostinfo.vpnAddrs, "from", via)
  751. hm.DeleteHostInfo(hostinfo)
  752. return
  753. }
  754. vpnNetworks := remoteCert.Certificate.Networks()
  755. hostinfo.remoteIndexId = result.RemoteIndex
  756. hostinfo.lastHandshakeTime = result.HandshakeTime
  757. if !via.IsRelayed {
  758. hostinfo.SetRemote(via.UdpAddr)
  759. } else {
  760. hostinfo.relayState.InsertRelayTo(via.relayHI.vpnAddrs[0])
  761. }
  762. // Verify correct host responded (initiator check)
  763. vpnAddrs := make([]netip.Addr, len(vpnNetworks))
  764. correctHostResponded := false
  765. anyVpnAddrsInCommon := false
  766. for i, network := range vpnNetworks {
  767. // inside.go drops self-routed packets at the firewall stage, but we'd
  768. // rather not let a self-handshake complete in the first place: it
  769. // wastes a hostmap slot, suppresses no log, and obscures routing
  770. // misconfig. Explicit refusal here mirrors the responder-side check
  771. // in validatePeerCert.
  772. if f.myVpnAddrsTable.Contains(network.Addr()) {
  773. f.l.Error("Refusing to handshake with myself",
  774. "vpnNetworks", vpnNetworks,
  775. "from", via,
  776. "certName", remoteCert.Certificate.Name(),
  777. "certVersion", remoteCert.Certificate.Version(),
  778. "fingerprint", remoteCert.Fingerprint,
  779. "issuer", remoteCert.Certificate.Issuer(),
  780. "handshake", m{"stage": uint64(machine.MessageIndex()), "style": header.SubTypeName(header.Handshake, machine.Subtype())},
  781. )
  782. hm.DeleteHostInfo(hostinfo)
  783. return
  784. }
  785. vpnAddrs[i] = network.Addr()
  786. if hostinfo.vpnAddrs[0] == network.Addr() {
  787. correctHostResponded = true
  788. }
  789. if f.myVpnNetworksTable.Contains(network.Addr()) {
  790. anyVpnAddrsInCommon = true
  791. }
  792. }
  793. if !correctHostResponded {
  794. f.l.Info("Incorrect host responded to handshake",
  795. "intendedVpnAddrs", hostinfo.vpnAddrs,
  796. "haveVpnNetworks", vpnNetworks,
  797. "from", via,
  798. "certName", remoteCert.Certificate.Name(),
  799. "certVersion", remoteCert.Certificate.Version(),
  800. "fingerprint", remoteCert.Fingerprint,
  801. "issuer", remoteCert.Certificate.Issuer(),
  802. "handshake", m{"stage": uint64(machine.MessageIndex()), "style": header.SubTypeName(header.Handshake, machine.Subtype())},
  803. )
  804. hm.DeleteHostInfo(hostinfo)
  805. hm.StartHandshake(hostinfo.vpnAddrs[0], func(newHH *HandshakeHostInfo) {
  806. newHH.hostinfo.remotes = hostinfo.remotes
  807. newHH.hostinfo.remotes.BlockRemote(via)
  808. newHH.packetStore = hh.packetStore
  809. hh.packetStore = []*cachedPacket{}
  810. hostinfo.vpnAddrs = vpnAddrs
  811. f.sendCloseTunnel(hostinfo)
  812. })
  813. return
  814. }
  815. duration := time.Since(hh.startTime).Nanoseconds()
  816. msg := "Handshake message received"
  817. if !anyVpnAddrsInCommon {
  818. msg = "Handshake message received, but no vpnNetworks in common."
  819. }
  820. f.l.Info(msg,
  821. "vpnAddrs", vpnAddrs,
  822. "from", via,
  823. "certName", remoteCert.Certificate.Name(),
  824. "certVersion", remoteCert.Certificate.Version(),
  825. "fingerprint", remoteCert.Fingerprint,
  826. "issuer", remoteCert.Certificate.Issuer(),
  827. "initiatorIndex", result.LocalIndex,
  828. "responderIndex", result.RemoteIndex,
  829. "handshake", m{"stage": uint64(machine.MessageIndex()), "style": header.SubTypeName(header.Handshake, machine.Subtype())},
  830. "durationNs", duration,
  831. "sentCachedPackets", len(hh.packetStore),
  832. )
  833. hostinfo.vpnAddrs = vpnAddrs
  834. hostinfo.buildNetworks(f.myVpnNetworksTable, remoteCert.Certificate)
  835. hm.Complete(hostinfo, f)
  836. f.connectionManager.AddTrafficWatch(hostinfo)
  837. if len(hh.packetStore) > 0 {
  838. if f.l.Enabled(context.Background(), slog.LevelDebug) {
  839. hostinfo.logger(f.l).Debug("Sending stored packets", "count", len(hh.packetStore))
  840. }
  841. nb := make([]byte, 12, 12)
  842. out := make([]byte, mtu)
  843. for _, cp := range hh.packetStore {
  844. //todo use a sendbatcher
  845. cp.callback(cp.messageType, cp.messageSubType, hostinfo, cp.packet, nb, out)
  846. }
  847. f.cachedPacketMetrics.sent.Inc(int64(len(hh.packetStore)))
  848. }
  849. hostinfo.remotes.RefreshFromHandshake(vpnAddrs)
  850. f.metricHandshakes.Update(duration)
  851. // Don't wait for UpdateWorker
  852. if f.lightHouse.IsAnyLighthouseAddr(vpnAddrs) {
  853. f.lightHouse.TriggerUpdate()
  854. }
  855. }
  856. // validatePeerCert checks the peer certificate for self-connection and remote allow list.
  857. // Returns the VPN addrs, whether any of them fall within one of our own VPN
  858. // networks, and true if valid; false if rejected.
  859. func (hm *HandshakeManager) validatePeerCert(via ViaSender, remoteCert *cert.CachedCertificate) ([]netip.Addr, bool, bool) {
  860. f := hm.f
  861. vpnNetworks := remoteCert.Certificate.Networks()
  862. // The cert package rejects host certs with no networks at parse time, so
  863. // reaching this state would mean an invariant was bypassed elsewhere.
  864. // Refuse explicitly so downstream code (which indexes vpnAddrs[0]) can't
  865. // panic if that invariant ever changes.
  866. if len(vpnNetworks) == 0 {
  867. f.l.Info("No networks in certificate",
  868. "from", via, "cert", remoteCert)
  869. return nil, false, false
  870. }
  871. vpnAddrs := make([]netip.Addr, len(vpnNetworks))
  872. anyVpnAddrsInCommon := false
  873. for i, network := range vpnNetworks {
  874. if f.myVpnAddrsTable.Contains(network.Addr()) {
  875. f.l.Error("Refusing to handshake with myself",
  876. "vpnNetworks", vpnNetworks,
  877. "from", via,
  878. "certName", remoteCert.Certificate.Name(),
  879. "certVersion", remoteCert.Certificate.Version(),
  880. "fingerprint", remoteCert.Fingerprint,
  881. "issuer", remoteCert.Certificate.Issuer(),
  882. )
  883. return nil, false, false
  884. }
  885. vpnAddrs[i] = network.Addr()
  886. if f.myVpnNetworksTable.Contains(network.Addr()) {
  887. anyVpnAddrsInCommon = true
  888. }
  889. }
  890. if !via.IsRelayed {
  891. if !f.lightHouse.GetRemoteAllowList().AllowAll(vpnAddrs, via.UdpAddr.Addr()) {
  892. f.l.Debug("lighthouse.remote_allow_list denied incoming handshake",
  893. "vpnAddrs", vpnAddrs, "from", via)
  894. return nil, false, false
  895. }
  896. }
  897. return vpnAddrs, anyVpnAddrsInCommon, true
  898. }
  899. // sendHandshakeResponse sends a handshake response via the appropriate transport.
  900. // cached is true when msg is a stored response being retransmitted because
  901. // the peer's stage-1 retransmit landed (the ErrAlreadySeen path); false on a
  902. // fresh response.
  903. func (hm *HandshakeManager) sendHandshakeResponse(via ViaSender, msg []byte, hostinfo *HostInfo, cached bool) {
  904. if msg == nil {
  905. return
  906. }
  907. f := hm.f
  908. f.messageMetrics.Tx(header.Handshake, header.MessageSubType(msg[1]), 1)
  909. // Common log fields. peerCert may be nil during intermediate
  910. // multi-message flows (handshake hasn't completed yet); skip the cert
  911. // block if so.
  912. logFields := []any{
  913. "vpnAddrs", hostinfo.vpnAddrs,
  914. "handshake", m{"stage": uint64(2), "style": header.SubTypeName(header.Handshake, header.HandshakeIXPSK0)},
  915. "cached", cached,
  916. "initiatorIndex", hostinfo.remoteIndexId,
  917. "responderIndex", hostinfo.localIndexId,
  918. }
  919. if peerCert := hostinfo.ConnectionState.peerCert; peerCert != nil {
  920. logFields = append(logFields,
  921. "certName", peerCert.Certificate.Name(),
  922. "certVersion", peerCert.Certificate.Version(),
  923. "fingerprint", peerCert.Fingerprint,
  924. "issuer", peerCert.Certificate.Issuer(),
  925. )
  926. }
  927. if !via.IsRelayed {
  928. fields := append(logFields, "from", via)
  929. err := f.outside.WriteTo(msg, via.UdpAddr)
  930. if err != nil {
  931. f.l.Error("Failed to send handshake message", append(fields, "error", err)...)
  932. } else {
  933. f.l.Info("Handshake message sent", fields...)
  934. }
  935. } else {
  936. if via.relay == nil {
  937. f.l.Error("Handshake send failed: both addr and via.relay are nil.")
  938. return
  939. }
  940. hostinfo.relayState.InsertRelayTo(via.relayHI.vpnAddrs[0])
  941. // We received a valid handshake on this relay, so make sure the relay
  942. // state reflects that, in case it had been marked Disestablished.
  943. via.relayHI.relayState.UpdateRelayForByIdxState(via.remoteIdx, Established)
  944. f.SendVia(via.relayHI, via.relay, msg, make([]byte, 12), make([]byte, mtu), false)
  945. f.l.Info("Handshake message sent", append(logFields, "relay", via.relayHI.vpnAddrs[0])...)
  946. }
  947. }
  948. // handleCheckAndCompleteError handles errors from CheckAndComplete.
  949. // This only fires from the responder-side beginHandshake path, after the
  950. // peer cert has been validated and ConnectionState populated, so peerCert
  951. // is always non-nil for the cases that log it.
  952. func (hm *HandshakeManager) handleCheckAndCompleteError(err error, existing, hostinfo *HostInfo, via ViaSender) {
  953. f := hm.f
  954. peerCert := hostinfo.ConnectionState.peerCert
  955. hsFields := m{"stage": uint64(1), "style": header.SubTypeName(header.Handshake, header.HandshakeIXPSK0)}
  956. switch err {
  957. case ErrAlreadySeen:
  958. if existing.SetRemoteIfPreferred(f.hostMap, via) {
  959. f.SendMessageToVpnAddr(header.Test, header.TestRequest, hostinfo.vpnAddrs[0], []byte(""), make([]byte, 12, 12), make([]byte, mtu))
  960. }
  961. // Resend the original response. The peer is committed to that response's
  962. // ephemeral keys; a freshly-built one would have different keys and break
  963. // the tunnel even though both sides "completed" the handshake.
  964. if msg := existing.HandshakePacket[handshakePacketStage2]; msg != nil {
  965. hm.sendHandshakeResponse(via, msg, existing, true)
  966. }
  967. case ErrExistingHostInfo:
  968. f.l.Info("Handshake too old",
  969. "vpnAddrs", hostinfo.vpnAddrs,
  970. "from", via,
  971. "certName", peerCert.Certificate.Name(),
  972. "certVersion", peerCert.Certificate.Version(),
  973. "fingerprint", peerCert.Fingerprint,
  974. "issuer", peerCert.Certificate.Issuer(),
  975. "oldHandshakeTime", existing.lastHandshakeTime,
  976. "newHandshakeTime", hostinfo.lastHandshakeTime,
  977. "initiatorIndex", hostinfo.remoteIndexId,
  978. "responderIndex", hostinfo.localIndexId,
  979. "handshake", hsFields,
  980. )
  981. f.SendMessageToVpnAddr(header.Test, header.TestRequest, hostinfo.vpnAddrs[0], []byte(""), make([]byte, 12, 12), make([]byte, mtu))
  982. case ErrLocalIndexCollision:
  983. f.l.Error("Failed to add HostInfo due to localIndex collision",
  984. "vpnAddrs", hostinfo.vpnAddrs,
  985. "from", via,
  986. "certName", peerCert.Certificate.Name(),
  987. "certVersion", peerCert.Certificate.Version(),
  988. "fingerprint", peerCert.Fingerprint,
  989. "issuer", peerCert.Certificate.Issuer(),
  990. "localIndex", hostinfo.localIndexId,
  991. "initiatorIndex", hostinfo.remoteIndexId,
  992. "responderIndex", hostinfo.localIndexId,
  993. "handshake", hsFields,
  994. )
  995. default:
  996. f.l.Error("Failed to add HostInfo to HostMap",
  997. "vpnAddrs", hostinfo.vpnAddrs,
  998. "from", via,
  999. "error", err,
  1000. "certName", peerCert.Certificate.Name(),
  1001. "certVersion", peerCert.Certificate.Version(),
  1002. "fingerprint", peerCert.Fingerprint,
  1003. "issuer", peerCert.Certificate.Issuer(),
  1004. "initiatorIndex", hostinfo.remoteIndexId,
  1005. "responderIndex", hostinfo.localIndexId,
  1006. "handshake", hsFields,
  1007. )
  1008. }
  1009. }
  1010. // certVerifier returns a CertVerifier that validates certs against the current CA pool.
  1011. func (hm *HandshakeManager) certVerifier() handshake.CertVerifier {
  1012. return func(c cert.Certificate) (*cert.CachedCertificate, error) {
  1013. return hm.f.pki.GetCAPool().VerifyCertificate(time.Now(), c)
  1014. }
  1015. }