remote_list.go 14 KB

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