hostmap.go 19 KB

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