remote_list.go 14 KB

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