hostmap.go 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814
  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 HostInfo struct {
  190. remote netip.AddrPort
  191. remotes *RemoteList
  192. promoteCounter atomic.Uint32
  193. ConnectionState *ConnectionState
  194. remoteIndexId uint32
  195. localIndexId uint32
  196. // vpnAddrs is a list of vpn addresses assigned to this host
  197. vpnAddrs []netip.Addr
  198. // networks is a combination of specific vpn addresses (not prefixes!) and full unsafe networks assigned to this host.
  199. networks *bart.Lite
  200. relayState RelayState
  201. // HandshakePacket records the packets used to create this hostinfo
  202. // We need these to avoid replayed handshake packets creating new hostinfos which causes churn
  203. HandshakePacket map[uint8][]byte
  204. // nextLHQuery is the earliest we can ask the lighthouse for new information.
  205. // This is used to limit lighthouse re-queries in chatty clients
  206. nextLHQuery atomic.Int64
  207. // lastRebindCount is the other side of Interface.rebindCount, if these values don't match then we need to ask LH
  208. // for a punch from the remote end of this tunnel. The goal being to prime their conntrack for our traffic just like
  209. // with a handshake
  210. lastRebindCount int8
  211. // lastHandshakeTime records the time the remote side told us about at the stage when the handshake was completed locally
  212. // Stage 1 packet will contain it if I am a responder, stage 2 packet if I am an initiator
  213. // This is used to avoid an attack where a handshake packet is replayed after some time
  214. lastHandshakeTime uint64
  215. lastRoam time.Time
  216. lastRoamRemote netip.AddrPort
  217. // Used to track other hostinfos for this vpn ip since only 1 can be primary
  218. // Synchronised via hostmap lock and not the hostinfo lock.
  219. next, prev *HostInfo
  220. //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
  221. in, out, pendingDeletion atomic.Bool
  222. // lastUsed tracks the last time ConnectionManager checked the tunnel and it was in use.
  223. // This value will be behind against actual tunnel utilization in the hot path.
  224. // This should only be used by the ConnectionManagers ticker routine.
  225. lastUsed time.Time
  226. }
  227. type ViaSender struct {
  228. relayHI *HostInfo // relayHI is the host info object of the relay
  229. remoteIdx uint32 // remoteIdx is the index included in the header of the received packet
  230. relay *Relay // relay contains the rest of the relay information, including the PeerIP of the host trying to communicate with us.
  231. }
  232. type cachedPacket struct {
  233. messageType header.MessageType
  234. messageSubType header.MessageSubType
  235. callback packetCallback
  236. packet []byte
  237. }
  238. type packetCallback func(t header.MessageType, st header.MessageSubType, h *HostInfo, p, nb, out []byte)
  239. type cachedPacketMetrics struct {
  240. sent metrics.Counter
  241. dropped metrics.Counter
  242. }
  243. func NewHostMapFromConfig(l *logrus.Logger, c *config.C) *HostMap {
  244. hm := newHostMap(l)
  245. hm.reload(c, true)
  246. c.RegisterReloadCallback(func(c *config.C) {
  247. hm.reload(c, false)
  248. })
  249. l.WithField("preferredRanges", hm.GetPreferredRanges()).
  250. Info("Main HostMap created")
  251. return hm
  252. }
  253. func newHostMap(l *logrus.Logger) *HostMap {
  254. return &HostMap{
  255. Indexes: map[uint32]*HostInfo{},
  256. Relays: map[uint32]*HostInfo{},
  257. RemoteIndexes: map[uint32]*HostInfo{},
  258. Hosts: map[netip.Addr]*HostInfo{},
  259. l: l,
  260. }
  261. }
  262. func (hm *HostMap) reload(c *config.C, initial bool) {
  263. if initial || c.HasChanged("preferred_ranges") {
  264. var preferredRanges []netip.Prefix
  265. rawPreferredRanges := c.GetStringSlice("preferred_ranges", []string{})
  266. for _, rawPreferredRange := range rawPreferredRanges {
  267. preferredRange, err := netip.ParsePrefix(rawPreferredRange)
  268. if err != nil {
  269. hm.l.WithError(err).WithField("range", rawPreferredRanges).Warn("Failed to parse preferred ranges, ignoring")
  270. continue
  271. }
  272. preferredRanges = append(preferredRanges, preferredRange)
  273. }
  274. oldRanges := hm.preferredRanges.Swap(&preferredRanges)
  275. if !initial {
  276. hm.l.WithField("oldPreferredRanges", *oldRanges).WithField("newPreferredRanges", preferredRanges).Info("preferred_ranges changed")
  277. }
  278. }
  279. }
  280. // EmitStats reports host, index, and relay counts to the stats collection system
  281. func (hm *HostMap) EmitStats() {
  282. hm.RLock()
  283. hostLen := len(hm.Hosts)
  284. indexLen := len(hm.Indexes)
  285. remoteIndexLen := len(hm.RemoteIndexes)
  286. relaysLen := len(hm.Relays)
  287. hm.RUnlock()
  288. metrics.GetOrRegisterGauge("hostmap.main.hosts", nil).Update(int64(hostLen))
  289. metrics.GetOrRegisterGauge("hostmap.main.indexes", nil).Update(int64(indexLen))
  290. metrics.GetOrRegisterGauge("hostmap.main.remoteIndexes", nil).Update(int64(remoteIndexLen))
  291. metrics.GetOrRegisterGauge("hostmap.main.relayIndexes", nil).Update(int64(relaysLen))
  292. }
  293. // DeleteHostInfo will fully unlink the hostinfo and return true if it was the final hostinfo for this vpn ip
  294. func (hm *HostMap) DeleteHostInfo(hostinfo *HostInfo) bool {
  295. // Delete the host itself, ensuring it's not modified anymore
  296. hm.Lock()
  297. // If we have a previous or next hostinfo then we are not the last one for this vpn ip
  298. final := (hostinfo.next == nil && hostinfo.prev == nil)
  299. hm.unlockedDeleteHostInfo(hostinfo)
  300. hm.Unlock()
  301. return final
  302. }
  303. func (hm *HostMap) MakePrimary(hostinfo *HostInfo) {
  304. hm.Lock()
  305. defer hm.Unlock()
  306. hm.unlockedMakePrimary(hostinfo)
  307. }
  308. func (hm *HostMap) unlockedMakePrimary(hostinfo *HostInfo) {
  309. // Get the current primary, if it exists
  310. oldHostinfo := hm.Hosts[hostinfo.vpnAddrs[0]]
  311. // Every address in the hostinfo gets elevated to primary
  312. for _, vpnAddr := range hostinfo.vpnAddrs {
  313. //NOTE: It is possible that we leave a dangling hostinfo here but connection manager works on
  314. // indexes so it should be fine.
  315. hm.Hosts[vpnAddr] = hostinfo
  316. }
  317. // If we are already primary then we won't bother re-linking
  318. if oldHostinfo == hostinfo {
  319. return
  320. }
  321. // Unlink this hostinfo
  322. if hostinfo.prev != nil {
  323. hostinfo.prev.next = hostinfo.next
  324. }
  325. if hostinfo.next != nil {
  326. hostinfo.next.prev = hostinfo.prev
  327. }
  328. // If there wasn't a previous primary then clear out any links
  329. if oldHostinfo == nil {
  330. hostinfo.next = nil
  331. hostinfo.prev = nil
  332. return
  333. }
  334. // Relink the hostinfo as primary
  335. hostinfo.next = oldHostinfo
  336. oldHostinfo.prev = hostinfo
  337. hostinfo.prev = nil
  338. }
  339. func (hm *HostMap) unlockedDeleteHostInfo(hostinfo *HostInfo) {
  340. for _, addr := range hostinfo.vpnAddrs {
  341. h := hm.Hosts[addr]
  342. for h != nil {
  343. if h == hostinfo {
  344. hm.unlockedInnerDeleteHostInfo(h, addr)
  345. }
  346. h = h.next
  347. }
  348. }
  349. }
  350. func (hm *HostMap) unlockedInnerDeleteHostInfo(hostinfo *HostInfo, addr netip.Addr) {
  351. primary, ok := hm.Hosts[addr]
  352. isLastHostinfo := hostinfo.next == nil && hostinfo.prev == nil
  353. if ok && primary == hostinfo {
  354. // The vpn addr pointer points to the same hostinfo as the local index id, we can remove it
  355. delete(hm.Hosts, addr)
  356. if len(hm.Hosts) == 0 {
  357. hm.Hosts = map[netip.Addr]*HostInfo{}
  358. }
  359. if hostinfo.next != nil {
  360. // We had more than 1 hostinfo at this vpn addr, promote the next in the list to primary
  361. hm.Hosts[addr] = hostinfo.next
  362. // It is primary, there is no previous hostinfo now
  363. hostinfo.next.prev = nil
  364. }
  365. } else {
  366. // Relink if we were in the middle of multiple hostinfos for this vpn addr
  367. if hostinfo.prev != nil {
  368. hostinfo.prev.next = hostinfo.next
  369. }
  370. if hostinfo.next != nil {
  371. hostinfo.next.prev = hostinfo.prev
  372. }
  373. }
  374. hostinfo.next = nil
  375. hostinfo.prev = nil
  376. // The remote index uses index ids outside our control so lets make sure we are only removing
  377. // the remote index pointer here if it points to the hostinfo we are deleting
  378. hostinfo2, ok := hm.RemoteIndexes[hostinfo.remoteIndexId]
  379. if ok && hostinfo2 == hostinfo {
  380. delete(hm.RemoteIndexes, hostinfo.remoteIndexId)
  381. if len(hm.RemoteIndexes) == 0 {
  382. hm.RemoteIndexes = map[uint32]*HostInfo{}
  383. }
  384. }
  385. delete(hm.Indexes, hostinfo.localIndexId)
  386. if len(hm.Indexes) == 0 {
  387. hm.Indexes = map[uint32]*HostInfo{}
  388. }
  389. if hm.l.Level >= logrus.DebugLevel {
  390. hm.l.WithField("hostMap", m{"mapTotalSize": len(hm.Hosts),
  391. "vpnAddrs": hostinfo.vpnAddrs, "indexNumber": hostinfo.localIndexId, "remoteIndexNumber": hostinfo.remoteIndexId}).
  392. Debug("Hostmap hostInfo deleted")
  393. }
  394. if isLastHostinfo {
  395. // I have lost connectivity to my peers. My relay tunnel is likely broken. Mark the next
  396. // hops as 'Requested' so that new relay tunnels are created in the future.
  397. hm.unlockedDisestablishVpnAddrRelayFor(hostinfo)
  398. }
  399. // Clean up any local relay indexes for which I am acting as a relay hop
  400. for _, localRelayIdx := range hostinfo.relayState.CopyRelayForIdxs() {
  401. delete(hm.Relays, localRelayIdx)
  402. }
  403. }
  404. func (hm *HostMap) QueryIndex(index uint32) *HostInfo {
  405. hm.RLock()
  406. if h, ok := hm.Indexes[index]; ok {
  407. hm.RUnlock()
  408. return h
  409. } else {
  410. hm.RUnlock()
  411. return nil
  412. }
  413. }
  414. func (hm *HostMap) QueryRelayIndex(index uint32) *HostInfo {
  415. hm.RLock()
  416. if h, ok := hm.Relays[index]; ok {
  417. hm.RUnlock()
  418. return h
  419. } else {
  420. hm.RUnlock()
  421. return nil
  422. }
  423. }
  424. func (hm *HostMap) QueryReverseIndex(index uint32) *HostInfo {
  425. hm.RLock()
  426. if h, ok := hm.RemoteIndexes[index]; ok {
  427. hm.RUnlock()
  428. return h
  429. } else {
  430. hm.RUnlock()
  431. return nil
  432. }
  433. }
  434. func (hm *HostMap) QueryVpnAddr(vpnIp netip.Addr) *HostInfo {
  435. return hm.queryVpnAddr(vpnIp, nil)
  436. }
  437. func (hm *HostMap) QueryVpnAddrsRelayFor(targetIps []netip.Addr, relayHostIp netip.Addr) (*HostInfo, *Relay, error) {
  438. hm.RLock()
  439. defer hm.RUnlock()
  440. h, ok := hm.Hosts[relayHostIp]
  441. if !ok {
  442. return nil, nil, errors.New("unable to find host")
  443. }
  444. for h != nil {
  445. for _, targetIp := range targetIps {
  446. r, ok := h.relayState.QueryRelayForByIp(targetIp)
  447. if ok && r.State == Established {
  448. return h, r, nil
  449. }
  450. }
  451. h = h.next
  452. }
  453. return nil, nil, errors.New("unable to find host with relay")
  454. }
  455. func (hm *HostMap) unlockedDisestablishVpnAddrRelayFor(hi *HostInfo) {
  456. for _, relayHostIp := range hi.relayState.CopyRelayIps() {
  457. if h, ok := hm.Hosts[relayHostIp]; ok {
  458. for h != nil {
  459. h.relayState.UpdateRelayForByIpState(hi.vpnAddrs[0], Disestablished)
  460. h = h.next
  461. }
  462. }
  463. }
  464. for _, rs := range hi.relayState.CopyAllRelayFor() {
  465. if rs.Type == ForwardingType {
  466. if h, ok := hm.Hosts[rs.PeerAddr]; ok {
  467. for h != nil {
  468. h.relayState.UpdateRelayForByIpState(hi.vpnAddrs[0], Disestablished)
  469. h = h.next
  470. }
  471. }
  472. }
  473. }
  474. }
  475. func (hm *HostMap) queryVpnAddr(vpnIp netip.Addr, promoteIfce *Interface) *HostInfo {
  476. hm.RLock()
  477. if h, ok := hm.Hosts[vpnIp]; ok {
  478. hm.RUnlock()
  479. // Do not attempt promotion if you are a lighthouse
  480. if promoteIfce != nil && !promoteIfce.lightHouse.amLighthouse {
  481. h.TryPromoteBest(hm.GetPreferredRanges(), promoteIfce)
  482. }
  483. return h
  484. }
  485. hm.RUnlock()
  486. return nil
  487. }
  488. // unlockedAddHostInfo assumes you have a write-lock and will add a hostinfo object to the hostmap Indexes and RemoteIndexes maps.
  489. // If an entry exists for the Hosts table (vpnIp -> hostinfo) then the provided hostinfo will be made primary
  490. func (hm *HostMap) unlockedAddHostInfo(hostinfo *HostInfo, f *Interface) {
  491. if f.serveDns {
  492. remoteCert := hostinfo.ConnectionState.peerCert
  493. dnsR.Add(remoteCert.Certificate.Name()+".", hostinfo.vpnAddrs)
  494. }
  495. for _, addr := range hostinfo.vpnAddrs {
  496. hm.unlockedInnerAddHostInfo(addr, hostinfo, f)
  497. }
  498. hm.Indexes[hostinfo.localIndexId] = hostinfo
  499. hm.RemoteIndexes[hostinfo.remoteIndexId] = hostinfo
  500. if hm.l.Level >= logrus.DebugLevel {
  501. hm.l.WithField("hostMap", m{"vpnAddrs": hostinfo.vpnAddrs, "mapTotalSize": len(hm.Hosts),
  502. "hostinfo": m{"existing": true, "localIndexId": hostinfo.localIndexId, "vpnAddrs": hostinfo.vpnAddrs}}).
  503. Debug("Hostmap vpnIp added")
  504. }
  505. }
  506. func (hm *HostMap) unlockedInnerAddHostInfo(vpnAddr netip.Addr, hostinfo *HostInfo, f *Interface) {
  507. existing := hm.Hosts[vpnAddr]
  508. hm.Hosts[vpnAddr] = hostinfo
  509. if existing != nil && existing != hostinfo {
  510. hostinfo.next = existing
  511. existing.prev = hostinfo
  512. }
  513. i := 1
  514. check := hostinfo
  515. for check != nil {
  516. if i > MaxHostInfosPerVpnIp {
  517. hm.unlockedDeleteHostInfo(check)
  518. }
  519. check = check.next
  520. i++
  521. }
  522. }
  523. func (hm *HostMap) GetPreferredRanges() []netip.Prefix {
  524. //NOTE: if preferredRanges is ever not stored before a load this will fail to dereference a nil pointer
  525. return *hm.preferredRanges.Load()
  526. }
  527. func (hm *HostMap) ForEachVpnAddr(f controlEach) {
  528. hm.RLock()
  529. defer hm.RUnlock()
  530. for _, v := range hm.Hosts {
  531. f(v)
  532. }
  533. }
  534. func (hm *HostMap) ForEachIndex(f controlEach) {
  535. hm.RLock()
  536. defer hm.RUnlock()
  537. for _, v := range hm.Indexes {
  538. f(v)
  539. }
  540. }
  541. // TryPromoteBest handles re-querying lighthouses and probing for better paths
  542. // NOTE: It is an error to call this if you are a lighthouse since they should not roam clients!
  543. func (i *HostInfo) TryPromoteBest(preferredRanges []netip.Prefix, ifce *Interface) {
  544. c := i.promoteCounter.Add(1)
  545. if c%ifce.tryPromoteEvery.Load() == 0 {
  546. remote := i.remote
  547. // return early if we are already on a preferred remote
  548. if remote.IsValid() {
  549. rIP := remote.Addr()
  550. for _, l := range preferredRanges {
  551. if l.Contains(rIP) {
  552. return
  553. }
  554. }
  555. }
  556. i.remotes.ForEach(preferredRanges, func(addr netip.AddrPort, preferred bool) {
  557. if remote.IsValid() && (!addr.IsValid() || !preferred) {
  558. return
  559. }
  560. // Try to send a test packet to that host, this should
  561. // cause it to detect a roaming event and switch remotes
  562. ifce.sendTo(header.Test, header.TestRequest, i.ConnectionState, i, addr, []byte(""), make([]byte, 12, 12), make([]byte, mtu))
  563. })
  564. }
  565. // Re query our lighthouses for new remotes occasionally
  566. if c%ifce.reQueryEvery.Load() == 0 && ifce.lightHouse != nil {
  567. now := time.Now().UnixNano()
  568. if now < i.nextLHQuery.Load() {
  569. return
  570. }
  571. i.nextLHQuery.Store(now + ifce.reQueryWait.Load())
  572. ifce.lightHouse.QueryServer(i.vpnAddrs[0])
  573. }
  574. }
  575. func (i *HostInfo) GetCert() *cert.CachedCertificate {
  576. if i.ConnectionState != nil {
  577. return i.ConnectionState.peerCert
  578. }
  579. return nil
  580. }
  581. func (i *HostInfo) SetRemote(remote netip.AddrPort) {
  582. // We copy here because we likely got this remote from a source that reuses the object
  583. if i.remote != remote {
  584. i.remote = remote
  585. i.remotes.LearnRemote(i.vpnAddrs[0], remote)
  586. }
  587. }
  588. // SetRemoteIfPreferred returns true if the remote was changed. The lastRoam
  589. // time on the HostInfo will also be updated.
  590. func (i *HostInfo) SetRemoteIfPreferred(hm *HostMap, newRemote netip.AddrPort) bool {
  591. if !newRemote.IsValid() {
  592. // relays have nil udp Addrs
  593. return false
  594. }
  595. currentRemote := i.remote
  596. if !currentRemote.IsValid() {
  597. i.SetRemote(newRemote)
  598. return true
  599. }
  600. // NOTE: We do this loop here instead of calling `isPreferred` in
  601. // remote_list.go so that we only have to loop over preferredRanges once.
  602. newIsPreferred := false
  603. for _, l := range hm.GetPreferredRanges() {
  604. // return early if we are already on a preferred remote
  605. if l.Contains(currentRemote.Addr()) {
  606. return false
  607. }
  608. if l.Contains(newRemote.Addr()) {
  609. newIsPreferred = true
  610. }
  611. }
  612. if newIsPreferred {
  613. // Consider this a roaming event
  614. i.lastRoam = time.Now()
  615. i.lastRoamRemote = currentRemote
  616. i.SetRemote(newRemote)
  617. return true
  618. }
  619. return false
  620. }
  621. func (i *HostInfo) buildNetworks(networks, unsafeNetworks []netip.Prefix) {
  622. if len(networks) == 1 && len(unsafeNetworks) == 0 {
  623. // Simple case, no CIDRTree needed
  624. return
  625. }
  626. i.networks = new(bart.Lite)
  627. for _, network := range networks {
  628. nprefix := netip.PrefixFrom(network.Addr(), network.Addr().BitLen())
  629. i.networks.Insert(nprefix)
  630. }
  631. for _, network := range unsafeNetworks {
  632. i.networks.Insert(network)
  633. }
  634. }
  635. func (i *HostInfo) logger(l *logrus.Logger) *logrus.Entry {
  636. if i == nil {
  637. return logrus.NewEntry(l)
  638. }
  639. li := l.WithField("vpnAddrs", i.vpnAddrs).
  640. WithField("localIndex", i.localIndexId).
  641. WithField("remoteIndex", i.remoteIndexId)
  642. if connState := i.ConnectionState; connState != nil {
  643. if peerCert := connState.peerCert; peerCert != nil {
  644. li = li.WithField("certName", peerCert.Certificate.Name())
  645. }
  646. }
  647. return li
  648. }
  649. // Utility functions
  650. func localAddrs(l *logrus.Logger, allowList *LocalAllowList) []netip.Addr {
  651. //FIXME: This function is pretty garbage
  652. var finalAddrs []netip.Addr
  653. ifaces, _ := net.Interfaces()
  654. for _, i := range ifaces {
  655. allow := allowList.AllowName(i.Name)
  656. if l.Level >= logrus.TraceLevel {
  657. l.WithField("interfaceName", i.Name).WithField("allow", allow).Trace("localAllowList.AllowName")
  658. }
  659. if !allow {
  660. continue
  661. }
  662. addrs, _ := i.Addrs()
  663. for _, rawAddr := range addrs {
  664. var addr netip.Addr
  665. switch v := rawAddr.(type) {
  666. case *net.IPNet:
  667. //continue
  668. addr, _ = netip.AddrFromSlice(v.IP)
  669. case *net.IPAddr:
  670. addr, _ = netip.AddrFromSlice(v.IP)
  671. }
  672. if !addr.IsValid() {
  673. if l.Level >= logrus.DebugLevel {
  674. l.WithField("localAddr", rawAddr).Debug("addr was invalid")
  675. }
  676. continue
  677. }
  678. addr = addr.Unmap()
  679. if addr.IsLoopback() == false && addr.IsLinkLocalUnicast() == false {
  680. isAllowed := allowList.Allow(addr)
  681. if l.Level >= logrus.TraceLevel {
  682. l.WithField("localAddr", addr).WithField("allowed", isAllowed).Trace("localAllowList.Allow")
  683. }
  684. if !isAllowed {
  685. continue
  686. }
  687. finalAddrs = append(finalAddrs, addr)
  688. }
  689. }
  690. }
  691. return finalAddrs
  692. }