hostmap.go 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620
  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. lastRoam time.Time
  54. lastRoamRemote *udpAddr
  55. }
  56. type cachedPacket struct {
  57. messageType NebulaMessageType
  58. messageSubType NebulaMessageSubType
  59. callback packetCallback
  60. packet []byte
  61. }
  62. type packetCallback func(t NebulaMessageType, st NebulaMessageSubType, h *HostInfo, p, nb, out []byte)
  63. func NewHostMap(l *logrus.Logger, name string, vpnCIDR *net.IPNet, preferredRanges []*net.IPNet) *HostMap {
  64. h := map[uint32]*HostInfo{}
  65. i := map[uint32]*HostInfo{}
  66. r := map[uint32]*HostInfo{}
  67. m := HostMap{
  68. name: name,
  69. Indexes: i,
  70. RemoteIndexes: r,
  71. Hosts: h,
  72. preferredRanges: preferredRanges,
  73. vpnCIDR: vpnCIDR,
  74. unsafeRoutes: NewCIDRTree(),
  75. l: l,
  76. }
  77. return &m
  78. }
  79. // UpdateStats takes a name and reports host and index counts to the stats collection system
  80. func (hm *HostMap) EmitStats(name string) {
  81. hm.RLock()
  82. hostLen := len(hm.Hosts)
  83. indexLen := len(hm.Indexes)
  84. remoteIndexLen := len(hm.RemoteIndexes)
  85. hm.RUnlock()
  86. metrics.GetOrRegisterGauge("hostmap."+name+".hosts", nil).Update(int64(hostLen))
  87. metrics.GetOrRegisterGauge("hostmap."+name+".indexes", nil).Update(int64(indexLen))
  88. metrics.GetOrRegisterGauge("hostmap."+name+".remoteIndexes", nil).Update(int64(remoteIndexLen))
  89. }
  90. func (hm *HostMap) GetIndexByVpnIP(vpnIP uint32) (uint32, error) {
  91. hm.RLock()
  92. if i, ok := hm.Hosts[vpnIP]; ok {
  93. index := i.localIndexId
  94. hm.RUnlock()
  95. return index, nil
  96. }
  97. hm.RUnlock()
  98. return 0, errors.New("vpn IP not found")
  99. }
  100. func (hm *HostMap) Add(ip uint32, hostinfo *HostInfo) {
  101. hm.Lock()
  102. hm.Hosts[ip] = hostinfo
  103. hm.Unlock()
  104. }
  105. func (hm *HostMap) AddVpnIP(vpnIP uint32) *HostInfo {
  106. h := &HostInfo{}
  107. hm.RLock()
  108. if _, ok := hm.Hosts[vpnIP]; !ok {
  109. hm.RUnlock()
  110. h = &HostInfo{
  111. promoteCounter: 0,
  112. hostId: vpnIP,
  113. HandshakePacket: make(map[uint8][]byte, 0),
  114. }
  115. hm.Lock()
  116. hm.Hosts[vpnIP] = h
  117. hm.Unlock()
  118. return h
  119. } else {
  120. h = hm.Hosts[vpnIP]
  121. hm.RUnlock()
  122. return h
  123. }
  124. }
  125. func (hm *HostMap) DeleteVpnIP(vpnIP uint32) {
  126. hm.Lock()
  127. delete(hm.Hosts, vpnIP)
  128. if len(hm.Hosts) == 0 {
  129. hm.Hosts = map[uint32]*HostInfo{}
  130. }
  131. hm.Unlock()
  132. if hm.l.Level >= logrus.DebugLevel {
  133. hm.l.WithField("hostMap", m{"mapName": hm.name, "vpnIp": IntIp(vpnIP), "mapTotalSize": len(hm.Hosts)}).
  134. Debug("Hostmap vpnIp deleted")
  135. }
  136. }
  137. // Only used by pendingHostMap when the remote index is not initially known
  138. func (hm *HostMap) addRemoteIndexHostInfo(index uint32, h *HostInfo) {
  139. hm.Lock()
  140. h.remoteIndexId = index
  141. hm.RemoteIndexes[index] = h
  142. hm.Unlock()
  143. if hm.l.Level > logrus.DebugLevel {
  144. hm.l.WithField("hostMap", m{"mapName": hm.name, "indexNumber": index, "mapTotalSize": len(hm.Indexes),
  145. "hostinfo": m{"existing": true, "localIndexId": h.localIndexId, "hostId": IntIp(h.hostId)}}).
  146. Debug("Hostmap remoteIndex added")
  147. }
  148. }
  149. func (hm *HostMap) AddVpnIPHostInfo(vpnIP uint32, h *HostInfo) {
  150. hm.Lock()
  151. h.hostId = vpnIP
  152. hm.Hosts[vpnIP] = h
  153. hm.Indexes[h.localIndexId] = h
  154. hm.RemoteIndexes[h.remoteIndexId] = h
  155. hm.Unlock()
  156. if hm.l.Level > logrus.DebugLevel {
  157. hm.l.WithField("hostMap", m{"mapName": hm.name, "vpnIp": IntIp(vpnIP), "mapTotalSize": len(hm.Hosts),
  158. "hostinfo": m{"existing": true, "localIndexId": h.localIndexId, "hostId": IntIp(h.hostId)}}).
  159. Debug("Hostmap vpnIp added")
  160. }
  161. }
  162. // This is only called in pendingHostmap, to cleanup an inbound handshake
  163. func (hm *HostMap) DeleteIndex(index uint32) {
  164. hm.Lock()
  165. hostinfo, ok := hm.Indexes[index]
  166. if ok {
  167. delete(hm.Indexes, index)
  168. delete(hm.RemoteIndexes, hostinfo.remoteIndexId)
  169. // Check if we have an entry under hostId that matches the same hostinfo
  170. // instance. Clean it up as well if we do.
  171. hostinfo2, ok := hm.Hosts[hostinfo.hostId]
  172. if ok && hostinfo2 == hostinfo {
  173. delete(hm.Hosts, hostinfo.hostId)
  174. }
  175. }
  176. hm.Unlock()
  177. if hm.l.Level >= logrus.DebugLevel {
  178. hm.l.WithField("hostMap", m{"mapName": hm.name, "indexNumber": index, "mapTotalSize": len(hm.Indexes)}).
  179. Debug("Hostmap index deleted")
  180. }
  181. }
  182. // This is used to cleanup on recv_error
  183. func (hm *HostMap) DeleteReverseIndex(index uint32) {
  184. hm.Lock()
  185. hostinfo, ok := hm.RemoteIndexes[index]
  186. if ok {
  187. delete(hm.Indexes, hostinfo.localIndexId)
  188. delete(hm.RemoteIndexes, index)
  189. // Check if we have an entry under hostId that matches the same hostinfo
  190. // instance. Clean it up as well if we do (they might not match in pendingHostmap)
  191. var hostinfo2 *HostInfo
  192. hostinfo2, ok = hm.Hosts[hostinfo.hostId]
  193. if ok && hostinfo2 == hostinfo {
  194. delete(hm.Hosts, hostinfo.hostId)
  195. }
  196. }
  197. hm.Unlock()
  198. if hm.l.Level >= logrus.DebugLevel {
  199. hm.l.WithField("hostMap", m{"mapName": hm.name, "indexNumber": index, "mapTotalSize": len(hm.Indexes)}).
  200. Debug("Hostmap remote index deleted")
  201. }
  202. }
  203. func (hm *HostMap) DeleteHostInfo(hostinfo *HostInfo) {
  204. hm.Lock()
  205. defer hm.Unlock()
  206. hm.unlockedDeleteHostInfo(hostinfo)
  207. }
  208. func (hm *HostMap) unlockedDeleteHostInfo(hostinfo *HostInfo) {
  209. // Check if this same hostId is in the hostmap with a different instance.
  210. // This could happen if we have an entry in the pending hostmap with different
  211. // index values than the one in the main hostmap.
  212. hostinfo2, ok := hm.Hosts[hostinfo.hostId]
  213. if ok && hostinfo2 != hostinfo {
  214. delete(hm.Hosts, hostinfo2.hostId)
  215. delete(hm.Indexes, hostinfo2.localIndexId)
  216. delete(hm.RemoteIndexes, hostinfo2.remoteIndexId)
  217. }
  218. delete(hm.Hosts, hostinfo.hostId)
  219. if len(hm.Hosts) == 0 {
  220. hm.Hosts = map[uint32]*HostInfo{}
  221. }
  222. delete(hm.Indexes, hostinfo.localIndexId)
  223. if len(hm.Indexes) == 0 {
  224. hm.Indexes = map[uint32]*HostInfo{}
  225. }
  226. delete(hm.RemoteIndexes, hostinfo.remoteIndexId)
  227. if len(hm.RemoteIndexes) == 0 {
  228. hm.RemoteIndexes = map[uint32]*HostInfo{}
  229. }
  230. if hm.l.Level >= logrus.DebugLevel {
  231. hm.l.WithField("hostMap", m{"mapName": hm.name, "mapTotalSize": len(hm.Hosts),
  232. "vpnIp": IntIp(hostinfo.hostId), "indexNumber": hostinfo.localIndexId, "remoteIndexNumber": hostinfo.remoteIndexId}).
  233. Debug("Hostmap hostInfo deleted")
  234. }
  235. }
  236. func (hm *HostMap) QueryIndex(index uint32) (*HostInfo, error) {
  237. //TODO: we probably just want ot return bool instead of error, or at least a static error
  238. hm.RLock()
  239. if h, ok := hm.Indexes[index]; ok {
  240. hm.RUnlock()
  241. return h, nil
  242. } else {
  243. hm.RUnlock()
  244. return nil, errors.New("unable to find index")
  245. }
  246. }
  247. func (hm *HostMap) QueryReverseIndex(index uint32) (*HostInfo, error) {
  248. hm.RLock()
  249. if h, ok := hm.RemoteIndexes[index]; ok {
  250. hm.RUnlock()
  251. return h, nil
  252. } else {
  253. hm.RUnlock()
  254. return nil, fmt.Errorf("unable to find reverse index or connectionstate nil in %s hostmap", hm.name)
  255. }
  256. }
  257. func (hm *HostMap) QueryVpnIP(vpnIp uint32) (*HostInfo, error) {
  258. return hm.queryVpnIP(vpnIp, nil)
  259. }
  260. // PromoteBestQueryVpnIP will attempt to lazily switch to the best remote every
  261. // `PromoteEvery` calls to this function for a given host.
  262. func (hm *HostMap) PromoteBestQueryVpnIP(vpnIp uint32, ifce *Interface) (*HostInfo, error) {
  263. return hm.queryVpnIP(vpnIp, ifce)
  264. }
  265. func (hm *HostMap) queryVpnIP(vpnIp uint32, promoteIfce *Interface) (*HostInfo, error) {
  266. hm.RLock()
  267. if h, ok := hm.Hosts[vpnIp]; ok {
  268. // Do not attempt promotion if you are a lighthouse
  269. if promoteIfce != nil && !promoteIfce.lightHouse.amLighthouse {
  270. h.TryPromoteBest(hm.preferredRanges, promoteIfce)
  271. }
  272. hm.RUnlock()
  273. return h, nil
  274. } else {
  275. //return &net.UDPAddr{}, nil, errors.New("Unable to find host")
  276. hm.RUnlock()
  277. /*
  278. if lightHouse != nil {
  279. lightHouse.Query(vpnIp)
  280. return nil, errors.New("Unable to find host")
  281. }
  282. */
  283. return nil, errors.New("unable to find host")
  284. }
  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. // 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 *udpAddr, 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(test, 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.hostId, ifce)
  377. }
  378. }
  379. func (i *HostInfo) cachePacket(l *logrus.Logger, t NebulaMessageType, st NebulaMessageSubType, packet []byte, f packetCallback) {
  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. i.logger(l).
  394. WithField("length", len(i.packetStore)).
  395. WithField("stored", false).
  396. Debugf("Packet store")
  397. }
  398. }
  399. // handshakeComplete will set the connection as ready to communicate, as well as flush any stored packets
  400. func (i *HostInfo) handshakeComplete(l *logrus.Logger) {
  401. //TODO: I'm not certain the distinction between handshake complete and ConnectionState being ready matters because:
  402. //TODO: HandshakeComplete means send stored packets and ConnectionState.ready means we are ready to send
  403. //TODO: if the transition from HandhsakeComplete to ConnectionState.ready happens all within this function they are identical
  404. i.ConnectionState.queueLock.Lock()
  405. i.HandshakeComplete = true
  406. //TODO: this should be managed by the handshake state machine to set it based on how many handshake were seen.
  407. // Clamping it to 2 gets us out of the woods for now
  408. atomic.StoreUint64(&i.ConnectionState.atomicMessageCounter, 2)
  409. if l.Level >= logrus.DebugLevel {
  410. i.logger(l).Debugf("Sending %d stored packets", len(i.packetStore))
  411. }
  412. if len(i.packetStore) > 0 {
  413. nb := make([]byte, 12, 12)
  414. out := make([]byte, mtu)
  415. for _, cp := range i.packetStore {
  416. cp.callback(cp.messageType, cp.messageSubType, i, cp.packet, nb, out)
  417. }
  418. }
  419. i.remotes.ResetBlockedRemotes()
  420. i.packetStore = make([]*cachedPacket, 0)
  421. i.ConnectionState.ready = true
  422. i.ConnectionState.queueLock.Unlock()
  423. i.ConnectionState.certState = nil
  424. }
  425. func (i *HostInfo) GetCert() *cert.NebulaCertificate {
  426. if i.ConnectionState != nil {
  427. return i.ConnectionState.peerCert
  428. }
  429. return nil
  430. }
  431. func (i *HostInfo) SetRemote(remote *udpAddr) {
  432. // We copy here because we likely got this remote from a source that reuses the object
  433. if !i.remote.Equals(remote) {
  434. i.remote = remote.Copy()
  435. i.remotes.LearnRemote(i.hostId, remote.Copy())
  436. }
  437. }
  438. func (i *HostInfo) ClearConnectionState() {
  439. i.ConnectionState = nil
  440. }
  441. func (i *HostInfo) RecvErrorExceeded() bool {
  442. if i.recvError < 3 {
  443. i.recvError += 1
  444. return false
  445. }
  446. return true
  447. }
  448. func (i *HostInfo) CreateRemoteCIDR(c *cert.NebulaCertificate) {
  449. if len(c.Details.Ips) == 1 && len(c.Details.Subnets) == 0 {
  450. // Simple case, no CIDRTree needed
  451. return
  452. }
  453. remoteCidr := NewCIDRTree()
  454. for _, ip := range c.Details.Ips {
  455. remoteCidr.AddCIDR(&net.IPNet{IP: ip.IP, Mask: net.IPMask{255, 255, 255, 255}}, struct{}{})
  456. }
  457. for _, n := range c.Details.Subnets {
  458. remoteCidr.AddCIDR(n, struct{}{})
  459. }
  460. i.remoteCidr = remoteCidr
  461. }
  462. func (i *HostInfo) logger(l *logrus.Logger) *logrus.Entry {
  463. if i == nil {
  464. return logrus.NewEntry(l)
  465. }
  466. li := l.WithField("vpnIp", IntIp(i.hostId))
  467. if connState := i.ConnectionState; connState != nil {
  468. if peerCert := connState.peerCert; peerCert != nil {
  469. li = li.WithField("certName", peerCert.Details.Name)
  470. }
  471. }
  472. return li
  473. }
  474. //########################
  475. /*
  476. func (hm *HostMap) DebugRemotes(vpnIp uint32) string {
  477. s := "\n"
  478. for _, h := range hm.Hosts {
  479. for _, r := range h.Remotes {
  480. s += fmt.Sprintf("%s : %d ## %v\n", r.addr.IP.String(), r.addr.Port, r.probes)
  481. }
  482. }
  483. return s
  484. }
  485. func (i *HostInfo) HandleReply(addr *net.UDPAddr, counter int) {
  486. for _, r := range i.Remotes {
  487. if r.addr.IP.Equal(addr.IP) && r.addr.Port == addr.Port {
  488. r.ProbeReceived(counter)
  489. }
  490. }
  491. }
  492. func (i *HostInfo) Probes() []*Probe {
  493. p := []*Probe{}
  494. for _, d := range i.Remotes {
  495. p = append(p, &Probe{Addr: d.addr, Counter: d.Probe()})
  496. }
  497. return p
  498. }
  499. */
  500. // Utility functions
  501. func localIps(l *logrus.Logger, allowList *AllowList) *[]net.IP {
  502. //FIXME: This function is pretty garbage
  503. var ips []net.IP
  504. ifaces, _ := net.Interfaces()
  505. for _, i := range ifaces {
  506. allow := allowList.AllowName(i.Name)
  507. if l.Level >= logrus.TraceLevel {
  508. l.WithField("interfaceName", i.Name).WithField("allow", allow).Trace("localAllowList.AllowName")
  509. }
  510. if !allow {
  511. continue
  512. }
  513. addrs, _ := i.Addrs()
  514. for _, addr := range addrs {
  515. var ip net.IP
  516. switch v := addr.(type) {
  517. case *net.IPNet:
  518. //continue
  519. ip = v.IP
  520. case *net.IPAddr:
  521. ip = v.IP
  522. }
  523. //TODO: Filtering out link local for now, this is probably the most correct thing
  524. //TODO: Would be nice to filter out SLAAC MAC based ips as well
  525. if ip.IsLoopback() == false && !ip.IsLinkLocalUnicast() {
  526. allow := allowList.Allow(ip)
  527. if l.Level >= logrus.TraceLevel {
  528. l.WithField("localIp", ip).WithField("allow", allow).Trace("localAllowList.Allow")
  529. }
  530. if !allow {
  531. continue
  532. }
  533. ips = append(ips, ip)
  534. }
  535. }
  536. }
  537. return &ips
  538. }