hostmap.go 19 KB

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