handshake_manager.go 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158
  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. // Is it just a delayed handshake packet? Check every hostinfo we hold for this address.
  378. for _, testHostInfo := range hm.mainHostMap.unlockedGetHostList(hostinfo.vpnAddrs[0]) {
  379. if bytes.Equal(hostinfo.HandshakePacket[handshakePacket], testHostInfo.HandshakePacket[handshakePacket]) {
  380. return testHostInfo, ErrAlreadySeen
  381. }
  382. }
  383. // Is this a newer handshake?
  384. if existingHostInfo.lastHandshakeTime >= hostinfo.lastHandshakeTime && !existingHostInfo.ConnectionState.initiator {
  385. return existingHostInfo, ErrExistingHostInfo
  386. }
  387. existingHostInfo.logger(hm.l).Info("Taking new handshake")
  388. }
  389. existingIndex, found := hm.mainHostMap.Indexes[hostinfo.localIndexId]
  390. if found {
  391. // We have a collision, but for a different hostinfo
  392. return existingIndex, ErrLocalIndexCollision
  393. }
  394. existingPendingIndex, found := hm.indexes[hostinfo.localIndexId]
  395. if found && existingPendingIndex.hostinfo != hostinfo {
  396. // We have a collision, but for a different hostinfo
  397. return existingPendingIndex.hostinfo, ErrLocalIndexCollision
  398. }
  399. existingRemoteIndex, found := hm.mainHostMap.RemoteIndexes[hostinfo.remoteIndexId]
  400. if found && existingRemoteIndex != nil && existingRemoteIndex.vpnAddrs[0] != hostinfo.vpnAddrs[0] {
  401. // We have a collision, but this can happen since we can't control
  402. // the remote ID. Just log about the situation as a note.
  403. hostinfo.logger(hm.l).Info("New host shadows existing host remoteIndex",
  404. "collision", existingRemoteIndex.vpnAddrs,
  405. )
  406. }
  407. hm.mainHostMap.unlockedAddHostInfo(hostinfo, f)
  408. return existingHostInfo, nil
  409. }
  410. // Complete is a simpler version of CheckAndComplete when we already know we
  411. // won't have a localIndexId collision because we already have an entry in the
  412. // pendingHostMap. An existing hostinfo is returned if there was one.
  413. func (hm *HandshakeManager) Complete(hostinfo *HostInfo, f *Interface) {
  414. hm.mainHostMap.Lock()
  415. defer hm.mainHostMap.Unlock()
  416. hm.Lock()
  417. defer hm.Unlock()
  418. existingRemoteIndex, found := hm.mainHostMap.RemoteIndexes[hostinfo.remoteIndexId]
  419. if found && existingRemoteIndex != nil {
  420. // We have a collision, but this can happen since we can't control
  421. // the remote ID. Just log about the situation as a note.
  422. hostinfo.logger(hm.l).Info("New host shadows existing host remoteIndex",
  423. "collision", existingRemoteIndex.vpnAddrs,
  424. )
  425. }
  426. // We need to remove from the pending hostmap first to avoid undoing work when after to the main hostmap.
  427. hm.unlockedDeleteHostInfo(hostinfo)
  428. hm.mainHostMap.unlockedAddHostInfo(hostinfo, f)
  429. }
  430. // allocateIndex generates a unique localIndexId for this HostInfo
  431. // and adds it to the pendingHostMap. Will error if we are unable to generate
  432. // a unique localIndexId
  433. func (hm *HandshakeManager) allocateIndex(hh *HandshakeHostInfo) (uint32, error) {
  434. hm.mainHostMap.RLock()
  435. defer hm.mainHostMap.RUnlock()
  436. hm.Lock()
  437. defer hm.Unlock()
  438. for range 32 {
  439. index, err := generateIndex(hm.l)
  440. if err != nil {
  441. return 0, err
  442. }
  443. _, inPending := hm.indexes[index]
  444. _, inMain := hm.mainHostMap.Indexes[index]
  445. if !inMain && !inPending {
  446. hh.hostinfo.localIndexId = index
  447. hm.indexes[index] = hh
  448. return index, nil
  449. }
  450. }
  451. return 0, errors.New("failed to generate unique localIndexId")
  452. }
  453. func (hm *HandshakeManager) DeleteHostInfo(hostinfo *HostInfo) {
  454. hm.Lock()
  455. defer hm.Unlock()
  456. hm.unlockedDeleteHostInfo(hostinfo)
  457. }
  458. func (hm *HandshakeManager) unlockedDeleteHostInfo(hostinfo *HostInfo) {
  459. for _, addr := range hostinfo.vpnAddrs {
  460. delete(hm.vpnIps, addr)
  461. }
  462. if len(hm.vpnIps) == 0 {
  463. hm.vpnIps = map[netip.Addr]*HandshakeHostInfo{}
  464. }
  465. delete(hm.indexes, hostinfo.localIndexId)
  466. if len(hm.indexes) == 0 {
  467. hm.indexes = map[uint32]*HandshakeHostInfo{}
  468. }
  469. if hm.l.Enabled(context.Background(), slog.LevelDebug) {
  470. hm.l.Debug("Pending hostmap hostInfo deleted",
  471. "hostMap", m{"mapTotalSize": len(hm.vpnIps),
  472. "vpnAddrs": hostinfo.vpnAddrs, "indexNumber": hostinfo.localIndexId, "remoteIndexNumber": hostinfo.remoteIndexId},
  473. )
  474. }
  475. }
  476. func (hm *HandshakeManager) QueryVpnAddr(vpnIp netip.Addr) *HostInfo {
  477. hh := hm.queryVpnIp(vpnIp)
  478. if hh != nil {
  479. return hh.hostinfo
  480. }
  481. return nil
  482. }
  483. func (hm *HandshakeManager) queryVpnIp(vpnIp netip.Addr) *HandshakeHostInfo {
  484. hm.RLock()
  485. defer hm.RUnlock()
  486. return hm.vpnIps[vpnIp]
  487. }
  488. func (hm *HandshakeManager) QueryIndex(index uint32) *HostInfo {
  489. hh := hm.queryIndex(index)
  490. if hh != nil {
  491. return hh.hostinfo
  492. }
  493. return nil
  494. }
  495. func (hm *HandshakeManager) queryIndex(index uint32) *HandshakeHostInfo {
  496. hm.RLock()
  497. defer hm.RUnlock()
  498. return hm.indexes[index]
  499. }
  500. func (hm *HandshakeManager) GetPreferredRanges() []netip.Prefix {
  501. return hm.mainHostMap.GetPreferredRanges()
  502. }
  503. func (hm *HandshakeManager) ForEachVpnAddr(f controlEach) {
  504. hm.RLock()
  505. defer hm.RUnlock()
  506. for _, v := range hm.vpnIps {
  507. f(v.hostinfo)
  508. }
  509. }
  510. func (hm *HandshakeManager) ForEachIndex(f controlEach) {
  511. hm.RLock()
  512. defer hm.RUnlock()
  513. for _, v := range hm.indexes {
  514. f(v.hostinfo)
  515. }
  516. }
  517. func (hm *HandshakeManager) EmitStats() {
  518. hm.RLock()
  519. hostLen := len(hm.vpnIps)
  520. indexLen := len(hm.indexes)
  521. hm.RUnlock()
  522. metrics.GetOrRegisterGauge("hostmap.pending.hosts", nil).Update(int64(hostLen))
  523. metrics.GetOrRegisterGauge("hostmap.pending.indexes", nil).Update(int64(indexLen))
  524. hm.mainHostMap.EmitStats()
  525. }
  526. // Utility functions below
  527. func generateIndex(l *slog.Logger) (uint32, error) {
  528. b := make([]byte, 4)
  529. // Let zero mean we don't know the ID, so don't generate zero
  530. var index uint32
  531. for index == 0 {
  532. _, err := rand.Read(b)
  533. if err != nil {
  534. l.Error("Failed to generate index", "error", err)
  535. return 0, err
  536. }
  537. index = binary.BigEndian.Uint32(b)
  538. }
  539. if l.Enabled(context.Background(), slog.LevelDebug) {
  540. l.Debug("Generated index", "index", index)
  541. }
  542. return index, nil
  543. }
  544. func hsTimeout(tries int64, interval time.Duration) time.Duration {
  545. return time.Duration(tries / 2 * ((2 * int64(interval)) + (tries-1)*int64(interval)))
  546. }
  547. // buildStage0Packet creates the initial handshake packet for the initiator.
  548. func (hm *HandshakeManager) buildStage0Packet(hh *HandshakeHostInfo) bool {
  549. cs := hm.f.pki.getCertState()
  550. v := cs.DefaultVersion()
  551. if hh.initiatingVersionOverride != cert.VersionPre1 {
  552. v = hh.initiatingVersionOverride
  553. } else if v < cert.Version2 {
  554. for _, a := range hh.hostinfo.vpnAddrs {
  555. if a.Is6() {
  556. v = cert.Version2
  557. break
  558. }
  559. }
  560. }
  561. cred := cs.GetCredential(v)
  562. if cred == nil {
  563. hm.f.l.Error("Unable to handshake with host because no certificate is available",
  564. "vpnAddrs", hh.hostinfo.vpnAddrs, "certVersion", v)
  565. return false
  566. }
  567. machine, err := handshake.NewMachine(
  568. v, cs.GetCredential,
  569. hm.certVerifier(), func() (uint32, error) { return hm.allocateIndex(hh) },
  570. true, header.HandshakeIXPSK0,
  571. )
  572. if err != nil {
  573. hm.f.l.Error("Failed to create handshake machine",
  574. "vpnAddrs", hh.hostinfo.vpnAddrs, "error", err)
  575. return false
  576. }
  577. msg, err := machine.Initiate(nil)
  578. if err != nil {
  579. hm.f.l.Error("Failed to initiate handshake",
  580. "vpnAddrs", hh.hostinfo.vpnAddrs, "error", err)
  581. return false
  582. }
  583. // hostinfo.ConnectionState stays nil until the handshake completes in
  584. // continueHandshake. Pre-completion control surfaces guard with nil
  585. // checks; the data plane never observes a pending hostinfo.
  586. hh.hostinfo.HandshakePacket[handshakePacketStage0] = msg
  587. hh.machine = machine
  588. hh.ready = true
  589. return true
  590. }
  591. // beginHandshake handles an incoming handshake packet that doesn't match any
  592. // existing pending handshake. It creates a new responder Machine and processes
  593. // the first message.
  594. func (hm *HandshakeManager) beginHandshake(via ViaSender, packet []byte, h *header.H) {
  595. f := hm.f
  596. cs := f.pki.getCertState()
  597. v := cs.DefaultVersion()
  598. if cs.GetCredential(v) == nil {
  599. f.l.Error("Unable to handshake with host because no certificate is available",
  600. "from", via, "certVersion", v)
  601. return
  602. }
  603. machine, err := handshake.NewMachine(
  604. v, cs.GetCredential,
  605. hm.certVerifier(), func() (uint32, error) { return generateIndex(f.l) },
  606. false, header.HandshakeIXPSK0,
  607. )
  608. if err != nil {
  609. f.l.Error("Failed to create handshake machine", "from", via, "error", err)
  610. return
  611. }
  612. response, result, err := machine.ProcessPacket(nil, packet)
  613. if err != nil {
  614. f.l.Error("Failed to process handshake packet", "from", via, "error", err)
  615. return
  616. }
  617. if result == nil {
  618. // Multi-message pattern: the responder Machine would need to be
  619. // registered in hm.indexes so a future inbound packet finds it via
  620. // continueHandshake. The current manager doesn't do that yet, so
  621. // fail loudly rather than silently dropping the in-flight handshake.
  622. // TODO: support multi-message responder flows (XX, pqIX, etc.).
  623. // See also the IX-shaped cipher key assignment in handshake.Machine.
  624. f.l.Error("multi-message handshake responder is not supported",
  625. "from", via, "error", handshake.ErrMultiMessageUnsupported)
  626. return
  627. }
  628. remoteCert := result.RemoteCert
  629. if remoteCert == nil {
  630. f.l.Error("Handshake did not produce a peer certificate", "from", via)
  631. return
  632. }
  633. // Validate peer identity
  634. vpnAddrs, anyVpnAddrsInCommon, ok := hm.validatePeerCert(via, remoteCert)
  635. if !ok {
  636. return
  637. }
  638. hostinfo := &HostInfo{
  639. ConnectionState: newConnectionStateFromResult(result),
  640. localIndexId: result.LocalIndex,
  641. remoteIndexId: result.RemoteIndex,
  642. vpnAddrs: vpnAddrs,
  643. HandshakePacket: make(map[uint8][]byte, 0),
  644. lastHandshakeTime: result.HandshakeTime,
  645. relayState: RelayState{
  646. relays: nil,
  647. relayForByAddr: map[netip.Addr]*Relay{},
  648. relayForByIdx: map[uint32]*Relay{},
  649. },
  650. }
  651. msg := "Handshake message received"
  652. if !anyVpnAddrsInCommon {
  653. msg = "Handshake message received, but no vpnNetworks in common."
  654. }
  655. f.l.Info(msg,
  656. "vpnAddrs", vpnAddrs,
  657. "from", via,
  658. "certName", remoteCert.Certificate.Name(),
  659. "certVersion", remoteCert.Certificate.Version(),
  660. "fingerprint", remoteCert.Fingerprint,
  661. "issuer", remoteCert.Certificate.Issuer(),
  662. "initiatorIndex", result.RemoteIndex,
  663. "responderIndex", result.LocalIndex,
  664. "handshake", m{"stage": uint64(machine.MessageIndex()), "style": header.SubTypeName(header.Handshake, machine.Subtype())},
  665. )
  666. // packet aliases the listener's incoming buffer, so this copy must stay.
  667. hostinfo.HandshakePacket[handshakePacketStage0] = make([]byte, len(packet[header.Len:]))
  668. copy(hostinfo.HandshakePacket[handshakePacketStage0], packet[header.Len:])
  669. // response was freshly allocated by ProcessPacket; safe to retain directly.
  670. if response != nil {
  671. hostinfo.HandshakePacket[handshakePacketStage2] = response
  672. }
  673. hostinfo.remotes = f.lightHouse.QueryCache(vpnAddrs)
  674. if !via.IsRelayed {
  675. hostinfo.SetRemote(via.UdpAddr)
  676. }
  677. hostinfo.buildNetworks(f.myVpnNetworksTable, remoteCert.Certificate)
  678. existing, err := hm.CheckAndComplete(hostinfo, handshakePacketStage0, f)
  679. if err != nil {
  680. hm.handleCheckAndCompleteError(err, existing, hostinfo, via)
  681. return
  682. }
  683. hm.sendHandshakeResponse(via, response, hostinfo, false)
  684. hostinfo.remotes.RefreshFromHandshake(vpnAddrs)
  685. // Don't wait for UpdateWorker
  686. if f.lightHouse.IsAnyLighthouseAddr(vpnAddrs) {
  687. f.lightHouse.TriggerUpdate()
  688. }
  689. }
  690. // continueHandshake feeds an incoming packet to an existing pending handshake Machine.
  691. func (hm *HandshakeManager) continueHandshake(via ViaSender, hh *HandshakeHostInfo, packet []byte) {
  692. f := hm.f
  693. hh.Lock()
  694. defer hh.Unlock()
  695. // Re-verify hh is still tracked. Between queryIndex returning and us taking
  696. // hh.Lock, handleOutbound may have timed out and deleted it. Once we hold
  697. // hh.Lock no other deleter can race our index: handleOutbound also takes
  698. // hh.Lock first, and handleRecvError targets a main-hostmap entry with a
  699. // different localIndexId.
  700. hm.RLock()
  701. cur, ok := hm.indexes[hh.hostinfo.localIndexId]
  702. hm.RUnlock()
  703. if !ok || cur != hh {
  704. return
  705. }
  706. hostinfo := hh.hostinfo
  707. if !via.IsRelayed {
  708. if !f.lightHouse.GetRemoteAllowList().AllowAll(hostinfo.vpnAddrs, via.UdpAddr.Addr()) {
  709. f.l.Debug("lighthouse.remote_allow_list denied incoming handshake",
  710. "vpnAddrs", hostinfo.vpnAddrs, "from", via)
  711. return
  712. }
  713. }
  714. machine := hh.machine
  715. if machine == nil {
  716. f.l.Error("No handshake machine available for continuation",
  717. "vpnAddrs", hostinfo.vpnAddrs, "from", via)
  718. hm.DeleteHostInfo(hostinfo)
  719. return
  720. }
  721. response, result, err := machine.ProcessPacket(nil, packet)
  722. if err != nil {
  723. // Recoverable errors are routine noise, log at Debug. Fatal errors get a Warn.
  724. if machine.Failed() {
  725. f.l.Warn("Failed to process handshake packet, abandoning",
  726. "vpnAddrs", hostinfo.vpnAddrs, "from", via, "error", err)
  727. hm.DeleteHostInfo(hostinfo)
  728. } else {
  729. f.l.Debug("Failed to process handshake packet",
  730. "vpnAddrs", hostinfo.vpnAddrs, "from", via, "error", err)
  731. }
  732. return
  733. }
  734. if response != nil {
  735. hm.sendHandshakeResponse(via, response, hostinfo, false)
  736. }
  737. if result == nil {
  738. return
  739. }
  740. // Handshake complete; build the ConnectionState now that we have keys and a verified peer cert.
  741. hostinfo.ConnectionState = newConnectionStateFromResult(result)
  742. remoteCert := result.RemoteCert
  743. if remoteCert == nil {
  744. f.l.Error("Handshake completed without peer certificate",
  745. "vpnAddrs", hostinfo.vpnAddrs, "from", via)
  746. hm.DeleteHostInfo(hostinfo)
  747. return
  748. }
  749. vpnNetworks := remoteCert.Certificate.Networks()
  750. hostinfo.remoteIndexId = result.RemoteIndex
  751. hostinfo.lastHandshakeTime = result.HandshakeTime
  752. if !via.IsRelayed {
  753. hostinfo.SetRemote(via.UdpAddr)
  754. } else {
  755. hostinfo.relayState.InsertRelayTo(via.relayHI.vpnAddrs[0])
  756. }
  757. // Verify correct host responded (initiator check)
  758. vpnAddrs := make([]netip.Addr, len(vpnNetworks))
  759. correctHostResponded := false
  760. anyVpnAddrsInCommon := false
  761. for i, network := range vpnNetworks {
  762. // inside.go drops self-routed packets at the firewall stage, but we'd
  763. // rather not let a self-handshake complete in the first place: it
  764. // wastes a hostmap slot, suppresses no log, and obscures routing
  765. // misconfig. Explicit refusal here mirrors the responder-side check
  766. // in validatePeerCert.
  767. if f.myVpnAddrsTable.Contains(network.Addr()) {
  768. f.l.Error("Refusing to handshake with myself",
  769. "vpnNetworks", vpnNetworks,
  770. "from", via,
  771. "certName", remoteCert.Certificate.Name(),
  772. "certVersion", remoteCert.Certificate.Version(),
  773. "fingerprint", remoteCert.Fingerprint,
  774. "issuer", remoteCert.Certificate.Issuer(),
  775. "handshake", m{"stage": uint64(machine.MessageIndex()), "style": header.SubTypeName(header.Handshake, machine.Subtype())},
  776. )
  777. hm.DeleteHostInfo(hostinfo)
  778. return
  779. }
  780. vpnAddrs[i] = network.Addr()
  781. if hostinfo.vpnAddrs[0] == network.Addr() {
  782. correctHostResponded = true
  783. }
  784. if f.myVpnNetworksTable.Contains(network.Addr()) {
  785. anyVpnAddrsInCommon = true
  786. }
  787. }
  788. if !correctHostResponded {
  789. f.l.Info("Incorrect host responded to handshake",
  790. "intendedVpnAddrs", hostinfo.vpnAddrs,
  791. "haveVpnNetworks", vpnNetworks,
  792. "from", via,
  793. "certName", remoteCert.Certificate.Name(),
  794. "certVersion", remoteCert.Certificate.Version(),
  795. "fingerprint", remoteCert.Fingerprint,
  796. "issuer", remoteCert.Certificate.Issuer(),
  797. "handshake", m{"stage": uint64(machine.MessageIndex()), "style": header.SubTypeName(header.Handshake, machine.Subtype())},
  798. )
  799. hm.DeleteHostInfo(hostinfo)
  800. hm.StartHandshake(hostinfo.vpnAddrs[0], func(newHH *HandshakeHostInfo) {
  801. newHH.hostinfo.remotes = hostinfo.remotes
  802. newHH.hostinfo.remotes.BlockRemote(via)
  803. newHH.packetStore = hh.packetStore
  804. hh.packetStore = []*cachedPacket{}
  805. hostinfo.vpnAddrs = vpnAddrs
  806. f.sendCloseTunnel(hostinfo)
  807. })
  808. return
  809. }
  810. duration := time.Since(hh.startTime).Nanoseconds()
  811. msg := "Handshake message received"
  812. if !anyVpnAddrsInCommon {
  813. msg = "Handshake message received, but no vpnNetworks in common."
  814. }
  815. f.l.Info(msg,
  816. "vpnAddrs", vpnAddrs,
  817. "from", via,
  818. "certName", remoteCert.Certificate.Name(),
  819. "certVersion", remoteCert.Certificate.Version(),
  820. "fingerprint", remoteCert.Fingerprint,
  821. "issuer", remoteCert.Certificate.Issuer(),
  822. "initiatorIndex", result.LocalIndex,
  823. "responderIndex", result.RemoteIndex,
  824. "handshake", m{"stage": uint64(machine.MessageIndex()), "style": header.SubTypeName(header.Handshake, machine.Subtype())},
  825. "durationNs", duration,
  826. "sentCachedPackets", len(hh.packetStore),
  827. )
  828. hostinfo.vpnAddrs = vpnAddrs
  829. hostinfo.buildNetworks(f.myVpnNetworksTable, remoteCert.Certificate)
  830. hm.Complete(hostinfo, f)
  831. if len(hh.packetStore) > 0 {
  832. if f.l.Enabled(context.Background(), slog.LevelDebug) {
  833. hostinfo.logger(f.l).Debug("Sending stored packets", "count", len(hh.packetStore))
  834. }
  835. nb := make([]byte, 12, 12)
  836. out := make([]byte, mtu)
  837. for _, cp := range hh.packetStore {
  838. cp.callback(cp.messageType, cp.messageSubType, hostinfo, cp.packet, nb, out)
  839. }
  840. f.cachedPacketMetrics.sent.Inc(int64(len(hh.packetStore)))
  841. }
  842. hostinfo.remotes.RefreshFromHandshake(vpnAddrs)
  843. f.metricHandshakes.Update(duration)
  844. // Don't wait for UpdateWorker
  845. if f.lightHouse.IsAnyLighthouseAddr(vpnAddrs) {
  846. f.lightHouse.TriggerUpdate()
  847. }
  848. }
  849. // validatePeerCert checks the peer certificate for self-connection and remote allow list.
  850. // Returns the VPN addrs, whether any of them fall within one of our own VPN
  851. // networks, and true if valid; false if rejected.
  852. func (hm *HandshakeManager) validatePeerCert(via ViaSender, remoteCert *cert.CachedCertificate) ([]netip.Addr, bool, bool) {
  853. f := hm.f
  854. vpnNetworks := remoteCert.Certificate.Networks()
  855. // The cert package rejects host certs with no networks at parse time, so
  856. // reaching this state would mean an invariant was bypassed elsewhere.
  857. // Refuse explicitly so downstream code (which indexes vpnAddrs[0]) can't
  858. // panic if that invariant ever changes.
  859. if len(vpnNetworks) == 0 {
  860. f.l.Info("No networks in certificate",
  861. "from", via, "cert", remoteCert)
  862. return nil, false, false
  863. }
  864. vpnAddrs := make([]netip.Addr, len(vpnNetworks))
  865. anyVpnAddrsInCommon := false
  866. for i, network := range vpnNetworks {
  867. if f.myVpnAddrsTable.Contains(network.Addr()) {
  868. f.l.Error("Refusing to handshake with myself",
  869. "vpnNetworks", vpnNetworks,
  870. "from", via,
  871. "certName", remoteCert.Certificate.Name(),
  872. "certVersion", remoteCert.Certificate.Version(),
  873. "fingerprint", remoteCert.Fingerprint,
  874. "issuer", remoteCert.Certificate.Issuer(),
  875. )
  876. return nil, false, false
  877. }
  878. vpnAddrs[i] = network.Addr()
  879. if f.myVpnNetworksTable.Contains(network.Addr()) {
  880. anyVpnAddrsInCommon = true
  881. }
  882. }
  883. if !via.IsRelayed {
  884. if !f.lightHouse.GetRemoteAllowList().AllowAll(vpnAddrs, via.UdpAddr.Addr()) {
  885. f.l.Debug("lighthouse.remote_allow_list denied incoming handshake",
  886. "vpnAddrs", vpnAddrs, "from", via)
  887. return nil, false, false
  888. }
  889. }
  890. return vpnAddrs, anyVpnAddrsInCommon, true
  891. }
  892. // sendHandshakeResponse sends a handshake response via the appropriate transport.
  893. // cached is true when msg is a stored response being retransmitted because
  894. // the peer's stage-1 retransmit landed (the ErrAlreadySeen path); false on a
  895. // fresh response.
  896. func (hm *HandshakeManager) sendHandshakeResponse(via ViaSender, msg []byte, hostinfo *HostInfo, cached bool) {
  897. if msg == nil {
  898. return
  899. }
  900. f := hm.f
  901. f.messageMetrics.Tx(header.Handshake, header.MessageSubType(msg[1]), 1)
  902. // Common log fields. peerCert may be nil during intermediate
  903. // multi-message flows (handshake hasn't completed yet); skip the cert
  904. // block if so.
  905. logFields := []any{
  906. "vpnAddrs", hostinfo.vpnAddrs,
  907. "handshake", m{"stage": uint64(2), "style": header.SubTypeName(header.Handshake, header.HandshakeIXPSK0)},
  908. "cached", cached,
  909. "initiatorIndex", hostinfo.remoteIndexId,
  910. "responderIndex", hostinfo.localIndexId,
  911. }
  912. if peerCert := hostinfo.ConnectionState.peerCert; peerCert != nil {
  913. logFields = append(logFields,
  914. "certName", peerCert.Certificate.Name(),
  915. "certVersion", peerCert.Certificate.Version(),
  916. "fingerprint", peerCert.Fingerprint,
  917. "issuer", peerCert.Certificate.Issuer(),
  918. )
  919. }
  920. if !via.IsRelayed {
  921. fields := append(logFields, "from", via)
  922. err := f.outside.WriteTo(msg, via.UdpAddr)
  923. if err != nil {
  924. f.l.Error("Failed to send handshake message", append(fields, "error", err)...)
  925. } else {
  926. f.l.Info("Handshake message sent", fields...)
  927. }
  928. } else {
  929. if via.relay == nil {
  930. f.l.Error("Handshake send failed: both addr and via.relay are nil.")
  931. return
  932. }
  933. hostinfo.relayState.InsertRelayTo(via.relayHI.vpnAddrs[0])
  934. // We received a valid handshake on this relay, so make sure the relay
  935. // state reflects that, in case it had been marked Disestablished.
  936. via.relayHI.relayState.UpdateRelayForByIdxState(via.relay.LocalIndex, Established)
  937. f.SendVia(via.relayHI, via.relay, msg, make([]byte, 12), make([]byte, mtu), false)
  938. f.l.Info("Handshake message sent", append(logFields, "relay", via.relayHI.vpnAddrs[0])...)
  939. }
  940. }
  941. // handleCheckAndCompleteError handles errors from CheckAndComplete.
  942. // This only fires from the responder-side beginHandshake path, after the
  943. // peer cert has been validated and ConnectionState populated, so peerCert
  944. // is always non-nil for the cases that log it.
  945. func (hm *HandshakeManager) handleCheckAndCompleteError(err error, existing, hostinfo *HostInfo, via ViaSender) {
  946. f := hm.f
  947. peerCert := hostinfo.ConnectionState.peerCert
  948. hsFields := m{"stage": uint64(1), "style": header.SubTypeName(header.Handshake, header.HandshakeIXPSK0)}
  949. switch err {
  950. case ErrAlreadySeen:
  951. if existing.SetRemoteIfPreferred(f.hostMap, via) {
  952. f.SendMessageToVpnAddr(header.Test, header.TestRequest, hostinfo.vpnAddrs[0], []byte(""), make([]byte, 12, 12), make([]byte, mtu))
  953. }
  954. // Resend the original response. The peer is committed to that response's
  955. // ephemeral keys; a freshly-built one would have different keys and break
  956. // the tunnel even though both sides "completed" the handshake.
  957. if msg := existing.HandshakePacket[handshakePacketStage2]; msg != nil {
  958. hm.sendHandshakeResponse(via, msg, existing, true)
  959. }
  960. case ErrExistingHostInfo:
  961. f.l.Info("Handshake too old",
  962. "vpnAddrs", hostinfo.vpnAddrs,
  963. "from", via,
  964. "certName", peerCert.Certificate.Name(),
  965. "certVersion", peerCert.Certificate.Version(),
  966. "fingerprint", peerCert.Fingerprint,
  967. "issuer", peerCert.Certificate.Issuer(),
  968. "oldHandshakeTime", existing.lastHandshakeTime,
  969. "newHandshakeTime", hostinfo.lastHandshakeTime,
  970. "initiatorIndex", hostinfo.remoteIndexId,
  971. "responderIndex", hostinfo.localIndexId,
  972. "handshake", hsFields,
  973. )
  974. f.SendMessageToVpnAddr(header.Test, header.TestRequest, hostinfo.vpnAddrs[0], []byte(""), make([]byte, 12, 12), make([]byte, mtu))
  975. case ErrLocalIndexCollision:
  976. f.l.Error("Failed to add HostInfo due to localIndex collision",
  977. "vpnAddrs", hostinfo.vpnAddrs,
  978. "from", via,
  979. "certName", peerCert.Certificate.Name(),
  980. "certVersion", peerCert.Certificate.Version(),
  981. "fingerprint", peerCert.Fingerprint,
  982. "issuer", peerCert.Certificate.Issuer(),
  983. "localIndex", hostinfo.localIndexId,
  984. "initiatorIndex", hostinfo.remoteIndexId,
  985. "responderIndex", hostinfo.localIndexId,
  986. "handshake", hsFields,
  987. )
  988. default:
  989. f.l.Error("Failed to add HostInfo to HostMap",
  990. "vpnAddrs", hostinfo.vpnAddrs,
  991. "from", via,
  992. "error", err,
  993. "certName", peerCert.Certificate.Name(),
  994. "certVersion", peerCert.Certificate.Version(),
  995. "fingerprint", peerCert.Fingerprint,
  996. "issuer", peerCert.Certificate.Issuer(),
  997. "initiatorIndex", hostinfo.remoteIndexId,
  998. "responderIndex", hostinfo.localIndexId,
  999. "handshake", hsFields,
  1000. )
  1001. }
  1002. }
  1003. // certVerifier returns a CertVerifier that validates certs against the current CA pool.
  1004. func (hm *HandshakeManager) certVerifier() handshake.CertVerifier {
  1005. return func(c cert.Certificate) (*cert.CachedCertificate, error) {
  1006. return hm.f.pki.GetCAPool().VerifyCertificate(time.Now(), c)
  1007. }
  1008. }