hostmap.go 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809
  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 ProbeLen = 100
  18. const defaultPromoteEvery = 1000 // Count of packets sent before we try moving a tunnel to a preferred underlay ip address
  19. const defaultReQueryEvery = 5000 // Count of packets sent before re-querying a hostinfo to the lighthouse
  20. const defaultReQueryWait = time.Minute // Minimum amount of seconds to wait before re-querying a hostinfo the lighthouse. Evaluated every ReQueryEvery
  21. const MaxRemotes = 10
  22. const maxRecvError = 4
  23. // MaxHostInfosPerVpnIp is the max number of hostinfos we will track for a given vpn ip
  24. // 5 allows for an initial handshake and each host pair re-handshaking twice
  25. const MaxHostInfosPerVpnIp = 5
  26. // How long we should prevent roaming back to the previous IP.
  27. // This helps prevent flapping due to packets already in flight
  28. const RoamingSuppressSeconds = 2
  29. const (
  30. Requested = iota
  31. PeerRequested
  32. Established
  33. Disestablished
  34. )
  35. const (
  36. Unknowntype = iota
  37. ForwardingType
  38. TerminalType
  39. )
  40. type Relay struct {
  41. Type int
  42. State int
  43. LocalIndex uint32
  44. RemoteIndex uint32
  45. PeerIp netip.Addr
  46. }
  47. type HostMap struct {
  48. sync.RWMutex //Because we concurrently read and write to our maps
  49. Indexes map[uint32]*HostInfo
  50. Relays map[uint32]*HostInfo // Maps a Relay IDX to a Relay HostInfo object
  51. RemoteIndexes map[uint32]*HostInfo
  52. Hosts map[netip.Addr]*HostInfo
  53. preferredRanges atomic.Pointer[[]netip.Prefix]
  54. vpnCIDR netip.Prefix
  55. l *logrus.Logger
  56. }
  57. // For synchronization, treat the pointed-to Relay struct as immutable. To edit the Relay
  58. // struct, make a copy of an existing value, edit the fileds in the copy, and
  59. // then store a pointer to the new copy in both realyForBy* maps.
  60. type RelayState struct {
  61. sync.RWMutex
  62. relays []netip.Addr // Ordered set of VpnIp's of Hosts to use as relays to access this peer
  63. relayForByIp map[netip.Addr]*Relay // Maps VpnIps 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.relayForByIp[vpnIp]; ok {
  80. newRelay := *r
  81. newRelay.State = state
  82. rs.relayForByIp[newRelay.PeerIp] = &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.relayForByIp[newRelay.PeerIp] = &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) GetRelayForByIp(ip netip.Addr) (*Relay, bool) {
  106. rs.RLock()
  107. defer rs.RUnlock()
  108. r, ok := rs.relayForByIp[ip]
  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.relayForByIp))
  129. for relayIp := range rs.relayForByIp {
  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.relayForByIp[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.relayForByIp[r.PeerIp] = &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.relayForByIp[r.PeerIp] = &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.relayForByIp[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.relayForByIp[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. vpnIp netip.Addr
  197. recvError atomic.Uint32
  198. remoteCidr *bart.Table[struct{}]
  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. //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
  220. in, out, pendingDeletion atomic.Bool
  221. // lastUsed tracks the last time ConnectionManager checked the tunnel and it was in use.
  222. // This value will be behind against actual tunnel utilization in the hot path.
  223. // This should only be used by the ConnectionManagers ticker routine.
  224. lastUsed time.Time
  225. }
  226. type ViaSender struct {
  227. relayHI *HostInfo // relayHI is the host info object of the relay
  228. remoteIdx uint32 // remoteIdx is the index included in the header of the received packet
  229. relay *Relay // relay contains the rest of the relay information, including the PeerIP of the host trying to communicate with us.
  230. }
  231. type cachedPacket struct {
  232. messageType header.MessageType
  233. messageSubType header.MessageSubType
  234. callback packetCallback
  235. packet []byte
  236. }
  237. type packetCallback func(t header.MessageType, st header.MessageSubType, h *HostInfo, p, nb, out []byte)
  238. type cachedPacketMetrics struct {
  239. sent metrics.Counter
  240. dropped metrics.Counter
  241. }
  242. func NewHostMapFromConfig(l *logrus.Logger, vpnCIDR netip.Prefix, c *config.C) *HostMap {
  243. hm := newHostMap(l, vpnCIDR)
  244. hm.reload(c, true)
  245. c.RegisterReloadCallback(func(c *config.C) {
  246. hm.reload(c, false)
  247. })
  248. l.WithField("network", hm.vpnCIDR.String()).
  249. WithField("preferredRanges", hm.GetPreferredRanges()).
  250. Info("Main HostMap created")
  251. return hm
  252. }
  253. func newHostMap(l *logrus.Logger, vpnCIDR netip.Prefix) *HostMap {
  254. return &HostMap{
  255. Indexes: map[uint32]*HostInfo{},
  256. Relays: map[uint32]*HostInfo{},
  257. RemoteIndexes: map[uint32]*HostInfo{},
  258. Hosts: map[netip.Addr]*HostInfo{},
  259. vpnCIDR: vpnCIDR,
  260. l: l,
  261. }
  262. }
  263. func (hm *HostMap) reload(c *config.C, initial bool) {
  264. if initial || c.HasChanged("preferred_ranges") {
  265. var preferredRanges []netip.Prefix
  266. rawPreferredRanges := c.GetStringSlice("preferred_ranges", []string{})
  267. for _, rawPreferredRange := range rawPreferredRanges {
  268. preferredRange, err := netip.ParsePrefix(rawPreferredRange)
  269. if err != nil {
  270. hm.l.WithError(err).WithField("range", rawPreferredRanges).Warn("Failed to parse preferred ranges, ignoring")
  271. continue
  272. }
  273. preferredRanges = append(preferredRanges, preferredRange)
  274. }
  275. oldRanges := hm.preferredRanges.Swap(&preferredRanges)
  276. if !initial {
  277. hm.l.WithField("oldPreferredRanges", *oldRanges).WithField("newPreferredRanges", preferredRanges).Info("preferred_ranges changed")
  278. }
  279. }
  280. }
  281. // EmitStats reports host, index, and relay counts to the stats collection system
  282. func (hm *HostMap) EmitStats() {
  283. hm.RLock()
  284. hostLen := len(hm.Hosts)
  285. indexLen := len(hm.Indexes)
  286. remoteIndexLen := len(hm.RemoteIndexes)
  287. relaysLen := len(hm.Relays)
  288. hm.RUnlock()
  289. metrics.GetOrRegisterGauge("hostmap.main.hosts", nil).Update(int64(hostLen))
  290. metrics.GetOrRegisterGauge("hostmap.main.indexes", nil).Update(int64(indexLen))
  291. metrics.GetOrRegisterGauge("hostmap.main.remoteIndexes", nil).Update(int64(remoteIndexLen))
  292. metrics.GetOrRegisterGauge("hostmap.main.relayIndexes", nil).Update(int64(relaysLen))
  293. }
  294. func (hm *HostMap) RemoveRelay(localIdx uint32) {
  295. hm.Lock()
  296. _, ok := hm.Relays[localIdx]
  297. if !ok {
  298. hm.Unlock()
  299. return
  300. }
  301. delete(hm.Relays, localIdx)
  302. hm.Unlock()
  303. }
  304. // DeleteHostInfo will fully unlink the hostinfo and return true if it was the final hostinfo for this vpn ip
  305. func (hm *HostMap) DeleteHostInfo(hostinfo *HostInfo) bool {
  306. // Delete the host itself, ensuring it's not modified anymore
  307. hm.Lock()
  308. // If we have a previous or next hostinfo then we are not the last one for this vpn ip
  309. final := (hostinfo.next == nil && hostinfo.prev == nil)
  310. hm.unlockedDeleteHostInfo(hostinfo)
  311. hm.Unlock()
  312. return final
  313. }
  314. func (hm *HostMap) MakePrimary(hostinfo *HostInfo) {
  315. hm.Lock()
  316. defer hm.Unlock()
  317. hm.unlockedMakePrimary(hostinfo)
  318. }
  319. func (hm *HostMap) unlockedMakePrimary(hostinfo *HostInfo) {
  320. oldHostinfo := hm.Hosts[hostinfo.vpnIp]
  321. if oldHostinfo == hostinfo {
  322. return
  323. }
  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. hm.Hosts[hostinfo.vpnIp] = hostinfo
  331. if oldHostinfo == nil {
  332. return
  333. }
  334. hostinfo.next = oldHostinfo
  335. oldHostinfo.prev = hostinfo
  336. hostinfo.prev = nil
  337. }
  338. func (hm *HostMap) unlockedDeleteHostInfo(hostinfo *HostInfo) {
  339. primary, ok := hm.Hosts[hostinfo.vpnIp]
  340. isLastHostinfo := hostinfo.next == nil && hostinfo.prev == nil
  341. if ok && primary == hostinfo {
  342. // The vpnIp pointer points to the same hostinfo as the local index id, we can remove it
  343. delete(hm.Hosts, hostinfo.vpnIp)
  344. if len(hm.Hosts) == 0 {
  345. hm.Hosts = map[netip.Addr]*HostInfo{}
  346. }
  347. if hostinfo.next != nil {
  348. // We had more than 1 hostinfo at this vpnip, promote the next in the list to primary
  349. hm.Hosts[hostinfo.vpnIp] = hostinfo.next
  350. // It is primary, there is no previous hostinfo now
  351. hostinfo.next.prev = nil
  352. }
  353. } else {
  354. // Relink if we were in the middle of multiple hostinfos for this vpn ip
  355. if hostinfo.prev != nil {
  356. hostinfo.prev.next = hostinfo.next
  357. }
  358. if hostinfo.next != nil {
  359. hostinfo.next.prev = hostinfo.prev
  360. }
  361. }
  362. hostinfo.next = nil
  363. hostinfo.prev = nil
  364. // The remote index uses index ids outside our control so lets make sure we are only removing
  365. // the remote index pointer here if it points to the hostinfo we are deleting
  366. hostinfo2, ok := hm.RemoteIndexes[hostinfo.remoteIndexId]
  367. if ok && hostinfo2 == hostinfo {
  368. delete(hm.RemoteIndexes, hostinfo.remoteIndexId)
  369. if len(hm.RemoteIndexes) == 0 {
  370. hm.RemoteIndexes = map[uint32]*HostInfo{}
  371. }
  372. }
  373. delete(hm.Indexes, hostinfo.localIndexId)
  374. if len(hm.Indexes) == 0 {
  375. hm.Indexes = map[uint32]*HostInfo{}
  376. }
  377. if hm.l.Level >= logrus.DebugLevel {
  378. hm.l.WithField("hostMap", m{"mapTotalSize": len(hm.Hosts),
  379. "vpnIp": hostinfo.vpnIp, "indexNumber": hostinfo.localIndexId, "remoteIndexNumber": hostinfo.remoteIndexId}).
  380. Debug("Hostmap hostInfo deleted")
  381. }
  382. if isLastHostinfo {
  383. // I have lost connectivity to my peers. My relay tunnel is likely broken. Mark the next
  384. // hops as 'Disestablished' so that new relay tunnels are created in the future.
  385. hm.unlockedDisestablishVpnAddrRelayFor(hostinfo)
  386. }
  387. // Clean up any local relay indexes for which I am acting as a relay hop
  388. for _, localRelayIdx := range hostinfo.relayState.CopyRelayForIdxs() {
  389. delete(hm.Relays, localRelayIdx)
  390. }
  391. }
  392. func (hm *HostMap) QueryIndex(index uint32) *HostInfo {
  393. hm.RLock()
  394. if h, ok := hm.Indexes[index]; ok {
  395. hm.RUnlock()
  396. return h
  397. } else {
  398. hm.RUnlock()
  399. return nil
  400. }
  401. }
  402. func (hm *HostMap) QueryRelayIndex(index uint32) *HostInfo {
  403. hm.RLock()
  404. if h, ok := hm.Relays[index]; ok {
  405. hm.RUnlock()
  406. return h
  407. } else {
  408. hm.RUnlock()
  409. return nil
  410. }
  411. }
  412. func (hm *HostMap) QueryReverseIndex(index uint32) *HostInfo {
  413. hm.RLock()
  414. if h, ok := hm.RemoteIndexes[index]; ok {
  415. hm.RUnlock()
  416. return h
  417. } else {
  418. hm.RUnlock()
  419. return nil
  420. }
  421. }
  422. func (hm *HostMap) QueryVpnIp(vpnIp netip.Addr) *HostInfo {
  423. return hm.queryVpnIp(vpnIp, nil)
  424. }
  425. func (hm *HostMap) QueryVpnIpRelayFor(targetIp, relayHostIp netip.Addr) (*HostInfo, *Relay, error) {
  426. hm.RLock()
  427. defer hm.RUnlock()
  428. h, ok := hm.Hosts[relayHostIp]
  429. if !ok {
  430. return nil, nil, errors.New("unable to find host")
  431. }
  432. for h != nil {
  433. r, ok := h.relayState.QueryRelayForByIp(targetIp)
  434. if ok && r.State == Established {
  435. return h, r, nil
  436. }
  437. h = h.next
  438. }
  439. return nil, nil, errors.New("unable to find host with relay")
  440. }
  441. func (hm *HostMap) unlockedDisestablishVpnAddrRelayFor(hi *HostInfo) {
  442. for _, relayHostIp := range hi.relayState.CopyRelayIps() {
  443. if h, ok := hm.Hosts[relayHostIp]; ok {
  444. for h != nil {
  445. h.relayState.UpdateRelayForByIpState(hi.vpnIp, Disestablished)
  446. h = h.next
  447. }
  448. }
  449. }
  450. for _, rs := range hi.relayState.CopyAllRelayFor() {
  451. if rs.Type == ForwardingType {
  452. if h, ok := hm.Hosts[rs.PeerIp]; ok {
  453. for h != nil {
  454. h.relayState.UpdateRelayForByIpState(hi.vpnIp, Disestablished)
  455. h = h.next
  456. }
  457. }
  458. }
  459. }
  460. }
  461. func (hm *HostMap) queryVpnIp(vpnIp netip.Addr, promoteIfce *Interface) *HostInfo {
  462. hm.RLock()
  463. if h, ok := hm.Hosts[vpnIp]; ok {
  464. hm.RUnlock()
  465. // Do not attempt promotion if you are a lighthouse
  466. if promoteIfce != nil && !promoteIfce.lightHouse.amLighthouse {
  467. h.TryPromoteBest(hm.GetPreferredRanges(), promoteIfce)
  468. }
  469. return h
  470. }
  471. hm.RUnlock()
  472. return nil
  473. }
  474. // unlockedAddHostInfo assumes you have a write-lock and will add a hostinfo object to the hostmap Indexes and RemoteIndexes maps.
  475. // If an entry exists for the Hosts table (vpnIp -> hostinfo) then the provided hostinfo will be made primary
  476. func (hm *HostMap) unlockedAddHostInfo(hostinfo *HostInfo, f *Interface) {
  477. if f.serveDns {
  478. remoteCert := hostinfo.ConnectionState.peerCert
  479. dnsR.Add(remoteCert.Details.Name+".", remoteCert.Details.Ips[0].IP.String())
  480. }
  481. existing := hm.Hosts[hostinfo.vpnIp]
  482. hm.Hosts[hostinfo.vpnIp] = hostinfo
  483. if existing != nil {
  484. hostinfo.next = existing
  485. existing.prev = hostinfo
  486. }
  487. hm.Indexes[hostinfo.localIndexId] = hostinfo
  488. hm.RemoteIndexes[hostinfo.remoteIndexId] = hostinfo
  489. if hm.l.Level >= logrus.DebugLevel {
  490. hm.l.WithField("hostMap", m{"vpnIp": hostinfo.vpnIp, "mapTotalSize": len(hm.Hosts),
  491. "hostinfo": m{"existing": true, "localIndexId": hostinfo.localIndexId, "hostId": hostinfo.vpnIp}}).
  492. Debug("Hostmap vpnIp added")
  493. }
  494. i := 1
  495. check := hostinfo
  496. for check != nil {
  497. if i > MaxHostInfosPerVpnIp {
  498. hm.unlockedDeleteHostInfo(check)
  499. }
  500. check = check.next
  501. i++
  502. }
  503. }
  504. func (hm *HostMap) GetPreferredRanges() []netip.Prefix {
  505. //NOTE: if preferredRanges is ever not stored before a load this will fail to dereference a nil pointer
  506. return *hm.preferredRanges.Load()
  507. }
  508. func (hm *HostMap) ForEachVpnIp(f controlEach) {
  509. hm.RLock()
  510. defer hm.RUnlock()
  511. for _, v := range hm.Hosts {
  512. f(v)
  513. }
  514. }
  515. func (hm *HostMap) ForEachIndex(f controlEach) {
  516. hm.RLock()
  517. defer hm.RUnlock()
  518. for _, v := range hm.Indexes {
  519. f(v)
  520. }
  521. }
  522. // TryPromoteBest handles re-querying lighthouses and probing for better paths
  523. // NOTE: It is an error to call this if you are a lighthouse since they should not roam clients!
  524. func (i *HostInfo) TryPromoteBest(preferredRanges []netip.Prefix, ifce *Interface) {
  525. c := i.promoteCounter.Add(1)
  526. if c%ifce.tryPromoteEvery.Load() == 0 {
  527. remote := i.remote
  528. // return early if we are already on a preferred remote
  529. if remote.IsValid() {
  530. rIP := remote.Addr()
  531. for _, l := range preferredRanges {
  532. if l.Contains(rIP) {
  533. return
  534. }
  535. }
  536. }
  537. i.remotes.ForEach(preferredRanges, func(addr netip.AddrPort, preferred bool) {
  538. if remote.IsValid() && (!addr.IsValid() || !preferred) {
  539. return
  540. }
  541. // Try to send a test packet to that host, this should
  542. // cause it to detect a roaming event and switch remotes
  543. ifce.sendTo(header.Test, header.TestRequest, i.ConnectionState, i, addr, []byte(""), make([]byte, 12, 12), make([]byte, mtu))
  544. })
  545. }
  546. // Re query our lighthouses for new remotes occasionally
  547. if c%ifce.reQueryEvery.Load() == 0 && ifce.lightHouse != nil {
  548. now := time.Now().UnixNano()
  549. if now < i.nextLHQuery.Load() {
  550. return
  551. }
  552. i.nextLHQuery.Store(now + ifce.reQueryWait.Load())
  553. ifce.lightHouse.QueryServer(i.vpnIp)
  554. }
  555. }
  556. func (i *HostInfo) GetCert() *cert.NebulaCertificate {
  557. if i.ConnectionState != nil {
  558. return i.ConnectionState.peerCert
  559. }
  560. return nil
  561. }
  562. func (i *HostInfo) SetRemote(remote netip.AddrPort) {
  563. // We copy here because we likely got this remote from a source that reuses the object
  564. if i.remote != remote {
  565. i.remote = remote
  566. i.remotes.LearnRemote(i.vpnIp, remote)
  567. }
  568. }
  569. // SetRemoteIfPreferred returns true if the remote was changed. The lastRoam
  570. // time on the HostInfo will also be updated.
  571. func (i *HostInfo) SetRemoteIfPreferred(hm *HostMap, newRemote netip.AddrPort) bool {
  572. if !newRemote.IsValid() {
  573. // relays have nil udp Addrs
  574. return false
  575. }
  576. currentRemote := i.remote
  577. if !currentRemote.IsValid() {
  578. i.SetRemote(newRemote)
  579. return true
  580. }
  581. // NOTE: We do this loop here instead of calling `isPreferred` in
  582. // remote_list.go so that we only have to loop over preferredRanges once.
  583. newIsPreferred := false
  584. for _, l := range hm.GetPreferredRanges() {
  585. // return early if we are already on a preferred remote
  586. if l.Contains(currentRemote.Addr()) {
  587. return false
  588. }
  589. if l.Contains(newRemote.Addr()) {
  590. newIsPreferred = true
  591. }
  592. }
  593. if newIsPreferred {
  594. // Consider this a roaming event
  595. i.lastRoam = time.Now()
  596. i.lastRoamRemote = currentRemote
  597. i.SetRemote(newRemote)
  598. return true
  599. }
  600. return false
  601. }
  602. func (i *HostInfo) RecvErrorExceeded() bool {
  603. if i.recvError.Add(1) >= maxRecvError {
  604. return true
  605. }
  606. return true
  607. }
  608. func (i *HostInfo) CreateRemoteCIDR(c *cert.NebulaCertificate) {
  609. if len(c.Details.Ips) == 1 && len(c.Details.Subnets) == 0 {
  610. // Simple case, no CIDRTree needed
  611. return
  612. }
  613. remoteCidr := new(bart.Table[struct{}])
  614. for _, ip := range c.Details.Ips {
  615. //TODO: IPV6-WORK what to do when ip is invalid?
  616. nip, _ := netip.AddrFromSlice(ip.IP)
  617. nip = nip.Unmap()
  618. bits, _ := ip.Mask.Size()
  619. remoteCidr.Insert(netip.PrefixFrom(nip, bits), struct{}{})
  620. }
  621. for _, n := range c.Details.Subnets {
  622. //TODO: IPV6-WORK what to do when ip is invalid?
  623. nip, _ := netip.AddrFromSlice(n.IP)
  624. nip = nip.Unmap()
  625. bits, _ := n.Mask.Size()
  626. remoteCidr.Insert(netip.PrefixFrom(nip, bits), struct{}{})
  627. }
  628. i.remoteCidr = remoteCidr
  629. }
  630. func (i *HostInfo) logger(l *logrus.Logger) *logrus.Entry {
  631. if i == nil {
  632. return logrus.NewEntry(l)
  633. }
  634. li := l.WithField("vpnIp", i.vpnIp).
  635. WithField("localIndex", i.localIndexId).
  636. WithField("remoteIndex", i.remoteIndexId)
  637. if connState := i.ConnectionState; connState != nil {
  638. if peerCert := connState.peerCert; peerCert != nil {
  639. li = li.WithField("certName", peerCert.Details.Name)
  640. }
  641. }
  642. return li
  643. }
  644. // Utility functions
  645. func localIps(l *logrus.Logger, allowList *LocalAllowList) []netip.Addr {
  646. //FIXME: This function is pretty garbage
  647. var ips []netip.Addr
  648. ifaces, _ := net.Interfaces()
  649. for _, i := range ifaces {
  650. allow := allowList.AllowName(i.Name)
  651. if l.Level >= logrus.TraceLevel {
  652. l.WithField("interfaceName", i.Name).WithField("allow", allow).Trace("localAllowList.AllowName")
  653. }
  654. if !allow {
  655. continue
  656. }
  657. addrs, _ := i.Addrs()
  658. for _, addr := range addrs {
  659. var ip net.IP
  660. switch v := addr.(type) {
  661. case *net.IPNet:
  662. //continue
  663. ip = v.IP
  664. case *net.IPAddr:
  665. ip = v.IP
  666. }
  667. nip, ok := netip.AddrFromSlice(ip)
  668. if !ok {
  669. if l.Level >= logrus.DebugLevel {
  670. l.WithField("localIp", ip).Debug("ip was invalid for netip")
  671. }
  672. continue
  673. }
  674. nip = nip.Unmap()
  675. //TODO: Filtering out link local for now, this is probably the most correct thing
  676. //TODO: Would be nice to filter out SLAAC MAC based ips as well
  677. if nip.IsLoopback() == false && nip.IsLinkLocalUnicast() == false {
  678. allow := allowList.Allow(nip)
  679. if l.Level >= logrus.TraceLevel {
  680. l.WithField("localIp", nip).WithField("allow", allow).Trace("localAllowList.Allow")
  681. }
  682. if !allow {
  683. continue
  684. }
  685. ips = append(ips, nip)
  686. }
  687. }
  688. }
  689. return ips
  690. }