handshake_manager.go 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744
  1. package nebula
  2. import (
  3. "bytes"
  4. "context"
  5. "crypto/rand"
  6. "encoding/binary"
  7. "errors"
  8. "net/netip"
  9. "slices"
  10. "sync"
  11. "time"
  12. "github.com/rcrowley/go-metrics"
  13. "github.com/sirupsen/logrus"
  14. "github.com/slackhq/nebula/cert"
  15. "github.com/slackhq/nebula/header"
  16. "github.com/slackhq/nebula/udp"
  17. )
  18. const (
  19. DefaultHandshakeTryInterval = time.Millisecond * 100
  20. DefaultHandshakeRetries = 10
  21. DefaultHandshakeTriggerBuffer = 64
  22. DefaultUseRelays = true
  23. )
  24. var (
  25. defaultHandshakeConfig = HandshakeConfig{
  26. tryInterval: DefaultHandshakeTryInterval,
  27. retries: DefaultHandshakeRetries,
  28. triggerBuffer: DefaultHandshakeTriggerBuffer,
  29. useRelays: DefaultUseRelays,
  30. }
  31. )
  32. type HandshakeConfig struct {
  33. tryInterval time.Duration
  34. retries int64
  35. triggerBuffer int
  36. useRelays bool
  37. messageMetrics *MessageMetrics
  38. }
  39. type HandshakeManager struct {
  40. // Mutex for interacting with the vpnIps and indexes maps
  41. sync.RWMutex
  42. vpnIps map[netip.Addr]*HandshakeHostInfo
  43. indexes map[uint32]*HandshakeHostInfo
  44. mainHostMap *HostMap
  45. lightHouse *LightHouse
  46. outside udp.Conn
  47. config HandshakeConfig
  48. OutboundHandshakeTimer *LockingTimerWheel[netip.Addr]
  49. messageMetrics *MessageMetrics
  50. metricInitiated metrics.Counter
  51. metricTimedOut metrics.Counter
  52. f *Interface
  53. l *logrus.Logger
  54. // can be used to trigger outbound handshake for the given vpnIp
  55. trigger chan netip.Addr
  56. }
  57. type HandshakeHostInfo struct {
  58. sync.Mutex
  59. startTime time.Time // Time that we first started trying with this handshake
  60. ready bool // Is the handshake ready
  61. initiatingVersionOverride cert.Version // Should we use a non-default cert version for this handshake?
  62. counter int64 // How many attempts have we made so far
  63. lastRemotes []netip.AddrPort // Remotes that we sent to during the previous attempt
  64. packetStore []*cachedPacket // A set of packets to be transmitted once the handshake completes
  65. hostinfo *HostInfo
  66. }
  67. func (hh *HandshakeHostInfo) cachePacket(l *logrus.Logger, t header.MessageType, st header.MessageSubType, packet []byte, f packetCallback, m *cachedPacketMetrics) {
  68. if len(hh.packetStore) < 100 {
  69. tempPacket := make([]byte, len(packet))
  70. copy(tempPacket, packet)
  71. hh.packetStore = append(hh.packetStore, &cachedPacket{t, st, f, tempPacket})
  72. if l.Level >= logrus.DebugLevel {
  73. hh.hostinfo.logger(l).
  74. WithField("length", len(hh.packetStore)).
  75. WithField("stored", true).
  76. Debugf("Packet store")
  77. }
  78. } else {
  79. m.dropped.Inc(1)
  80. if l.Level >= logrus.DebugLevel {
  81. hh.hostinfo.logger(l).
  82. WithField("length", len(hh.packetStore)).
  83. WithField("stored", false).
  84. Debugf("Packet store")
  85. }
  86. }
  87. }
  88. func NewHandshakeManager(l *logrus.Logger, mainHostMap *HostMap, lightHouse *LightHouse, outside udp.Conn, config HandshakeConfig) *HandshakeManager {
  89. return &HandshakeManager{
  90. vpnIps: map[netip.Addr]*HandshakeHostInfo{},
  91. indexes: map[uint32]*HandshakeHostInfo{},
  92. mainHostMap: mainHostMap,
  93. lightHouse: lightHouse,
  94. outside: outside,
  95. config: config,
  96. trigger: make(chan netip.Addr, config.triggerBuffer),
  97. OutboundHandshakeTimer: NewLockingTimerWheel[netip.Addr](config.tryInterval, hsTimeout(config.retries, config.tryInterval)),
  98. messageMetrics: config.messageMetrics,
  99. metricInitiated: metrics.GetOrRegisterCounter("handshake_manager.initiated", nil),
  100. metricTimedOut: metrics.GetOrRegisterCounter("handshake_manager.timed_out", nil),
  101. l: l,
  102. }
  103. }
  104. func (hm *HandshakeManager) Run(ctx context.Context) {
  105. clockSource := time.NewTicker(hm.config.tryInterval)
  106. defer clockSource.Stop()
  107. for {
  108. select {
  109. case <-ctx.Done():
  110. return
  111. case vpnIP := <-hm.trigger:
  112. hm.handleOutbound(vpnIP, true)
  113. case now := <-clockSource.C:
  114. hm.NextOutboundHandshakeTimerTick(now)
  115. }
  116. }
  117. }
  118. func (hm *HandshakeManager) HandleIncoming(addr netip.AddrPort, via *ViaSender, packet []byte, h *header.H) {
  119. // First remote allow list check before we know the vpnIp
  120. if addr.IsValid() {
  121. if !hm.lightHouse.GetRemoteAllowList().AllowUnknownVpnAddr(addr.Addr()) {
  122. hm.l.WithField("udpAddr", addr).Debug("lighthouse.remote_allow_list denied incoming handshake")
  123. return
  124. }
  125. }
  126. switch h.Subtype {
  127. case header.HandshakeIXPSK0:
  128. switch h.MessageCounter {
  129. case 1:
  130. ixHandshakeStage1(hm.f, addr, via, packet, h)
  131. case 2:
  132. newHostinfo := hm.queryIndex(h.RemoteIndex)
  133. tearDown := ixHandshakeStage2(hm.f, addr, via, newHostinfo, packet, h)
  134. if tearDown && newHostinfo != nil {
  135. hm.DeleteHostInfo(newHostinfo.hostinfo)
  136. }
  137. }
  138. }
  139. }
  140. func (hm *HandshakeManager) NextOutboundHandshakeTimerTick(now time.Time) {
  141. hm.OutboundHandshakeTimer.Advance(now)
  142. for {
  143. vpnIp, has := hm.OutboundHandshakeTimer.Purge()
  144. if !has {
  145. break
  146. }
  147. hm.handleOutbound(vpnIp, false)
  148. }
  149. }
  150. func (hm *HandshakeManager) handleOutbound(vpnIp netip.Addr, lighthouseTriggered bool) {
  151. hh := hm.queryVpnIp(vpnIp)
  152. if hh == nil {
  153. return
  154. }
  155. hh.Lock()
  156. defer hh.Unlock()
  157. hostinfo := hh.hostinfo
  158. // If we are out of time, clean up
  159. if hh.counter >= hm.config.retries {
  160. hh.hostinfo.logger(hm.l).WithField("udpAddrs", hh.hostinfo.remotes.CopyAddrs(hm.mainHostMap.GetPreferredRanges())).
  161. WithField("initiatorIndex", hh.hostinfo.localIndexId).
  162. WithField("remoteIndex", hh.hostinfo.remoteIndexId).
  163. WithField("handshake", m{"stage": 1, "style": "ix_psk0"}).
  164. WithField("durationNs", time.Since(hh.startTime).Nanoseconds()).
  165. Info("Handshake timed out")
  166. hm.metricTimedOut.Inc(1)
  167. hm.DeleteHostInfo(hostinfo)
  168. return
  169. }
  170. // Increment the counter to increase our delay, linear backoff
  171. hh.counter++
  172. // Check if we have a handshake packet to transmit yet
  173. if !hh.ready {
  174. if !ixHandshakeStage0(hm.f, hh) {
  175. hm.OutboundHandshakeTimer.Add(vpnIp, hm.config.tryInterval*time.Duration(hh.counter))
  176. return
  177. }
  178. }
  179. // Get a remotes object if we don't already have one.
  180. // This is mainly to protect us as this should never be the case
  181. // NB ^ This comment doesn't jive. It's how the thing gets initialized.
  182. // It's the common path. Should it update every time, in case a future LH query/queries give us more info?
  183. if hostinfo.remotes == nil {
  184. hostinfo.remotes = hm.lightHouse.QueryCache([]netip.Addr{vpnIp})
  185. }
  186. remotes := hostinfo.remotes.CopyAddrs(hm.mainHostMap.GetPreferredRanges())
  187. remotesHaveChanged := !slices.Equal(remotes, hh.lastRemotes)
  188. // We only care about a lighthouse trigger if we have new remotes to send to.
  189. // This is a very specific optimization for a fast lighthouse reply.
  190. if lighthouseTriggered && !remotesHaveChanged {
  191. // If we didn't return here a lighthouse could cause us to aggressively send handshakes
  192. return
  193. }
  194. hh.lastRemotes = remotes
  195. // This will generate a load of queries for hosts with only 1 ip
  196. // (such as ones registered to the lighthouse with only a private IP)
  197. // So we only do it one time after attempting 5 handshakes already.
  198. if len(remotes) <= 1 && hh.counter == 5 {
  199. // If we only have 1 remote it is highly likely our query raced with the other host registered within the lighthouse
  200. // Our vpnIp here has a tunnel with a lighthouse but has yet to send a host update packet there so we only know about
  201. // the learned public ip for them. Query again to short circuit the promotion counter
  202. hm.lightHouse.QueryServer(vpnIp)
  203. }
  204. // Send the handshake to all known ips, stage 2 takes care of assigning the hostinfo.remote based on the first to reply
  205. var sentTo []netip.AddrPort
  206. hostinfo.remotes.ForEach(hm.mainHostMap.GetPreferredRanges(), func(addr netip.AddrPort, _ bool) {
  207. hm.messageMetrics.Tx(header.Handshake, header.MessageSubType(hostinfo.HandshakePacket[0][1]), 1)
  208. err := hm.outside.WriteTo(hostinfo.HandshakePacket[0], addr)
  209. if err != nil {
  210. hostinfo.logger(hm.l).WithField("udpAddr", addr).
  211. WithField("initiatorIndex", hostinfo.localIndexId).
  212. WithField("handshake", m{"stage": 1, "style": "ix_psk0"}).
  213. WithError(err).Error("Failed to send handshake message")
  214. } else {
  215. sentTo = append(sentTo, addr)
  216. }
  217. })
  218. // 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,
  219. // so only log when the list of remotes has changed
  220. if remotesHaveChanged {
  221. hostinfo.logger(hm.l).WithField("udpAddrs", sentTo).
  222. WithField("initiatorIndex", hostinfo.localIndexId).
  223. WithField("handshake", m{"stage": 1, "style": "ix_psk0"}).
  224. Info("Handshake message sent")
  225. } else if hm.l.Level >= logrus.DebugLevel {
  226. hostinfo.logger(hm.l).WithField("udpAddrs", sentTo).
  227. WithField("initiatorIndex", hostinfo.localIndexId).
  228. WithField("handshake", m{"stage": 1, "style": "ix_psk0"}).
  229. Debug("Handshake message sent")
  230. }
  231. if hm.config.useRelays && len(hostinfo.remotes.relays) > 0 {
  232. hostinfo.logger(hm.l).WithField("relays", hostinfo.remotes.relays).Info("Attempt to relay through hosts")
  233. // Send a RelayRequest to all known Relay IP's
  234. for _, relay := range hostinfo.remotes.relays {
  235. // Don't relay to myself
  236. if relay == vpnIp {
  237. continue
  238. }
  239. // Don't relay through the host I'm trying to connect to
  240. if hm.f.myVpnAddrsTable.Contains(relay) {
  241. continue
  242. }
  243. relayHostInfo := hm.mainHostMap.QueryVpnAddr(relay)
  244. if relayHostInfo == nil || !relayHostInfo.remote.IsValid() {
  245. hostinfo.logger(hm.l).WithField("relay", relay.String()).Info("Establish tunnel to relay target")
  246. hm.f.Handshake(relay)
  247. continue
  248. }
  249. // Check the relay HostInfo to see if we already established a relay through
  250. existingRelay, ok := relayHostInfo.relayState.QueryRelayForByIp(vpnIp)
  251. if !ok {
  252. // No relays exist or requested yet.
  253. if relayHostInfo.remote.IsValid() {
  254. idx, err := AddRelay(hm.l, relayHostInfo, hm.mainHostMap, vpnIp, nil, TerminalType, Requested)
  255. if err != nil {
  256. hostinfo.logger(hm.l).WithField("relay", relay.String()).WithError(err).Info("Failed to add relay to hostmap")
  257. }
  258. m := NebulaControl{
  259. Type: NebulaControl_CreateRelayRequest,
  260. InitiatorRelayIndex: idx,
  261. }
  262. relayFrom := hm.f.myVpnAddrs[0]
  263. switch relayHostInfo.GetCert().Certificate.Version() {
  264. case cert.Version1:
  265. if !hm.f.myVpnAddrs[0].Is4() {
  266. hostinfo.logger(hm.l).Error("can not establish v1 relay with a v6 network because the relay is not running a current nebula version")
  267. continue
  268. }
  269. if !vpnIp.Is4() {
  270. hostinfo.logger(hm.l).Error("can not establish v1 relay with a v6 remote network because the relay is not running a current nebula version")
  271. continue
  272. }
  273. b := hm.f.myVpnAddrs[0].As4()
  274. m.OldRelayFromAddr = binary.BigEndian.Uint32(b[:])
  275. b = vpnIp.As4()
  276. m.OldRelayToAddr = binary.BigEndian.Uint32(b[:])
  277. case cert.Version2:
  278. if vpnIp.Is4() {
  279. relayFrom = hm.f.myVpnAddrs[0]
  280. } else {
  281. //todo do this smarter
  282. relayFrom = hm.f.myVpnAddrs[len(hm.f.myVpnAddrs)-1]
  283. }
  284. m.RelayFromAddr = netAddrToProtoAddr(relayFrom)
  285. m.RelayToAddr = netAddrToProtoAddr(vpnIp)
  286. default:
  287. hostinfo.logger(hm.l).Error("Unknown certificate version found while creating relay")
  288. continue
  289. }
  290. msg, err := m.Marshal()
  291. if err != nil {
  292. hostinfo.logger(hm.l).
  293. WithError(err).
  294. Error("Failed to marshal Control message to create relay")
  295. } else {
  296. hm.f.SendMessageToHostInfo(header.Control, 0, relayHostInfo, msg, make([]byte, 12), make([]byte, mtu))
  297. hm.l.WithFields(logrus.Fields{
  298. "relayFrom": relayFrom,
  299. "relayTo": vpnIp,
  300. "initiatorRelayIndex": idx,
  301. "relay": relay}).
  302. Info("send CreateRelayRequest")
  303. }
  304. }
  305. continue
  306. }
  307. switch existingRelay.State {
  308. case Established:
  309. hostinfo.logger(hm.l).WithField("relay", relay.String()).Info("Send handshake via relay")
  310. hm.f.SendVia(relayHostInfo, existingRelay, hostinfo.HandshakePacket[0], make([]byte, 12), make([]byte, mtu), false)
  311. case Disestablished:
  312. // Mark this relay as 'requested'
  313. relayHostInfo.relayState.UpdateRelayForByIpState(vpnIp, Requested)
  314. fallthrough
  315. case Requested:
  316. hostinfo.logger(hm.l).WithField("relay", relay.String()).Info("Re-send CreateRelay request")
  317. // Re-send the CreateRelay request, in case the previous one was lost.
  318. m := NebulaControl{
  319. Type: NebulaControl_CreateRelayRequest,
  320. InitiatorRelayIndex: existingRelay.LocalIndex,
  321. }
  322. relayFrom := hm.f.myVpnAddrs[0]
  323. switch relayHostInfo.GetCert().Certificate.Version() {
  324. case cert.Version1:
  325. if !hm.f.myVpnAddrs[0].Is4() {
  326. hostinfo.logger(hm.l).Error("can not establish v1 relay with a v6 network because the relay is not running a current nebula version")
  327. continue
  328. }
  329. if !vpnIp.Is4() {
  330. hostinfo.logger(hm.l).Error("can not establish v1 relay with a v6 remote network because the relay is not running a current nebula version")
  331. continue
  332. }
  333. b := hm.f.myVpnAddrs[0].As4()
  334. m.OldRelayFromAddr = binary.BigEndian.Uint32(b[:])
  335. b = vpnIp.As4()
  336. m.OldRelayToAddr = binary.BigEndian.Uint32(b[:])
  337. case cert.Version2:
  338. if vpnIp.Is4() {
  339. relayFrom = hm.f.myVpnAddrs[0]
  340. } else {
  341. //todo do this smarter
  342. relayFrom = hm.f.myVpnAddrs[len(hm.f.myVpnAddrs)-1]
  343. }
  344. m.RelayFromAddr = netAddrToProtoAddr(relayFrom)
  345. m.RelayToAddr = netAddrToProtoAddr(vpnIp)
  346. default:
  347. hostinfo.logger(hm.l).Error("Unknown certificate version found while creating relay")
  348. continue
  349. }
  350. msg, err := m.Marshal()
  351. if err != nil {
  352. hostinfo.logger(hm.l).
  353. WithError(err).
  354. Error("Failed to marshal Control message to create relay")
  355. } else {
  356. // This must send over the hostinfo, not over hm.Hosts[ip]
  357. hm.f.SendMessageToHostInfo(header.Control, 0, relayHostInfo, msg, make([]byte, 12), make([]byte, mtu))
  358. hm.l.WithFields(logrus.Fields{
  359. "relayFrom": relayFrom,
  360. "relayTo": vpnIp,
  361. "initiatorRelayIndex": existingRelay.LocalIndex,
  362. "relay": relay}).
  363. Info("send CreateRelayRequest")
  364. }
  365. case PeerRequested:
  366. // PeerRequested only occurs in Forwarding relays, not Terminal relays, and this is a Terminal relay case.
  367. fallthrough
  368. default:
  369. hostinfo.logger(hm.l).
  370. WithField("vpnIp", vpnIp).
  371. WithField("state", existingRelay.State).
  372. WithField("relay", relay).
  373. Errorf("Relay unexpected state")
  374. }
  375. }
  376. }
  377. // If a lighthouse triggered this attempt then we are still in the timer wheel and do not need to re-add
  378. if !lighthouseTriggered {
  379. hm.OutboundHandshakeTimer.Add(vpnIp, hm.config.tryInterval*time.Duration(hh.counter))
  380. }
  381. }
  382. // GetOrHandshake will try to find a hostinfo with a fully formed tunnel or start a new handshake if one is not present
  383. // The 2nd argument will be true if the hostinfo is ready to transmit traffic
  384. func (hm *HandshakeManager) GetOrHandshake(vpnIp netip.Addr, cacheCb func(*HandshakeHostInfo)) (*HostInfo, bool) {
  385. hm.mainHostMap.RLock()
  386. h, ok := hm.mainHostMap.Hosts[vpnIp]
  387. hm.mainHostMap.RUnlock()
  388. if ok {
  389. // Do not attempt promotion if you are a lighthouse
  390. if !hm.lightHouse.amLighthouse {
  391. h.TryPromoteBest(hm.mainHostMap.GetPreferredRanges(), hm.f)
  392. }
  393. return h, true
  394. }
  395. return hm.StartHandshake(vpnIp, cacheCb), false
  396. }
  397. // StartHandshake will ensure a handshake is currently being attempted for the provided vpn ip
  398. func (hm *HandshakeManager) StartHandshake(vpnAddr netip.Addr, cacheCb func(*HandshakeHostInfo)) *HostInfo {
  399. hm.Lock()
  400. if hh, ok := hm.vpnIps[vpnAddr]; ok {
  401. // We are already trying to handshake with this vpn ip
  402. if cacheCb != nil {
  403. cacheCb(hh)
  404. }
  405. hm.Unlock()
  406. return hh.hostinfo
  407. }
  408. hostinfo := &HostInfo{
  409. vpnAddrs: []netip.Addr{vpnAddr},
  410. HandshakePacket: make(map[uint8][]byte, 0),
  411. relayState: RelayState{
  412. relays: nil,
  413. relayForByAddr: map[netip.Addr]*Relay{},
  414. relayForByIdx: map[uint32]*Relay{},
  415. },
  416. }
  417. hh := &HandshakeHostInfo{
  418. hostinfo: hostinfo,
  419. startTime: time.Now(),
  420. }
  421. hm.vpnIps[vpnAddr] = hh
  422. hm.metricInitiated.Inc(1)
  423. hm.OutboundHandshakeTimer.Add(vpnAddr, hm.config.tryInterval)
  424. if cacheCb != nil {
  425. cacheCb(hh)
  426. }
  427. // If this is a static host, we don't need to wait for the HostQueryReply
  428. // We can trigger the handshake right now
  429. _, doTrigger := hm.lightHouse.GetStaticHostList()[vpnAddr]
  430. if !doTrigger {
  431. // Add any calculated remotes, and trigger early handshake if one found
  432. doTrigger = hm.lightHouse.addCalculatedRemotes(vpnAddr)
  433. }
  434. if doTrigger {
  435. select {
  436. case hm.trigger <- vpnAddr:
  437. default:
  438. }
  439. }
  440. hm.Unlock()
  441. hm.lightHouse.QueryServer(vpnAddr)
  442. return hostinfo
  443. }
  444. var (
  445. ErrExistingHostInfo = errors.New("existing hostinfo")
  446. ErrAlreadySeen = errors.New("already seen")
  447. ErrLocalIndexCollision = errors.New("local index collision")
  448. )
  449. // CheckAndComplete checks for any conflicts in the main and pending hostmap
  450. // before adding hostinfo to main. If err is nil, it was added. Otherwise err will be:
  451. //
  452. // ErrAlreadySeen if we already have an entry in the hostmap that has seen the
  453. // exact same handshake packet
  454. //
  455. // ErrExistingHostInfo if we already have an entry in the hostmap for this
  456. // VpnIp and the new handshake was older than the one we currently have
  457. //
  458. // ErrLocalIndexCollision if we already have an entry in the main or pending
  459. // hostmap for the hostinfo.localIndexId.
  460. func (hm *HandshakeManager) CheckAndComplete(hostinfo *HostInfo, handshakePacket uint8, f *Interface) (*HostInfo, error) {
  461. hm.mainHostMap.Lock()
  462. defer hm.mainHostMap.Unlock()
  463. hm.Lock()
  464. defer hm.Unlock()
  465. // Check if we already have a tunnel with this vpn ip
  466. existingHostInfo, found := hm.mainHostMap.Hosts[hostinfo.vpnAddrs[0]]
  467. if found && existingHostInfo != nil {
  468. testHostInfo := existingHostInfo
  469. for testHostInfo != nil {
  470. // Is it just a delayed handshake packet?
  471. if bytes.Equal(hostinfo.HandshakePacket[handshakePacket], testHostInfo.HandshakePacket[handshakePacket]) {
  472. return testHostInfo, ErrAlreadySeen
  473. }
  474. testHostInfo = testHostInfo.next
  475. }
  476. // Is this a newer handshake?
  477. if existingHostInfo.lastHandshakeTime >= hostinfo.lastHandshakeTime && !existingHostInfo.ConnectionState.initiator {
  478. return existingHostInfo, ErrExistingHostInfo
  479. }
  480. existingHostInfo.logger(hm.l).Info("Taking new handshake")
  481. }
  482. existingIndex, found := hm.mainHostMap.Indexes[hostinfo.localIndexId]
  483. if found {
  484. // We have a collision, but for a different hostinfo
  485. return existingIndex, ErrLocalIndexCollision
  486. }
  487. existingPendingIndex, found := hm.indexes[hostinfo.localIndexId]
  488. if found && existingPendingIndex.hostinfo != hostinfo {
  489. // We have a collision, but for a different hostinfo
  490. return existingPendingIndex.hostinfo, ErrLocalIndexCollision
  491. }
  492. existingRemoteIndex, found := hm.mainHostMap.RemoteIndexes[hostinfo.remoteIndexId]
  493. if found && existingRemoteIndex != nil && existingRemoteIndex.vpnAddrs[0] != hostinfo.vpnAddrs[0] {
  494. // We have a collision, but this can happen since we can't control
  495. // the remote ID. Just log about the situation as a note.
  496. hostinfo.logger(hm.l).
  497. WithField("remoteIndex", hostinfo.remoteIndexId).WithField("collision", existingRemoteIndex.vpnAddrs).
  498. Info("New host shadows existing host remoteIndex")
  499. }
  500. hm.mainHostMap.unlockedAddHostInfo(hostinfo, f)
  501. return existingHostInfo, nil
  502. }
  503. // Complete is a simpler version of CheckAndComplete when we already know we
  504. // won't have a localIndexId collision because we already have an entry in the
  505. // pendingHostMap. An existing hostinfo is returned if there was one.
  506. func (hm *HandshakeManager) Complete(hostinfo *HostInfo, f *Interface) {
  507. hm.mainHostMap.Lock()
  508. defer hm.mainHostMap.Unlock()
  509. hm.Lock()
  510. defer hm.Unlock()
  511. existingRemoteIndex, found := hm.mainHostMap.RemoteIndexes[hostinfo.remoteIndexId]
  512. if found && existingRemoteIndex != nil {
  513. // We have a collision, but this can happen since we can't control
  514. // the remote ID. Just log about the situation as a note.
  515. hostinfo.logger(hm.l).
  516. WithField("remoteIndex", hostinfo.remoteIndexId).WithField("collision", existingRemoteIndex.vpnAddrs).
  517. Info("New host shadows existing host remoteIndex")
  518. }
  519. // We need to remove from the pending hostmap first to avoid undoing work when after to the main hostmap.
  520. hm.unlockedDeleteHostInfo(hostinfo)
  521. hm.mainHostMap.unlockedAddHostInfo(hostinfo, f)
  522. }
  523. // allocateIndex generates a unique localIndexId for this HostInfo
  524. // and adds it to the pendingHostMap. Will error if we are unable to generate
  525. // a unique localIndexId
  526. func (hm *HandshakeManager) allocateIndex(hh *HandshakeHostInfo) error {
  527. hm.mainHostMap.RLock()
  528. defer hm.mainHostMap.RUnlock()
  529. hm.Lock()
  530. defer hm.Unlock()
  531. for i := 0; i < 32; i++ {
  532. index, err := generateIndex(hm.l)
  533. if err != nil {
  534. return err
  535. }
  536. _, inPending := hm.indexes[index]
  537. _, inMain := hm.mainHostMap.Indexes[index]
  538. if !inMain && !inPending {
  539. hh.hostinfo.localIndexId = index
  540. hm.indexes[index] = hh
  541. return nil
  542. }
  543. }
  544. return errors.New("failed to generate unique localIndexId")
  545. }
  546. func (hm *HandshakeManager) DeleteHostInfo(hostinfo *HostInfo) {
  547. hm.Lock()
  548. defer hm.Unlock()
  549. hm.unlockedDeleteHostInfo(hostinfo)
  550. }
  551. func (hm *HandshakeManager) unlockedDeleteHostInfo(hostinfo *HostInfo) {
  552. for _, addr := range hostinfo.vpnAddrs {
  553. delete(hm.vpnIps, addr)
  554. }
  555. if len(hm.vpnIps) == 0 {
  556. hm.vpnIps = map[netip.Addr]*HandshakeHostInfo{}
  557. }
  558. delete(hm.indexes, hostinfo.localIndexId)
  559. if len(hm.indexes) == 0 {
  560. hm.indexes = map[uint32]*HandshakeHostInfo{}
  561. }
  562. if hm.l.Level >= logrus.DebugLevel {
  563. hm.l.WithField("hostMap", m{"mapTotalSize": len(hm.vpnIps),
  564. "vpnAddrs": hostinfo.vpnAddrs, "indexNumber": hostinfo.localIndexId, "remoteIndexNumber": hostinfo.remoteIndexId}).
  565. Debug("Pending hostmap hostInfo deleted")
  566. }
  567. }
  568. func (hm *HandshakeManager) QueryVpnAddr(vpnIp netip.Addr) *HostInfo {
  569. hh := hm.queryVpnIp(vpnIp)
  570. if hh != nil {
  571. return hh.hostinfo
  572. }
  573. return nil
  574. }
  575. func (hm *HandshakeManager) queryVpnIp(vpnIp netip.Addr) *HandshakeHostInfo {
  576. hm.RLock()
  577. defer hm.RUnlock()
  578. return hm.vpnIps[vpnIp]
  579. }
  580. func (hm *HandshakeManager) QueryIndex(index uint32) *HostInfo {
  581. hh := hm.queryIndex(index)
  582. if hh != nil {
  583. return hh.hostinfo
  584. }
  585. return nil
  586. }
  587. func (hm *HandshakeManager) queryIndex(index uint32) *HandshakeHostInfo {
  588. hm.RLock()
  589. defer hm.RUnlock()
  590. return hm.indexes[index]
  591. }
  592. func (hm *HandshakeManager) GetPreferredRanges() []netip.Prefix {
  593. return hm.mainHostMap.GetPreferredRanges()
  594. }
  595. func (hm *HandshakeManager) ForEachVpnAddr(f controlEach) {
  596. hm.RLock()
  597. defer hm.RUnlock()
  598. for _, v := range hm.vpnIps {
  599. f(v.hostinfo)
  600. }
  601. }
  602. func (hm *HandshakeManager) ForEachIndex(f controlEach) {
  603. hm.RLock()
  604. defer hm.RUnlock()
  605. for _, v := range hm.indexes {
  606. f(v.hostinfo)
  607. }
  608. }
  609. func (hm *HandshakeManager) EmitStats() {
  610. hm.RLock()
  611. hostLen := len(hm.vpnIps)
  612. indexLen := len(hm.indexes)
  613. hm.RUnlock()
  614. metrics.GetOrRegisterGauge("hostmap.pending.hosts", nil).Update(int64(hostLen))
  615. metrics.GetOrRegisterGauge("hostmap.pending.indexes", nil).Update(int64(indexLen))
  616. hm.mainHostMap.EmitStats()
  617. }
  618. // Utility functions below
  619. func generateIndex(l *logrus.Logger) (uint32, error) {
  620. b := make([]byte, 4)
  621. // Let zero mean we don't know the ID, so don't generate zero
  622. var index uint32
  623. for index == 0 {
  624. _, err := rand.Read(b)
  625. if err != nil {
  626. l.Errorln(err)
  627. return 0, err
  628. }
  629. index = binary.BigEndian.Uint32(b)
  630. }
  631. if l.Level >= logrus.DebugLevel {
  632. l.WithField("index", index).
  633. Debug("Generated index")
  634. }
  635. return index, nil
  636. }
  637. func hsTimeout(tries int64, interval time.Duration) time.Duration {
  638. return time.Duration(tries / 2 * ((2 * int64(interval)) + (tries-1)*int64(interval)))
  639. }