remote_list.go 14 KB

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