hostmap.go 21 KB

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