hostmap.go 22 KB

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