hostmap.go 22 KB

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