hostmap.go 19 KB

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