hostmap.go 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924
  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. remotes *RemoteList
  215. promoteCounter atomic.Uint32
  216. ConnectionState *ConnectionState
  217. remoteIndexId uint32
  218. localIndexId uint32
  219. // vpnAddrs is a list of vpn addresses assigned to this host that are within our own vpn networks
  220. // The host may have other vpn addresses that are outside our
  221. // vpn networks but were removed because they are not usable
  222. vpnAddrs []netip.Addr
  223. // networks is a combination of specific vpn addresses (not prefixes!) and full unsafe networks assigned to this host.
  224. networks *bart.Table[NetworkType]
  225. relayState RelayState
  226. // HandshakePacket records the packets used to create this hostinfo
  227. // We need these to avoid replayed handshake packets creating new hostinfos which causes churn
  228. HandshakePacket map[uint8][]byte
  229. // nextLHQuery is the earliest we can ask the lighthouse for new information.
  230. // This is used to limit lighthouse re-queries in chatty clients
  231. nextLHQuery atomic.Int64
  232. // lastRebindCount is the other side of Interface.rebindCount, if these values don't match then we need to ask LH
  233. // for a punch from the remote end of this tunnel. The goal being to prime their conntrack for our traffic just like
  234. // with a handshake
  235. lastRebindCount int8
  236. // lastHandshakeTime records the time the remote side told us about at the stage when the handshake was completed locally
  237. // Stage 1 packet will contain it if I am a responder, stage 2 packet if I am an initiator
  238. // This is used to avoid an attack where a handshake packet is replayed after some time
  239. lastHandshakeTime uint64
  240. lastRoam time.Time
  241. lastRoamRemote netip.AddrPort
  242. //TODO: in, out, and others might benefit from being an atomic.Int32. We could collapse connectionManager pendingDeletion, relayUsed, and in/out into this 1 thing
  243. in, out, pendingDeletion atomic.Bool
  244. // lastUsed tracks the last time ConnectionManager checked the tunnel and it was in use.
  245. // This value will be behind against actual tunnel utilization in the hot path.
  246. // This should only be used by the ConnectionManagers ticker routine.
  247. lastUsed time.Time
  248. }
  249. type ViaSender struct {
  250. UdpAddr netip.AddrPort
  251. relayHI *HostInfo // relayHI is the host info object of the relay
  252. remoteIdx uint32 // remoteIdx is the index included in the header of the received packet
  253. relay *Relay // relay contains the rest of the relay information, including the PeerIP of the host trying to communicate with us.
  254. IsRelayed bool // IsRelayed is true if the packet was sent through a relay
  255. }
  256. func (v ViaSender) String() string {
  257. if v.IsRelayed {
  258. return fmt.Sprintf("%s (relayed)", v.UdpAddr)
  259. }
  260. return v.UdpAddr.String()
  261. }
  262. func (v ViaSender) MarshalJSON() ([]byte, error) {
  263. if v.IsRelayed {
  264. return json.Marshal(m{"relay": v.UdpAddr})
  265. }
  266. return json.Marshal(m{"direct": v.UdpAddr})
  267. }
  268. type cachedPacket struct {
  269. messageType header.MessageType
  270. messageSubType header.MessageSubType
  271. callback packetCallback
  272. packet []byte
  273. }
  274. type packetCallback func(t header.MessageType, st header.MessageSubType, h *HostInfo, p, nb, out []byte)
  275. type cachedPacketMetrics struct {
  276. sent metrics.Counter
  277. dropped metrics.Counter
  278. }
  279. func NewHostMapFromConfig(l *slog.Logger, c *config.C) *HostMap {
  280. hm := newHostMap(l)
  281. hm.reload(c, true)
  282. c.RegisterReloadCallback(func(c *config.C) {
  283. hm.reload(c, false)
  284. })
  285. l.Info("Main HostMap created", "preferredRanges", hm.GetPreferredRanges())
  286. return hm
  287. }
  288. func newHostMap(l *slog.Logger) *HostMap {
  289. return &HostMap{
  290. Indexes: map[uint32]*HostInfo{},
  291. Relays: map[uint32]*HostInfo{},
  292. RemoteIndexes: map[uint32]*HostInfo{},
  293. Hosts: map[netip.Addr]*HostInfo{},
  294. moreHosts: map[netip.Addr][]*HostInfo{},
  295. l: l,
  296. }
  297. }
  298. func (hm *HostMap) reload(c *config.C, initial bool) {
  299. if initial || c.HasChanged("preferred_ranges") {
  300. var preferredRanges []netip.Prefix
  301. rawPreferredRanges := c.GetStringSlice("preferred_ranges", []string{})
  302. for _, rawPreferredRange := range rawPreferredRanges {
  303. preferredRange, err := netip.ParsePrefix(rawPreferredRange)
  304. if err != nil {
  305. hm.l.Warn("Failed to parse preferred ranges, ignoring",
  306. "error", err,
  307. "range", rawPreferredRanges,
  308. )
  309. continue
  310. }
  311. preferredRanges = append(preferredRanges, preferredRange)
  312. }
  313. oldRanges := hm.preferredRanges.Swap(&preferredRanges)
  314. if !initial {
  315. hm.l.Info("preferred_ranges changed",
  316. "oldPreferredRanges", *oldRanges,
  317. "newPreferredRanges", preferredRanges,
  318. )
  319. }
  320. }
  321. }
  322. // EmitStats reports host, index, and relay counts to the stats collection system
  323. func (hm *HostMap) EmitStats() {
  324. hm.RLock()
  325. hostLen := len(hm.Hosts)
  326. indexLen := len(hm.Indexes)
  327. remoteIndexLen := len(hm.RemoteIndexes)
  328. relaysLen := len(hm.Relays)
  329. hm.RUnlock()
  330. metrics.GetOrRegisterGauge("hostmap.main.hosts", nil).Update(int64(hostLen))
  331. metrics.GetOrRegisterGauge("hostmap.main.indexes", nil).Update(int64(indexLen))
  332. metrics.GetOrRegisterGauge("hostmap.main.remoteIndexes", nil).Update(int64(remoteIndexLen))
  333. metrics.GetOrRegisterGauge("hostmap.main.relayIndexes", nil).Update(int64(relaysLen))
  334. }
  335. // unlockedSetHostsForAddr stores the per-address hostinfo list (list[0] is the primary). An empty
  336. // list removes the address. This is the one place Hosts and moreHosts are written together, keep
  337. // it that way. Callers must hold the write lock.
  338. func (hm *HostMap) unlockedSetHostsForAddr(addr netip.Addr, list []*HostInfo) {
  339. if len(list) == 0 {
  340. delete(hm.Hosts, addr)
  341. delete(hm.moreHosts, addr)
  342. return
  343. }
  344. hm.Hosts[addr] = list[0]
  345. if len(list) > 1 {
  346. hm.moreHosts[addr] = list
  347. } else {
  348. delete(hm.moreHosts, addr)
  349. }
  350. }
  351. // unlockedGetHostList returns every hostinfo holding addr, primary first, or nil if we have no
  352. // tunnel for addr. The common single-hostinfo case builds a fresh one element list, so keep this
  353. // off the packet hot path; the primary is a direct Hosts read. Callers must hold the lock (read
  354. // or write).
  355. func (hm *HostMap) unlockedGetHostList(addr netip.Addr) []*HostInfo {
  356. if list, ok := hm.moreHosts[addr]; ok {
  357. return list
  358. }
  359. if h, ok := hm.Hosts[addr]; ok {
  360. return []*HostInfo{h}
  361. }
  362. return nil
  363. }
  364. // removeHostInfo returns list with hi removed (order preserved), or list unchanged if hi is
  365. // absent. It deletes in place: every mutator holds the hostmap write lock and no reader ever
  366. // retains a slice across a mutation (readers iterate under RLock), so there is no snapshot to
  367. // invalidate.
  368. func removeHostInfo(list []*HostInfo, hi *HostInfo) []*HostInfo {
  369. idx := slices.Index(list, hi)
  370. if idx < 0 {
  371. return list
  372. }
  373. return slices.Delete(list, idx, idx+1)
  374. }
  375. // DeleteHostInfo will fully unlink the hostinfo and return true if no other hostinfo still holds
  376. // any of its vpn addrs, meaning we no longer have a tunnel to the peer
  377. func (hm *HostMap) DeleteHostInfo(hostinfo *HostInfo) bool {
  378. // Delete the host itself, ensuring it's not modified anymore
  379. hm.Lock()
  380. final := hm.unlockedDeleteHostInfo(hostinfo)
  381. hm.Unlock()
  382. return final
  383. }
  384. func (hm *HostMap) MakePrimary(hostinfo *HostInfo) {
  385. hm.Lock()
  386. defer hm.Unlock()
  387. hm.unlockedMakePrimary(hostinfo)
  388. }
  389. // unlockedMakePrimary reports whether hostinfo is (now) the primary for each of its addresses,
  390. // false only when it is no longer in the hostmap at all.
  391. func (hm *HostMap) unlockedMakePrimary(hostinfo *HostInfo) bool {
  392. // A hostinfo that is no longer in the hostmap must not be re-inserted here. Callers can race
  393. // tunnel teardown, deciding to promote under the read lock and only taking the write lock
  394. // after a delete fully unlinked the hostinfo (connection manager swapPrimary, AddRelay). Every
  395. // live hostinfo is registered in Indexes by unlockedAddHostInfo, so this is a membership test.
  396. if hm.Indexes[hostinfo.localIndexId] != hostinfo {
  397. return false
  398. }
  399. // Move hostinfo to the front (primary) of each of its address lists. The lists are
  400. // independent per address, so this can never leave a dangling entry the way promoting
  401. // against a single shared chain could.
  402. for _, addr := range hostinfo.vpnAddrs {
  403. if hm.Hosts[addr] == hostinfo {
  404. // Already primary for this address, the list is already in the right order
  405. continue
  406. }
  407. list := removeHostInfo(hm.unlockedGetHostList(addr), hostinfo)
  408. list = append([]*HostInfo{hostinfo}, list...)
  409. hm.unlockedSetHostsForAddr(addr, list)
  410. }
  411. return true
  412. }
  413. // unlockedDeleteHostInfo removes hostinfo from every one of its address lists and from the index
  414. // maps. It returns true if this was the last hostinfo for all of its addresses (we no longer have
  415. // any tunnel to the peer), which the caller uses to decide whether to clear learned lighthouse
  416. // state and disestablish relays.
  417. func (hm *HostMap) unlockedDeleteHostInfo(hostinfo *HostInfo) bool {
  418. // Remove this hostinfo from each of its address lists. The lists are independent, so a
  419. // sibling is never promoted to an address it does not own and no other list is touched.
  420. final := true
  421. for _, addr := range hostinfo.vpnAddrs {
  422. if list, ok := hm.moreHosts[addr]; ok {
  423. list = removeHostInfo(list, hostinfo)
  424. hm.unlockedSetHostsForAddr(addr, list)
  425. if len(list) > 0 {
  426. final = false
  427. }
  428. } else if existing, ok := hm.Hosts[addr]; ok {
  429. if existing == hostinfo {
  430. // Common case, the only hostinfo for this address. moreHosts has no entry to clean up.
  431. delete(hm.Hosts, addr)
  432. } else {
  433. // We don't hold this address but another hostinfo does, we still have a tunnel to the peer
  434. final = false
  435. }
  436. }
  437. }
  438. // Go maps never shrink their buckets, replace fully drained maps so a node that churned
  439. // through a large peer count gives the memory back. Same idiom as the index maps below.
  440. if len(hm.Hosts) == 0 {
  441. hm.Hosts = map[netip.Addr]*HostInfo{}
  442. }
  443. if len(hm.moreHosts) == 0 {
  444. hm.moreHosts = map[netip.Addr][]*HostInfo{}
  445. }
  446. // The remote index uses index ids outside our control so lets make sure we are only removing
  447. // the remote index pointer here if it points to the hostinfo we are deleting
  448. hostinfo2, ok := hm.RemoteIndexes[hostinfo.remoteIndexId]
  449. if ok && hostinfo2 == hostinfo {
  450. delete(hm.RemoteIndexes, hostinfo.remoteIndexId)
  451. if len(hm.RemoteIndexes) == 0 {
  452. hm.RemoteIndexes = map[uint32]*HostInfo{}
  453. }
  454. }
  455. delete(hm.Indexes, hostinfo.localIndexId)
  456. if len(hm.Indexes) == 0 {
  457. hm.Indexes = map[uint32]*HostInfo{}
  458. }
  459. if hm.l.Enabled(context.Background(), slog.LevelDebug) {
  460. hm.l.Debug("Hostmap hostInfo deleted",
  461. "hostMap", m{"mapTotalSize": len(hm.Hosts),
  462. "vpnAddrs": hostinfo.vpnAddrs, "indexNumber": hostinfo.localIndexId, "remoteIndexNumber": hostinfo.remoteIndexId},
  463. )
  464. }
  465. if final {
  466. // I have lost connectivity to my peers. My relay tunnel is likely broken. Mark the next
  467. // hops as 'Requested' so that new relay tunnels are created in the future.
  468. hm.unlockedDisestablishVpnAddrRelayFor(hostinfo)
  469. }
  470. // Clean up any local relay indexes for which I am acting as a relay hop
  471. for _, localRelayIdx := range hostinfo.relayState.CopyRelayForIdxs() {
  472. delete(hm.Relays, localRelayIdx)
  473. }
  474. return final
  475. }
  476. func (hm *HostMap) QueryIndex(index uint32) *HostInfo {
  477. hm.RLock()
  478. if h, ok := hm.Indexes[index]; ok {
  479. hm.RUnlock()
  480. return h
  481. } else {
  482. hm.RUnlock()
  483. return nil
  484. }
  485. }
  486. func (hm *HostMap) QueryRelayIndex(index uint32) *HostInfo {
  487. hm.RLock()
  488. if h, ok := hm.Relays[index]; ok {
  489. hm.RUnlock()
  490. return h
  491. } else {
  492. hm.RUnlock()
  493. return nil
  494. }
  495. }
  496. func (hm *HostMap) QueryReverseIndex(index uint32) *HostInfo {
  497. hm.RLock()
  498. if h, ok := hm.RemoteIndexes[index]; ok {
  499. hm.RUnlock()
  500. return h
  501. } else {
  502. hm.RUnlock()
  503. return nil
  504. }
  505. }
  506. func (hm *HostMap) QueryVpnAddr(vpnIp netip.Addr) *HostInfo {
  507. return hm.queryVpnAddr(vpnIp, nil)
  508. }
  509. func (hm *HostMap) QueryVpnAddrsRelayFor(targetIps []netip.Addr, relayHostIp netip.Addr) (*HostInfo, *Relay, error) {
  510. hm.RLock()
  511. defer hm.RUnlock()
  512. // This runs per relayed packet, so check the primary with a single map probe and only consult
  513. // moreHosts when the primary can't relay for us.
  514. h, ok := hm.Hosts[relayHostIp]
  515. if !ok {
  516. return nil, nil, errors.New("unable to find host")
  517. }
  518. for _, targetIp := range targetIps {
  519. r, ok := h.relayState.QueryRelayForByIp(targetIp)
  520. if ok && r.State == Established {
  521. return h, r, nil
  522. }
  523. }
  524. if list, ok := hm.moreHosts[relayHostIp]; ok {
  525. // list[0] is the primary we already checked
  526. for _, h := range list[1:] {
  527. for _, targetIp := range targetIps {
  528. r, ok := h.relayState.QueryRelayForByIp(targetIp)
  529. if ok && r.State == Established {
  530. return h, r, nil
  531. }
  532. }
  533. }
  534. }
  535. return nil, nil, errors.New("unable to find host with relay")
  536. }
  537. func (hm *HostMap) unlockedDisestablishVpnAddrRelayFor(hi *HostInfo) {
  538. for _, relayHostIp := range hi.relayState.CopyRelayIps() {
  539. for _, h := range hm.unlockedGetHostList(relayHostIp) {
  540. h.relayState.UpdateRelayForByIpState(hi.vpnAddrs[0], Disestablished)
  541. }
  542. }
  543. for _, rs := range hi.relayState.CopyAllRelayFor() {
  544. if rs.Type == ForwardingType {
  545. for _, h := range hm.unlockedGetHostList(rs.PeerAddr) {
  546. h.relayState.UpdateRelayForByIpState(hi.vpnAddrs[0], Disestablished)
  547. }
  548. }
  549. }
  550. }
  551. func (hm *HostMap) queryVpnAddr(vpnIp netip.Addr, promoteIfce *Interface) *HostInfo {
  552. hm.RLock()
  553. if h, ok := hm.Hosts[vpnIp]; ok {
  554. hm.RUnlock()
  555. // Do not attempt promotion if you are a lighthouse
  556. if promoteIfce != nil && !promoteIfce.lightHouse.amLighthouse {
  557. h.TryPromoteBest(hm.GetPreferredRanges(), promoteIfce)
  558. }
  559. return h
  560. }
  561. hm.RUnlock()
  562. return nil
  563. }
  564. // unlockedAddHostInfo assumes you have a write-lock and will add a hostinfo object to the hostmap Indexes and RemoteIndexes maps.
  565. // If an entry exists for the Hosts table (vpnIp -> hostinfo) then the provided hostinfo will be made primary
  566. func (hm *HostMap) unlockedAddHostInfo(hostinfo *HostInfo, f *Interface) {
  567. if f.dnsServer != nil {
  568. remoteCert := hostinfo.ConnectionState.peerCert
  569. f.dnsServer.Add(remoteCert.Certificate.Name()+".", hostinfo.vpnAddrs)
  570. }
  571. for _, addr := range hostinfo.vpnAddrs {
  572. hm.unlockedInnerAddHostInfo(addr, hostinfo, f)
  573. }
  574. hm.Indexes[hostinfo.localIndexId] = hostinfo
  575. hm.RemoteIndexes[hostinfo.remoteIndexId] = hostinfo
  576. hostinfo.out.Store(true)
  577. if f.connectionManager != nil { // f.connectionManager is only nil in some unit tests
  578. f.connectionManager.trafficTimer.Add(hostinfo.localIndexId, f.connectionManager.checkInterval)
  579. }
  580. if hm.l.Enabled(context.Background(), slog.LevelDebug) {
  581. hm.l.Debug("Hostmap vpnIp added",
  582. "hostMap", m{"vpnAddrs": hostinfo.vpnAddrs, "mapTotalSize": len(hm.Hosts),
  583. "hostinfo": m{"existing": true, "localIndexId": hostinfo.localIndexId, "vpnAddrs": hostinfo.vpnAddrs}},
  584. )
  585. }
  586. }
  587. func (hm *HostMap) unlockedInnerAddHostInfo(vpnAddr netip.Addr, hostinfo *HostInfo, f *Interface) {
  588. existing, ok := hm.Hosts[vpnAddr]
  589. if !ok {
  590. // Common case, the first hostinfo for this address. moreHosts stays empty.
  591. hm.Hosts[vpnAddr] = hostinfo
  592. return
  593. }
  594. // The new hostinfo becomes the primary for this address. Remove any stale copy of it first so
  595. // we never hold a duplicate, then prepend.
  596. list, ok := hm.moreHosts[vpnAddr]
  597. if !ok {
  598. list = []*HostInfo{existing}
  599. }
  600. list = removeHostInfo(list, hostinfo)
  601. list = append([]*HostInfo{hostinfo}, list...)
  602. hm.unlockedSetHostsForAddr(vpnAddr, list)
  603. // Enforce the per-address cap by fully retiring the oldest hostinfo once we exceed it.
  604. // Deleting it removes it from all of its addresses and the index maps, matching prior behavior.
  605. if len(list) > MaxHostInfosPerVpnIp {
  606. hm.unlockedDeleteHostInfo(list[len(list)-1])
  607. }
  608. }
  609. func (hm *HostMap) GetPreferredRanges() []netip.Prefix {
  610. //NOTE: if preferredRanges is ever not stored before a load this will fail to dereference a nil pointer
  611. return *hm.preferredRanges.Load()
  612. }
  613. func (hm *HostMap) ForEachVpnAddr(f controlEach) {
  614. hm.RLock()
  615. defer hm.RUnlock()
  616. for _, v := range hm.Hosts {
  617. f(v)
  618. }
  619. }
  620. func (hm *HostMap) ForEachIndex(f controlEach) {
  621. hm.RLock()
  622. defer hm.RUnlock()
  623. for _, v := range hm.Indexes {
  624. f(v)
  625. }
  626. }
  627. // TryPromoteBest handles re-querying lighthouses and probing for better paths
  628. // NOTE: It is an error to call this if you are a lighthouse since they should not roam clients!
  629. func (i *HostInfo) TryPromoteBest(preferredRanges []netip.Prefix, ifce *Interface) {
  630. c := i.promoteCounter.Add(1)
  631. if c%ifce.tryPromoteEvery.Load() == 0 {
  632. remote := i.GetRemote()
  633. // return early if we are already on a preferred remote
  634. if remote.IsValid() {
  635. rIP := remote.Addr()
  636. for _, l := range preferredRanges {
  637. if l.Contains(rIP) {
  638. return
  639. }
  640. }
  641. }
  642. i.remotes.ForEach(preferredRanges, func(addr netip.AddrPort, preferred bool) {
  643. if remote.IsValid() && (!addr.IsValid() || !preferred) {
  644. return
  645. }
  646. // Try to send a test packet to that host, this should
  647. // cause it to detect a roaming event and switch remotes
  648. ifce.sendTo(header.Test, header.TestRequest, i.ConnectionState, i, addr, []byte(""), make([]byte, 12, 12), make([]byte, mtu))
  649. })
  650. }
  651. // Re query our lighthouses for new remotes occasionally
  652. if c%ifce.reQueryEvery.Load() == 0 && ifce.lightHouse != nil {
  653. now := time.Now().UnixNano()
  654. if now < i.nextLHQuery.Load() {
  655. return
  656. }
  657. i.nextLHQuery.Store(now + ifce.reQueryWait.Load())
  658. ifce.lightHouse.QueryServer(i.vpnAddrs[0])
  659. }
  660. }
  661. func (i *HostInfo) GetCert() *cert.CachedCertificate {
  662. if i.ConnectionState != nil {
  663. return i.ConnectionState.peerCert
  664. }
  665. return nil
  666. }
  667. func (i *HostInfo) GetRemote() netip.AddrPort {
  668. if p := i.remote.Load(); p != nil {
  669. return *p
  670. }
  671. return netip.AddrPort{}
  672. }
  673. // TODO: Maybe use ViaSender here?
  674. func (i *HostInfo) SetRemote(remote netip.AddrPort) {
  675. // We copy here because we likely got this remote from a source that reuses the object
  676. if i.GetRemote() != remote {
  677. i.remote.Store(&remote)
  678. i.remotes.LearnRemote(i.vpnAddrs[0], remote)
  679. }
  680. }
  681. // SetRemoteIfPreferred returns true if the remote was changed. The lastRoam
  682. // time on the HostInfo will also be updated.
  683. func (i *HostInfo) SetRemoteIfPreferred(hm *HostMap, via ViaSender) bool {
  684. if via.IsRelayed {
  685. return false
  686. }
  687. currentRemote := i.GetRemote()
  688. if !currentRemote.IsValid() {
  689. i.SetRemote(via.UdpAddr)
  690. return true
  691. }
  692. // NOTE: We do this loop here instead of calling `isPreferred` in
  693. // remote_list.go so that we only have to loop over preferredRanges once.
  694. newIsPreferred := false
  695. for _, l := range hm.GetPreferredRanges() {
  696. // return early if we are already on a preferred remote
  697. if l.Contains(currentRemote.Addr()) {
  698. return false
  699. }
  700. if l.Contains(via.UdpAddr.Addr()) {
  701. newIsPreferred = true
  702. }
  703. }
  704. if newIsPreferred {
  705. // Consider this a roaming event
  706. i.lastRoam = time.Now()
  707. i.lastRoamRemote = currentRemote
  708. i.SetRemote(via.UdpAddr)
  709. return true
  710. }
  711. return false
  712. }
  713. // buildNetworks fills in the networks field of HostInfo. It accepts a cert.Certificate so you never ever mix the network types up.
  714. func (i *HostInfo) buildNetworks(myVpnNetworksTable *bart.Lite, c cert.Certificate) {
  715. if len(c.Networks()) == 1 && len(c.UnsafeNetworks()) == 0 {
  716. if myVpnNetworksTable.Contains(c.Networks()[0].Addr()) {
  717. return // Simple case, no BART needed
  718. }
  719. }
  720. i.networks = new(bart.Table[NetworkType])
  721. for _, network := range c.Networks() {
  722. nprefix := netip.PrefixFrom(network.Addr(), network.Addr().BitLen())
  723. if myVpnNetworksTable.Contains(network.Addr()) {
  724. i.networks.Insert(nprefix, NetworkTypeVPN)
  725. } else {
  726. i.networks.Insert(nprefix, NetworkTypeVPNPeer)
  727. }
  728. }
  729. for _, network := range c.UnsafeNetworks() {
  730. i.networks.Insert(network, NetworkTypeUnsafe)
  731. }
  732. }
  733. // logger returns a derived slog.Logger with per-hostinfo fields pre-bound.
  734. func (i *HostInfo) logger(l *slog.Logger) *slog.Logger {
  735. if i == nil {
  736. return l
  737. }
  738. li := l.With(
  739. "vpnAddrs", i.vpnAddrs,
  740. "localIndex", i.localIndexId,
  741. "remoteIndex", i.remoteIndexId,
  742. )
  743. if connState := i.ConnectionState; connState != nil {
  744. if peerCert := connState.peerCert; peerCert != nil {
  745. li = li.With("certName", peerCert.Certificate.Name())
  746. }
  747. }
  748. return li
  749. }
  750. // Utility functions
  751. func localAddrs(l *slog.Logger, allowList *LocalAllowList) []netip.Addr {
  752. //FIXME: This function is pretty garbage
  753. var finalAddrs []netip.Addr
  754. ifaces, _ := net.Interfaces()
  755. for _, i := range ifaces {
  756. allow := allowList.AllowName(i.Name)
  757. if l.Enabled(context.Background(), logging.LevelTrace) {
  758. l.Log(context.Background(), logging.LevelTrace, "localAllowList.AllowName",
  759. "interfaceName", i.Name,
  760. "allow", allow,
  761. )
  762. }
  763. if !allow {
  764. continue
  765. }
  766. addrs, _ := i.Addrs()
  767. for _, rawAddr := range addrs {
  768. var addr netip.Addr
  769. switch v := rawAddr.(type) {
  770. case *net.IPNet:
  771. //continue
  772. addr, _ = netip.AddrFromSlice(v.IP)
  773. case *net.IPAddr:
  774. addr, _ = netip.AddrFromSlice(v.IP)
  775. }
  776. if !addr.IsValid() {
  777. if l.Enabled(context.Background(), slog.LevelDebug) {
  778. l.Debug("addr was invalid", "localAddr", rawAddr)
  779. }
  780. continue
  781. }
  782. addr = addr.Unmap()
  783. if addr.IsLoopback() == false && addr.IsLinkLocalUnicast() == false {
  784. isAllowed := allowList.Allow(addr)
  785. if l.Enabled(context.Background(), logging.LevelTrace) {
  786. l.Log(context.Background(), logging.LevelTrace, "localAllowList.Allow",
  787. "localAddr", addr,
  788. "allowed", isAllowed,
  789. )
  790. }
  791. if !isAllowed {
  792. continue
  793. }
  794. finalAddrs = append(finalAddrs, addr)
  795. }
  796. }
  797. }
  798. return finalAddrs
  799. }