hostmap.go 20 KB

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