hostmap.go 20 KB

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