hostmap.go 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648
  1. package nebula
  2. import (
  3. "context"
  4. "errors"
  5. "fmt"
  6. "net"
  7. "sync"
  8. "sync/atomic"
  9. "time"
  10. "github.com/rcrowley/go-metrics"
  11. "github.com/sirupsen/logrus"
  12. "github.com/slackhq/nebula/cert"
  13. "github.com/slackhq/nebula/cidr"
  14. "github.com/slackhq/nebula/header"
  15. "github.com/slackhq/nebula/iputil"
  16. "github.com/slackhq/nebula/udp"
  17. )
  18. //const ProbeLen = 100
  19. const PromoteEvery = 1000
  20. const ReQueryEvery = 5000
  21. const MaxRemotes = 10
  22. // How long we should prevent roaming back to the previous IP.
  23. // This helps prevent flapping due to packets already in flight
  24. const RoamingSuppressSeconds = 2
  25. type HostMap struct {
  26. sync.RWMutex //Because we concurrently read and write to our maps
  27. name string
  28. Indexes map[uint32]*HostInfo
  29. RemoteIndexes map[uint32]*HostInfo
  30. Hosts map[iputil.VpnIp]*HostInfo
  31. preferredRanges []*net.IPNet
  32. vpnCIDR *net.IPNet
  33. unsafeRoutes *cidr.Tree4
  34. metricsEnabled bool
  35. l *logrus.Logger
  36. }
  37. type HostInfo struct {
  38. sync.RWMutex
  39. remote *udp.Addr
  40. remotes *RemoteList
  41. promoteCounter uint32
  42. ConnectionState *ConnectionState
  43. handshakeStart time.Time //todo: this an entry in the handshake manager
  44. HandshakeReady bool //todo: being in the manager means you are ready
  45. HandshakeCounter int //todo: another handshake manager entry
  46. HandshakeComplete bool //todo: this should go away in favor of ConnectionState.ready
  47. HandshakePacket map[uint8][]byte //todo: this is other handshake manager entry
  48. packetStore []*cachedPacket //todo: this is other handshake manager entry
  49. remoteIndexId uint32
  50. localIndexId uint32
  51. vpnIp iputil.VpnIp
  52. recvError int
  53. remoteCidr *cidr.Tree4
  54. // lastRebindCount is the other side of Interface.rebindCount, if these values don't match then we need to ask LH
  55. // for a punch from the remote end of this tunnel. The goal being to prime their conntrack for our traffic just like
  56. // with a handshake
  57. lastRebindCount int8
  58. // lastHandshakeTime records the time the remote side told us about at the stage when the handshake was completed locally
  59. // Stage 1 packet will contain it if I am a responder, stage 2 packet if I am an initiator
  60. // This is used to avoid an attack where a handshake packet is replayed after some time
  61. lastHandshakeTime uint64
  62. lastRoam time.Time
  63. lastRoamRemote *udp.Addr
  64. }
  65. type cachedPacket struct {
  66. messageType header.MessageType
  67. messageSubType header.MessageSubType
  68. callback packetCallback
  69. packet []byte
  70. }
  71. type packetCallback func(t header.MessageType, st header.MessageSubType, h *HostInfo, p, nb, out []byte)
  72. type cachedPacketMetrics struct {
  73. sent metrics.Counter
  74. dropped metrics.Counter
  75. }
  76. func NewHostMap(l *logrus.Logger, name string, vpnCIDR *net.IPNet, preferredRanges []*net.IPNet) *HostMap {
  77. h := map[iputil.VpnIp]*HostInfo{}
  78. i := map[uint32]*HostInfo{}
  79. r := map[uint32]*HostInfo{}
  80. m := HostMap{
  81. name: name,
  82. Indexes: i,
  83. RemoteIndexes: r,
  84. Hosts: h,
  85. preferredRanges: preferredRanges,
  86. vpnCIDR: vpnCIDR,
  87. unsafeRoutes: cidr.NewTree4(),
  88. l: l,
  89. }
  90. return &m
  91. }
  92. // UpdateStats takes a name and reports host and index counts to the stats collection system
  93. func (hm *HostMap) EmitStats(name string) {
  94. hm.RLock()
  95. hostLen := len(hm.Hosts)
  96. indexLen := len(hm.Indexes)
  97. remoteIndexLen := len(hm.RemoteIndexes)
  98. hm.RUnlock()
  99. metrics.GetOrRegisterGauge("hostmap."+name+".hosts", nil).Update(int64(hostLen))
  100. metrics.GetOrRegisterGauge("hostmap."+name+".indexes", nil).Update(int64(indexLen))
  101. metrics.GetOrRegisterGauge("hostmap."+name+".remoteIndexes", nil).Update(int64(remoteIndexLen))
  102. }
  103. func (hm *HostMap) GetIndexByVpnIp(vpnIp iputil.VpnIp) (uint32, error) {
  104. hm.RLock()
  105. if i, ok := hm.Hosts[vpnIp]; ok {
  106. index := i.localIndexId
  107. hm.RUnlock()
  108. return index, nil
  109. }
  110. hm.RUnlock()
  111. return 0, errors.New("vpn IP not found")
  112. }
  113. func (hm *HostMap) Add(ip iputil.VpnIp, hostinfo *HostInfo) {
  114. hm.Lock()
  115. hm.Hosts[ip] = hostinfo
  116. hm.Unlock()
  117. }
  118. func (hm *HostMap) AddVpnIp(vpnIp iputil.VpnIp, init func(hostinfo *HostInfo)) (hostinfo *HostInfo, created bool) {
  119. hm.RLock()
  120. if h, ok := hm.Hosts[vpnIp]; !ok {
  121. hm.RUnlock()
  122. h = &HostInfo{
  123. promoteCounter: 0,
  124. vpnIp: vpnIp,
  125. HandshakePacket: make(map[uint8][]byte, 0),
  126. }
  127. if init != nil {
  128. init(h)
  129. }
  130. hm.Lock()
  131. hm.Hosts[vpnIp] = h
  132. hm.Unlock()
  133. return h, true
  134. } else {
  135. hm.RUnlock()
  136. return h, false
  137. }
  138. }
  139. func (hm *HostMap) DeleteVpnIp(vpnIp iputil.VpnIp) {
  140. hm.Lock()
  141. delete(hm.Hosts, vpnIp)
  142. if len(hm.Hosts) == 0 {
  143. hm.Hosts = map[iputil.VpnIp]*HostInfo{}
  144. }
  145. hm.Unlock()
  146. if hm.l.Level >= logrus.DebugLevel {
  147. hm.l.WithField("hostMap", m{"mapName": hm.name, "vpnIp": vpnIp, "mapTotalSize": len(hm.Hosts)}).
  148. Debug("Hostmap vpnIp deleted")
  149. }
  150. }
  151. // Only used by pendingHostMap when the remote index is not initially known
  152. func (hm *HostMap) addRemoteIndexHostInfo(index uint32, h *HostInfo) {
  153. hm.Lock()
  154. h.remoteIndexId = index
  155. hm.RemoteIndexes[index] = h
  156. hm.Unlock()
  157. if hm.l.Level > logrus.DebugLevel {
  158. hm.l.WithField("hostMap", m{"mapName": hm.name, "indexNumber": index, "mapTotalSize": len(hm.Indexes),
  159. "hostinfo": m{"existing": true, "localIndexId": h.localIndexId, "hostId": h.vpnIp}}).
  160. Debug("Hostmap remoteIndex added")
  161. }
  162. }
  163. func (hm *HostMap) AddVpnIpHostInfo(vpnIp iputil.VpnIp, h *HostInfo) {
  164. hm.Lock()
  165. h.vpnIp = vpnIp
  166. hm.Hosts[vpnIp] = h
  167. hm.Indexes[h.localIndexId] = h
  168. hm.RemoteIndexes[h.remoteIndexId] = h
  169. hm.Unlock()
  170. if hm.l.Level > logrus.DebugLevel {
  171. hm.l.WithField("hostMap", m{"mapName": hm.name, "vpnIp": vpnIp, "mapTotalSize": len(hm.Hosts),
  172. "hostinfo": m{"existing": true, "localIndexId": h.localIndexId, "vpnIp": h.vpnIp}}).
  173. Debug("Hostmap vpnIp added")
  174. }
  175. }
  176. // This is only called in pendingHostmap, to cleanup an inbound handshake
  177. func (hm *HostMap) DeleteIndex(index uint32) {
  178. hm.Lock()
  179. hostinfo, ok := hm.Indexes[index]
  180. if ok {
  181. delete(hm.Indexes, index)
  182. delete(hm.RemoteIndexes, hostinfo.remoteIndexId)
  183. // Check if we have an entry under hostId that matches the same hostinfo
  184. // instance. Clean it up as well if we do.
  185. hostinfo2, ok := hm.Hosts[hostinfo.vpnIp]
  186. if ok && hostinfo2 == hostinfo {
  187. delete(hm.Hosts, hostinfo.vpnIp)
  188. }
  189. }
  190. hm.Unlock()
  191. if hm.l.Level >= logrus.DebugLevel {
  192. hm.l.WithField("hostMap", m{"mapName": hm.name, "indexNumber": index, "mapTotalSize": len(hm.Indexes)}).
  193. Debug("Hostmap index deleted")
  194. }
  195. }
  196. // This is used to cleanup on recv_error
  197. func (hm *HostMap) DeleteReverseIndex(index uint32) {
  198. hm.Lock()
  199. hostinfo, ok := hm.RemoteIndexes[index]
  200. if ok {
  201. delete(hm.Indexes, hostinfo.localIndexId)
  202. delete(hm.RemoteIndexes, index)
  203. // Check if we have an entry under hostId that matches the same hostinfo
  204. // instance. Clean it up as well if we do (they might not match in pendingHostmap)
  205. var hostinfo2 *HostInfo
  206. hostinfo2, ok = hm.Hosts[hostinfo.vpnIp]
  207. if ok && hostinfo2 == hostinfo {
  208. delete(hm.Hosts, hostinfo.vpnIp)
  209. }
  210. }
  211. hm.Unlock()
  212. if hm.l.Level >= logrus.DebugLevel {
  213. hm.l.WithField("hostMap", m{"mapName": hm.name, "indexNumber": index, "mapTotalSize": len(hm.Indexes)}).
  214. Debug("Hostmap remote index deleted")
  215. }
  216. }
  217. func (hm *HostMap) DeleteHostInfo(hostinfo *HostInfo) {
  218. hm.Lock()
  219. defer hm.Unlock()
  220. hm.unlockedDeleteHostInfo(hostinfo)
  221. }
  222. func (hm *HostMap) unlockedDeleteHostInfo(hostinfo *HostInfo) {
  223. // Check if this same hostId is in the hostmap with a different instance.
  224. // This could happen if we have an entry in the pending hostmap with different
  225. // index values than the one in the main hostmap.
  226. hostinfo2, ok := hm.Hosts[hostinfo.vpnIp]
  227. if ok && hostinfo2 != hostinfo {
  228. delete(hm.Hosts, hostinfo2.vpnIp)
  229. delete(hm.Indexes, hostinfo2.localIndexId)
  230. delete(hm.RemoteIndexes, hostinfo2.remoteIndexId)
  231. }
  232. delete(hm.Hosts, hostinfo.vpnIp)
  233. if len(hm.Hosts) == 0 {
  234. hm.Hosts = map[iputil.VpnIp]*HostInfo{}
  235. }
  236. delete(hm.Indexes, hostinfo.localIndexId)
  237. if len(hm.Indexes) == 0 {
  238. hm.Indexes = map[uint32]*HostInfo{}
  239. }
  240. delete(hm.RemoteIndexes, hostinfo.remoteIndexId)
  241. if len(hm.RemoteIndexes) == 0 {
  242. hm.RemoteIndexes = map[uint32]*HostInfo{}
  243. }
  244. if hm.l.Level >= logrus.DebugLevel {
  245. hm.l.WithField("hostMap", m{"mapName": hm.name, "mapTotalSize": len(hm.Hosts),
  246. "vpnIp": hostinfo.vpnIp, "indexNumber": hostinfo.localIndexId, "remoteIndexNumber": hostinfo.remoteIndexId}).
  247. Debug("Hostmap hostInfo deleted")
  248. }
  249. }
  250. func (hm *HostMap) QueryIndex(index uint32) (*HostInfo, error) {
  251. //TODO: we probably just want ot return bool instead of error, or at least a static error
  252. hm.RLock()
  253. if h, ok := hm.Indexes[index]; ok {
  254. hm.RUnlock()
  255. return h, nil
  256. } else {
  257. hm.RUnlock()
  258. return nil, errors.New("unable to find index")
  259. }
  260. }
  261. func (hm *HostMap) QueryReverseIndex(index uint32) (*HostInfo, error) {
  262. hm.RLock()
  263. if h, ok := hm.RemoteIndexes[index]; ok {
  264. hm.RUnlock()
  265. return h, nil
  266. } else {
  267. hm.RUnlock()
  268. return nil, fmt.Errorf("unable to find reverse index or connectionstate nil in %s hostmap", hm.name)
  269. }
  270. }
  271. func (hm *HostMap) QueryVpnIp(vpnIp iputil.VpnIp) (*HostInfo, error) {
  272. return hm.queryVpnIp(vpnIp, nil)
  273. }
  274. // PromoteBestQueryVpnIp will attempt to lazily switch to the best remote every
  275. // `PromoteEvery` calls to this function for a given host.
  276. func (hm *HostMap) PromoteBestQueryVpnIp(vpnIp iputil.VpnIp, ifce *Interface) (*HostInfo, error) {
  277. return hm.queryVpnIp(vpnIp, ifce)
  278. }
  279. func (hm *HostMap) queryVpnIp(vpnIp iputil.VpnIp, promoteIfce *Interface) (*HostInfo, error) {
  280. hm.RLock()
  281. if h, ok := hm.Hosts[vpnIp]; ok {
  282. hm.RUnlock()
  283. // Do not attempt promotion if you are a lighthouse
  284. if promoteIfce != nil && !promoteIfce.lightHouse.amLighthouse {
  285. h.TryPromoteBest(hm.preferredRanges, promoteIfce)
  286. }
  287. return h, nil
  288. }
  289. hm.RUnlock()
  290. return nil, errors.New("unable to find host")
  291. }
  292. func (hm *HostMap) queryUnsafeRoute(ip iputil.VpnIp) iputil.VpnIp {
  293. r := hm.unsafeRoutes.MostSpecificContains(ip)
  294. if r != nil {
  295. return r.(iputil.VpnIp)
  296. } else {
  297. return 0
  298. }
  299. }
  300. // We already have the hm Lock when this is called, so make sure to not call
  301. // any other methods that might try to grab it again
  302. func (hm *HostMap) addHostInfo(hostinfo *HostInfo, f *Interface) {
  303. if f.serveDns {
  304. remoteCert := hostinfo.ConnectionState.peerCert
  305. dnsR.Add(remoteCert.Details.Name+".", remoteCert.Details.Ips[0].IP.String())
  306. }
  307. hm.Hosts[hostinfo.vpnIp] = hostinfo
  308. hm.Indexes[hostinfo.localIndexId] = hostinfo
  309. hm.RemoteIndexes[hostinfo.remoteIndexId] = hostinfo
  310. if hm.l.Level >= logrus.DebugLevel {
  311. hm.l.WithField("hostMap", m{"mapName": hm.name, "vpnIp": hostinfo.vpnIp, "mapTotalSize": len(hm.Hosts),
  312. "hostinfo": m{"existing": true, "localIndexId": hostinfo.localIndexId, "hostId": hostinfo.vpnIp}}).
  313. Debug("Hostmap vpnIp added")
  314. }
  315. }
  316. // punchList assembles a list of all non nil RemoteList pointer entries in this hostmap
  317. // The caller can then do the its work outside of the read lock
  318. func (hm *HostMap) punchList(rl []*RemoteList) []*RemoteList {
  319. hm.RLock()
  320. defer hm.RUnlock()
  321. for _, v := range hm.Hosts {
  322. if v.remotes != nil {
  323. rl = append(rl, v.remotes)
  324. }
  325. }
  326. return rl
  327. }
  328. // Punchy iterates through the result of punchList() to assemble all known addresses and sends a hole punch packet to them
  329. func (hm *HostMap) Punchy(ctx context.Context, conn *udp.Conn) {
  330. var metricsTxPunchy metrics.Counter
  331. if hm.metricsEnabled {
  332. metricsTxPunchy = metrics.GetOrRegisterCounter("messages.tx.punchy", nil)
  333. } else {
  334. metricsTxPunchy = metrics.NilCounter{}
  335. }
  336. var remotes []*RemoteList
  337. b := []byte{1}
  338. clockSource := time.NewTicker(time.Second * 10)
  339. defer clockSource.Stop()
  340. for {
  341. remotes = hm.punchList(remotes[:0])
  342. for _, rl := range remotes {
  343. //TODO: CopyAddrs generates garbage but ForEach locks for the work here, figure out which way is better
  344. for _, addr := range rl.CopyAddrs(hm.preferredRanges) {
  345. metricsTxPunchy.Inc(1)
  346. conn.WriteTo(b, addr)
  347. }
  348. }
  349. select {
  350. case <-ctx.Done():
  351. return
  352. case <-clockSource.C:
  353. continue
  354. }
  355. }
  356. }
  357. func (hm *HostMap) addUnsafeRoutes(routes *[]route) {
  358. for _, r := range *routes {
  359. hm.l.WithField("route", r.route).WithField("via", r.via).Warn("Adding UNSAFE Route")
  360. hm.unsafeRoutes.AddCIDR(r.route, iputil.Ip2VpnIp(*r.via))
  361. }
  362. }
  363. func (i *HostInfo) BindConnectionState(cs *ConnectionState) {
  364. i.ConnectionState = cs
  365. }
  366. // TryPromoteBest handles re-querying lighthouses and probing for better paths
  367. // NOTE: It is an error to call this if you are a lighthouse since they should not roam clients!
  368. func (i *HostInfo) TryPromoteBest(preferredRanges []*net.IPNet, ifce *Interface) {
  369. c := atomic.AddUint32(&i.promoteCounter, 1)
  370. if c%PromoteEvery == 0 {
  371. // The lock here is currently protecting i.remote access
  372. i.RLock()
  373. defer i.RUnlock()
  374. // return early if we are already on a preferred remote
  375. rIP := i.remote.IP
  376. for _, l := range preferredRanges {
  377. if l.Contains(rIP) {
  378. return
  379. }
  380. }
  381. i.remotes.ForEach(preferredRanges, func(addr *udp.Addr, preferred bool) {
  382. if addr == nil || !preferred {
  383. return
  384. }
  385. // Try to send a test packet to that host, this should
  386. // cause it to detect a roaming event and switch remotes
  387. ifce.send(header.Test, header.TestRequest, i.ConnectionState, i, addr, []byte(""), make([]byte, 12, 12), make([]byte, mtu))
  388. })
  389. }
  390. // Re query our lighthouses for new remotes occasionally
  391. if c%ReQueryEvery == 0 && ifce.lightHouse != nil {
  392. ifce.lightHouse.QueryServer(i.vpnIp, ifce)
  393. }
  394. }
  395. func (i *HostInfo) cachePacket(l *logrus.Logger, t header.MessageType, st header.MessageSubType, packet []byte, f packetCallback, m *cachedPacketMetrics) {
  396. //TODO: return the error so we can log with more context
  397. if len(i.packetStore) < 100 {
  398. tempPacket := make([]byte, len(packet))
  399. copy(tempPacket, packet)
  400. //l.WithField("trace", string(debug.Stack())).Error("Caching packet", tempPacket)
  401. i.packetStore = append(i.packetStore, &cachedPacket{t, st, f, tempPacket})
  402. if l.Level >= logrus.DebugLevel {
  403. i.logger(l).
  404. WithField("length", len(i.packetStore)).
  405. WithField("stored", true).
  406. Debugf("Packet store")
  407. }
  408. } else if l.Level >= logrus.DebugLevel {
  409. m.dropped.Inc(1)
  410. i.logger(l).
  411. WithField("length", len(i.packetStore)).
  412. WithField("stored", false).
  413. Debugf("Packet store")
  414. }
  415. }
  416. // handshakeComplete will set the connection as ready to communicate, as well as flush any stored packets
  417. func (i *HostInfo) handshakeComplete(l *logrus.Logger, m *cachedPacketMetrics) {
  418. //TODO: I'm not certain the distinction between handshake complete and ConnectionState being ready matters because:
  419. //TODO: HandshakeComplete means send stored packets and ConnectionState.ready means we are ready to send
  420. //TODO: if the transition from HandhsakeComplete to ConnectionState.ready happens all within this function they are identical
  421. i.ConnectionState.queueLock.Lock()
  422. i.HandshakeComplete = true
  423. //TODO: this should be managed by the handshake state machine to set it based on how many handshake were seen.
  424. // Clamping it to 2 gets us out of the woods for now
  425. atomic.StoreUint64(&i.ConnectionState.atomicMessageCounter, 2)
  426. if l.Level >= logrus.DebugLevel {
  427. i.logger(l).Debugf("Sending %d stored packets", len(i.packetStore))
  428. }
  429. if len(i.packetStore) > 0 {
  430. nb := make([]byte, 12, 12)
  431. out := make([]byte, mtu)
  432. for _, cp := range i.packetStore {
  433. cp.callback(cp.messageType, cp.messageSubType, i, cp.packet, nb, out)
  434. }
  435. m.sent.Inc(int64(len(i.packetStore)))
  436. }
  437. i.remotes.ResetBlockedRemotes()
  438. i.packetStore = make([]*cachedPacket, 0)
  439. i.ConnectionState.ready = true
  440. i.ConnectionState.queueLock.Unlock()
  441. i.ConnectionState.certState = nil
  442. }
  443. func (i *HostInfo) GetCert() *cert.NebulaCertificate {
  444. if i.ConnectionState != nil {
  445. return i.ConnectionState.peerCert
  446. }
  447. return nil
  448. }
  449. func (i *HostInfo) SetRemote(remote *udp.Addr) {
  450. // We copy here because we likely got this remote from a source that reuses the object
  451. if !i.remote.Equals(remote) {
  452. i.remote = remote.Copy()
  453. i.remotes.LearnRemote(i.vpnIp, remote.Copy())
  454. }
  455. }
  456. // SetRemoteIfPreferred returns true if the remote was changed. The lastRoam
  457. // time on the HostInfo will also be updated.
  458. func (i *HostInfo) SetRemoteIfPreferred(hm *HostMap, newRemote *udp.Addr) bool {
  459. currentRemote := i.remote
  460. if currentRemote == nil {
  461. i.SetRemote(newRemote)
  462. return true
  463. }
  464. // NOTE: We do this loop here instead of calling `isPreferred` in
  465. // remote_list.go so that we only have to loop over preferredRanges once.
  466. newIsPreferred := false
  467. for _, l := range hm.preferredRanges {
  468. // return early if we are already on a preferred remote
  469. if l.Contains(currentRemote.IP) {
  470. return false
  471. }
  472. if l.Contains(newRemote.IP) {
  473. newIsPreferred = true
  474. }
  475. }
  476. if newIsPreferred {
  477. // Consider this a roaming event
  478. i.lastRoam = time.Now()
  479. i.lastRoamRemote = currentRemote.Copy()
  480. i.SetRemote(newRemote)
  481. return true
  482. }
  483. return false
  484. }
  485. func (i *HostInfo) ClearConnectionState() {
  486. i.ConnectionState = nil
  487. }
  488. func (i *HostInfo) RecvErrorExceeded() bool {
  489. if i.recvError < 3 {
  490. i.recvError += 1
  491. return false
  492. }
  493. return true
  494. }
  495. func (i *HostInfo) CreateRemoteCIDR(c *cert.NebulaCertificate) {
  496. if len(c.Details.Ips) == 1 && len(c.Details.Subnets) == 0 {
  497. // Simple case, no CIDRTree needed
  498. return
  499. }
  500. remoteCidr := cidr.NewTree4()
  501. for _, ip := range c.Details.Ips {
  502. remoteCidr.AddCIDR(&net.IPNet{IP: ip.IP, Mask: net.IPMask{255, 255, 255, 255}}, struct{}{})
  503. }
  504. for _, n := range c.Details.Subnets {
  505. remoteCidr.AddCIDR(n, struct{}{})
  506. }
  507. i.remoteCidr = remoteCidr
  508. }
  509. func (i *HostInfo) logger(l *logrus.Logger) *logrus.Entry {
  510. if i == nil {
  511. return logrus.NewEntry(l)
  512. }
  513. li := l.WithField("vpnIp", i.vpnIp)
  514. if connState := i.ConnectionState; connState != nil {
  515. if peerCert := connState.peerCert; peerCert != nil {
  516. li = li.WithField("certName", peerCert.Details.Name)
  517. }
  518. }
  519. return li
  520. }
  521. // Utility functions
  522. func localIps(l *logrus.Logger, allowList *LocalAllowList) *[]net.IP {
  523. //FIXME: This function is pretty garbage
  524. var ips []net.IP
  525. ifaces, _ := net.Interfaces()
  526. for _, i := range ifaces {
  527. allow := allowList.AllowName(i.Name)
  528. if l.Level >= logrus.TraceLevel {
  529. l.WithField("interfaceName", i.Name).WithField("allow", allow).Trace("localAllowList.AllowName")
  530. }
  531. if !allow {
  532. continue
  533. }
  534. addrs, _ := i.Addrs()
  535. for _, addr := range addrs {
  536. var ip net.IP
  537. switch v := addr.(type) {
  538. case *net.IPNet:
  539. //continue
  540. ip = v.IP
  541. case *net.IPAddr:
  542. ip = v.IP
  543. }
  544. //TODO: Filtering out link local for now, this is probably the most correct thing
  545. //TODO: Would be nice to filter out SLAAC MAC based ips as well
  546. if ip.IsLoopback() == false && !ip.IsLinkLocalUnicast() {
  547. allow := allowList.Allow(ip)
  548. if l.Level >= logrus.TraceLevel {
  549. l.WithField("localIp", ip).WithField("allow", allow).Trace("localAllowList.Allow")
  550. }
  551. if !allow {
  552. continue
  553. }
  554. ips = append(ips, ip)
  555. }
  556. }
  557. }
  558. return &ips
  559. }