hostmap.go 23 KB

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