hostmap.go 19 KB

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