handshake_manager.go 25 KB

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