hostmap.go 22 KB

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