hostmap.go 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707
  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/header"
  13. "github.com/slackhq/nebula/iputil"
  14. "github.com/slackhq/nebula/udp"
  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 iputil.VpnIp
  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[iputil.VpnIp]*HostInfo
  51. preferredRanges []*net.IPNet
  52. vpnCIDR *net.IPNet
  53. metricsEnabled bool
  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 NewHostMap(l *logrus.Logger, vpnCIDR *net.IPNet, preferredRanges []*net.IPNet) *HostMap {
  222. h := map[iputil.VpnIp]*HostInfo{}
  223. i := map[uint32]*HostInfo{}
  224. r := map[uint32]*HostInfo{}
  225. relays := map[uint32]*HostInfo{}
  226. m := HostMap{
  227. Indexes: i,
  228. Relays: relays,
  229. RemoteIndexes: r,
  230. Hosts: h,
  231. preferredRanges: preferredRanges,
  232. vpnCIDR: vpnCIDR,
  233. l: l,
  234. }
  235. return &m
  236. }
  237. // EmitStats reports host, index, and relay counts to the stats collection system
  238. func (hm *HostMap) EmitStats() {
  239. hm.RLock()
  240. hostLen := len(hm.Hosts)
  241. indexLen := len(hm.Indexes)
  242. remoteIndexLen := len(hm.RemoteIndexes)
  243. relaysLen := len(hm.Relays)
  244. hm.RUnlock()
  245. metrics.GetOrRegisterGauge("hostmap.main.hosts", nil).Update(int64(hostLen))
  246. metrics.GetOrRegisterGauge("hostmap.main.indexes", nil).Update(int64(indexLen))
  247. metrics.GetOrRegisterGauge("hostmap.main.remoteIndexes", nil).Update(int64(remoteIndexLen))
  248. metrics.GetOrRegisterGauge("hostmap.main.relayIndexes", nil).Update(int64(relaysLen))
  249. }
  250. func (hm *HostMap) RemoveRelay(localIdx uint32) {
  251. hm.Lock()
  252. _, ok := hm.Relays[localIdx]
  253. if !ok {
  254. hm.Unlock()
  255. return
  256. }
  257. delete(hm.Relays, localIdx)
  258. hm.Unlock()
  259. }
  260. // DeleteHostInfo will fully unlink the hostinfo and return true if it was the final hostinfo for this vpn ip
  261. func (hm *HostMap) DeleteHostInfo(hostinfo *HostInfo) bool {
  262. // Delete the host itself, ensuring it's not modified anymore
  263. hm.Lock()
  264. // If we have a previous or next hostinfo then we are not the last one for this vpn ip
  265. final := (hostinfo.next == nil && hostinfo.prev == nil)
  266. hm.unlockedDeleteHostInfo(hostinfo)
  267. hm.Unlock()
  268. return final
  269. }
  270. func (hm *HostMap) MakePrimary(hostinfo *HostInfo) {
  271. hm.Lock()
  272. defer hm.Unlock()
  273. hm.unlockedMakePrimary(hostinfo)
  274. }
  275. func (hm *HostMap) unlockedMakePrimary(hostinfo *HostInfo) {
  276. oldHostinfo := hm.Hosts[hostinfo.vpnIp]
  277. if oldHostinfo == hostinfo {
  278. return
  279. }
  280. if hostinfo.prev != nil {
  281. hostinfo.prev.next = hostinfo.next
  282. }
  283. if hostinfo.next != nil {
  284. hostinfo.next.prev = hostinfo.prev
  285. }
  286. hm.Hosts[hostinfo.vpnIp] = hostinfo
  287. if oldHostinfo == nil {
  288. return
  289. }
  290. hostinfo.next = oldHostinfo
  291. oldHostinfo.prev = hostinfo
  292. hostinfo.prev = nil
  293. }
  294. func (hm *HostMap) unlockedDeleteHostInfo(hostinfo *HostInfo) {
  295. primary, ok := hm.Hosts[hostinfo.vpnIp]
  296. if ok && primary == hostinfo {
  297. // The vpnIp pointer points to the same hostinfo as the local index id, we can remove it
  298. delete(hm.Hosts, hostinfo.vpnIp)
  299. if len(hm.Hosts) == 0 {
  300. hm.Hosts = map[iputil.VpnIp]*HostInfo{}
  301. }
  302. if hostinfo.next != nil {
  303. // We had more than 1 hostinfo at this vpnip, promote the next in the list to primary
  304. hm.Hosts[hostinfo.vpnIp] = hostinfo.next
  305. // It is primary, there is no previous hostinfo now
  306. hostinfo.next.prev = nil
  307. }
  308. } else {
  309. // Relink if we were in the middle of multiple hostinfos for this vpn ip
  310. if hostinfo.prev != nil {
  311. hostinfo.prev.next = hostinfo.next
  312. }
  313. if hostinfo.next != nil {
  314. hostinfo.next.prev = hostinfo.prev
  315. }
  316. }
  317. hostinfo.next = nil
  318. hostinfo.prev = nil
  319. // The remote index uses index ids outside our control so lets make sure we are only removing
  320. // the remote index pointer here if it points to the hostinfo we are deleting
  321. hostinfo2, ok := hm.RemoteIndexes[hostinfo.remoteIndexId]
  322. if ok && hostinfo2 == hostinfo {
  323. delete(hm.RemoteIndexes, hostinfo.remoteIndexId)
  324. if len(hm.RemoteIndexes) == 0 {
  325. hm.RemoteIndexes = map[uint32]*HostInfo{}
  326. }
  327. }
  328. delete(hm.Indexes, hostinfo.localIndexId)
  329. if len(hm.Indexes) == 0 {
  330. hm.Indexes = map[uint32]*HostInfo{}
  331. }
  332. if hm.l.Level >= logrus.DebugLevel {
  333. hm.l.WithField("hostMap", m{"mapTotalSize": len(hm.Hosts),
  334. "vpnIp": hostinfo.vpnIp, "indexNumber": hostinfo.localIndexId, "remoteIndexNumber": hostinfo.remoteIndexId}).
  335. Debug("Hostmap hostInfo deleted")
  336. }
  337. for _, localRelayIdx := range hostinfo.relayState.CopyRelayForIdxs() {
  338. delete(hm.Relays, localRelayIdx)
  339. }
  340. }
  341. func (hm *HostMap) QueryIndex(index uint32) *HostInfo {
  342. hm.RLock()
  343. if h, ok := hm.Indexes[index]; ok {
  344. hm.RUnlock()
  345. return h
  346. } else {
  347. hm.RUnlock()
  348. return nil
  349. }
  350. }
  351. func (hm *HostMap) QueryRelayIndex(index uint32) *HostInfo {
  352. hm.RLock()
  353. if h, ok := hm.Relays[index]; ok {
  354. hm.RUnlock()
  355. return h
  356. } else {
  357. hm.RUnlock()
  358. return nil
  359. }
  360. }
  361. func (hm *HostMap) QueryReverseIndex(index uint32) *HostInfo {
  362. hm.RLock()
  363. if h, ok := hm.RemoteIndexes[index]; ok {
  364. hm.RUnlock()
  365. return h
  366. } else {
  367. hm.RUnlock()
  368. return nil
  369. }
  370. }
  371. func (hm *HostMap) QueryVpnIp(vpnIp iputil.VpnIp) *HostInfo {
  372. return hm.queryVpnIp(vpnIp, nil)
  373. }
  374. func (hm *HostMap) QueryVpnIpRelayFor(targetIp, relayHostIp iputil.VpnIp) (*HostInfo, *Relay, error) {
  375. hm.RLock()
  376. defer hm.RUnlock()
  377. h, ok := hm.Hosts[relayHostIp]
  378. if !ok {
  379. return nil, nil, errors.New("unable to find host")
  380. }
  381. for h != nil {
  382. r, ok := h.relayState.QueryRelayForByIp(targetIp)
  383. if ok && r.State == Established {
  384. return h, r, nil
  385. }
  386. h = h.next
  387. }
  388. return nil, nil, errors.New("unable to find host with relay")
  389. }
  390. func (hm *HostMap) queryVpnIp(vpnIp iputil.VpnIp, promoteIfce *Interface) *HostInfo {
  391. hm.RLock()
  392. if h, ok := hm.Hosts[vpnIp]; ok {
  393. hm.RUnlock()
  394. // Do not attempt promotion if you are a lighthouse
  395. if promoteIfce != nil && !promoteIfce.lightHouse.amLighthouse {
  396. h.TryPromoteBest(hm.preferredRanges, promoteIfce)
  397. }
  398. return h
  399. }
  400. hm.RUnlock()
  401. return nil
  402. }
  403. // unlockedAddHostInfo assumes you have a write-lock and will add a hostinfo object to the hostmap Indexes and RemoteIndexes maps.
  404. // If an entry exists for the Hosts table (vpnIp -> hostinfo) then the provided hostinfo will be made primary
  405. func (hm *HostMap) unlockedAddHostInfo(hostinfo *HostInfo, f *Interface) {
  406. if f.serveDns {
  407. remoteCert := hostinfo.ConnectionState.peerCert
  408. dnsR.Add(remoteCert.Details.Name+".", remoteCert.Details.Ips[0].IP.String())
  409. }
  410. existing := hm.Hosts[hostinfo.vpnIp]
  411. hm.Hosts[hostinfo.vpnIp] = hostinfo
  412. if existing != nil {
  413. hostinfo.next = existing
  414. existing.prev = hostinfo
  415. }
  416. hm.Indexes[hostinfo.localIndexId] = hostinfo
  417. hm.RemoteIndexes[hostinfo.remoteIndexId] = hostinfo
  418. if hm.l.Level >= logrus.DebugLevel {
  419. hm.l.WithField("hostMap", m{"vpnIp": hostinfo.vpnIp, "mapTotalSize": len(hm.Hosts),
  420. "hostinfo": m{"existing": true, "localIndexId": hostinfo.localIndexId, "hostId": hostinfo.vpnIp}}).
  421. Debug("Hostmap vpnIp added")
  422. }
  423. i := 1
  424. check := hostinfo
  425. for check != nil {
  426. if i > MaxHostInfosPerVpnIp {
  427. hm.unlockedDeleteHostInfo(check)
  428. }
  429. check = check.next
  430. i++
  431. }
  432. }
  433. func (hm *HostMap) GetPreferredRanges() []*net.IPNet {
  434. return hm.preferredRanges
  435. }
  436. func (hm *HostMap) ForEachVpnIp(f controlEach) {
  437. hm.RLock()
  438. defer hm.RUnlock()
  439. for _, v := range hm.Hosts {
  440. f(v)
  441. }
  442. }
  443. func (hm *HostMap) ForEachIndex(f controlEach) {
  444. hm.RLock()
  445. defer hm.RUnlock()
  446. for _, v := range hm.Indexes {
  447. f(v)
  448. }
  449. }
  450. // TryPromoteBest handles re-querying lighthouses and probing for better paths
  451. // NOTE: It is an error to call this if you are a lighthouse since they should not roam clients!
  452. func (i *HostInfo) TryPromoteBest(preferredRanges []*net.IPNet, ifce *Interface) {
  453. c := i.promoteCounter.Add(1)
  454. if c%ifce.tryPromoteEvery.Load() == 0 {
  455. remote := i.remote
  456. // return early if we are already on a preferred remote
  457. if remote != nil {
  458. rIP := remote.IP
  459. for _, l := range preferredRanges {
  460. if l.Contains(rIP) {
  461. return
  462. }
  463. }
  464. }
  465. i.remotes.ForEach(preferredRanges, func(addr *udp.Addr, preferred bool) {
  466. if remote != nil && (addr == nil || !preferred) {
  467. return
  468. }
  469. // Try to send a test packet to that host, this should
  470. // cause it to detect a roaming event and switch remotes
  471. ifce.sendTo(header.Test, header.TestRequest, i.ConnectionState, i, addr, []byte(""), make([]byte, 12, 12), make([]byte, mtu))
  472. })
  473. }
  474. // Re query our lighthouses for new remotes occasionally
  475. if c%ifce.reQueryEvery.Load() == 0 && ifce.lightHouse != nil {
  476. now := time.Now().UnixNano()
  477. if now < i.nextLHQuery.Load() {
  478. return
  479. }
  480. i.nextLHQuery.Store(now + ifce.reQueryWait.Load())
  481. ifce.lightHouse.QueryServer(i.vpnIp)
  482. }
  483. }
  484. func (i *HostInfo) GetCert() *cert.NebulaCertificate {
  485. if i.ConnectionState != nil {
  486. return i.ConnectionState.peerCert
  487. }
  488. return nil
  489. }
  490. func (i *HostInfo) SetRemote(remote *udp.Addr) {
  491. // We copy here because we likely got this remote from a source that reuses the object
  492. if !i.remote.Equals(remote) {
  493. i.remote = remote.Copy()
  494. i.remotes.LearnRemote(i.vpnIp, remote.Copy())
  495. }
  496. }
  497. // SetRemoteIfPreferred returns true if the remote was changed. The lastRoam
  498. // time on the HostInfo will also be updated.
  499. func (i *HostInfo) SetRemoteIfPreferred(hm *HostMap, newRemote *udp.Addr) bool {
  500. if newRemote == nil {
  501. // relays have nil udp Addrs
  502. return false
  503. }
  504. currentRemote := i.remote
  505. if currentRemote == nil {
  506. i.SetRemote(newRemote)
  507. return true
  508. }
  509. // NOTE: We do this loop here instead of calling `isPreferred` in
  510. // remote_list.go so that we only have to loop over preferredRanges once.
  511. newIsPreferred := false
  512. for _, l := range hm.preferredRanges {
  513. // return early if we are already on a preferred remote
  514. if l.Contains(currentRemote.IP) {
  515. return false
  516. }
  517. if l.Contains(newRemote.IP) {
  518. newIsPreferred = true
  519. }
  520. }
  521. if newIsPreferred {
  522. // Consider this a roaming event
  523. i.lastRoam = time.Now()
  524. i.lastRoamRemote = currentRemote.Copy()
  525. i.SetRemote(newRemote)
  526. return true
  527. }
  528. return false
  529. }
  530. func (i *HostInfo) RecvErrorExceeded() bool {
  531. if i.recvError.Add(1) >= maxRecvError {
  532. return true
  533. }
  534. return true
  535. }
  536. func (i *HostInfo) CreateRemoteCIDR(c *cert.NebulaCertificate) {
  537. if len(c.Details.Ips) == 1 && len(c.Details.Subnets) == 0 {
  538. // Simple case, no CIDRTree needed
  539. return
  540. }
  541. remoteCidr := cidr.NewTree4[struct{}]()
  542. for _, ip := range c.Details.Ips {
  543. remoteCidr.AddCIDR(&net.IPNet{IP: ip.IP, Mask: net.IPMask{255, 255, 255, 255}}, struct{}{})
  544. }
  545. for _, n := range c.Details.Subnets {
  546. remoteCidr.AddCIDR(n, struct{}{})
  547. }
  548. i.remoteCidr = remoteCidr
  549. }
  550. func (i *HostInfo) logger(l *logrus.Logger) *logrus.Entry {
  551. if i == nil {
  552. return logrus.NewEntry(l)
  553. }
  554. li := l.WithField("vpnIp", i.vpnIp).
  555. WithField("localIndex", i.localIndexId).
  556. WithField("remoteIndex", i.remoteIndexId)
  557. if connState := i.ConnectionState; connState != nil {
  558. if peerCert := connState.peerCert; peerCert != nil {
  559. li = li.WithField("certName", peerCert.Details.Name)
  560. }
  561. }
  562. return li
  563. }
  564. // Utility functions
  565. func localIps(l *logrus.Logger, allowList *LocalAllowList) *[]net.IP {
  566. //FIXME: This function is pretty garbage
  567. var ips []net.IP
  568. ifaces, _ := net.Interfaces()
  569. for _, i := range ifaces {
  570. allow := allowList.AllowName(i.Name)
  571. if l.Level >= logrus.TraceLevel {
  572. l.WithField("interfaceName", i.Name).WithField("allow", allow).Trace("localAllowList.AllowName")
  573. }
  574. if !allow {
  575. continue
  576. }
  577. addrs, _ := i.Addrs()
  578. for _, addr := range addrs {
  579. var ip net.IP
  580. switch v := addr.(type) {
  581. case *net.IPNet:
  582. //continue
  583. ip = v.IP
  584. case *net.IPAddr:
  585. ip = v.IP
  586. }
  587. //TODO: Filtering out link local for now, this is probably the most correct thing
  588. //TODO: Would be nice to filter out SLAAC MAC based ips as well
  589. if ip.IsLoopback() == false && !ip.IsLinkLocalUnicast() {
  590. allow := allowList.Allow(ip)
  591. if l.Level >= logrus.TraceLevel {
  592. l.WithField("localIp", ip).WithField("allow", allow).Trace("localAllowList.Allow")
  593. }
  594. if !allow {
  595. continue
  596. }
  597. ips = append(ips, ip)
  598. }
  599. }
  600. }
  601. return &ips
  602. }