hostmap.go 20 KB

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