hostmap.go 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622
  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. // TryPromoteBest handles re-querying lighthouses and probing for better paths
  348. // NOTE: It is an error to call this if you are a lighthouse since they should not roam clients!
  349. func (i *HostInfo) TryPromoteBest(preferredRanges []*net.IPNet, ifce *Interface) {
  350. c := atomic.AddUint32(&i.promoteCounter, 1)
  351. if c%PromoteEvery == 0 {
  352. // The lock here is currently protecting i.remote access
  353. i.RLock()
  354. defer i.RUnlock()
  355. // return early if we are already on a preferred remote
  356. rIP := i.remote.IP
  357. for _, l := range preferredRanges {
  358. if l.Contains(rIP) {
  359. return
  360. }
  361. }
  362. i.remotes.ForEach(preferredRanges, func(addr *udp.Addr, preferred bool) {
  363. if addr == nil || !preferred {
  364. return
  365. }
  366. // Try to send a test packet to that host, this should
  367. // cause it to detect a roaming event and switch remotes
  368. ifce.send(header.Test, header.TestRequest, i.ConnectionState, i, addr, []byte(""), make([]byte, 12, 12), make([]byte, mtu))
  369. })
  370. }
  371. // Re query our lighthouses for new remotes occasionally
  372. if c%ReQueryEvery == 0 && ifce.lightHouse != nil {
  373. ifce.lightHouse.QueryServer(i.vpnIp, ifce)
  374. }
  375. }
  376. func (i *HostInfo) cachePacket(l *logrus.Logger, t header.MessageType, st header.MessageSubType, packet []byte, f packetCallback, m *cachedPacketMetrics) {
  377. //TODO: return the error so we can log with more context
  378. if len(i.packetStore) < 100 {
  379. tempPacket := make([]byte, len(packet))
  380. copy(tempPacket, packet)
  381. //l.WithField("trace", string(debug.Stack())).Error("Caching packet", tempPacket)
  382. i.packetStore = append(i.packetStore, &cachedPacket{t, st, f, tempPacket})
  383. if l.Level >= logrus.DebugLevel {
  384. i.logger(l).
  385. WithField("length", len(i.packetStore)).
  386. WithField("stored", true).
  387. Debugf("Packet store")
  388. }
  389. } else if l.Level >= logrus.DebugLevel {
  390. m.dropped.Inc(1)
  391. i.logger(l).
  392. WithField("length", len(i.packetStore)).
  393. WithField("stored", false).
  394. Debugf("Packet store")
  395. }
  396. }
  397. // handshakeComplete will set the connection as ready to communicate, as well as flush any stored packets
  398. func (i *HostInfo) handshakeComplete(l *logrus.Logger, m *cachedPacketMetrics) {
  399. //TODO: I'm not certain the distinction between handshake complete and ConnectionState being ready matters because:
  400. //TODO: HandshakeComplete means send stored packets and ConnectionState.ready means we are ready to send
  401. //TODO: if the transition from HandhsakeComplete to ConnectionState.ready happens all within this function they are identical
  402. i.ConnectionState.queueLock.Lock()
  403. i.HandshakeComplete = true
  404. //TODO: this should be managed by the handshake state machine to set it based on how many handshake were seen.
  405. // Clamping it to 2 gets us out of the woods for now
  406. atomic.StoreUint64(&i.ConnectionState.atomicMessageCounter, 2)
  407. if l.Level >= logrus.DebugLevel {
  408. i.logger(l).Debugf("Sending %d stored packets", len(i.packetStore))
  409. }
  410. if len(i.packetStore) > 0 {
  411. nb := make([]byte, 12, 12)
  412. out := make([]byte, mtu)
  413. for _, cp := range i.packetStore {
  414. cp.callback(cp.messageType, cp.messageSubType, i, cp.packet, nb, out)
  415. }
  416. m.sent.Inc(int64(len(i.packetStore)))
  417. }
  418. i.remotes.ResetBlockedRemotes()
  419. i.packetStore = make([]*cachedPacket, 0)
  420. i.ConnectionState.ready = true
  421. i.ConnectionState.queueLock.Unlock()
  422. i.ConnectionState.certState = nil
  423. }
  424. func (i *HostInfo) GetCert() *cert.NebulaCertificate {
  425. if i.ConnectionState != nil {
  426. return i.ConnectionState.peerCert
  427. }
  428. return nil
  429. }
  430. func (i *HostInfo) SetRemote(remote *udp.Addr) {
  431. // We copy here because we likely got this remote from a source that reuses the object
  432. if !i.remote.Equals(remote) {
  433. i.remote = remote.Copy()
  434. i.remotes.LearnRemote(i.vpnIp, remote.Copy())
  435. }
  436. }
  437. // SetRemoteIfPreferred returns true if the remote was changed. The lastRoam
  438. // time on the HostInfo will also be updated.
  439. func (i *HostInfo) SetRemoteIfPreferred(hm *HostMap, newRemote *udp.Addr) bool {
  440. currentRemote := i.remote
  441. if currentRemote == nil {
  442. i.SetRemote(newRemote)
  443. return true
  444. }
  445. // NOTE: We do this loop here instead of calling `isPreferred` in
  446. // remote_list.go so that we only have to loop over preferredRanges once.
  447. newIsPreferred := false
  448. for _, l := range hm.preferredRanges {
  449. // return early if we are already on a preferred remote
  450. if l.Contains(currentRemote.IP) {
  451. return false
  452. }
  453. if l.Contains(newRemote.IP) {
  454. newIsPreferred = true
  455. }
  456. }
  457. if newIsPreferred {
  458. // Consider this a roaming event
  459. i.lastRoam = time.Now()
  460. i.lastRoamRemote = currentRemote.Copy()
  461. i.SetRemote(newRemote)
  462. return true
  463. }
  464. return false
  465. }
  466. func (i *HostInfo) RecvErrorExceeded() bool {
  467. if i.recvError < 3 {
  468. i.recvError += 1
  469. return false
  470. }
  471. return true
  472. }
  473. func (i *HostInfo) CreateRemoteCIDR(c *cert.NebulaCertificate) {
  474. if len(c.Details.Ips) == 1 && len(c.Details.Subnets) == 0 {
  475. // Simple case, no CIDRTree needed
  476. return
  477. }
  478. remoteCidr := cidr.NewTree4()
  479. for _, ip := range c.Details.Ips {
  480. remoteCidr.AddCIDR(&net.IPNet{IP: ip.IP, Mask: net.IPMask{255, 255, 255, 255}}, struct{}{})
  481. }
  482. for _, n := range c.Details.Subnets {
  483. remoteCidr.AddCIDR(n, struct{}{})
  484. }
  485. i.remoteCidr = remoteCidr
  486. }
  487. func (i *HostInfo) logger(l *logrus.Logger) *logrus.Entry {
  488. if i == nil {
  489. return logrus.NewEntry(l)
  490. }
  491. li := l.WithField("vpnIp", i.vpnIp)
  492. if connState := i.ConnectionState; connState != nil {
  493. if peerCert := connState.peerCert; peerCert != nil {
  494. li = li.WithField("certName", peerCert.Details.Name)
  495. }
  496. }
  497. return li
  498. }
  499. // Utility functions
  500. func localIps(l *logrus.Logger, allowList *LocalAllowList) *[]net.IP {
  501. //FIXME: This function is pretty garbage
  502. var ips []net.IP
  503. ifaces, _ := net.Interfaces()
  504. for _, i := range ifaces {
  505. allow := allowList.AllowName(i.Name)
  506. if l.Level >= logrus.TraceLevel {
  507. l.WithField("interfaceName", i.Name).WithField("allow", allow).Trace("localAllowList.AllowName")
  508. }
  509. if !allow {
  510. continue
  511. }
  512. addrs, _ := i.Addrs()
  513. for _, addr := range addrs {
  514. var ip net.IP
  515. switch v := addr.(type) {
  516. case *net.IPNet:
  517. //continue
  518. ip = v.IP
  519. case *net.IPAddr:
  520. ip = v.IP
  521. }
  522. //TODO: Filtering out link local for now, this is probably the most correct thing
  523. //TODO: Would be nice to filter out SLAAC MAC based ips as well
  524. if ip.IsLoopback() == false && !ip.IsLinkLocalUnicast() {
  525. allow := allowList.Allow(ip)
  526. if l.Level >= logrus.TraceLevel {
  527. l.WithField("localIp", ip).WithField("allow", allow).Trace("localAllowList.Allow")
  528. }
  529. if !allow {
  530. continue
  531. }
  532. ips = append(ips, ip)
  533. }
  534. }
  535. }
  536. return &ips
  537. }