hostmap.go 18 KB

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