hostmap.go 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833
  1. package nebula
  2. import (
  3. "errors"
  4. "net"
  5. "net/netip"
  6. "slices"
  7. "sync"
  8. "sync/atomic"
  9. "time"
  10. "github.com/gaissmai/bart"
  11. "github.com/rcrowley/go-metrics"
  12. "github.com/sirupsen/logrus"
  13. "github.com/slackhq/nebula/cert"
  14. "github.com/slackhq/nebula/config"
  15. "github.com/slackhq/nebula/header"
  16. )
  17. const defaultPromoteEvery = 1000 // Count of packets sent before we try moving a tunnel to a preferred underlay ip address
  18. const defaultReQueryEvery = 5000 // Count of packets sent before re-querying a hostinfo to the lighthouse
  19. const defaultReQueryWait = time.Minute // Minimum amount of seconds to wait before re-querying a hostinfo the lighthouse. Evaluated every ReQueryEvery
  20. const MaxRemotes = 10
  21. // MaxHostInfosPerVpnIp is the max number of hostinfos we will track for a given vpn ip
  22. // 5 allows for an initial handshake and each host pair re-handshaking twice
  23. const MaxHostInfosPerVpnIp = 5
  24. // How long we should prevent roaming back to the previous IP.
  25. // This helps prevent flapping due to packets already in flight
  26. const RoamingSuppressSeconds = 2
  27. const (
  28. Requested = iota
  29. PeerRequested
  30. Established
  31. Disestablished
  32. )
  33. const (
  34. Unknowntype = iota
  35. ForwardingType
  36. TerminalType
  37. )
  38. type Relay struct {
  39. Type int
  40. State int
  41. LocalIndex uint32
  42. RemoteIndex uint32
  43. PeerAddr netip.Addr
  44. }
  45. type HostMap struct {
  46. sync.RWMutex //Because we concurrently read and write to our maps
  47. Indexes map[uint32]*HostInfo
  48. Relays map[uint32]*HostInfo // Maps a Relay IDX to a Relay HostInfo object
  49. RemoteIndexes map[uint32]*HostInfo
  50. Hosts map[netip.Addr]*HostInfo
  51. preferredRanges atomic.Pointer[[]netip.Prefix]
  52. l *logrus.Logger
  53. }
  54. // For synchronization, treat the pointed-to Relay struct as immutable. To edit the Relay
  55. // struct, make a copy of an existing value, edit the fileds in the copy, and
  56. // then store a pointer to the new copy in both realyForBy* maps.
  57. type RelayState struct {
  58. sync.RWMutex
  59. relays []netip.Addr // Ordered set of VpnAddrs of Hosts to use as relays to access this peer
  60. // For data race avoidance, the contents of a *Relay are treated immutably. To update a *Relay, copy the existing data,
  61. // modify what needs to be updated, and store the new modified copy in the relayForByIp and relayForByIdx maps (with
  62. // the RelayState Lock held)
  63. relayForByAddr map[netip.Addr]*Relay // Maps vpnAddr of peers for which this HostInfo is a relay to some Relay info
  64. relayForByIdx map[uint32]*Relay // Maps a local index to some Relay info
  65. }
  66. func (rs *RelayState) DeleteRelay(ip netip.Addr) {
  67. rs.Lock()
  68. defer rs.Unlock()
  69. for idx, val := range rs.relays {
  70. if val == ip {
  71. rs.relays = append(rs.relays[:idx], rs.relays[idx+1:]...)
  72. return
  73. }
  74. }
  75. }
  76. func (rs *RelayState) UpdateRelayForByIpState(vpnIp netip.Addr, state int) {
  77. rs.Lock()
  78. defer rs.Unlock()
  79. if r, ok := rs.relayForByAddr[vpnIp]; ok {
  80. newRelay := *r
  81. newRelay.State = state
  82. rs.relayForByAddr[newRelay.PeerAddr] = &newRelay
  83. rs.relayForByIdx[newRelay.LocalIndex] = &newRelay
  84. }
  85. }
  86. func (rs *RelayState) UpdateRelayForByIdxState(idx uint32, state int) {
  87. rs.Lock()
  88. defer rs.Unlock()
  89. if r, ok := rs.relayForByIdx[idx]; ok {
  90. newRelay := *r
  91. newRelay.State = state
  92. rs.relayForByAddr[newRelay.PeerAddr] = &newRelay
  93. rs.relayForByIdx[newRelay.LocalIndex] = &newRelay
  94. }
  95. }
  96. func (rs *RelayState) CopyAllRelayFor() []*Relay {
  97. rs.RLock()
  98. defer rs.RUnlock()
  99. ret := make([]*Relay, 0, len(rs.relayForByIdx))
  100. for _, r := range rs.relayForByIdx {
  101. ret = append(ret, r)
  102. }
  103. return ret
  104. }
  105. func (rs *RelayState) GetRelayForByAddr(addr netip.Addr) (*Relay, bool) {
  106. rs.RLock()
  107. defer rs.RUnlock()
  108. r, ok := rs.relayForByAddr[addr]
  109. return r, ok
  110. }
  111. func (rs *RelayState) InsertRelayTo(ip netip.Addr) {
  112. rs.Lock()
  113. defer rs.Unlock()
  114. if !slices.Contains(rs.relays, ip) {
  115. rs.relays = append(rs.relays, ip)
  116. }
  117. }
  118. func (rs *RelayState) CopyRelayIps() []netip.Addr {
  119. ret := make([]netip.Addr, len(rs.relays))
  120. rs.RLock()
  121. defer rs.RUnlock()
  122. copy(ret, rs.relays)
  123. return ret
  124. }
  125. func (rs *RelayState) CopyRelayForIps() []netip.Addr {
  126. rs.RLock()
  127. defer rs.RUnlock()
  128. currentRelays := make([]netip.Addr, 0, len(rs.relayForByAddr))
  129. for relayIp := range rs.relayForByAddr {
  130. currentRelays = append(currentRelays, relayIp)
  131. }
  132. return currentRelays
  133. }
  134. func (rs *RelayState) CopyRelayForIdxs() []uint32 {
  135. rs.RLock()
  136. defer rs.RUnlock()
  137. ret := make([]uint32, 0, len(rs.relayForByIdx))
  138. for i := range rs.relayForByIdx {
  139. ret = append(ret, i)
  140. }
  141. return ret
  142. }
  143. func (rs *RelayState) CompleteRelayByIP(vpnIp netip.Addr, remoteIdx uint32) bool {
  144. rs.Lock()
  145. defer rs.Unlock()
  146. r, ok := rs.relayForByAddr[vpnIp]
  147. if !ok {
  148. return false
  149. }
  150. newRelay := *r
  151. newRelay.State = Established
  152. newRelay.RemoteIndex = remoteIdx
  153. rs.relayForByIdx[r.LocalIndex] = &newRelay
  154. rs.relayForByAddr[r.PeerAddr] = &newRelay
  155. return true
  156. }
  157. func (rs *RelayState) CompleteRelayByIdx(localIdx uint32, remoteIdx uint32) (*Relay, bool) {
  158. rs.Lock()
  159. defer rs.Unlock()
  160. r, ok := rs.relayForByIdx[localIdx]
  161. if !ok {
  162. return nil, false
  163. }
  164. newRelay := *r
  165. newRelay.State = Established
  166. newRelay.RemoteIndex = remoteIdx
  167. rs.relayForByIdx[r.LocalIndex] = &newRelay
  168. rs.relayForByAddr[r.PeerAddr] = &newRelay
  169. return &newRelay, true
  170. }
  171. func (rs *RelayState) QueryRelayForByIp(vpnIp netip.Addr) (*Relay, bool) {
  172. rs.RLock()
  173. defer rs.RUnlock()
  174. r, ok := rs.relayForByAddr[vpnIp]
  175. return r, ok
  176. }
  177. func (rs *RelayState) QueryRelayForByIdx(idx uint32) (*Relay, bool) {
  178. rs.RLock()
  179. defer rs.RUnlock()
  180. r, ok := rs.relayForByIdx[idx]
  181. return r, ok
  182. }
  183. func (rs *RelayState) InsertRelay(ip netip.Addr, idx uint32, r *Relay) {
  184. rs.Lock()
  185. defer rs.Unlock()
  186. rs.relayForByAddr[ip] = r
  187. rs.relayForByIdx[idx] = r
  188. }
  189. type NetworkType uint8
  190. const (
  191. NetworkTypeUnknown NetworkType = iota
  192. // NetworkTypeVPN is a network that overlaps one or more of the vpnNetworks in our certificate
  193. NetworkTypeVPN
  194. // NetworkTypeVPNPeer is a network that does not overlap one of our networks
  195. NetworkTypeVPNPeer
  196. // NetworkTypeUnsafe is a network from Certificate.UnsafeNetworks()
  197. NetworkTypeUnsafe
  198. )
  199. type HostInfo struct {
  200. remote netip.AddrPort
  201. remotes *RemoteList
  202. promoteCounter atomic.Uint32
  203. ConnectionState *ConnectionState
  204. remoteIndexId uint32
  205. localIndexId uint32
  206. // vpnAddrs is a list of vpn addresses assigned to this host
  207. vpnAddrs []netip.Addr
  208. // networks is a combination of specific vpn addresses (not prefixes!) and full unsafe networks assigned to this host.
  209. networks *bart.Table[NetworkType]
  210. relayState RelayState
  211. // HandshakePacket records the packets used to create this hostinfo
  212. // We need these to avoid replayed handshake packets creating new hostinfos which causes churn
  213. HandshakePacket map[uint8][]byte
  214. // nextLHQuery is the earliest we can ask the lighthouse for new information.
  215. // This is used to limit lighthouse re-queries in chatty clients
  216. nextLHQuery atomic.Int64
  217. // lastRebindCount is the other side of Interface.rebindCount, if these values don't match then we need to ask LH
  218. // for a punch from the remote end of this tunnel. The goal being to prime their conntrack for our traffic just like
  219. // with a handshake
  220. lastRebindCount int8
  221. // lastHandshakeTime records the time the remote side told us about at the stage when the handshake was completed locally
  222. // Stage 1 packet will contain it if I am a responder, stage 2 packet if I am an initiator
  223. // This is used to avoid an attack where a handshake packet is replayed after some time
  224. lastHandshakeTime uint64
  225. lastRoam time.Time
  226. lastRoamRemote netip.AddrPort
  227. // Used to track other hostinfos for this vpn ip since only 1 can be primary
  228. // Synchronised via hostmap lock and not the hostinfo lock.
  229. next, prev *HostInfo
  230. //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
  231. in, out, pendingDeletion atomic.Bool
  232. // lastUsed tracks the last time ConnectionManager checked the tunnel and it was in use.
  233. // This value will be behind against actual tunnel utilization in the hot path.
  234. // This should only be used by the ConnectionManagers ticker routine.
  235. lastUsed time.Time
  236. }
  237. type ViaSender struct {
  238. relayHI *HostInfo // relayHI is the host info object of the relay
  239. remoteIdx uint32 // remoteIdx is the index included in the header of the received packet
  240. relay *Relay // relay contains the rest of the relay information, including the PeerIP of the host trying to communicate with us.
  241. }
  242. type cachedPacket struct {
  243. messageType header.MessageType
  244. messageSubType header.MessageSubType
  245. callback packetCallback
  246. packet []byte
  247. }
  248. type packetCallback func(t header.MessageType, st header.MessageSubType, h *HostInfo, p, nb, out []byte)
  249. type cachedPacketMetrics struct {
  250. sent metrics.Counter
  251. dropped metrics.Counter
  252. }
  253. func NewHostMapFromConfig(l *logrus.Logger, c *config.C) *HostMap {
  254. hm := newHostMap(l)
  255. hm.reload(c, true)
  256. c.RegisterReloadCallback(func(c *config.C) {
  257. hm.reload(c, false)
  258. })
  259. l.WithField("preferredRanges", hm.GetPreferredRanges()).
  260. Info("Main HostMap created")
  261. return hm
  262. }
  263. func newHostMap(l *logrus.Logger) *HostMap {
  264. return &HostMap{
  265. Indexes: map[uint32]*HostInfo{},
  266. Relays: map[uint32]*HostInfo{},
  267. RemoteIndexes: map[uint32]*HostInfo{},
  268. Hosts: map[netip.Addr]*HostInfo{},
  269. l: l,
  270. }
  271. }
  272. func (hm *HostMap) reload(c *config.C, initial bool) {
  273. if initial || c.HasChanged("preferred_ranges") {
  274. var preferredRanges []netip.Prefix
  275. rawPreferredRanges := c.GetStringSlice("preferred_ranges", []string{})
  276. for _, rawPreferredRange := range rawPreferredRanges {
  277. preferredRange, err := netip.ParsePrefix(rawPreferredRange)
  278. if err != nil {
  279. hm.l.WithError(err).WithField("range", rawPreferredRanges).Warn("Failed to parse preferred ranges, ignoring")
  280. continue
  281. }
  282. preferredRanges = append(preferredRanges, preferredRange)
  283. }
  284. oldRanges := hm.preferredRanges.Swap(&preferredRanges)
  285. if !initial {
  286. hm.l.WithField("oldPreferredRanges", *oldRanges).WithField("newPreferredRanges", preferredRanges).Info("preferred_ranges changed")
  287. }
  288. }
  289. }
  290. // EmitStats reports host, index, and relay counts to the stats collection system
  291. func (hm *HostMap) EmitStats() {
  292. hm.RLock()
  293. hostLen := len(hm.Hosts)
  294. indexLen := len(hm.Indexes)
  295. remoteIndexLen := len(hm.RemoteIndexes)
  296. relaysLen := len(hm.Relays)
  297. hm.RUnlock()
  298. metrics.GetOrRegisterGauge("hostmap.main.hosts", nil).Update(int64(hostLen))
  299. metrics.GetOrRegisterGauge("hostmap.main.indexes", nil).Update(int64(indexLen))
  300. metrics.GetOrRegisterGauge("hostmap.main.remoteIndexes", nil).Update(int64(remoteIndexLen))
  301. metrics.GetOrRegisterGauge("hostmap.main.relayIndexes", nil).Update(int64(relaysLen))
  302. }
  303. // DeleteHostInfo will fully unlink the hostinfo and return true if it was the final hostinfo for this vpn ip
  304. func (hm *HostMap) DeleteHostInfo(hostinfo *HostInfo) bool {
  305. // Delete the host itself, ensuring it's not modified anymore
  306. hm.Lock()
  307. // If we have a previous or next hostinfo then we are not the last one for this vpn ip
  308. final := (hostinfo.next == nil && hostinfo.prev == nil)
  309. hm.unlockedDeleteHostInfo(hostinfo)
  310. hm.Unlock()
  311. return final
  312. }
  313. func (hm *HostMap) MakePrimary(hostinfo *HostInfo) {
  314. hm.Lock()
  315. defer hm.Unlock()
  316. hm.unlockedMakePrimary(hostinfo)
  317. }
  318. func (hm *HostMap) unlockedMakePrimary(hostinfo *HostInfo) {
  319. // Get the current primary, if it exists
  320. oldHostinfo := hm.Hosts[hostinfo.vpnAddrs[0]]
  321. // Every address in the hostinfo gets elevated to primary
  322. for _, vpnAddr := range hostinfo.vpnAddrs {
  323. //NOTE: It is possible that we leave a dangling hostinfo here but connection manager works on
  324. // indexes so it should be fine.
  325. hm.Hosts[vpnAddr] = hostinfo
  326. }
  327. // If we are already primary then we won't bother re-linking
  328. if oldHostinfo == hostinfo {
  329. return
  330. }
  331. // Unlink this hostinfo
  332. if hostinfo.prev != nil {
  333. hostinfo.prev.next = hostinfo.next
  334. }
  335. if hostinfo.next != nil {
  336. hostinfo.next.prev = hostinfo.prev
  337. }
  338. // If there wasn't a previous primary then clear out any links
  339. if oldHostinfo == nil {
  340. hostinfo.next = nil
  341. hostinfo.prev = nil
  342. return
  343. }
  344. // Relink the hostinfo as primary
  345. hostinfo.next = oldHostinfo
  346. oldHostinfo.prev = hostinfo
  347. hostinfo.prev = nil
  348. }
  349. func (hm *HostMap) unlockedDeleteHostInfo(hostinfo *HostInfo) {
  350. for _, addr := range hostinfo.vpnAddrs {
  351. h := hm.Hosts[addr]
  352. for h != nil {
  353. if h == hostinfo {
  354. hm.unlockedInnerDeleteHostInfo(h, addr)
  355. }
  356. h = h.next
  357. }
  358. }
  359. }
  360. func (hm *HostMap) unlockedInnerDeleteHostInfo(hostinfo *HostInfo, addr netip.Addr) {
  361. primary, ok := hm.Hosts[addr]
  362. isLastHostinfo := hostinfo.next == nil && hostinfo.prev == nil
  363. if ok && primary == hostinfo {
  364. // The vpn addr pointer points to the same hostinfo as the local index id, we can remove it
  365. delete(hm.Hosts, addr)
  366. if len(hm.Hosts) == 0 {
  367. hm.Hosts = map[netip.Addr]*HostInfo{}
  368. }
  369. if hostinfo.next != nil {
  370. // We had more than 1 hostinfo at this vpn addr, promote the next in the list to primary
  371. hm.Hosts[addr] = hostinfo.next
  372. // It is primary, there is no previous hostinfo now
  373. hostinfo.next.prev = nil
  374. }
  375. } else {
  376. // Relink if we were in the middle of multiple hostinfos for this vpn addr
  377. if hostinfo.prev != nil {
  378. hostinfo.prev.next = hostinfo.next
  379. }
  380. if hostinfo.next != nil {
  381. hostinfo.next.prev = hostinfo.prev
  382. }
  383. }
  384. hostinfo.next = nil
  385. hostinfo.prev = nil
  386. // The remote index uses index ids outside our control so lets make sure we are only removing
  387. // the remote index pointer here if it points to the hostinfo we are deleting
  388. hostinfo2, ok := hm.RemoteIndexes[hostinfo.remoteIndexId]
  389. if ok && hostinfo2 == hostinfo {
  390. delete(hm.RemoteIndexes, hostinfo.remoteIndexId)
  391. if len(hm.RemoteIndexes) == 0 {
  392. hm.RemoteIndexes = map[uint32]*HostInfo{}
  393. }
  394. }
  395. delete(hm.Indexes, hostinfo.localIndexId)
  396. if len(hm.Indexes) == 0 {
  397. hm.Indexes = map[uint32]*HostInfo{}
  398. }
  399. if hm.l.Level >= logrus.DebugLevel {
  400. hm.l.WithField("hostMap", m{"mapTotalSize": len(hm.Hosts),
  401. "vpnAddrs": hostinfo.vpnAddrs, "indexNumber": hostinfo.localIndexId, "remoteIndexNumber": hostinfo.remoteIndexId}).
  402. Debug("Hostmap hostInfo deleted")
  403. }
  404. if isLastHostinfo {
  405. // I have lost connectivity to my peers. My relay tunnel is likely broken. Mark the next
  406. // hops as 'Requested' so that new relay tunnels are created in the future.
  407. hm.unlockedDisestablishVpnAddrRelayFor(hostinfo)
  408. }
  409. // Clean up any local relay indexes for which I am acting as a relay hop
  410. for _, localRelayIdx := range hostinfo.relayState.CopyRelayForIdxs() {
  411. delete(hm.Relays, localRelayIdx)
  412. }
  413. }
  414. func (hm *HostMap) QueryIndex(index uint32) *HostInfo {
  415. hm.RLock()
  416. if h, ok := hm.Indexes[index]; ok {
  417. hm.RUnlock()
  418. return h
  419. } else {
  420. hm.RUnlock()
  421. return nil
  422. }
  423. }
  424. func (hm *HostMap) QueryRelayIndex(index uint32) *HostInfo {
  425. hm.RLock()
  426. if h, ok := hm.Relays[index]; ok {
  427. hm.RUnlock()
  428. return h
  429. } else {
  430. hm.RUnlock()
  431. return nil
  432. }
  433. }
  434. func (hm *HostMap) QueryReverseIndex(index uint32) *HostInfo {
  435. hm.RLock()
  436. if h, ok := hm.RemoteIndexes[index]; ok {
  437. hm.RUnlock()
  438. return h
  439. } else {
  440. hm.RUnlock()
  441. return nil
  442. }
  443. }
  444. func (hm *HostMap) QueryVpnAddr(vpnIp netip.Addr) *HostInfo {
  445. return hm.queryVpnAddr(vpnIp, nil)
  446. }
  447. func (hm *HostMap) QueryVpnAddrsRelayFor(targetIps []netip.Addr, relayHostIp netip.Addr) (*HostInfo, *Relay, error) {
  448. hm.RLock()
  449. defer hm.RUnlock()
  450. h, ok := hm.Hosts[relayHostIp]
  451. if !ok {
  452. return nil, nil, errors.New("unable to find host")
  453. }
  454. for h != nil {
  455. for _, targetIp := range targetIps {
  456. r, ok := h.relayState.QueryRelayForByIp(targetIp)
  457. if ok && r.State == Established {
  458. return h, r, nil
  459. }
  460. }
  461. h = h.next
  462. }
  463. return nil, nil, errors.New("unable to find host with relay")
  464. }
  465. func (hm *HostMap) unlockedDisestablishVpnAddrRelayFor(hi *HostInfo) {
  466. for _, relayHostIp := range hi.relayState.CopyRelayIps() {
  467. if h, ok := hm.Hosts[relayHostIp]; ok {
  468. for h != nil {
  469. h.relayState.UpdateRelayForByIpState(hi.vpnAddrs[0], Disestablished)
  470. h = h.next
  471. }
  472. }
  473. }
  474. for _, rs := range hi.relayState.CopyAllRelayFor() {
  475. if rs.Type == ForwardingType {
  476. if h, ok := hm.Hosts[rs.PeerAddr]; ok {
  477. for h != nil {
  478. h.relayState.UpdateRelayForByIpState(hi.vpnAddrs[0], Disestablished)
  479. h = h.next
  480. }
  481. }
  482. }
  483. }
  484. }
  485. func (hm *HostMap) queryVpnAddr(vpnIp netip.Addr, promoteIfce *Interface) *HostInfo {
  486. hm.RLock()
  487. if h, ok := hm.Hosts[vpnIp]; ok {
  488. hm.RUnlock()
  489. // Do not attempt promotion if you are a lighthouse
  490. if promoteIfce != nil && !promoteIfce.lightHouse.amLighthouse {
  491. h.TryPromoteBest(hm.GetPreferredRanges(), promoteIfce)
  492. }
  493. return h
  494. }
  495. hm.RUnlock()
  496. return nil
  497. }
  498. // unlockedAddHostInfo assumes you have a write-lock and will add a hostinfo object to the hostmap Indexes and RemoteIndexes maps.
  499. // If an entry exists for the Hosts table (vpnIp -> hostinfo) then the provided hostinfo will be made primary
  500. func (hm *HostMap) unlockedAddHostInfo(hostinfo *HostInfo, f *Interface) {
  501. if f.serveDns {
  502. remoteCert := hostinfo.ConnectionState.peerCert
  503. dnsR.Add(remoteCert.Certificate.Name()+".", hostinfo.vpnAddrs)
  504. }
  505. for _, addr := range hostinfo.vpnAddrs {
  506. hm.unlockedInnerAddHostInfo(addr, hostinfo, f)
  507. }
  508. hm.Indexes[hostinfo.localIndexId] = hostinfo
  509. hm.RemoteIndexes[hostinfo.remoteIndexId] = hostinfo
  510. if hm.l.Level >= logrus.DebugLevel {
  511. hm.l.WithField("hostMap", m{"vpnAddrs": hostinfo.vpnAddrs, "mapTotalSize": len(hm.Hosts),
  512. "hostinfo": m{"existing": true, "localIndexId": hostinfo.localIndexId, "vpnAddrs": hostinfo.vpnAddrs}}).
  513. Debug("Hostmap vpnIp added")
  514. }
  515. }
  516. func (hm *HostMap) unlockedInnerAddHostInfo(vpnAddr netip.Addr, hostinfo *HostInfo, f *Interface) {
  517. existing := hm.Hosts[vpnAddr]
  518. hm.Hosts[vpnAddr] = hostinfo
  519. if existing != nil && existing != hostinfo {
  520. hostinfo.next = existing
  521. existing.prev = hostinfo
  522. }
  523. i := 1
  524. check := hostinfo
  525. for check != nil {
  526. if i > MaxHostInfosPerVpnIp {
  527. hm.unlockedDeleteHostInfo(check)
  528. }
  529. check = check.next
  530. i++
  531. }
  532. }
  533. func (hm *HostMap) GetPreferredRanges() []netip.Prefix {
  534. //NOTE: if preferredRanges is ever not stored before a load this will fail to dereference a nil pointer
  535. return *hm.preferredRanges.Load()
  536. }
  537. func (hm *HostMap) ForEachVpnAddr(f controlEach) {
  538. hm.RLock()
  539. defer hm.RUnlock()
  540. for _, v := range hm.Hosts {
  541. f(v)
  542. }
  543. }
  544. func (hm *HostMap) ForEachIndex(f controlEach) {
  545. hm.RLock()
  546. defer hm.RUnlock()
  547. for _, v := range hm.Indexes {
  548. f(v)
  549. }
  550. }
  551. // TryPromoteBest handles re-querying lighthouses and probing for better paths
  552. // NOTE: It is an error to call this if you are a lighthouse since they should not roam clients!
  553. func (i *HostInfo) TryPromoteBest(preferredRanges []netip.Prefix, ifce *Interface) {
  554. c := i.promoteCounter.Add(1)
  555. if c%ifce.tryPromoteEvery.Load() == 0 {
  556. remote := i.remote
  557. // return early if we are already on a preferred remote
  558. if remote.IsValid() {
  559. rIP := remote.Addr()
  560. for _, l := range preferredRanges {
  561. if l.Contains(rIP) {
  562. return
  563. }
  564. }
  565. }
  566. i.remotes.ForEach(preferredRanges, func(addr netip.AddrPort, preferred bool) {
  567. if remote.IsValid() && (!addr.IsValid() || !preferred) {
  568. return
  569. }
  570. // Try to send a test packet to that host, this should
  571. // cause it to detect a roaming event and switch remotes
  572. ifce.sendTo(header.Test, header.TestRequest, i.ConnectionState, i, addr, []byte(""), make([]byte, 12, 12), make([]byte, mtu))
  573. })
  574. }
  575. // Re query our lighthouses for new remotes occasionally
  576. if c%ifce.reQueryEvery.Load() == 0 && ifce.lightHouse != nil {
  577. now := time.Now().UnixNano()
  578. if now < i.nextLHQuery.Load() {
  579. return
  580. }
  581. i.nextLHQuery.Store(now + ifce.reQueryWait.Load())
  582. ifce.lightHouse.QueryServer(i.vpnAddrs[0])
  583. }
  584. }
  585. func (i *HostInfo) GetCert() *cert.CachedCertificate {
  586. if i.ConnectionState != nil {
  587. return i.ConnectionState.peerCert
  588. }
  589. return nil
  590. }
  591. func (i *HostInfo) SetRemote(remote netip.AddrPort) {
  592. // We copy here because we likely got this remote from a source that reuses the object
  593. if i.remote != remote {
  594. i.remote = remote
  595. i.remotes.LearnRemote(i.vpnAddrs[0], remote)
  596. }
  597. }
  598. // SetRemoteIfPreferred returns true if the remote was changed. The lastRoam
  599. // time on the HostInfo will also be updated.
  600. func (i *HostInfo) SetRemoteIfPreferred(hm *HostMap, newRemote netip.AddrPort) bool {
  601. if !newRemote.IsValid() {
  602. // relays have nil udp Addrs
  603. return false
  604. }
  605. currentRemote := i.remote
  606. if !currentRemote.IsValid() {
  607. i.SetRemote(newRemote)
  608. return true
  609. }
  610. // NOTE: We do this loop here instead of calling `isPreferred` in
  611. // remote_list.go so that we only have to loop over preferredRanges once.
  612. newIsPreferred := false
  613. for _, l := range hm.GetPreferredRanges() {
  614. // return early if we are already on a preferred remote
  615. if l.Contains(currentRemote.Addr()) {
  616. return false
  617. }
  618. if l.Contains(newRemote.Addr()) {
  619. newIsPreferred = true
  620. }
  621. }
  622. if newIsPreferred {
  623. // Consider this a roaming event
  624. i.lastRoam = time.Now()
  625. i.lastRoamRemote = currentRemote
  626. i.SetRemote(newRemote)
  627. return true
  628. }
  629. return false
  630. }
  631. func (i *HostInfo) buildNetworks(myVpnNetworksTable *bart.Lite, networks, unsafeNetworks []netip.Prefix) {
  632. if len(networks) == 1 && len(unsafeNetworks) == 0 {
  633. if myVpnNetworksTable.Contains(networks[0].Addr()) {
  634. return // Simple case, no CIDRTree needed
  635. }
  636. }
  637. i.networks = new(bart.Table[NetworkType])
  638. for _, network := range networks {
  639. var nwType NetworkType
  640. if myVpnNetworksTable.Contains(network.Addr()) {
  641. nwType = NetworkTypeVPN
  642. } else {
  643. nwType = NetworkTypeVPNPeer
  644. }
  645. nprefix := netip.PrefixFrom(network.Addr(), network.Addr().BitLen())
  646. i.networks.Insert(nprefix, nwType)
  647. }
  648. for _, network := range unsafeNetworks {
  649. i.networks.Insert(network, NetworkTypeUnsafe)
  650. }
  651. }
  652. func (i *HostInfo) logger(l *logrus.Logger) *logrus.Entry {
  653. if i == nil {
  654. return logrus.NewEntry(l)
  655. }
  656. li := l.WithField("vpnAddrs", i.vpnAddrs).
  657. WithField("localIndex", i.localIndexId).
  658. WithField("remoteIndex", i.remoteIndexId)
  659. if connState := i.ConnectionState; connState != nil {
  660. if peerCert := connState.peerCert; peerCert != nil {
  661. li = li.WithField("certName", peerCert.Certificate.Name())
  662. }
  663. }
  664. return li
  665. }
  666. // Utility functions
  667. func localAddrs(l *logrus.Logger, allowList *LocalAllowList) []netip.Addr {
  668. //FIXME: This function is pretty garbage
  669. var finalAddrs []netip.Addr
  670. ifaces, _ := net.Interfaces()
  671. for _, i := range ifaces {
  672. allow := allowList.AllowName(i.Name)
  673. if l.Level >= logrus.TraceLevel {
  674. l.WithField("interfaceName", i.Name).WithField("allow", allow).Trace("localAllowList.AllowName")
  675. }
  676. if !allow {
  677. continue
  678. }
  679. addrs, _ := i.Addrs()
  680. for _, rawAddr := range addrs {
  681. var addr netip.Addr
  682. switch v := rawAddr.(type) {
  683. case *net.IPNet:
  684. //continue
  685. addr, _ = netip.AddrFromSlice(v.IP)
  686. case *net.IPAddr:
  687. addr, _ = netip.AddrFromSlice(v.IP)
  688. }
  689. if !addr.IsValid() {
  690. if l.Level >= logrus.DebugLevel {
  691. l.WithField("localAddr", rawAddr).Debug("addr was invalid")
  692. }
  693. continue
  694. }
  695. addr = addr.Unmap()
  696. if addr.IsLoopback() == false && addr.IsLinkLocalUnicast() == false {
  697. isAllowed := allowList.Allow(addr)
  698. if l.Level >= logrus.TraceLevel {
  699. l.WithField("localAddr", addr).WithField("allowed", isAllowed).Trace("localAllowList.Allow")
  700. }
  701. if !isAllowed {
  702. continue
  703. }
  704. finalAddrs = append(finalAddrs, addr)
  705. }
  706. }
  707. }
  708. return finalAddrs
  709. }