hostmap.go 30 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001
  1. package nebula
  2. import (
  3. "context"
  4. "encoding/json"
  5. "errors"
  6. "fmt"
  7. "log/slog"
  8. "net"
  9. "net/netip"
  10. "slices"
  11. "sync"
  12. "sync/atomic"
  13. "time"
  14. "github.com/gaissmai/bart"
  15. "github.com/rcrowley/go-metrics"
  16. "github.com/slackhq/nebula/cert"
  17. "github.com/slackhq/nebula/config"
  18. "github.com/slackhq/nebula/header"
  19. "github.com/slackhq/nebula/logging"
  20. )
  21. const defaultPromoteEvery = 1000 // Count of packets sent before we try moving a tunnel to a preferred underlay ip address
  22. const defaultReQueryEvery = 5000 // Count of packets sent before re-querying a hostinfo to the lighthouse
  23. const defaultReQueryWait = time.Minute // Minimum amount of seconds to wait before re-querying a hostinfo the lighthouse. Evaluated every ReQueryEvery
  24. const MaxRemotes = 10
  25. // MaxHostInfosPerVpnIp is the max number of hostinfos we will track for a given vpn ip
  26. // 5 allows for an initial handshake and each host pair re-handshaking twice
  27. const MaxHostInfosPerVpnIp = 5
  28. // How long we should prevent roaming back to the previous IP.
  29. // This helps prevent flapping due to packets already in flight
  30. const RoamingSuppressSeconds = 2
  31. const (
  32. Requested = iota
  33. PeerRequested
  34. Established
  35. Disestablished
  36. )
  37. const (
  38. Unknowntype = iota
  39. ForwardingType
  40. TerminalType
  41. )
  42. type Relay struct {
  43. Type int
  44. State int
  45. LocalIndex uint32
  46. RemoteIndex uint32
  47. PeerAddr netip.Addr
  48. }
  49. type HostMap struct {
  50. sync.RWMutex //Because we concurrently read and write to our maps
  51. Indexes map[uint32]*HostInfo
  52. Relays map[uint32]*HostInfo // Maps a Relay IDX to a Relay HostInfo object
  53. RemoteIndexes map[uint32]*HostInfo
  54. // Hosts maps a vpn address to its primary hostinfo, one entry per address we hold a tunnel
  55. // for. moreHosts only has an entry while an address is held by 2 or more hostinfos and stores
  56. // the full most-recent-first list; moreHosts[a][0] is always the same hostinfo as Hosts[a].
  57. // Each address gets its own independent list, so a hostinfo owning multiple addresses can
  58. // never corrupt another address's ordering the way the old shared next/prev chain could.
  59. // Entries in moreHosts are only ever written by unlockedSetHostsForAddr; Hosts is written
  60. // directly only in the single-hostinfo fast paths where moreHosts is known to have no entry,
  61. // and unlockedDeleteHostInfo swaps either map for a fresh one when it fully drains.
  62. Hosts map[netip.Addr]*HostInfo
  63. moreHosts map[netip.Addr][]*HostInfo
  64. preferredRanges atomic.Pointer[[]netip.Prefix]
  65. l *slog.Logger
  66. }
  67. // For synchronization, treat the pointed-to Relay struct as immutable. To edit the Relay
  68. // struct, make a copy of an existing value, edit the fileds in the copy, and
  69. // then store a pointer to the new copy in both realyForBy* maps.
  70. type RelayState struct {
  71. sync.RWMutex
  72. relays []netip.Addr // Ordered set of VpnAddrs of Hosts to use as relays to access this peer
  73. // For data race avoidance, the contents of a *Relay are treated immutably. To update a *Relay, copy the existing data,
  74. // modify what needs to be updated, and store the new modified copy in the relayForByIp and relayForByIdx maps (with
  75. // the RelayState Lock held)
  76. relayForByAddr map[netip.Addr]*Relay // Maps vpnAddr of peers for which this HostInfo is a relay to some Relay info
  77. relayForByIdx map[uint32]*Relay // Maps a local index to some Relay info
  78. }
  79. func (rs *RelayState) DeleteRelay(ip netip.Addr) {
  80. rs.Lock()
  81. defer rs.Unlock()
  82. for idx, val := range rs.relays {
  83. if val == ip {
  84. rs.relays = append(rs.relays[:idx], rs.relays[idx+1:]...)
  85. return
  86. }
  87. }
  88. }
  89. func (rs *RelayState) UpdateRelayForByIpState(vpnIp netip.Addr, state int) {
  90. rs.Lock()
  91. defer rs.Unlock()
  92. if r, ok := rs.relayForByAddr[vpnIp]; ok {
  93. newRelay := *r
  94. newRelay.State = state
  95. rs.relayForByAddr[newRelay.PeerAddr] = &newRelay
  96. rs.relayForByIdx[newRelay.LocalIndex] = &newRelay
  97. }
  98. }
  99. func (rs *RelayState) UpdateRelayForByIdxState(idx uint32, state int) {
  100. rs.Lock()
  101. defer rs.Unlock()
  102. if r, ok := rs.relayForByIdx[idx]; ok {
  103. newRelay := *r
  104. newRelay.State = state
  105. rs.relayForByAddr[newRelay.PeerAddr] = &newRelay
  106. rs.relayForByIdx[newRelay.LocalIndex] = &newRelay
  107. }
  108. }
  109. func (rs *RelayState) CopyAllRelayFor() []*Relay {
  110. rs.RLock()
  111. defer rs.RUnlock()
  112. ret := make([]*Relay, 0, len(rs.relayForByIdx))
  113. for _, r := range rs.relayForByIdx {
  114. ret = append(ret, r)
  115. }
  116. return ret
  117. }
  118. func (rs *RelayState) GetRelayForByAddr(addr netip.Addr) (*Relay, bool) {
  119. rs.RLock()
  120. defer rs.RUnlock()
  121. r, ok := rs.relayForByAddr[addr]
  122. return r, ok
  123. }
  124. func (rs *RelayState) InsertRelayTo(ip netip.Addr) {
  125. rs.Lock()
  126. defer rs.Unlock()
  127. if !slices.Contains(rs.relays, ip) {
  128. rs.relays = append(rs.relays, ip)
  129. }
  130. }
  131. func (rs *RelayState) CopyRelayIps() []netip.Addr {
  132. rs.RLock()
  133. defer rs.RUnlock()
  134. ret := make([]netip.Addr, len(rs.relays))
  135. copy(ret, rs.relays)
  136. return ret
  137. }
  138. func (rs *RelayState) CopyRelayForIps() []netip.Addr {
  139. rs.RLock()
  140. defer rs.RUnlock()
  141. currentRelays := make([]netip.Addr, 0, len(rs.relayForByAddr))
  142. for relayIp := range rs.relayForByAddr {
  143. currentRelays = append(currentRelays, relayIp)
  144. }
  145. return currentRelays
  146. }
  147. func (rs *RelayState) CopyRelayForIdxs() []uint32 {
  148. rs.RLock()
  149. defer rs.RUnlock()
  150. ret := make([]uint32, 0, len(rs.relayForByIdx))
  151. for i := range rs.relayForByIdx {
  152. ret = append(ret, i)
  153. }
  154. return ret
  155. }
  156. func (rs *RelayState) CompleteRelayByIP(vpnIp netip.Addr, remoteIdx uint32) bool {
  157. rs.Lock()
  158. defer rs.Unlock()
  159. r, ok := rs.relayForByAddr[vpnIp]
  160. if !ok {
  161. return false
  162. }
  163. newRelay := *r
  164. newRelay.State = Established
  165. newRelay.RemoteIndex = remoteIdx
  166. rs.relayForByIdx[r.LocalIndex] = &newRelay
  167. rs.relayForByAddr[r.PeerAddr] = &newRelay
  168. return true
  169. }
  170. func (rs *RelayState) CompleteRelayByIdx(localIdx uint32, remoteIdx uint32) (*Relay, bool) {
  171. rs.Lock()
  172. defer rs.Unlock()
  173. r, ok := rs.relayForByIdx[localIdx]
  174. if !ok {
  175. return nil, false
  176. }
  177. newRelay := *r
  178. newRelay.State = Established
  179. newRelay.RemoteIndex = remoteIdx
  180. rs.relayForByIdx[r.LocalIndex] = &newRelay
  181. rs.relayForByAddr[r.PeerAddr] = &newRelay
  182. return &newRelay, true
  183. }
  184. func (rs *RelayState) QueryRelayForByIp(vpnIp netip.Addr) (*Relay, bool) {
  185. rs.RLock()
  186. defer rs.RUnlock()
  187. r, ok := rs.relayForByAddr[vpnIp]
  188. return r, ok
  189. }
  190. func (rs *RelayState) QueryRelayForByIdx(idx uint32) (*Relay, bool) {
  191. rs.RLock()
  192. defer rs.RUnlock()
  193. r, ok := rs.relayForByIdx[idx]
  194. return r, ok
  195. }
  196. func (rs *RelayState) InsertRelay(ip netip.Addr, idx uint32, r *Relay) {
  197. rs.Lock()
  198. defer rs.Unlock()
  199. rs.relayForByAddr[ip] = r
  200. rs.relayForByIdx[idx] = r
  201. }
  202. type NetworkType uint8
  203. const (
  204. NetworkTypeUnknown NetworkType = iota
  205. // NetworkTypeVPN is a network that overlaps one or more of the vpnNetworks in our certificate
  206. NetworkTypeVPN
  207. // NetworkTypeVPNPeer is a network that does not overlap one of our networks
  208. NetworkTypeVPNPeer
  209. // NetworkTypeUnsafe is a network from Certificate.UnsafeNetworks()
  210. NetworkTypeUnsafe
  211. )
  212. type HostInfo struct {
  213. remote atomic.Pointer[netip.AddrPort]
  214. ConnectionState *ConnectionState
  215. // Traffic bits, pendingDeletion, and the rebind epoch we last sent under
  216. state atomic.Uint32
  217. promoteCounter atomic.Uint32
  218. remoteIndexId uint32
  219. localIndexId uint32
  220. remotes *RemoteList
  221. // vpnAddrs is a list of vpn addresses assigned to this host that are within our own vpn networks
  222. // The host may have other vpn addresses that are outside our
  223. // vpn networks but were removed because they are not usable
  224. vpnAddrs []netip.Addr
  225. // networks is a combination of specific vpn addresses (not prefixes!) and full unsafe networks assigned to this host.
  226. networks *bart.Table[NetworkType]
  227. relayState RelayState
  228. // HandshakePacket records the packets used to create this hostinfo
  229. // We need these to avoid replayed handshake packets creating new hostinfos which causes churn
  230. HandshakePacket map[uint8][]byte
  231. // nextLHQuery is the earliest we can ask the lighthouse for new information.
  232. // This is used to limit lighthouse re-queries in chatty clients
  233. nextLHQuery atomic.Int64
  234. // lastHandshakeTime records the time the remote side told us about at the stage when the handshake was completed locally
  235. // Stage 1 packet will contain it if I am a responder, stage 2 packet if I am an initiator
  236. // This is used to avoid an attack where a handshake packet is replayed after some time
  237. lastHandshakeTime uint64
  238. lastRoam time.Time
  239. lastRoamRemote netip.AddrPort
  240. // lastUsed tracks the last time ConnectionManager checked the tunnel and it was in use.
  241. // This value will be behind against actual tunnel utilization in the hot path.
  242. // This should only be used by the ConnectionManagers ticker routine.
  243. lastUsed time.Time
  244. // lanes holds this tunnel's multiport lane sessions. Allocated when the
  245. // handshake completes if both sides advertised multiport, nil otherwise.
  246. // Immutable once the hostinfo is published to the data plane.
  247. lanes *laneSet
  248. }
  249. type ViaSender struct {
  250. UdpAddr netip.AddrPort
  251. relayHI *HostInfo // relayHI is the host info object of the relay
  252. relay *Relay // relay contains the rest of the relay information, including the PeerIP of the host trying to communicate with us.
  253. IsRelayed bool // IsRelayed is true if the packet was sent through a relay
  254. // SockIdx is the local socket (Interface.writers index) the packet
  255. // arrived on. Replies that must originate from the same 4-tuple egress
  256. // f.writers[SockIdx].
  257. SockIdx int
  258. }
  259. func (v ViaSender) String() string {
  260. if v.IsRelayed {
  261. return fmt.Sprintf("%s (relayed)", v.UdpAddr)
  262. }
  263. return v.UdpAddr.String()
  264. }
  265. func (v ViaSender) MarshalJSON() ([]byte, error) {
  266. if v.IsRelayed {
  267. return json.Marshal(m{"relay": v.UdpAddr})
  268. }
  269. return json.Marshal(m{"direct": v.UdpAddr})
  270. }
  271. type cachedPacket struct {
  272. messageType header.MessageType
  273. messageSubType header.MessageSubType
  274. callback packetCallback
  275. packet []byte
  276. }
  277. type packetCallback func(t header.MessageType, st header.MessageSubType, h *HostInfo, p, nb, out []byte)
  278. type cachedPacketMetrics struct {
  279. sent metrics.Counter
  280. dropped metrics.Counter
  281. }
  282. func NewHostMapFromConfig(l *slog.Logger, c *config.C) *HostMap {
  283. hm := newHostMap(l)
  284. hm.reload(c, true)
  285. c.RegisterReloadCallback(func(c *config.C) {
  286. hm.reload(c, false)
  287. })
  288. l.Info("Main HostMap created", "preferredRanges", hm.GetPreferredRanges())
  289. return hm
  290. }
  291. func newHostMap(l *slog.Logger) *HostMap {
  292. return &HostMap{
  293. Indexes: map[uint32]*HostInfo{},
  294. Relays: map[uint32]*HostInfo{},
  295. RemoteIndexes: map[uint32]*HostInfo{},
  296. Hosts: map[netip.Addr]*HostInfo{},
  297. moreHosts: map[netip.Addr][]*HostInfo{},
  298. l: l,
  299. }
  300. }
  301. func (hm *HostMap) reload(c *config.C, initial bool) {
  302. if initial || c.HasChanged("preferred_ranges") {
  303. var preferredRanges []netip.Prefix
  304. rawPreferredRanges := c.GetStringSlice("preferred_ranges", []string{})
  305. for _, rawPreferredRange := range rawPreferredRanges {
  306. preferredRange, err := netip.ParsePrefix(rawPreferredRange)
  307. if err != nil {
  308. hm.l.Warn("Failed to parse preferred ranges, ignoring",
  309. "error", err,
  310. "range", rawPreferredRanges,
  311. )
  312. continue
  313. }
  314. preferredRanges = append(preferredRanges, preferredRange)
  315. }
  316. oldRanges := hm.preferredRanges.Swap(&preferredRanges)
  317. if !initial {
  318. hm.l.Info("preferred_ranges changed",
  319. "oldPreferredRanges", *oldRanges,
  320. "newPreferredRanges", preferredRanges,
  321. )
  322. }
  323. }
  324. }
  325. // EmitStats reports host, index, and relay counts to the stats collection system
  326. func (hm *HostMap) EmitStats() {
  327. hm.RLock()
  328. hostLen := len(hm.Hosts)
  329. indexLen := len(hm.Indexes)
  330. remoteIndexLen := len(hm.RemoteIndexes)
  331. relaysLen := len(hm.Relays)
  332. hm.RUnlock()
  333. metrics.GetOrRegisterGauge("hostmap.main.hosts", nil).Update(int64(hostLen))
  334. metrics.GetOrRegisterGauge("hostmap.main.indexes", nil).Update(int64(indexLen))
  335. metrics.GetOrRegisterGauge("hostmap.main.remoteIndexes", nil).Update(int64(remoteIndexLen))
  336. metrics.GetOrRegisterGauge("hostmap.main.relayIndexes", nil).Update(int64(relaysLen))
  337. }
  338. // unlockedSetHostsForAddr stores the per-address hostinfo list (list[0] is the primary). An empty
  339. // list removes the address. This is the one place Hosts and moreHosts are written together, keep
  340. // it that way. Callers must hold the write lock.
  341. func (hm *HostMap) unlockedSetHostsForAddr(addr netip.Addr, list []*HostInfo) {
  342. if len(list) == 0 {
  343. delete(hm.Hosts, addr)
  344. delete(hm.moreHosts, addr)
  345. return
  346. }
  347. hm.Hosts[addr] = list[0]
  348. if len(list) > 1 {
  349. hm.moreHosts[addr] = list
  350. } else {
  351. delete(hm.moreHosts, addr)
  352. }
  353. }
  354. // unlockedGetHostList returns every hostinfo holding addr, primary first, or nil if we have no
  355. // tunnel for addr. The common single-hostinfo case builds a fresh one element list, so keep this
  356. // off the packet hot path; the primary is a direct Hosts read. Callers must hold the lock (read
  357. // or write).
  358. func (hm *HostMap) unlockedGetHostList(addr netip.Addr) []*HostInfo {
  359. if list, ok := hm.moreHosts[addr]; ok {
  360. return list
  361. }
  362. if h, ok := hm.Hosts[addr]; ok {
  363. return []*HostInfo{h}
  364. }
  365. return nil
  366. }
  367. // removeHostInfo returns list with hi removed (order preserved), or list unchanged if hi is
  368. // absent. It deletes in place: every mutator holds the hostmap write lock and no reader ever
  369. // retains a slice across a mutation (readers iterate under RLock), so there is no snapshot to
  370. // invalidate.
  371. func removeHostInfo(list []*HostInfo, hi *HostInfo) []*HostInfo {
  372. idx := slices.Index(list, hi)
  373. if idx < 0 {
  374. return list
  375. }
  376. return slices.Delete(list, idx, idx+1)
  377. }
  378. // DeleteHostInfo will fully unlink the hostinfo and return true if no other hostinfo still holds
  379. // any of its vpn addrs, meaning we no longer have a tunnel to the peer
  380. func (hm *HostMap) DeleteHostInfo(hostinfo *HostInfo) bool {
  381. // Delete the host itself, ensuring it's not modified anymore
  382. hm.Lock()
  383. final := hm.unlockedDeleteHostInfo(hostinfo)
  384. hm.Unlock()
  385. return final
  386. }
  387. func (hm *HostMap) MakePrimary(hostinfo *HostInfo) {
  388. hm.Lock()
  389. defer hm.Unlock()
  390. hm.unlockedMakePrimary(hostinfo)
  391. }
  392. // unlockedMakePrimary reports whether hostinfo is (now) the primary for each of its addresses,
  393. // false only when it is no longer in the hostmap at all.
  394. func (hm *HostMap) unlockedMakePrimary(hostinfo *HostInfo) bool {
  395. // A hostinfo that is no longer in the hostmap must not be re-inserted here. Callers can race
  396. // tunnel teardown, deciding to promote under the read lock and only taking the write lock
  397. // after a delete fully unlinked the hostinfo (connection manager swapPrimary, AddRelay). Every
  398. // live hostinfo is registered in Indexes by unlockedAddHostInfo, so this is a membership test.
  399. if hm.Indexes[hostinfo.localIndexId] != hostinfo {
  400. return false
  401. }
  402. // Move hostinfo to the front (primary) of each of its address lists. The lists are
  403. // independent per address, so this can never leave a dangling entry the way promoting
  404. // against a single shared chain could.
  405. for _, addr := range hostinfo.vpnAddrs {
  406. if hm.Hosts[addr] == hostinfo {
  407. // Already primary for this address, the list is already in the right order
  408. continue
  409. }
  410. list := removeHostInfo(hm.unlockedGetHostList(addr), hostinfo)
  411. list = append([]*HostInfo{hostinfo}, list...)
  412. hm.unlockedSetHostsForAddr(addr, list)
  413. }
  414. return true
  415. }
  416. // unlockedDeleteHostInfo removes hostinfo from every one of its address lists and from the index
  417. // maps. It returns true if this was the last hostinfo for all of its addresses (we no longer have
  418. // any tunnel to the peer), which the caller uses to decide whether to clear learned lighthouse
  419. // state and disestablish relays.
  420. func (hm *HostMap) unlockedDeleteHostInfo(hostinfo *HostInfo) bool {
  421. // Lane sessions hang off this hostinfo, so deleting it takes them with it
  422. // and there is nothing extra to unwind here.
  423. // Remove this hostinfo from each of its address lists. The lists are independent, so a
  424. // sibling is never promoted to an address it does not own and no other list is touched.
  425. final := true
  426. for _, addr := range hostinfo.vpnAddrs {
  427. if list, ok := hm.moreHosts[addr]; ok {
  428. list = removeHostInfo(list, hostinfo)
  429. hm.unlockedSetHostsForAddr(addr, list)
  430. if len(list) > 0 {
  431. final = false
  432. }
  433. } else if existing, ok := hm.Hosts[addr]; ok {
  434. if existing == hostinfo {
  435. // Common case, the only hostinfo for this address. moreHosts has no entry to clean up.
  436. delete(hm.Hosts, addr)
  437. } else {
  438. // We don't hold this address but another hostinfo does, we still have a tunnel to the peer
  439. final = false
  440. }
  441. }
  442. }
  443. // Go maps never shrink their buckets, replace fully drained maps so a node that churned
  444. // through a large peer count gives the memory back. Same idiom as the index maps below.
  445. if len(hm.Hosts) == 0 {
  446. hm.Hosts = map[netip.Addr]*HostInfo{}
  447. }
  448. if len(hm.moreHosts) == 0 {
  449. hm.moreHosts = map[netip.Addr][]*HostInfo{}
  450. }
  451. // The remote index uses index ids outside our control so lets make sure we are only removing
  452. // the remote index pointer here if it points to the hostinfo we are deleting
  453. hostinfo2, ok := hm.RemoteIndexes[hostinfo.remoteIndexId]
  454. if ok && hostinfo2 == hostinfo {
  455. delete(hm.RemoteIndexes, hostinfo.remoteIndexId)
  456. if len(hm.RemoteIndexes) == 0 {
  457. hm.RemoteIndexes = map[uint32]*HostInfo{}
  458. }
  459. }
  460. delete(hm.Indexes, hostinfo.localIndexId)
  461. if len(hm.Indexes) == 0 {
  462. hm.Indexes = map[uint32]*HostInfo{}
  463. }
  464. if hm.l.Enabled(context.Background(), slog.LevelDebug) {
  465. hm.l.Debug("Hostmap hostInfo deleted",
  466. "hostMap", m{"mapTotalSize": len(hm.Hosts),
  467. "vpnAddrs": hostinfo.vpnAddrs, "indexNumber": hostinfo.localIndexId, "remoteIndexNumber": hostinfo.remoteIndexId},
  468. )
  469. }
  470. if final {
  471. // I have lost connectivity to my peers. My relay tunnel is likely broken. Mark the next
  472. // hops as 'Requested' so that new relay tunnels are created in the future.
  473. hm.unlockedDisestablishVpnAddrRelayFor(hostinfo)
  474. }
  475. // Clean up any local relay indexes for which I am acting as a relay hop
  476. for _, localRelayIdx := range hostinfo.relayState.CopyRelayForIdxs() {
  477. delete(hm.Relays, localRelayIdx)
  478. }
  479. return final
  480. }
  481. func (hm *HostMap) QueryIndexCached(index uint32, cache map[uint32]*HostInfo) *HostInfo {
  482. if out, ok := cache[index]; ok {
  483. return out
  484. }
  485. out := hm.QueryIndex(index)
  486. if out != nil {
  487. cache[index] = out
  488. }
  489. return out
  490. }
  491. func (hm *HostMap) QueryIndex(index uint32) *HostInfo {
  492. hm.RLock()
  493. if h, ok := hm.Indexes[index]; ok {
  494. hm.RUnlock()
  495. return h
  496. } else {
  497. hm.RUnlock()
  498. return nil
  499. }
  500. }
  501. func (hm *HostMap) QueryRelayIndex(index uint32) *HostInfo {
  502. hm.RLock()
  503. if h, ok := hm.Relays[index]; ok {
  504. hm.RUnlock()
  505. return h
  506. } else {
  507. hm.RUnlock()
  508. return nil
  509. }
  510. }
  511. func (hm *HostMap) QueryReverseIndex(index uint32) *HostInfo {
  512. hm.RLock()
  513. if h, ok := hm.RemoteIndexes[index]; ok {
  514. hm.RUnlock()
  515. return h
  516. } else {
  517. hm.RUnlock()
  518. return nil
  519. }
  520. }
  521. func (hm *HostMap) QueryVpnAddr(vpnIp netip.Addr) *HostInfo {
  522. return hm.queryVpnAddr(vpnIp, nil)
  523. }
  524. func (hm *HostMap) QueryVpnAddrsRelayFor(targetIps []netip.Addr, relayHostIp netip.Addr) (*HostInfo, *Relay, error) {
  525. hm.RLock()
  526. defer hm.RUnlock()
  527. // This runs per relayed packet, so check the primary with a single map probe and only consult
  528. // moreHosts when the primary can't relay for us.
  529. h, ok := hm.Hosts[relayHostIp]
  530. if !ok {
  531. return nil, nil, errors.New("unable to find host")
  532. }
  533. for _, targetIp := range targetIps {
  534. r, ok := h.relayState.QueryRelayForByIp(targetIp)
  535. if ok && r.State == Established {
  536. return h, r, nil
  537. }
  538. }
  539. if list, ok := hm.moreHosts[relayHostIp]; ok {
  540. // list[0] is the primary we already checked
  541. for _, h := range list[1:] {
  542. for _, targetIp := range targetIps {
  543. r, ok := h.relayState.QueryRelayForByIp(targetIp)
  544. if ok && r.State == Established {
  545. return h, r, nil
  546. }
  547. }
  548. }
  549. }
  550. return nil, nil, errors.New("unable to find host with relay")
  551. }
  552. func (hm *HostMap) unlockedDisestablishVpnAddrRelayFor(hi *HostInfo) {
  553. for _, relayHostIp := range hi.relayState.CopyRelayIps() {
  554. for _, h := range hm.unlockedGetHostList(relayHostIp) {
  555. h.relayState.UpdateRelayForByIpState(hi.vpnAddrs[0], Disestablished)
  556. }
  557. }
  558. for _, rs := range hi.relayState.CopyAllRelayFor() {
  559. if rs.Type == ForwardingType {
  560. for _, h := range hm.unlockedGetHostList(rs.PeerAddr) {
  561. h.relayState.UpdateRelayForByIpState(hi.vpnAddrs[0], Disestablished)
  562. }
  563. }
  564. }
  565. }
  566. func (hm *HostMap) queryVpnAddr(vpnIp netip.Addr, promoteIfce *Interface) *HostInfo {
  567. hm.RLock()
  568. if h, ok := hm.Hosts[vpnIp]; ok {
  569. hm.RUnlock()
  570. // Do not attempt promotion if you are a lighthouse
  571. if promoteIfce != nil && !promoteIfce.lightHouse.amLighthouse {
  572. h.TryPromoteBest(hm.GetPreferredRanges(), promoteIfce)
  573. }
  574. return h
  575. }
  576. hm.RUnlock()
  577. return nil
  578. }
  579. // unlockedAddHostInfo assumes you have a write-lock and will add a hostinfo object to the hostmap Indexes and RemoteIndexes maps.
  580. // If an entry exists for the Hosts table (vpnIp -> hostinfo) then the provided hostinfo will be made primary
  581. func (hm *HostMap) unlockedAddHostInfo(hostinfo *HostInfo, f *Interface) {
  582. if f.dnsServer != nil {
  583. remoteCert := hostinfo.ConnectionState.peerCert
  584. f.dnsServer.Add(remoteCert.Certificate.Name()+".", hostinfo.vpnAddrs)
  585. }
  586. for _, addr := range hostinfo.vpnAddrs {
  587. hm.unlockedInnerAddHostInfo(addr, hostinfo, f)
  588. }
  589. hm.Indexes[hostinfo.localIndexId] = hostinfo
  590. hm.RemoteIndexes[hostinfo.remoteIndexId] = hostinfo
  591. hostinfo.markOut(f.rebindEpoch.Load())
  592. if f.connectionManager != nil { // f.connectionManager is only nil in some unit tests
  593. f.connectionManager.trafficTimer.Add(hostinfo.localIndexId, f.connectionManager.checkInterval)
  594. }
  595. if hm.l.Enabled(context.Background(), slog.LevelDebug) {
  596. hm.l.Debug("Hostmap vpnIp added",
  597. "hostMap", m{"vpnAddrs": hostinfo.vpnAddrs, "mapTotalSize": len(hm.Hosts),
  598. "hostinfo": m{"existing": true, "localIndexId": hostinfo.localIndexId, "vpnAddrs": hostinfo.vpnAddrs}},
  599. )
  600. }
  601. }
  602. func (hm *HostMap) unlockedInnerAddHostInfo(vpnAddr netip.Addr, hostinfo *HostInfo, f *Interface) {
  603. existing, ok := hm.Hosts[vpnAddr]
  604. if !ok {
  605. // Common case, the first hostinfo for this address. moreHosts stays empty.
  606. hm.Hosts[vpnAddr] = hostinfo
  607. return
  608. }
  609. // The new hostinfo becomes the primary for this address. Remove any stale copy of it first so
  610. // we never hold a duplicate, then prepend.
  611. list, ok := hm.moreHosts[vpnAddr]
  612. if !ok {
  613. list = []*HostInfo{existing}
  614. }
  615. list = removeHostInfo(list, hostinfo)
  616. list = append([]*HostInfo{hostinfo}, list...)
  617. hm.unlockedSetHostsForAddr(vpnAddr, list)
  618. // Enforce the per-address cap by fully retiring the oldest hostinfo once we exceed it.
  619. // Deleting it removes it from all of its addresses and the index maps, matching prior behavior.
  620. if len(list) > MaxHostInfosPerVpnIp {
  621. hm.unlockedDeleteHostInfo(list[len(list)-1])
  622. }
  623. }
  624. func (hm *HostMap) GetPreferredRanges() []netip.Prefix {
  625. //NOTE: if preferredRanges is ever not stored before a load this will fail to dereference a nil pointer
  626. return *hm.preferredRanges.Load()
  627. }
  628. func (hm *HostMap) ForEachVpnAddr(f controlEach) {
  629. hm.RLock()
  630. defer hm.RUnlock()
  631. for _, v := range hm.Hosts {
  632. f(v)
  633. }
  634. }
  635. func (hm *HostMap) ForEachIndex(f controlEach) {
  636. hm.RLock()
  637. defer hm.RUnlock()
  638. for _, v := range hm.Indexes {
  639. f(v)
  640. }
  641. }
  642. // TryPromoteBest handles re-querying lighthouses and probing for better paths
  643. // NOTE: It is an error to call this if you are a lighthouse since they should not roam clients!
  644. func (i *HostInfo) TryPromoteBest(preferredRanges []netip.Prefix, ifce *Interface) {
  645. c := i.promoteCounter.Add(1)
  646. if c%ifce.tryPromoteEvery.Load() == 0 {
  647. remote := i.GetRemote()
  648. // return early if we are already on a preferred remote
  649. if remote.IsValid() {
  650. rIP := remote.Addr()
  651. for _, l := range preferredRanges {
  652. if l.Contains(rIP) {
  653. return
  654. }
  655. }
  656. }
  657. i.remotes.ForEach(preferredRanges, func(addr netip.AddrPort, preferred bool) {
  658. if remote.IsValid() && (!addr.IsValid() || !preferred) {
  659. return
  660. }
  661. // Try to send a test packet to that host, this should
  662. // cause it to detect a roaming event and switch remotes
  663. ifce.sendTo(header.Test, header.TestRequest, i.ConnectionState, i, addr, []byte(""), make([]byte, 12, 12), make([]byte, mtu))
  664. })
  665. }
  666. // Re query our lighthouses for new remotes occasionally
  667. if c%ifce.reQueryEvery.Load() == 0 && ifce.lightHouse != nil {
  668. now := time.Now().UnixNano()
  669. if now < i.nextLHQuery.Load() {
  670. return
  671. }
  672. i.nextLHQuery.Store(now + ifce.reQueryWait.Load())
  673. ifce.lightHouse.QueryServer(i.vpnAddrs[0])
  674. }
  675. }
  676. // Bits within HostInfo.state, everything above stateEpochShift is the epoch
  677. const (
  678. stateIn uint32 = 1 << iota
  679. stateOut
  680. statePendingDeletion
  681. stateFlags = stateIn | stateOut | statePendingDeletion
  682. // The epoch is the top 29 bits, it would take 2^29 rebinds to wrap and we will never get there
  683. stateEpochShift = 3
  684. )
  685. // markIn records inbound traffic
  686. func (i *HostInfo) markIn() {
  687. if i.state.Load()&stateIn == 0 {
  688. i.state.Or(stateIn)
  689. }
  690. }
  691. // markOut records a send and reports whether the epoch moved, meaning we want a punch from the far side
  692. func (i *HostInfo) markOut(epoch uint32) bool {
  693. e := epoch << stateEpochShift
  694. for {
  695. old := i.state.Load()
  696. if old&stateOut != 0 && old&^stateFlags == e {
  697. return false
  698. }
  699. if i.state.CompareAndSwap(old, old&stateFlags|stateOut|e) {
  700. return old&^stateFlags != e
  701. }
  702. }
  703. }
  704. // markOutOnly records a send without consuming the rebind epoch, for paths that cannot act on a requery
  705. func (i *HostInfo) markOutOnly() {
  706. if i.state.Load()&stateOut == 0 {
  707. i.state.Or(stateOut)
  708. }
  709. }
  710. // takeTraffic clears both traffic bits, leaving the epoch alone, and reports what they were
  711. func (i *HostInfo) takeTraffic() (in bool, out bool) {
  712. old := i.state.And(^(stateIn | stateOut))
  713. return old&stateIn != 0, old&stateOut != 0
  714. }
  715. func (i *HostInfo) setPendingDeletion(v bool) {
  716. if v {
  717. i.state.Or(statePendingDeletion)
  718. } else {
  719. i.state.And(^statePendingDeletion)
  720. }
  721. }
  722. func (i *HostInfo) isPendingDeletion() bool {
  723. return i.state.Load()&statePendingDeletion != 0
  724. }
  725. func (i *HostInfo) GetCert() *cert.CachedCertificate {
  726. if i.ConnectionState != nil {
  727. return i.ConnectionState.peerCert
  728. }
  729. return nil
  730. }
  731. func (i *HostInfo) GetRemote() netip.AddrPort {
  732. if p := i.remote.Load(); p != nil {
  733. return *p
  734. }
  735. return netip.AddrPort{}
  736. }
  737. // TODO: Maybe use ViaSender here?
  738. func (i *HostInfo) SetRemote(remote netip.AddrPort) {
  739. // We copy here because we likely got this remote from a source that reuses the object
  740. if i.GetRemote() != remote {
  741. i.remote.Store(&remote)
  742. i.remotes.LearnRemote(i.vpnAddrs[0], remote)
  743. }
  744. }
  745. // SetRemoteIfPreferred returns true if the remote was changed. The lastRoam
  746. // time on the HostInfo will also be updated.
  747. func (i *HostInfo) SetRemoteIfPreferred(hm *HostMap, via ViaSender) bool {
  748. if via.IsRelayed {
  749. return false
  750. }
  751. currentRemote := i.GetRemote()
  752. if !currentRemote.IsValid() {
  753. i.SetRemote(via.UdpAddr)
  754. return true
  755. }
  756. // NOTE: We do this loop here instead of calling `isPreferred` in
  757. // remote_list.go so that we only have to loop over preferredRanges once.
  758. newIsPreferred := false
  759. for _, l := range hm.GetPreferredRanges() {
  760. // return early if we are already on a preferred remote
  761. if l.Contains(currentRemote.Addr()) {
  762. return false
  763. }
  764. if l.Contains(via.UdpAddr.Addr()) {
  765. newIsPreferred = true
  766. }
  767. }
  768. if newIsPreferred {
  769. // Consider this a roaming event
  770. i.lastRoam = time.Now()
  771. i.lastRoamRemote = currentRemote
  772. i.SetRemote(via.UdpAddr)
  773. return true
  774. }
  775. return false
  776. }
  777. // buildNetworks fills in the networks field of HostInfo. It accepts a cert.Certificate so you never ever mix the network types up.
  778. func (i *HostInfo) buildNetworks(myVpnNetworksTable *bart.Lite, c cert.Certificate) {
  779. if len(c.Networks()) == 1 && len(c.UnsafeNetworks()) == 0 {
  780. if myVpnNetworksTable.Contains(c.Networks()[0].Addr()) {
  781. return // Simple case, no BART needed
  782. }
  783. }
  784. i.networks = new(bart.Table[NetworkType])
  785. for _, network := range c.Networks() {
  786. nprefix := netip.PrefixFrom(network.Addr(), network.Addr().BitLen())
  787. if myVpnNetworksTable.Contains(network.Addr()) {
  788. i.networks.Insert(nprefix, NetworkTypeVPN)
  789. } else {
  790. i.networks.Insert(nprefix, NetworkTypeVPNPeer)
  791. }
  792. }
  793. for _, network := range c.UnsafeNetworks() {
  794. i.networks.Insert(network, NetworkTypeUnsafe)
  795. }
  796. }
  797. // logger returns a derived slog.Logger with per-hostinfo fields pre-bound.
  798. func (i *HostInfo) logger(l *slog.Logger) *slog.Logger {
  799. if i == nil {
  800. return l
  801. }
  802. li := l.With(
  803. "vpnAddrs", i.vpnAddrs,
  804. "localIndex", i.localIndexId,
  805. "remoteIndex", i.remoteIndexId,
  806. )
  807. if connState := i.ConnectionState; connState != nil {
  808. if peerCert := connState.peerCert; peerCert != nil {
  809. li = li.With("certName", peerCert.Certificate.Name())
  810. }
  811. }
  812. return li
  813. }
  814. // Utility functions
  815. func localAddrs(l *slog.Logger, allowList *LocalAllowList) []netip.Addr {
  816. //FIXME: This function is pretty garbage
  817. var finalAddrs []netip.Addr
  818. ifaces, _ := net.Interfaces()
  819. for _, i := range ifaces {
  820. allow := allowList.AllowName(i.Name)
  821. if l.Enabled(context.Background(), logging.LevelTrace) {
  822. l.Log(context.Background(), logging.LevelTrace, "localAllowList.AllowName",
  823. "interfaceName", i.Name,
  824. "allow", allow,
  825. )
  826. }
  827. if !allow {
  828. continue
  829. }
  830. addrs, _ := i.Addrs()
  831. for _, rawAddr := range addrs {
  832. var addr netip.Addr
  833. switch v := rawAddr.(type) {
  834. case *net.IPNet:
  835. //continue
  836. addr, _ = netip.AddrFromSlice(v.IP)
  837. case *net.IPAddr:
  838. addr, _ = netip.AddrFromSlice(v.IP)
  839. }
  840. if !addr.IsValid() {
  841. if l.Enabled(context.Background(), slog.LevelDebug) {
  842. l.Debug("addr was invalid", "localAddr", rawAddr)
  843. }
  844. continue
  845. }
  846. addr = addr.Unmap()
  847. if addr.IsLoopback() == false && addr.IsLinkLocalUnicast() == false {
  848. isAllowed := allowList.Allow(addr)
  849. if l.Enabled(context.Background(), logging.LevelTrace) {
  850. l.Log(context.Background(), logging.LevelTrace, "localAllowList.Allow",
  851. "localAddr", addr,
  852. "allowed", isAllowed,
  853. )
  854. }
  855. if !isAllowed {
  856. continue
  857. }
  858. finalAddrs = append(finalAddrs, addr)
  859. }
  860. }
  861. }
  862. return finalAddrs
  863. }