remote_list.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563
  1. package nebula
  2. import (
  3. "bytes"
  4. "net"
  5. "sort"
  6. "sync"
  7. "github.com/slackhq/nebula/iputil"
  8. "github.com/slackhq/nebula/udp"
  9. )
  10. // forEachFunc is used to benefit folks that want to do work inside the lock
  11. type forEachFunc func(addr *udp.Addr, preferred bool)
  12. // The checkFuncs here are to simplify bulk importing LH query response logic into a single function (reset slice and iterate)
  13. type checkFuncV4 func(vpnIp iputil.VpnIp, to *Ip4AndPort) bool
  14. type checkFuncV6 func(vpnIp iputil.VpnIp, to *Ip6AndPort) bool
  15. // CacheMap is a struct that better represents the lighthouse cache for humans
  16. // The string key is the owners vpnIp
  17. type CacheMap map[string]*Cache
  18. // Cache is the other part of CacheMap to better represent the lighthouse cache for humans
  19. // We don't reason about ipv4 vs ipv6 here
  20. type Cache struct {
  21. Learned []*udp.Addr `json:"learned,omitempty"`
  22. Reported []*udp.Addr `json:"reported,omitempty"`
  23. Relay []*net.IP `json:"relay"`
  24. }
  25. //TODO: Seems like we should plop static host entries in here too since the are protected by the lighthouse from deletion
  26. // We will never clean learned/reported information for them as it stands today
  27. // cache is an internal struct that splits v4 and v6 addresses inside the cache map
  28. type cache struct {
  29. v4 *cacheV4
  30. v6 *cacheV6
  31. relay *cacheRelay
  32. }
  33. type cacheRelay struct {
  34. relay []uint32
  35. }
  36. // cacheV4 stores learned and reported ipv4 records under cache
  37. type cacheV4 struct {
  38. learned *Ip4AndPort
  39. reported []*Ip4AndPort
  40. }
  41. // cacheV4 stores learned and reported ipv6 records under cache
  42. type cacheV6 struct {
  43. learned *Ip6AndPort
  44. reported []*Ip6AndPort
  45. }
  46. // RemoteList is a unifying concept for lighthouse servers and clients as well as hostinfos.
  47. // It serves as a local cache of query replies, host update notifications, and locally learned addresses
  48. type RemoteList struct {
  49. // Every interaction with internals requires a lock!
  50. sync.RWMutex
  51. // A deduplicated set of addresses. Any accessor should lock beforehand.
  52. addrs []*udp.Addr
  53. // A set of relay addresses. VpnIp addresses that the remote identified as relays.
  54. relays []*iputil.VpnIp
  55. // These are maps to store v4 and v6 addresses per lighthouse
  56. // Map key is the vpnIp of the person that told us about this the cached entries underneath.
  57. // For learned addresses, this is the vpnIp that sent the packet
  58. cache map[iputil.VpnIp]*cache
  59. // This is a list of remotes that we have tried to handshake with and have returned from the wrong vpn ip.
  60. // They should not be tried again during a handshake
  61. badRemotes []*udp.Addr
  62. // A flag that the cache may have changed and addrs needs to be rebuilt
  63. shouldRebuild bool
  64. }
  65. // NewRemoteList creates a new empty RemoteList
  66. func NewRemoteList() *RemoteList {
  67. return &RemoteList{
  68. addrs: make([]*udp.Addr, 0),
  69. relays: make([]*iputil.VpnIp, 0),
  70. cache: make(map[iputil.VpnIp]*cache),
  71. }
  72. }
  73. // Len locks and reports the size of the deduplicated address list
  74. // The deduplication work may need to occur here, so you must pass preferredRanges
  75. func (r *RemoteList) Len(preferredRanges []*net.IPNet) int {
  76. r.Rebuild(preferredRanges)
  77. r.RLock()
  78. defer r.RUnlock()
  79. return len(r.addrs)
  80. }
  81. // ForEach locks and will call the forEachFunc for every deduplicated address in the list
  82. // The deduplication work may need to occur here, so you must pass preferredRanges
  83. func (r *RemoteList) ForEach(preferredRanges []*net.IPNet, forEach forEachFunc) {
  84. r.Rebuild(preferredRanges)
  85. r.RLock()
  86. for _, v := range r.addrs {
  87. forEach(v, isPreferred(v.IP, preferredRanges))
  88. }
  89. r.RUnlock()
  90. }
  91. // CopyAddrs locks and makes a deep copy of the deduplicated address list
  92. // The deduplication work may need to occur here, so you must pass preferredRanges
  93. func (r *RemoteList) CopyAddrs(preferredRanges []*net.IPNet) []*udp.Addr {
  94. if r == nil {
  95. return nil
  96. }
  97. r.Rebuild(preferredRanges)
  98. r.RLock()
  99. defer r.RUnlock()
  100. c := make([]*udp.Addr, len(r.addrs))
  101. for i, v := range r.addrs {
  102. c[i] = v.Copy()
  103. }
  104. return c
  105. }
  106. // LearnRemote locks and sets the learned slot for the owner vpn ip to the provided addr
  107. // Currently this is only needed when HostInfo.SetRemote is called as that should cover both handshaking and roaming.
  108. // It will mark the deduplicated address list as dirty, so do not call it unless new information is available
  109. // TODO: this needs to support the allow list list
  110. func (r *RemoteList) LearnRemote(ownerVpnIp iputil.VpnIp, addr *udp.Addr) {
  111. r.Lock()
  112. defer r.Unlock()
  113. if v4 := addr.IP.To4(); v4 != nil {
  114. r.unlockedSetLearnedV4(ownerVpnIp, NewIp4AndPort(v4, uint32(addr.Port)))
  115. } else {
  116. r.unlockedSetLearnedV6(ownerVpnIp, NewIp6AndPort(addr.IP, uint32(addr.Port)))
  117. }
  118. }
  119. // CopyCache locks and creates a more human friendly form of the internal address cache.
  120. // This may contain duplicates and blocked addresses
  121. func (r *RemoteList) CopyCache() *CacheMap {
  122. r.RLock()
  123. defer r.RUnlock()
  124. cm := make(CacheMap)
  125. getOrMake := func(vpnIp string) *Cache {
  126. c := cm[vpnIp]
  127. if c == nil {
  128. c = &Cache{
  129. Learned: make([]*udp.Addr, 0),
  130. Reported: make([]*udp.Addr, 0),
  131. Relay: make([]*net.IP, 0),
  132. }
  133. cm[vpnIp] = c
  134. }
  135. return c
  136. }
  137. for owner, mc := range r.cache {
  138. c := getOrMake(owner.String())
  139. if mc.v4 != nil {
  140. if mc.v4.learned != nil {
  141. c.Learned = append(c.Learned, NewUDPAddrFromLH4(mc.v4.learned))
  142. }
  143. for _, a := range mc.v4.reported {
  144. c.Reported = append(c.Reported, NewUDPAddrFromLH4(a))
  145. }
  146. }
  147. if mc.v6 != nil {
  148. if mc.v6.learned != nil {
  149. c.Learned = append(c.Learned, NewUDPAddrFromLH6(mc.v6.learned))
  150. }
  151. for _, a := range mc.v6.reported {
  152. c.Reported = append(c.Reported, NewUDPAddrFromLH6(a))
  153. }
  154. }
  155. if mc.relay != nil {
  156. for _, a := range mc.relay.relay {
  157. nip := iputil.VpnIp(a).ToIP()
  158. c.Relay = append(c.Relay, &nip)
  159. }
  160. }
  161. }
  162. return &cm
  163. }
  164. // BlockRemote locks and records the address as bad, it will be excluded from the deduplicated address list
  165. func (r *RemoteList) BlockRemote(bad *udp.Addr) {
  166. if bad == nil {
  167. // relays can have nil udp Addrs
  168. return
  169. }
  170. r.Lock()
  171. defer r.Unlock()
  172. // Check if we already blocked this addr
  173. if r.unlockedIsBad(bad) {
  174. return
  175. }
  176. // We copy here because we are taking something else's memory and we can't trust everything
  177. r.badRemotes = append(r.badRemotes, bad.Copy())
  178. // Mark the next interaction must recollect/dedupe
  179. r.shouldRebuild = true
  180. }
  181. // CopyBlockedRemotes locks and makes a deep copy of the blocked remotes list
  182. func (r *RemoteList) CopyBlockedRemotes() []*udp.Addr {
  183. r.RLock()
  184. defer r.RUnlock()
  185. c := make([]*udp.Addr, len(r.badRemotes))
  186. for i, v := range r.badRemotes {
  187. c[i] = v.Copy()
  188. }
  189. return c
  190. }
  191. // ResetBlockedRemotes locks and clears the blocked remotes list
  192. func (r *RemoteList) ResetBlockedRemotes() {
  193. r.Lock()
  194. r.badRemotes = nil
  195. r.Unlock()
  196. }
  197. // Rebuild locks and generates the deduplicated address list only if there is work to be done
  198. // There is generally no reason to call this directly but it is safe to do so
  199. func (r *RemoteList) Rebuild(preferredRanges []*net.IPNet) {
  200. r.Lock()
  201. defer r.Unlock()
  202. // Only rebuild if the cache changed
  203. //TODO: shouldRebuild is probably pointless as we don't check for actual change when lighthouse updates come in
  204. if r.shouldRebuild {
  205. r.unlockedCollect()
  206. r.shouldRebuild = false
  207. }
  208. // Always re-sort, preferredRanges can change via HUP
  209. r.unlockedSort(preferredRanges)
  210. }
  211. // unlockedIsBad assumes you have the write lock and checks if the remote matches any entry in the blocked address list
  212. func (r *RemoteList) unlockedIsBad(remote *udp.Addr) bool {
  213. for _, v := range r.badRemotes {
  214. if v.Equals(remote) {
  215. return true
  216. }
  217. }
  218. return false
  219. }
  220. // unlockedSetLearnedV4 assumes you have the write lock and sets the current learned address for this owner and marks the
  221. // deduplicated address list as dirty
  222. func (r *RemoteList) unlockedSetLearnedV4(ownerVpnIp iputil.VpnIp, to *Ip4AndPort) {
  223. r.shouldRebuild = true
  224. r.unlockedGetOrMakeV4(ownerVpnIp).learned = to
  225. }
  226. // unlockedSetV4 assumes you have the write lock and resets the reported list of ips for this owner to the list provided
  227. // and marks the deduplicated address list as dirty
  228. func (r *RemoteList) unlockedSetV4(ownerVpnIp iputil.VpnIp, vpnIp iputil.VpnIp, to []*Ip4AndPort, check checkFuncV4) {
  229. r.shouldRebuild = true
  230. c := r.unlockedGetOrMakeV4(ownerVpnIp)
  231. // Reset the slice
  232. c.reported = c.reported[:0]
  233. // We can't take their array but we can take their pointers
  234. for _, v := range to[:minInt(len(to), MaxRemotes)] {
  235. if check(vpnIp, v) {
  236. c.reported = append(c.reported, v)
  237. }
  238. }
  239. }
  240. func (r *RemoteList) unlockedSetRelay(ownerVpnIp iputil.VpnIp, vpnIp iputil.VpnIp, to []uint32) {
  241. r.shouldRebuild = true
  242. c := r.unlockedGetOrMakeRelay(ownerVpnIp)
  243. // Reset the slice
  244. c.relay = c.relay[:0]
  245. // We can't take their array but we can take their pointers
  246. c.relay = append(c.relay, to[:minInt(len(to), MaxRemotes)]...)
  247. }
  248. // unlockedPrependV4 assumes you have the write lock and prepends the address in the reported list for this owner
  249. // This is only useful for establishing static hosts
  250. func (r *RemoteList) unlockedPrependV4(ownerVpnIp iputil.VpnIp, to *Ip4AndPort) {
  251. r.shouldRebuild = true
  252. c := r.unlockedGetOrMakeV4(ownerVpnIp)
  253. // We are doing the easy append because this is rarely called
  254. c.reported = append([]*Ip4AndPort{to}, c.reported...)
  255. if len(c.reported) > MaxRemotes {
  256. c.reported = c.reported[:MaxRemotes]
  257. }
  258. }
  259. // unlockedSetLearnedV6 assumes you have the write lock and sets the current learned address for this owner and marks the
  260. // deduplicated address list as dirty
  261. func (r *RemoteList) unlockedSetLearnedV6(ownerVpnIp iputil.VpnIp, to *Ip6AndPort) {
  262. r.shouldRebuild = true
  263. r.unlockedGetOrMakeV6(ownerVpnIp).learned = to
  264. }
  265. // unlockedSetV6 assumes you have the write lock and resets the reported list of ips for this owner to the list provided
  266. // and marks the deduplicated address list as dirty
  267. func (r *RemoteList) unlockedSetV6(ownerVpnIp iputil.VpnIp, vpnIp iputil.VpnIp, to []*Ip6AndPort, check checkFuncV6) {
  268. r.shouldRebuild = true
  269. c := r.unlockedGetOrMakeV6(ownerVpnIp)
  270. // Reset the slice
  271. c.reported = c.reported[:0]
  272. // We can't take their array but we can take their pointers
  273. for _, v := range to[:minInt(len(to), MaxRemotes)] {
  274. if check(vpnIp, v) {
  275. c.reported = append(c.reported, v)
  276. }
  277. }
  278. }
  279. // unlockedPrependV6 assumes you have the write lock and prepends the address in the reported list for this owner
  280. // This is only useful for establishing static hosts
  281. func (r *RemoteList) unlockedPrependV6(ownerVpnIp iputil.VpnIp, to *Ip6AndPort) {
  282. r.shouldRebuild = true
  283. c := r.unlockedGetOrMakeV6(ownerVpnIp)
  284. // We are doing the easy append because this is rarely called
  285. c.reported = append([]*Ip6AndPort{to}, c.reported...)
  286. if len(c.reported) > MaxRemotes {
  287. c.reported = c.reported[:MaxRemotes]
  288. }
  289. }
  290. func (r *RemoteList) unlockedGetOrMakeRelay(ownerVpnIp iputil.VpnIp) *cacheRelay {
  291. am := r.cache[ownerVpnIp]
  292. if am == nil {
  293. am = &cache{}
  294. r.cache[ownerVpnIp] = am
  295. }
  296. // Avoid occupying memory for relay if we never have any
  297. if am.relay == nil {
  298. am.relay = &cacheRelay{}
  299. }
  300. return am.relay
  301. }
  302. // unlockedGetOrMakeV4 assumes you have the write lock and builds the cache and owner entry. Only the v4 pointer is established.
  303. // The caller must dirty the learned address cache if required
  304. func (r *RemoteList) unlockedGetOrMakeV4(ownerVpnIp iputil.VpnIp) *cacheV4 {
  305. am := r.cache[ownerVpnIp]
  306. if am == nil {
  307. am = &cache{}
  308. r.cache[ownerVpnIp] = am
  309. }
  310. // Avoid occupying memory for v6 addresses if we never have any
  311. if am.v4 == nil {
  312. am.v4 = &cacheV4{}
  313. }
  314. return am.v4
  315. }
  316. // unlockedGetOrMakeV6 assumes you have the write lock and builds the cache and owner entry. Only the v6 pointer is established.
  317. // The caller must dirty the learned address cache if required
  318. func (r *RemoteList) unlockedGetOrMakeV6(ownerVpnIp iputil.VpnIp) *cacheV6 {
  319. am := r.cache[ownerVpnIp]
  320. if am == nil {
  321. am = &cache{}
  322. r.cache[ownerVpnIp] = am
  323. }
  324. // Avoid occupying memory for v4 addresses if we never have any
  325. if am.v6 == nil {
  326. am.v6 = &cacheV6{}
  327. }
  328. return am.v6
  329. }
  330. // unlockedCollect assumes you have the write lock and collects/transforms the cache into the deduped address list.
  331. // The result of this function can contain duplicates. unlockedSort handles cleaning it.
  332. func (r *RemoteList) unlockedCollect() {
  333. addrs := r.addrs[:0]
  334. relays := r.relays[:0]
  335. for _, c := range r.cache {
  336. if c.v4 != nil {
  337. if c.v4.learned != nil {
  338. u := NewUDPAddrFromLH4(c.v4.learned)
  339. if !r.unlockedIsBad(u) {
  340. addrs = append(addrs, u)
  341. }
  342. }
  343. for _, v := range c.v4.reported {
  344. u := NewUDPAddrFromLH4(v)
  345. if !r.unlockedIsBad(u) {
  346. addrs = append(addrs, u)
  347. }
  348. }
  349. }
  350. if c.v6 != nil {
  351. if c.v6.learned != nil {
  352. u := NewUDPAddrFromLH6(c.v6.learned)
  353. if !r.unlockedIsBad(u) {
  354. addrs = append(addrs, u)
  355. }
  356. }
  357. for _, v := range c.v6.reported {
  358. u := NewUDPAddrFromLH6(v)
  359. if !r.unlockedIsBad(u) {
  360. addrs = append(addrs, u)
  361. }
  362. }
  363. }
  364. if c.relay != nil {
  365. for _, v := range c.relay.relay {
  366. ip := iputil.VpnIp(v)
  367. relays = append(relays, &ip)
  368. }
  369. }
  370. }
  371. r.addrs = addrs
  372. r.relays = relays
  373. }
  374. // unlockedSort assumes you have the write lock and performs the deduping and sorting of the address list
  375. func (r *RemoteList) unlockedSort(preferredRanges []*net.IPNet) {
  376. n := len(r.addrs)
  377. if n < 2 {
  378. return
  379. }
  380. lessFunc := func(i, j int) bool {
  381. a := r.addrs[i]
  382. b := r.addrs[j]
  383. // Preferred addresses first
  384. aPref := isPreferred(a.IP, preferredRanges)
  385. bPref := isPreferred(b.IP, preferredRanges)
  386. switch {
  387. case aPref && !bPref:
  388. // If i is preferred and j is not, i is less than j
  389. return true
  390. case !aPref && bPref:
  391. // If j is preferred then i is not due to the else, i is not less than j
  392. return false
  393. default:
  394. // Both i an j are either preferred or not, sort within that
  395. }
  396. // ipv6 addresses 2nd
  397. a4 := a.IP.To4()
  398. b4 := b.IP.To4()
  399. switch {
  400. case a4 == nil && b4 != nil:
  401. // If i is v6 and j is v4, i is less than j
  402. return true
  403. case a4 != nil && b4 == nil:
  404. // If j is v6 and i is v4, i is not less than j
  405. return false
  406. case a4 != nil && b4 != nil:
  407. // Special case for ipv4, a4 and b4 are not nil
  408. aPrivate := isPrivateIP(a4)
  409. bPrivate := isPrivateIP(b4)
  410. switch {
  411. case !aPrivate && bPrivate:
  412. // If i is a public ip (not private) and j is a private ip, i is less then j
  413. return true
  414. case aPrivate && !bPrivate:
  415. // If j is public (not private) then i is private due to the else, i is not less than j
  416. return false
  417. default:
  418. // Both i an j are either public or private, sort within that
  419. }
  420. default:
  421. // Both i an j are either ipv4 or ipv6, sort within that
  422. }
  423. // lexical order of ips 3rd
  424. c := bytes.Compare(a.IP, b.IP)
  425. if c == 0 {
  426. // Ips are the same, Lexical order of ports 4th
  427. return a.Port < b.Port
  428. }
  429. // Ip wasn't the same
  430. return c < 0
  431. }
  432. // Sort it
  433. sort.Slice(r.addrs, lessFunc)
  434. // Deduplicate
  435. a, b := 0, 1
  436. for b < n {
  437. if !r.addrs[a].Equals(r.addrs[b]) {
  438. a++
  439. if a != b {
  440. r.addrs[a], r.addrs[b] = r.addrs[b], r.addrs[a]
  441. }
  442. }
  443. b++
  444. }
  445. r.addrs = r.addrs[:a+1]
  446. return
  447. }
  448. // minInt returns the minimum integer of a or b
  449. func minInt(a, b int) int {
  450. if a < b {
  451. return a
  452. }
  453. return b
  454. }
  455. // isPreferred returns true of the ip is contained in the preferredRanges list
  456. func isPreferred(ip net.IP, preferredRanges []*net.IPNet) bool {
  457. //TODO: this would be better in a CIDR6Tree
  458. for _, p := range preferredRanges {
  459. if p.Contains(ip) {
  460. return true
  461. }
  462. }
  463. return false
  464. }
  465. var _, private24BitBlock, _ = net.ParseCIDR("10.0.0.0/8")
  466. var _, private20BitBlock, _ = net.ParseCIDR("172.16.0.0/12")
  467. var _, private16BitBlock, _ = net.ParseCIDR("192.168.0.0/16")
  468. // isPrivateIP returns true if the ip is contained by a rfc 1918 private range
  469. func isPrivateIP(ip net.IP) bool {
  470. //TODO: another great cidrtree option
  471. //TODO: Private for ipv6 or just let it ride?
  472. return private24BitBlock.Contains(ip) || private20BitBlock.Contains(ip) || private16BitBlock.Contains(ip)
  473. }