1
0

handshake_manager.go 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161
  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. lastRelays []netip.Addr // Relays we attempted to use during the previous attempt
  73. packetStore []*cachedPacket // A set of packets to be transmitted once the handshake completes
  74. hostinfo *HostInfo
  75. machine *handshake.Machine // The handshake state machine, set during stage 0 (initiator) or beginHandshake (responder multi-message)
  76. }
  77. func (hh *HandshakeHostInfo) cachePacket(l *slog.Logger, t header.MessageType, st header.MessageSubType, packet []byte, f packetCallback, m *cachedPacketMetrics) {
  78. if len(hh.packetStore) < maxCachedPackets {
  79. tempPacket := make([]byte, len(packet))
  80. copy(tempPacket, packet)
  81. hh.packetStore = append(hh.packetStore, &cachedPacket{t, st, f, tempPacket})
  82. if l.Enabled(context.Background(), slog.LevelDebug) {
  83. hh.hostinfo.logger(l).Debug("Packet store",
  84. "length", len(hh.packetStore),
  85. "stored", true,
  86. )
  87. }
  88. } else {
  89. m.dropped.Inc(1)
  90. if l.Enabled(context.Background(), slog.LevelDebug) {
  91. hh.hostinfo.logger(l).Debug("Packet store",
  92. "length", len(hh.packetStore),
  93. "stored", false,
  94. )
  95. }
  96. }
  97. }
  98. func NewHandshakeManager(l *slog.Logger, mainHostMap *HostMap, lightHouse *LightHouse, outside udp.Conn, config HandshakeConfig) *HandshakeManager {
  99. return &HandshakeManager{
  100. vpnIps: map[netip.Addr]*HandshakeHostInfo{},
  101. indexes: map[uint32]*HandshakeHostInfo{},
  102. mainHostMap: mainHostMap,
  103. lightHouse: lightHouse,
  104. outside: outside,
  105. config: config,
  106. trigger: make(chan netip.Addr, config.triggerBuffer),
  107. OutboundHandshakeTimer: NewLockingTimerWheel[netip.Addr](config.tryInterval, hsTimeout(config.retries, config.tryInterval)),
  108. messageMetrics: config.messageMetrics,
  109. metricInitiated: metrics.GetOrRegisterCounter("handshake_manager.initiated", nil),
  110. metricTimedOut: metrics.GetOrRegisterCounter("handshake_manager.timed_out", nil),
  111. l: l,
  112. }
  113. }
  114. func (hm *HandshakeManager) Run(ctx context.Context) {
  115. clockSource := time.NewTicker(hm.config.tryInterval)
  116. defer clockSource.Stop()
  117. for {
  118. select {
  119. case <-ctx.Done():
  120. return
  121. case vpnIP := <-hm.trigger:
  122. hm.handleOutbound(vpnIP, true)
  123. case now := <-clockSource.C:
  124. hm.NextOutboundHandshakeTimerTick(now)
  125. }
  126. }
  127. }
  128. func (hm *HandshakeManager) HandleIncoming(via ViaSender, packet []byte, h *header.H) {
  129. // Gate on known handshake subtypes. Unknown subtypes (or future ones we
  130. // don't yet support) are dropped here rather than silently routed through
  131. // the IX path. Add a case when introducing a new pattern.
  132. switch h.Subtype {
  133. case header.HandshakeIXPSK0:
  134. // supported
  135. default:
  136. hm.l.Debug("dropping handshake with unsupported subtype",
  137. "from", via, "subtype", h.Subtype)
  138. return
  139. }
  140. // First remote allow list check before we know the vpnIp
  141. if !via.IsRelayed {
  142. if !hm.lightHouse.GetRemoteAllowList().AllowUnknownVpnAddr(via.UdpAddr.Addr()) {
  143. hm.l.Debug("lighthouse.remote_allow_list denied incoming handshake", "from", via)
  144. return
  145. }
  146. }
  147. // First message of a new handshake. The wire format requires RemoteIndex
  148. // to be zero here (the initiator has no responder index to fill in yet),
  149. // and generateIndex never allocates 0, so any non-zero RemoteIndex on a
  150. // stage-1 packet is malformed or someone probing for an index collision.
  151. // Drop without paying the cost of running noise on a pending Machine.
  152. if h.MessageCounter == 1 {
  153. if h.RemoteIndex != 0 {
  154. hm.l.Debug("dropping stage-1 handshake with non-zero RemoteIndex",
  155. "from", via, "remoteIndex", h.RemoteIndex)
  156. return
  157. }
  158. hm.beginHandshake(via, packet, h)
  159. return
  160. }
  161. // Continuation message must match a pending handshake by index.
  162. // Anything else is an orphaned packet (e.g., late retransmit after
  163. // timeout) and is dropped.
  164. if hh := hm.queryIndex(h.RemoteIndex); hh != nil {
  165. hm.continueHandshake(via, hh, packet)
  166. return
  167. }
  168. }
  169. func (hm *HandshakeManager) NextOutboundHandshakeTimerTick(now time.Time) {
  170. hm.OutboundHandshakeTimer.Advance(now)
  171. for {
  172. vpnIp, has := hm.OutboundHandshakeTimer.Purge()
  173. if !has {
  174. break
  175. }
  176. hm.handleOutbound(vpnIp, false)
  177. }
  178. }
  179. func (hm *HandshakeManager) handleOutbound(vpnIp netip.Addr, lighthouseTriggered bool) {
  180. hh := hm.queryVpnIp(vpnIp)
  181. if hh == nil {
  182. return
  183. }
  184. hh.Lock()
  185. defer hh.Unlock()
  186. hostinfo := hh.hostinfo
  187. // If we are out of time, clean up
  188. if hh.counter >= hm.config.retries {
  189. fields := []any{
  190. "udpAddrs", hh.hostinfo.remotes.CopyAddrs(hm.mainHostMap.GetPreferredRanges()),
  191. "initiatorIndex", hh.hostinfo.localIndexId,
  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, hh, 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. "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. delete(hm.vpnIps, addr)
  463. }
  464. if len(hm.vpnIps) == 0 {
  465. hm.vpnIps = map[netip.Addr]*HandshakeHostInfo{}
  466. }
  467. delete(hm.indexes, hostinfo.localIndexId)
  468. if len(hm.indexes) == 0 {
  469. hm.indexes = map[uint32]*HandshakeHostInfo{}
  470. }
  471. if hm.l.Enabled(context.Background(), slog.LevelDebug) {
  472. hm.l.Debug("Pending hostmap hostInfo deleted",
  473. "hostMap", m{"mapTotalSize": len(hm.vpnIps),
  474. "vpnAddrs": hostinfo.vpnAddrs, "indexNumber": hostinfo.localIndexId, "remoteIndexNumber": hostinfo.remoteIndexId},
  475. )
  476. }
  477. }
  478. func (hm *HandshakeManager) QueryVpnAddr(vpnIp netip.Addr) *HostInfo {
  479. hh := hm.queryVpnIp(vpnIp)
  480. if hh != nil {
  481. return hh.hostinfo
  482. }
  483. return nil
  484. }
  485. func (hm *HandshakeManager) queryVpnIp(vpnIp netip.Addr) *HandshakeHostInfo {
  486. hm.RLock()
  487. defer hm.RUnlock()
  488. return hm.vpnIps[vpnIp]
  489. }
  490. func (hm *HandshakeManager) QueryIndex(index uint32) *HostInfo {
  491. hh := hm.queryIndex(index)
  492. if hh != nil {
  493. return hh.hostinfo
  494. }
  495. return nil
  496. }
  497. func (hm *HandshakeManager) queryIndex(index uint32) *HandshakeHostInfo {
  498. hm.RLock()
  499. defer hm.RUnlock()
  500. return hm.indexes[index]
  501. }
  502. func (hm *HandshakeManager) GetPreferredRanges() []netip.Prefix {
  503. return hm.mainHostMap.GetPreferredRanges()
  504. }
  505. func (hm *HandshakeManager) ForEachVpnAddr(f controlEach) {
  506. hm.RLock()
  507. defer hm.RUnlock()
  508. for _, v := range hm.vpnIps {
  509. f(v.hostinfo)
  510. }
  511. }
  512. func (hm *HandshakeManager) ForEachIndex(f controlEach) {
  513. hm.RLock()
  514. defer hm.RUnlock()
  515. for _, v := range hm.indexes {
  516. f(v.hostinfo)
  517. }
  518. }
  519. func (hm *HandshakeManager) EmitStats() {
  520. hm.RLock()
  521. hostLen := len(hm.vpnIps)
  522. indexLen := len(hm.indexes)
  523. hm.RUnlock()
  524. metrics.GetOrRegisterGauge("hostmap.pending.hosts", nil).Update(int64(hostLen))
  525. metrics.GetOrRegisterGauge("hostmap.pending.indexes", nil).Update(int64(indexLen))
  526. hm.mainHostMap.EmitStats()
  527. }
  528. // Utility functions below
  529. func generateIndex(l *slog.Logger) (uint32, error) {
  530. b := make([]byte, 4)
  531. // Let zero mean we don't know the ID, so don't generate zero
  532. var index uint32
  533. for index == 0 {
  534. _, err := rand.Read(b)
  535. if err != nil {
  536. l.Error("Failed to generate index", "error", err)
  537. return 0, err
  538. }
  539. index = binary.BigEndian.Uint32(b)
  540. }
  541. if l.Enabled(context.Background(), slog.LevelDebug) {
  542. l.Debug("Generated index", "index", index)
  543. }
  544. return index, nil
  545. }
  546. func hsTimeout(tries int64, interval time.Duration) time.Duration {
  547. return time.Duration(tries / 2 * ((2 * int64(interval)) + (tries-1)*int64(interval)))
  548. }
  549. // buildStage0Packet creates the initial handshake packet for the initiator.
  550. func (hm *HandshakeManager) buildStage0Packet(hh *HandshakeHostInfo) bool {
  551. cs := hm.f.pki.getCertState()
  552. v := cs.DefaultVersion()
  553. if hh.initiatingVersionOverride != cert.VersionPre1 {
  554. v = hh.initiatingVersionOverride
  555. } else if v < cert.Version2 {
  556. for _, a := range hh.hostinfo.vpnAddrs {
  557. if a.Is6() {
  558. v = cert.Version2
  559. break
  560. }
  561. }
  562. }
  563. cred := cs.GetCredential(v)
  564. if cred == nil {
  565. hm.f.l.Error("Unable to handshake with host because no certificate is available",
  566. "vpnAddrs", hh.hostinfo.vpnAddrs, "certVersion", v)
  567. return false
  568. }
  569. machine, err := handshake.NewMachine(
  570. v, cs.GetCredential,
  571. hm.certVerifier(), func() (uint32, error) { return hm.allocateIndex(hh) },
  572. true, header.HandshakeIXPSK0,
  573. )
  574. if err != nil {
  575. hm.f.l.Error("Failed to create handshake machine",
  576. "vpnAddrs", hh.hostinfo.vpnAddrs, "error", err)
  577. return false
  578. }
  579. msg, err := machine.Initiate(nil)
  580. if err != nil {
  581. hm.f.l.Error("Failed to initiate handshake",
  582. "vpnAddrs", hh.hostinfo.vpnAddrs, "error", err)
  583. return false
  584. }
  585. // hostinfo.ConnectionState stays nil until the handshake completes in
  586. // continueHandshake. Pre-completion control surfaces guard with nil
  587. // checks; the data plane never observes a pending hostinfo.
  588. hh.hostinfo.HandshakePacket[handshakePacketStage0] = msg
  589. hh.machine = machine
  590. hh.ready = true
  591. return true
  592. }
  593. // beginHandshake handles an incoming handshake packet that doesn't match any
  594. // existing pending handshake. It creates a new responder Machine and processes
  595. // the first message.
  596. func (hm *HandshakeManager) beginHandshake(via ViaSender, packet []byte, h *header.H) {
  597. f := hm.f
  598. cs := f.pki.getCertState()
  599. v := cs.DefaultVersion()
  600. if cs.GetCredential(v) == nil {
  601. f.l.Error("Unable to handshake with host because no certificate is available",
  602. "from", via, "certVersion", v)
  603. return
  604. }
  605. machine, err := handshake.NewMachine(
  606. v, cs.GetCredential,
  607. hm.certVerifier(), func() (uint32, error) { return generateIndex(f.l) },
  608. false, header.HandshakeIXPSK0,
  609. )
  610. if err != nil {
  611. f.l.Error("Failed to create handshake machine", "from", via, "error", err)
  612. return
  613. }
  614. response, result, err := machine.ProcessPacket(nil, packet)
  615. if err != nil {
  616. f.l.Error("Failed to process handshake packet", "from", via, "error", err)
  617. return
  618. }
  619. if result == nil {
  620. // Multi-message pattern: the responder Machine would need to be
  621. // registered in hm.indexes so a future inbound packet finds it via
  622. // continueHandshake. The current manager doesn't do that yet, so
  623. // fail loudly rather than silently dropping the in-flight handshake.
  624. // TODO: support multi-message responder flows (XX, pqIX, etc.).
  625. // See also the IX-shaped cipher key assignment in handshake.Machine.
  626. f.l.Error("multi-message handshake responder is not supported",
  627. "from", via, "error", handshake.ErrMultiMessageUnsupported)
  628. return
  629. }
  630. remoteCert := result.RemoteCert
  631. if remoteCert == nil {
  632. f.l.Error("Handshake did not produce a peer certificate", "from", via)
  633. return
  634. }
  635. // Validate peer identity
  636. vpnAddrs, anyVpnAddrsInCommon, ok := hm.validatePeerCert(via, remoteCert)
  637. if !ok {
  638. return
  639. }
  640. hostinfo := &HostInfo{
  641. ConnectionState: newConnectionStateFromResult(result),
  642. localIndexId: result.LocalIndex,
  643. remoteIndexId: result.RemoteIndex,
  644. vpnAddrs: vpnAddrs,
  645. HandshakePacket: make(map[uint8][]byte, 0),
  646. lastHandshakeTime: result.HandshakeTime,
  647. relayState: RelayState{
  648. relays: nil,
  649. relayForByAddr: map[netip.Addr]*Relay{},
  650. relayForByIdx: map[uint32]*Relay{},
  651. },
  652. }
  653. msg := "Handshake message received"
  654. if !anyVpnAddrsInCommon {
  655. msg = "Handshake message received, but no vpnNetworks in common."
  656. }
  657. f.l.Info(msg,
  658. "vpnAddrs", vpnAddrs,
  659. "from", via,
  660. "certName", remoteCert.Certificate.Name(),
  661. "certVersion", remoteCert.Certificate.Version(),
  662. "fingerprint", remoteCert.Fingerprint,
  663. "issuer", remoteCert.Certificate.Issuer(),
  664. "initiatorIndex", result.RemoteIndex,
  665. "responderIndex", result.LocalIndex,
  666. "handshake", m{"stage": uint64(machine.MessageIndex()), "style": header.SubTypeName(header.Handshake, machine.Subtype())},
  667. )
  668. // packet aliases the listener's incoming buffer, so this copy must stay.
  669. hostinfo.HandshakePacket[handshakePacketStage0] = make([]byte, len(packet[header.Len:]))
  670. copy(hostinfo.HandshakePacket[handshakePacketStage0], packet[header.Len:])
  671. // response was freshly allocated by ProcessPacket; safe to retain directly.
  672. if response != nil {
  673. hostinfo.HandshakePacket[handshakePacketStage2] = response
  674. }
  675. hostinfo.remotes = f.lightHouse.QueryCache(vpnAddrs)
  676. if !via.IsRelayed {
  677. hostinfo.SetRemote(via.UdpAddr)
  678. }
  679. hostinfo.buildNetworks(f.myVpnNetworksTable, remoteCert.Certificate)
  680. existing, err := hm.CheckAndComplete(hostinfo, handshakePacketStage0, f)
  681. if err != nil {
  682. hm.handleCheckAndCompleteError(err, existing, hostinfo, via)
  683. return
  684. }
  685. hm.sendHandshakeResponse(via, response, hostinfo, false)
  686. hostinfo.remotes.RefreshFromHandshake(vpnAddrs)
  687. // Don't wait for UpdateWorker
  688. if f.lightHouse.IsAnyLighthouseAddr(vpnAddrs) {
  689. f.lightHouse.TriggerUpdate()
  690. }
  691. }
  692. // continueHandshake feeds an incoming packet to an existing pending handshake Machine.
  693. func (hm *HandshakeManager) continueHandshake(via ViaSender, hh *HandshakeHostInfo, packet []byte) {
  694. f := hm.f
  695. hh.Lock()
  696. defer hh.Unlock()
  697. // Re-verify hh is still tracked. Between queryIndex returning and us taking
  698. // hh.Lock, handleOutbound may have timed out and deleted it. Once we hold
  699. // hh.Lock no other deleter can race our index: handleOutbound also takes
  700. // hh.Lock first, and handleRecvError targets a main-hostmap entry with a
  701. // different localIndexId.
  702. hm.RLock()
  703. cur, ok := hm.indexes[hh.hostinfo.localIndexId]
  704. hm.RUnlock()
  705. if !ok || cur != hh {
  706. return
  707. }
  708. hostinfo := hh.hostinfo
  709. if !via.IsRelayed {
  710. if !f.lightHouse.GetRemoteAllowList().AllowAll(hostinfo.vpnAddrs, via.UdpAddr.Addr()) {
  711. f.l.Debug("lighthouse.remote_allow_list denied incoming handshake",
  712. "vpnAddrs", hostinfo.vpnAddrs, "from", via)
  713. return
  714. }
  715. }
  716. machine := hh.machine
  717. if machine == nil {
  718. f.l.Error("No handshake machine available for continuation",
  719. "vpnAddrs", hostinfo.vpnAddrs, "from", via)
  720. hm.DeleteHostInfo(hostinfo)
  721. return
  722. }
  723. response, result, err := machine.ProcessPacket(nil, packet)
  724. if err != nil {
  725. // Recoverable errors are routine noise, log at Debug. Fatal errors get a Warn.
  726. if machine.Failed() {
  727. f.l.Warn("Failed to process handshake packet, abandoning",
  728. "vpnAddrs", hostinfo.vpnAddrs, "from", via, "error", err)
  729. hm.DeleteHostInfo(hostinfo)
  730. } else {
  731. f.l.Debug("Failed to process handshake packet",
  732. "vpnAddrs", hostinfo.vpnAddrs, "from", via, "error", err)
  733. }
  734. return
  735. }
  736. if response != nil {
  737. hm.sendHandshakeResponse(via, response, hostinfo, false)
  738. }
  739. if result == nil {
  740. return
  741. }
  742. // Handshake complete; build the ConnectionState now that we have keys and a verified peer cert.
  743. hostinfo.ConnectionState = newConnectionStateFromResult(result)
  744. remoteCert := result.RemoteCert
  745. if remoteCert == nil {
  746. f.l.Error("Handshake completed without peer certificate",
  747. "vpnAddrs", hostinfo.vpnAddrs, "from", via)
  748. hm.DeleteHostInfo(hostinfo)
  749. return
  750. }
  751. vpnNetworks := remoteCert.Certificate.Networks()
  752. hostinfo.remoteIndexId = result.RemoteIndex
  753. hostinfo.lastHandshakeTime = result.HandshakeTime
  754. if !via.IsRelayed {
  755. hostinfo.SetRemote(via.UdpAddr)
  756. } else {
  757. hostinfo.relayState.InsertRelayTo(via.relayHI.vpnAddrs[0])
  758. }
  759. // Verify correct host responded (initiator check)
  760. vpnAddrs := make([]netip.Addr, len(vpnNetworks))
  761. correctHostResponded := false
  762. anyVpnAddrsInCommon := false
  763. for i, network := range vpnNetworks {
  764. // inside.go drops self-routed packets at the firewall stage, but we'd
  765. // rather not let a self-handshake complete in the first place: it
  766. // wastes a hostmap slot, suppresses no log, and obscures routing
  767. // misconfig. Explicit refusal here mirrors the responder-side check
  768. // in validatePeerCert.
  769. if f.myVpnAddrsTable.Contains(network.Addr()) {
  770. f.l.Error("Refusing to handshake with myself",
  771. "vpnNetworks", vpnNetworks,
  772. "from", via,
  773. "certName", remoteCert.Certificate.Name(),
  774. "certVersion", remoteCert.Certificate.Version(),
  775. "fingerprint", remoteCert.Fingerprint,
  776. "issuer", remoteCert.Certificate.Issuer(),
  777. "handshake", m{"stage": uint64(machine.MessageIndex()), "style": header.SubTypeName(header.Handshake, machine.Subtype())},
  778. )
  779. hm.DeleteHostInfo(hostinfo)
  780. return
  781. }
  782. vpnAddrs[i] = network.Addr()
  783. if hostinfo.vpnAddrs[0] == network.Addr() {
  784. correctHostResponded = true
  785. }
  786. if f.myVpnNetworksTable.Contains(network.Addr()) {
  787. anyVpnAddrsInCommon = true
  788. }
  789. }
  790. if !correctHostResponded {
  791. f.l.Info("Incorrect host responded to handshake",
  792. "intendedVpnAddrs", hostinfo.vpnAddrs,
  793. "haveVpnNetworks", vpnNetworks,
  794. "from", via,
  795. "certName", remoteCert.Certificate.Name(),
  796. "certVersion", remoteCert.Certificate.Version(),
  797. "fingerprint", remoteCert.Fingerprint,
  798. "issuer", remoteCert.Certificate.Issuer(),
  799. "handshake", m{"stage": uint64(machine.MessageIndex()), "style": header.SubTypeName(header.Handshake, machine.Subtype())},
  800. )
  801. hm.DeleteHostInfo(hostinfo)
  802. hm.StartHandshake(hostinfo.vpnAddrs[0], func(newHH *HandshakeHostInfo) {
  803. newHH.hostinfo.remotes = hostinfo.remotes
  804. newHH.hostinfo.remotes.BlockRemote(via)
  805. newHH.packetStore = hh.packetStore
  806. hh.packetStore = []*cachedPacket{}
  807. hostinfo.vpnAddrs = vpnAddrs
  808. f.sendCloseTunnel(hostinfo)
  809. })
  810. return
  811. }
  812. duration := time.Since(hh.startTime).Nanoseconds()
  813. msg := "Handshake message received"
  814. if !anyVpnAddrsInCommon {
  815. msg = "Handshake message received, but no vpnNetworks in common."
  816. }
  817. f.l.Info(msg,
  818. "vpnAddrs", vpnAddrs,
  819. "from", via,
  820. "certName", remoteCert.Certificate.Name(),
  821. "certVersion", remoteCert.Certificate.Version(),
  822. "fingerprint", remoteCert.Fingerprint,
  823. "issuer", remoteCert.Certificate.Issuer(),
  824. "initiatorIndex", result.LocalIndex,
  825. "responderIndex", result.RemoteIndex,
  826. "handshake", m{"stage": uint64(machine.MessageIndex()), "style": header.SubTypeName(header.Handshake, machine.Subtype())},
  827. "durationNs", duration,
  828. "sentCachedPackets", len(hh.packetStore),
  829. )
  830. hostinfo.vpnAddrs = vpnAddrs
  831. hostinfo.buildNetworks(f.myVpnNetworksTable, remoteCert.Certificate)
  832. hm.Complete(hostinfo, f)
  833. if len(hh.packetStore) > 0 {
  834. if f.l.Enabled(context.Background(), slog.LevelDebug) {
  835. hostinfo.logger(f.l).Debug("Sending stored packets", "count", len(hh.packetStore))
  836. }
  837. nb := make([]byte, 12, 12)
  838. out := make([]byte, mtu)
  839. for _, cp := range hh.packetStore {
  840. cp.callback(cp.messageType, cp.messageSubType, hostinfo, cp.packet, nb, out)
  841. }
  842. f.cachedPacketMetrics.sent.Inc(int64(len(hh.packetStore)))
  843. }
  844. hostinfo.remotes.RefreshFromHandshake(vpnAddrs)
  845. f.metricHandshakes.Update(duration)
  846. // Don't wait for UpdateWorker
  847. if f.lightHouse.IsAnyLighthouseAddr(vpnAddrs) {
  848. f.lightHouse.TriggerUpdate()
  849. }
  850. }
  851. // validatePeerCert checks the peer certificate for self-connection and remote allow list.
  852. // Returns the VPN addrs, whether any of them fall within one of our own VPN
  853. // networks, and true if valid; false if rejected.
  854. func (hm *HandshakeManager) validatePeerCert(via ViaSender, remoteCert *cert.CachedCertificate) ([]netip.Addr, bool, bool) {
  855. f := hm.f
  856. vpnNetworks := remoteCert.Certificate.Networks()
  857. // The cert package rejects host certs with no networks at parse time, so
  858. // reaching this state would mean an invariant was bypassed elsewhere.
  859. // Refuse explicitly so downstream code (which indexes vpnAddrs[0]) can't
  860. // panic if that invariant ever changes.
  861. if len(vpnNetworks) == 0 {
  862. f.l.Info("No networks in certificate",
  863. "from", via, "cert", remoteCert)
  864. return nil, false, false
  865. }
  866. vpnAddrs := make([]netip.Addr, len(vpnNetworks))
  867. anyVpnAddrsInCommon := false
  868. for i, network := range vpnNetworks {
  869. if f.myVpnAddrsTable.Contains(network.Addr()) {
  870. f.l.Error("Refusing to handshake with myself",
  871. "vpnNetworks", vpnNetworks,
  872. "from", via,
  873. "certName", remoteCert.Certificate.Name(),
  874. "certVersion", remoteCert.Certificate.Version(),
  875. "fingerprint", remoteCert.Fingerprint,
  876. "issuer", remoteCert.Certificate.Issuer(),
  877. )
  878. return nil, false, false
  879. }
  880. vpnAddrs[i] = network.Addr()
  881. if f.myVpnNetworksTable.Contains(network.Addr()) {
  882. anyVpnAddrsInCommon = true
  883. }
  884. }
  885. if !via.IsRelayed {
  886. if !f.lightHouse.GetRemoteAllowList().AllowAll(vpnAddrs, via.UdpAddr.Addr()) {
  887. f.l.Debug("lighthouse.remote_allow_list denied incoming handshake",
  888. "vpnAddrs", vpnAddrs, "from", via)
  889. return nil, false, false
  890. }
  891. }
  892. return vpnAddrs, anyVpnAddrsInCommon, true
  893. }
  894. // sendHandshakeResponse sends a handshake response via the appropriate transport.
  895. // cached is true when msg is a stored response being retransmitted because
  896. // the peer's stage-1 retransmit landed (the ErrAlreadySeen path); false on a
  897. // fresh response.
  898. func (hm *HandshakeManager) sendHandshakeResponse(via ViaSender, msg []byte, hostinfo *HostInfo, cached bool) {
  899. if msg == nil {
  900. return
  901. }
  902. f := hm.f
  903. f.messageMetrics.Tx(header.Handshake, header.MessageSubType(msg[1]), 1)
  904. // Common log fields. peerCert may be nil during intermediate
  905. // multi-message flows (handshake hasn't completed yet); skip the cert
  906. // block if so.
  907. logFields := []any{
  908. "vpnAddrs", hostinfo.vpnAddrs,
  909. "handshake", m{"stage": uint64(2), "style": header.SubTypeName(header.Handshake, header.HandshakeIXPSK0)},
  910. "cached", cached,
  911. "initiatorIndex", hostinfo.remoteIndexId,
  912. "responderIndex", hostinfo.localIndexId,
  913. }
  914. if peerCert := hostinfo.ConnectionState.peerCert; peerCert != nil {
  915. logFields = append(logFields,
  916. "certName", peerCert.Certificate.Name(),
  917. "certVersion", peerCert.Certificate.Version(),
  918. "fingerprint", peerCert.Fingerprint,
  919. "issuer", peerCert.Certificate.Issuer(),
  920. )
  921. }
  922. if !via.IsRelayed {
  923. fields := append(logFields, "from", via)
  924. err := f.outside.WriteTo(msg, via.UdpAddr)
  925. if err != nil {
  926. f.l.Error("Failed to send handshake message", append(fields, "error", err)...)
  927. } else {
  928. f.l.Info("Handshake message sent", fields...)
  929. }
  930. } else {
  931. if via.relay == nil {
  932. f.l.Error("Handshake send failed: both addr and via.relay are nil.")
  933. return
  934. }
  935. hostinfo.relayState.InsertRelayTo(via.relayHI.vpnAddrs[0])
  936. // We received a valid handshake on this relay, so make sure the relay
  937. // state reflects that, in case it had been marked Disestablished.
  938. via.relayHI.relayState.UpdateRelayForByIdxState(via.remoteIdx, Established)
  939. f.SendVia(via.relayHI, via.relay, msg, make([]byte, 12), make([]byte, mtu), false)
  940. f.l.Info("Handshake message sent", append(logFields, "relay", via.relayHI.vpnAddrs[0])...)
  941. }
  942. }
  943. // handleCheckAndCompleteError handles errors from CheckAndComplete.
  944. // This only fires from the responder-side beginHandshake path, after the
  945. // peer cert has been validated and ConnectionState populated, so peerCert
  946. // is always non-nil for the cases that log it.
  947. func (hm *HandshakeManager) handleCheckAndCompleteError(err error, existing, hostinfo *HostInfo, via ViaSender) {
  948. f := hm.f
  949. peerCert := hostinfo.ConnectionState.peerCert
  950. hsFields := m{"stage": uint64(1), "style": header.SubTypeName(header.Handshake, header.HandshakeIXPSK0)}
  951. switch err {
  952. case ErrAlreadySeen:
  953. if existing.SetRemoteIfPreferred(f.hostMap, via) {
  954. f.SendMessageToVpnAddr(header.Test, header.TestRequest, hostinfo.vpnAddrs[0], []byte(""), make([]byte, 12, 12), make([]byte, mtu))
  955. }
  956. // Resend the original response. The peer is committed to that response's
  957. // ephemeral keys; a freshly-built one would have different keys and break
  958. // the tunnel even though both sides "completed" the handshake.
  959. if msg := existing.HandshakePacket[handshakePacketStage2]; msg != nil {
  960. hm.sendHandshakeResponse(via, msg, existing, true)
  961. }
  962. case ErrExistingHostInfo:
  963. f.l.Info("Handshake too old",
  964. "vpnAddrs", hostinfo.vpnAddrs,
  965. "from", via,
  966. "certName", peerCert.Certificate.Name(),
  967. "certVersion", peerCert.Certificate.Version(),
  968. "fingerprint", peerCert.Fingerprint,
  969. "issuer", peerCert.Certificate.Issuer(),
  970. "oldHandshakeTime", existing.lastHandshakeTime,
  971. "newHandshakeTime", hostinfo.lastHandshakeTime,
  972. "initiatorIndex", hostinfo.remoteIndexId,
  973. "responderIndex", hostinfo.localIndexId,
  974. "handshake", hsFields,
  975. )
  976. f.SendMessageToVpnAddr(header.Test, header.TestRequest, hostinfo.vpnAddrs[0], []byte(""), make([]byte, 12, 12), make([]byte, mtu))
  977. case ErrLocalIndexCollision:
  978. f.l.Error("Failed to add HostInfo due to localIndex collision",
  979. "vpnAddrs", hostinfo.vpnAddrs,
  980. "from", via,
  981. "certName", peerCert.Certificate.Name(),
  982. "certVersion", peerCert.Certificate.Version(),
  983. "fingerprint", peerCert.Fingerprint,
  984. "issuer", peerCert.Certificate.Issuer(),
  985. "localIndex", hostinfo.localIndexId,
  986. "initiatorIndex", hostinfo.remoteIndexId,
  987. "responderIndex", hostinfo.localIndexId,
  988. "handshake", hsFields,
  989. )
  990. default:
  991. f.l.Error("Failed to add HostInfo to HostMap",
  992. "vpnAddrs", hostinfo.vpnAddrs,
  993. "from", via,
  994. "error", err,
  995. "certName", peerCert.Certificate.Name(),
  996. "certVersion", peerCert.Certificate.Version(),
  997. "fingerprint", peerCert.Fingerprint,
  998. "issuer", peerCert.Certificate.Issuer(),
  999. "initiatorIndex", hostinfo.remoteIndexId,
  1000. "responderIndex", hostinfo.localIndexId,
  1001. "handshake", hsFields,
  1002. )
  1003. }
  1004. }
  1005. // certVerifier returns a CertVerifier that validates certs against the current CA pool.
  1006. func (hm *HandshakeManager) certVerifier() handshake.CertVerifier {
  1007. return func(c cert.Certificate) (*cert.CachedCertificate, error) {
  1008. return hm.f.pki.GetCAPool().VerifyCertificate(time.Now(), c)
  1009. }
  1010. }