hostmap.go 23 KB

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