handshake_manager.go 39 KB

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