1
0

lighthouse.go 41 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535
  1. package nebula
  2. import (
  3. "context"
  4. "encoding/binary"
  5. "errors"
  6. "fmt"
  7. "log/slog"
  8. "net"
  9. "net/netip"
  10. "slices"
  11. "strconv"
  12. "sync"
  13. "sync/atomic"
  14. "time"
  15. "github.com/gaissmai/bart"
  16. "github.com/slackhq/nebula/cert"
  17. "github.com/slackhq/nebula/config"
  18. "github.com/slackhq/nebula/header"
  19. "github.com/slackhq/nebula/logging"
  20. "github.com/slackhq/nebula/udp"
  21. "github.com/slackhq/nebula/util"
  22. )
  23. var ErrHostNotKnown = errors.New("host not known")
  24. var ErrBadDetailsVpnAddr = errors.New("invalid packet, malformed detailsVpnAddr")
  25. type LightHouse struct {
  26. //TODO: We need a timer wheel to kick out vpnAddrs that haven't reported in a long time
  27. sync.RWMutex //Because we concurrently read and write to our maps
  28. ctx context.Context
  29. amLighthouse bool
  30. myVpnNetworks []netip.Prefix
  31. myVpnNetworksTable *bart.Lite
  32. punchy *Punchy
  33. // Local cache of answers from light houses
  34. // map of vpn addr to answers
  35. addrMap map[netip.Addr]*RemoteList
  36. // filters remote addresses allowed for each host
  37. // - When we are a lighthouse, this filters what addresses we store and
  38. // respond with.
  39. // - When we are not a lighthouse, this filters which addresses we accept
  40. // from lighthouses.
  41. remoteAllowList atomic.Pointer[RemoteAllowList]
  42. // filters local addresses that we advertise to lighthouses
  43. localAllowList atomic.Pointer[LocalAllowList]
  44. // used to trigger the HandshakeManager when we receive HostQueryReply
  45. handshakeTrigger chan<- netip.Addr
  46. // staticList exists to avoid having a bool in each addrMap entry
  47. // since static should be rare
  48. staticList atomic.Pointer[map[netip.Addr]struct{}]
  49. lighthouses atomic.Pointer[[]netip.Addr]
  50. interval atomic.Int64
  51. updateCancel context.CancelFunc
  52. ifce EncWriter
  53. nebulaPort uint32 // 32 bits because protobuf does not have a uint16
  54. advertiseAddrs atomic.Pointer[[]netip.AddrPort]
  55. // Addr's of relays that can be used by peers to access me
  56. relaysForMe atomic.Pointer[[]netip.Addr]
  57. updateTrigger chan struct{}
  58. queryChan chan netip.Addr
  59. calculatedRemotes atomic.Pointer[bart.Table[[]*calculatedRemote]] // Maps VpnAddr to []*calculatedRemote
  60. metrics *MessageMetrics
  61. l *slog.Logger
  62. }
  63. // NewLightHouseFromConfig will build a Lighthouse struct from the values provided in the config object
  64. // addrMap should be nil unless this is during a config reload
  65. func NewLightHouseFromConfig(ctx context.Context, l *slog.Logger, c *config.C, cs *CertState, pc udp.Conn, p *Punchy) (*LightHouse, error) {
  66. amLighthouse := c.GetBool("lighthouse.am_lighthouse", false)
  67. nebulaPort := uint32(c.GetInt("listen.port", 0))
  68. if amLighthouse && nebulaPort == 0 {
  69. return nil, util.NewContextualError("lighthouse.am_lighthouse enabled on node but no port number is set in config", nil, nil)
  70. }
  71. // If port is dynamic, discover it
  72. if nebulaPort == 0 && pc != nil {
  73. uPort, err := pc.LocalAddr()
  74. if err != nil {
  75. return nil, util.NewContextualError("Failed to get listening port", nil, err)
  76. }
  77. nebulaPort = uint32(uPort.Port())
  78. }
  79. h := LightHouse{
  80. ctx: ctx,
  81. amLighthouse: amLighthouse,
  82. myVpnNetworks: cs.myVpnNetworks,
  83. myVpnNetworksTable: cs.myVpnNetworksTable,
  84. addrMap: make(map[netip.Addr]*RemoteList),
  85. nebulaPort: nebulaPort,
  86. punchy: p,
  87. updateTrigger: make(chan struct{}, 1),
  88. queryChan: make(chan netip.Addr, c.GetUint32("handshakes.query_buffer", 64)),
  89. l: l,
  90. }
  91. lighthouses := make([]netip.Addr, 0)
  92. h.lighthouses.Store(&lighthouses)
  93. staticList := make(map[netip.Addr]struct{})
  94. h.staticList.Store(&staticList)
  95. if c.GetBool("stats.lighthouse_metrics", false) {
  96. h.metrics = newLighthouseMetrics()
  97. }
  98. err := h.reload(c, true)
  99. if err != nil {
  100. return nil, err
  101. }
  102. c.RegisterReloadCallback(func(c *config.C) {
  103. err := h.reload(c, false)
  104. switch v := err.(type) {
  105. case *util.ContextualError:
  106. v.Log(l)
  107. case error:
  108. l.Error("failed to reload lighthouse", "error", err)
  109. }
  110. })
  111. h.startQueryWorker()
  112. return &h, nil
  113. }
  114. func (lh *LightHouse) GetStaticHostList() map[netip.Addr]struct{} {
  115. return *lh.staticList.Load()
  116. }
  117. func (lh *LightHouse) GetLighthouses() []netip.Addr {
  118. return *lh.lighthouses.Load()
  119. }
  120. func (lh *LightHouse) GetRemoteAllowList() *RemoteAllowList {
  121. return lh.remoteAllowList.Load()
  122. }
  123. func (lh *LightHouse) GetLocalAllowList() *LocalAllowList {
  124. return lh.localAllowList.Load()
  125. }
  126. func (lh *LightHouse) GetAdvertiseAddrs() []netip.AddrPort {
  127. return *lh.advertiseAddrs.Load()
  128. }
  129. func (lh *LightHouse) GetRelaysForMe() []netip.Addr {
  130. return *lh.relaysForMe.Load()
  131. }
  132. func (lh *LightHouse) getCalculatedRemotes() *bart.Table[[]*calculatedRemote] {
  133. return lh.calculatedRemotes.Load()
  134. }
  135. func (lh *LightHouse) GetUpdateInterval() int64 {
  136. return lh.interval.Load()
  137. }
  138. func (lh *LightHouse) reload(c *config.C, initial bool) error {
  139. if initial || c.HasChanged("lighthouse.advertise_addrs") {
  140. rawAdvAddrs := c.GetStringSlice("lighthouse.advertise_addrs", []string{})
  141. advAddrs := make([]netip.AddrPort, 0)
  142. for i, rawAddr := range rawAdvAddrs {
  143. host, sport, err := net.SplitHostPort(rawAddr)
  144. if err != nil {
  145. return util.NewContextualError("Unable to parse lighthouse.advertise_addrs entry", m{"addr": rawAddr, "entry": i + 1}, err)
  146. }
  147. addrs, err := net.DefaultResolver.LookupNetIP(context.Background(), "ip", host)
  148. if err != nil {
  149. return util.NewContextualError("Unable to lookup lighthouse.advertise_addrs entry", m{"addr": rawAddr, "entry": i + 1}, err)
  150. }
  151. if len(addrs) == 0 {
  152. return util.NewContextualError("Unable to lookup lighthouse.advertise_addrs entry", m{"addr": rawAddr, "entry": i + 1}, nil)
  153. }
  154. port, err := strconv.Atoi(sport)
  155. if err != nil {
  156. return util.NewContextualError("Unable to parse port in lighthouse.advertise_addrs entry", m{"addr": rawAddr, "entry": i + 1}, err)
  157. }
  158. if port == 0 {
  159. port = int(lh.nebulaPort)
  160. }
  161. //TODO: we could technically insert all returned addrs instead of just the first one if a dns lookup was used
  162. addr := addrs[0].Unmap()
  163. if lh.myVpnNetworksTable.Contains(addr) {
  164. lh.l.Warn("Ignoring lighthouse.advertise_addrs report because it is within the nebula network range",
  165. "addr", rawAddr,
  166. "entry", i+1,
  167. )
  168. continue
  169. }
  170. advAddrs = append(advAddrs, netip.AddrPortFrom(addr, uint16(port)))
  171. }
  172. lh.advertiseAddrs.Store(&advAddrs)
  173. if !initial {
  174. lh.l.Info("lighthouse.advertise_addrs has changed")
  175. }
  176. }
  177. if initial || c.HasChanged("lighthouse.interval") {
  178. lh.interval.Store(int64(c.GetInt("lighthouse.interval", 10)))
  179. if !initial {
  180. lh.l.Info("lighthouse.interval changed",
  181. "interval", lh.interval.Load(),
  182. )
  183. if lh.updateCancel != nil {
  184. // May not always have a running routine
  185. lh.updateCancel()
  186. }
  187. lh.StartUpdateWorker()
  188. }
  189. }
  190. if initial || c.HasChanged("lighthouse.remote_allow_list") || c.HasChanged("lighthouse.remote_allow_ranges") {
  191. ral, err := NewRemoteAllowListFromConfig(c, "lighthouse.remote_allow_list", "lighthouse.remote_allow_ranges")
  192. if err != nil {
  193. return util.NewContextualError("Invalid lighthouse.remote_allow_list", nil, err)
  194. }
  195. lh.remoteAllowList.Store(ral)
  196. if !initial {
  197. lh.l.Info("lighthouse.remote_allow_list and/or lighthouse.remote_allow_ranges has changed")
  198. }
  199. }
  200. if initial || c.HasChanged("lighthouse.local_allow_list") {
  201. lal, err := NewLocalAllowListFromConfig(c, "lighthouse.local_allow_list")
  202. if err != nil {
  203. return util.NewContextualError("Invalid lighthouse.local_allow_list", nil, err)
  204. }
  205. lh.localAllowList.Store(lal)
  206. if !initial {
  207. lh.l.Info("lighthouse.local_allow_list has changed")
  208. }
  209. }
  210. if initial || c.HasChanged("lighthouse.calculated_remotes") {
  211. cr, err := NewCalculatedRemotesFromConfig(c, "lighthouse.calculated_remotes")
  212. if err != nil {
  213. return util.NewContextualError("Invalid lighthouse.calculated_remotes", nil, err)
  214. }
  215. lh.calculatedRemotes.Store(cr)
  216. if !initial {
  217. lh.l.Info("lighthouse.calculated_remotes has changed")
  218. }
  219. }
  220. //NOTE: many things will get much simpler when we combine static_host_map and lighthouse.hosts in config
  221. if initial || c.HasChanged("static_host_map") || c.HasChanged("static_map.cadence") || c.HasChanged("static_map.network") || c.HasChanged("static_map.lookup_timeout") {
  222. // Clean up. Entries still in the static_host_map will be re-built.
  223. ourselves := lh.myVpnNetworks[0].Addr()
  224. oldStaticList := lh.staticList.Load()
  225. if oldStaticList != nil {
  226. lh.RLock()
  227. for staticVpnAddr := range *oldStaticList {
  228. if am, ok := lh.addrMap[staticVpnAddr]; ok && am != nil {
  229. am.ResetForOwner(ourselves)
  230. }
  231. }
  232. lh.RUnlock()
  233. }
  234. // Build a new list based on current config.
  235. staticList := make(map[netip.Addr]struct{})
  236. err := lh.loadStaticMap(c, staticList)
  237. if err != nil {
  238. return err
  239. }
  240. // For entries removed from static_host_map, stop the DNS goroutine and drop the cached addrs.
  241. // All addrs must come from the lighthouses now that it's no longer a static host.
  242. if oldStaticList != nil {
  243. lh.RLock()
  244. for staticVpnAddr := range *oldStaticList {
  245. if _, stillStatic := staticList[staticVpnAddr]; stillStatic {
  246. continue
  247. }
  248. if am, ok := lh.addrMap[staticVpnAddr]; ok && am != nil {
  249. am.ClearHostnameResults()
  250. }
  251. }
  252. lh.RUnlock()
  253. }
  254. lh.staticList.Store(&staticList)
  255. if !initial {
  256. if c.HasChanged("static_host_map") {
  257. lh.l.Info("static_host_map has changed")
  258. }
  259. if c.HasChanged("static_map.cadence") {
  260. lh.l.Info("static_map.cadence has changed")
  261. }
  262. if c.HasChanged("static_map.network") {
  263. lh.l.Info("static_map.network has changed")
  264. }
  265. if c.HasChanged("static_map.lookup_timeout") {
  266. lh.l.Info("static_map.lookup_timeout has changed")
  267. }
  268. }
  269. }
  270. if initial || c.HasChanged("lighthouse.hosts") {
  271. lhList, err := lh.parseLighthouses(c)
  272. if err != nil {
  273. return err
  274. }
  275. lh.lighthouses.Store(&lhList)
  276. if !initial {
  277. //NOTE: we are not tearing down existing lighthouse connections because they might be used for non lighthouse traffic
  278. lh.l.Info("lighthouse.hosts has changed")
  279. lh.TriggerUpdate()
  280. }
  281. }
  282. if initial || c.HasChanged("relay.relays") {
  283. switch c.GetBool("relay.am_relay", false) {
  284. case true:
  285. // Relays aren't allowed to specify other relays
  286. if len(c.GetStringSlice("relay.relays", nil)) > 0 {
  287. lh.l.Info("Ignoring relays from config because am_relay is true")
  288. }
  289. relaysForMe := []netip.Addr{}
  290. lh.relaysForMe.Store(&relaysForMe)
  291. case false:
  292. relaysForMe := []netip.Addr{}
  293. for _, v := range c.GetStringSlice("relay.relays", nil) {
  294. configRIP, err := netip.ParseAddr(v)
  295. if err != nil {
  296. lh.l.Warn("Parse relay from config failed",
  297. "relay", v,
  298. "error", err,
  299. )
  300. } else {
  301. lh.l.Info("Read relay from config", "relay", v)
  302. relaysForMe = append(relaysForMe, configRIP)
  303. }
  304. }
  305. lh.relaysForMe.Store(&relaysForMe)
  306. }
  307. }
  308. return nil
  309. }
  310. func (lh *LightHouse) parseLighthouses(c *config.C) ([]netip.Addr, error) {
  311. lhs := c.GetStringSlice("lighthouse.hosts", []string{})
  312. if lh.amLighthouse && len(lhs) != 0 {
  313. lh.l.Warn("lighthouse.am_lighthouse enabled on node but upstream lighthouses exist in config")
  314. }
  315. out := make([]netip.Addr, len(lhs))
  316. for i, host := range lhs {
  317. addr, err := netip.ParseAddr(host)
  318. if err != nil {
  319. return nil, util.NewContextualError("Unable to parse lighthouse host entry", m{"host": host, "entry": i + 1}, err)
  320. }
  321. if !lh.myVpnNetworksTable.Contains(addr) {
  322. lh.l.Warn("lighthouse host is not within our networks, lighthouse functionality will work but layer 3 network traffic to the lighthouse will not",
  323. "vpnAddr", addr,
  324. "networks", lh.myVpnNetworks,
  325. )
  326. }
  327. out[i] = addr
  328. }
  329. if !lh.amLighthouse && len(out) == 0 {
  330. lh.l.Warn("No lighthouse.hosts configured, this host will only be able to initiate tunnels with static_host_map entries")
  331. }
  332. staticList := lh.GetStaticHostList()
  333. for i := range out {
  334. if _, ok := staticList[out[i]]; !ok {
  335. return nil, fmt.Errorf("lighthouse %s does not have a static_host_map entry", out[i])
  336. }
  337. }
  338. return out, nil
  339. }
  340. func getStaticMapCadence(c *config.C) (time.Duration, error) {
  341. cadence := c.GetString("static_map.cadence", "30s")
  342. d, err := time.ParseDuration(cadence)
  343. if err != nil {
  344. return 0, err
  345. }
  346. return d, nil
  347. }
  348. func getStaticMapLookupTimeout(c *config.C) (time.Duration, error) {
  349. lookupTimeout := c.GetString("static_map.lookup_timeout", "250ms")
  350. d, err := time.ParseDuration(lookupTimeout)
  351. if err != nil {
  352. return 0, err
  353. }
  354. return d, nil
  355. }
  356. func getStaticMapNetwork(c *config.C) (string, error) {
  357. network := c.GetString("static_map.network", "ip4")
  358. if network != "ip" && network != "ip4" && network != "ip6" {
  359. return "", fmt.Errorf("static_map.network must be one of ip, ip4, or ip6")
  360. }
  361. return network, nil
  362. }
  363. func (lh *LightHouse) loadStaticMap(c *config.C, staticList map[netip.Addr]struct{}) error {
  364. d, err := getStaticMapCadence(c)
  365. if err != nil {
  366. return err
  367. }
  368. network, err := getStaticMapNetwork(c)
  369. if err != nil {
  370. return err
  371. }
  372. lookupTimeout, err := getStaticMapLookupTimeout(c)
  373. if err != nil {
  374. return err
  375. }
  376. shm := c.GetMap("static_host_map", map[string]any{})
  377. i := 0
  378. for k, v := range shm {
  379. vpnAddr, err := netip.ParseAddr(fmt.Sprintf("%v", k))
  380. if err != nil {
  381. return util.NewContextualError("Unable to parse static_host_map entry", m{"host": k, "entry": i + 1}, err)
  382. }
  383. if !lh.myVpnNetworksTable.Contains(vpnAddr) {
  384. lh.l.Warn("static_host_map key is not within our networks, layer 3 network traffic to this host will not work",
  385. "vpnAddr", vpnAddr,
  386. "networks", lh.myVpnNetworks,
  387. "entry", i+1,
  388. )
  389. }
  390. vals, ok := v.([]any)
  391. if !ok {
  392. vals = []any{v}
  393. }
  394. remoteAddrs := []string{}
  395. for _, v := range vals {
  396. remoteAddrs = append(remoteAddrs, fmt.Sprintf("%v", v))
  397. }
  398. err = lh.addStaticRemotes(i, d, network, lookupTimeout, vpnAddr, remoteAddrs, staticList)
  399. if err != nil {
  400. return err
  401. }
  402. i++
  403. }
  404. return nil
  405. }
  406. func (lh *LightHouse) Query(vpnAddr netip.Addr) *RemoteList {
  407. if !lh.IsLighthouseAddr(vpnAddr) {
  408. lh.QueryServer(vpnAddr)
  409. }
  410. lh.RLock()
  411. if v, ok := lh.addrMap[vpnAddr]; ok {
  412. lh.RUnlock()
  413. return v
  414. }
  415. lh.RUnlock()
  416. return nil
  417. }
  418. // QueryServer is asynchronous so no reply should be expected
  419. func (lh *LightHouse) QueryServer(vpnAddr netip.Addr) {
  420. // Don't put lighthouse addrs in the query channel because we can't query lighthouses about lighthouses
  421. if lh.amLighthouse || lh.IsLighthouseAddr(vpnAddr) {
  422. return
  423. }
  424. lh.queryChan <- vpnAddr
  425. }
  426. func (lh *LightHouse) QueryCache(vpnAddrs []netip.Addr) *RemoteList {
  427. lh.RLock()
  428. if v, ok := lh.addrMap[vpnAddrs[0]]; ok {
  429. lh.RUnlock()
  430. return v
  431. }
  432. lh.RUnlock()
  433. lh.Lock()
  434. defer lh.Unlock()
  435. // Add an entry if we don't already have one
  436. return lh.unlockedGetRemoteList(vpnAddrs) //todo CERT-V2 this contains addrmap lookups we could potentially skip
  437. }
  438. // queryAndPrepMessage is a lock helper on RemoteList, assisting the caller to build a lighthouse message containing
  439. // details from the remote list. It looks for a hit in the addrMap and a hit in the RemoteList under the owner vpnAddr
  440. // If one is found then f() is called with proper locking, f() must return result of n.MarshalTo()
  441. func (lh *LightHouse) queryAndPrepMessage(vpnAddr netip.Addr, f func(*cache) (int, error)) (bool, int, error) {
  442. lh.RLock()
  443. // Do we have an entry in the main cache?
  444. if v, ok := lh.addrMap[vpnAddr]; ok {
  445. // Swap lh lock for remote list lock
  446. v.RLock()
  447. defer v.RUnlock()
  448. lh.RUnlock()
  449. // We may be asking about a non primary address so lets get the primary address
  450. if slices.Contains(v.vpnAddrs, vpnAddr) {
  451. vpnAddr = v.vpnAddrs[0]
  452. }
  453. c := v.cache[vpnAddr]
  454. // Make sure we have
  455. if c != nil {
  456. n, err := f(c)
  457. return true, n, err
  458. }
  459. return false, 0, nil
  460. }
  461. lh.RUnlock()
  462. return false, 0, nil
  463. }
  464. func (lh *LightHouse) DeleteVpnAddrs(allVpnAddrs []netip.Addr) {
  465. // First we check the static host map. If any of the VpnAddrs to be deleted are present, do nothing.
  466. staticList := lh.GetStaticHostList()
  467. for _, addr := range allVpnAddrs {
  468. if _, ok := staticList[addr]; ok {
  469. return
  470. }
  471. }
  472. // None of the VpnAddrs were present. Now we can do the deletes.
  473. lh.Lock()
  474. rm, ok := lh.addrMap[allVpnAddrs[0]]
  475. if ok {
  476. debugEnabled := lh.l.Enabled(context.Background(), slog.LevelDebug)
  477. for _, addr := range allVpnAddrs {
  478. srm := lh.addrMap[addr]
  479. if srm == rm {
  480. delete(lh.addrMap, addr)
  481. if debugEnabled {
  482. lh.l.Debug("deleting from lighthouse", "vpnAddr", addr)
  483. }
  484. }
  485. }
  486. }
  487. lh.Unlock()
  488. }
  489. // AddStaticRemote adds a static host entry for vpnAddr as ourselves as the owner
  490. // We are the owner because we don't want a lighthouse server to advertise for static hosts it was configured with
  491. // And we don't want a lighthouse query reply to interfere with our learned cache if we are a client
  492. // NOTE: this function should not interact with any hot path objects, like lh.staticList, the caller should handle it
  493. func (lh *LightHouse) addStaticRemotes(i int, d time.Duration, network string, timeout time.Duration, vpnAddr netip.Addr, toAddrs []string, staticList map[netip.Addr]struct{}) error {
  494. lh.Lock()
  495. am := lh.unlockedGetRemoteList([]netip.Addr{vpnAddr})
  496. am.Lock()
  497. defer am.Unlock()
  498. ctx := lh.ctx
  499. lh.Unlock()
  500. hr, err := NewHostnameResults(ctx, lh.l, d, network, timeout, toAddrs, func() {
  501. // This callback runs whenever the DNS hostname resolver finds a different set of addr's
  502. // in its resolution for hostnames.
  503. am.Lock()
  504. defer am.Unlock()
  505. am.shouldRebuild = true
  506. })
  507. if err != nil {
  508. return util.NewContextualError("Static host address could not be parsed", m{"vpnAddr": vpnAddr, "entry": i + 1}, err)
  509. }
  510. am.unlockedSetHostnamesResults(hr)
  511. for _, addrPort := range hr.GetAddrs() {
  512. if !lh.shouldAdd([]netip.Addr{vpnAddr}, addrPort.Addr()) {
  513. continue
  514. }
  515. switch {
  516. case addrPort.Addr().Is4():
  517. am.unlockedPrependV4(lh.myVpnNetworks[0].Addr(), netAddrToProtoV4AddrPort(addrPort.Addr(), addrPort.Port()))
  518. case addrPort.Addr().Is6():
  519. am.unlockedPrependV6(lh.myVpnNetworks[0].Addr(), netAddrToProtoV6AddrPort(addrPort.Addr(), addrPort.Port()))
  520. }
  521. }
  522. // Mark it as static in the caller provided map
  523. staticList[vpnAddr] = struct{}{}
  524. return nil
  525. }
  526. // addCalculatedRemotes adds any calculated remotes based on the
  527. // lighthouse.calculated_remotes configuration. It returns true if any
  528. // calculated remotes were added
  529. func (lh *LightHouse) addCalculatedRemotes(vpnAddr netip.Addr) bool {
  530. tree := lh.getCalculatedRemotes()
  531. if tree == nil {
  532. return false
  533. }
  534. calculatedRemotes, ok := tree.Lookup(vpnAddr)
  535. if !ok {
  536. return false
  537. }
  538. var calculatedV4 []*V4AddrPort
  539. var calculatedV6 []*V6AddrPort
  540. for _, cr := range calculatedRemotes {
  541. if vpnAddr.Is4() {
  542. c := cr.ApplyV4(vpnAddr)
  543. if c != nil {
  544. calculatedV4 = append(calculatedV4, c)
  545. }
  546. } else if vpnAddr.Is6() {
  547. c := cr.ApplyV6(vpnAddr)
  548. if c != nil {
  549. calculatedV6 = append(calculatedV6, c)
  550. }
  551. }
  552. }
  553. lh.Lock()
  554. am := lh.unlockedGetRemoteList([]netip.Addr{vpnAddr})
  555. am.Lock()
  556. defer am.Unlock()
  557. lh.Unlock()
  558. if len(calculatedV4) > 0 {
  559. am.unlockedSetV4(lh.myVpnNetworks[0].Addr(), vpnAddr, calculatedV4, lh.unlockedShouldAddV4)
  560. }
  561. if len(calculatedV6) > 0 {
  562. am.unlockedSetV6(lh.myVpnNetworks[0].Addr(), vpnAddr, calculatedV6, lh.unlockedShouldAddV6)
  563. }
  564. return len(calculatedV4) > 0 || len(calculatedV6) > 0
  565. }
  566. // unlockedGetRemoteList assumes you have the lh lock
  567. func (lh *LightHouse) unlockedGetRemoteList(allAddrs []netip.Addr) *RemoteList {
  568. // before we go and make a new remotelist, we need to make sure we don't have one for any of this set of vpnaddrs yet
  569. for i, addr := range allAddrs {
  570. am, ok := lh.addrMap[addr]
  571. if ok {
  572. if i != 0 {
  573. lh.addrMap[allAddrs[0]] = am
  574. }
  575. return am
  576. }
  577. }
  578. am := NewRemoteList(allAddrs, lh.shouldAdd)
  579. for _, addr := range allAddrs {
  580. lh.addrMap[addr] = am
  581. }
  582. return am
  583. }
  584. func (lh *LightHouse) shouldAdd(vpnAddrs []netip.Addr, to netip.Addr) bool {
  585. allow := lh.GetRemoteAllowList().AllowAll(vpnAddrs, to)
  586. if lh.l.Enabled(context.Background(), logging.LevelTrace) {
  587. lh.l.Log(context.Background(), logging.LevelTrace, "remoteAllowList.Allow",
  588. "vpnAddrs", vpnAddrs,
  589. "udpAddr", to,
  590. "allow", allow,
  591. )
  592. }
  593. if !allow {
  594. return false
  595. }
  596. if lh.myVpnNetworksTable.Contains(to) {
  597. return false
  598. }
  599. return true
  600. }
  601. // unlockedShouldAddV4 checks if to is allowed by our allow list
  602. func (lh *LightHouse) unlockedShouldAddV4(vpnAddr netip.Addr, to *V4AddrPort) bool {
  603. udpAddr := protoV4AddrPortToNetAddrPort(to)
  604. allow := lh.GetRemoteAllowList().Allow(vpnAddr, udpAddr.Addr())
  605. if lh.l.Enabled(context.Background(), logging.LevelTrace) {
  606. lh.l.Log(context.Background(), logging.LevelTrace, "remoteAllowList.Allow",
  607. "vpnAddr", vpnAddr,
  608. "udpAddr", udpAddr,
  609. "allow", allow,
  610. )
  611. }
  612. if !allow {
  613. return false
  614. }
  615. if lh.myVpnNetworksTable.Contains(udpAddr.Addr()) {
  616. return false
  617. }
  618. return true
  619. }
  620. // unlockedShouldAddV6 checks if to is allowed by our allow list
  621. func (lh *LightHouse) unlockedShouldAddV6(vpnAddr netip.Addr, to *V6AddrPort) bool {
  622. udpAddr := protoV6AddrPortToNetAddrPort(to)
  623. allow := lh.GetRemoteAllowList().Allow(vpnAddr, udpAddr.Addr())
  624. if lh.l.Enabled(context.Background(), logging.LevelTrace) {
  625. lh.l.Log(context.Background(), logging.LevelTrace, "remoteAllowList.Allow",
  626. "vpnAddr", vpnAddr,
  627. "udpAddr", udpAddr,
  628. "allow", allow,
  629. )
  630. }
  631. if !allow {
  632. return false
  633. }
  634. if lh.myVpnNetworksTable.Contains(udpAddr.Addr()) {
  635. return false
  636. }
  637. return true
  638. }
  639. func (lh *LightHouse) IsLighthouseAddr(vpnAddr netip.Addr) bool {
  640. l := lh.GetLighthouses()
  641. return slices.Contains(l, vpnAddr)
  642. }
  643. func (lh *LightHouse) IsAnyLighthouseAddr(vpnAddrs []netip.Addr) bool {
  644. l := lh.GetLighthouses()
  645. for i := range vpnAddrs {
  646. if slices.Contains(l, vpnAddrs[i]) {
  647. return true
  648. }
  649. }
  650. return false
  651. }
  652. func (lh *LightHouse) startQueryWorker() {
  653. if lh.amLighthouse {
  654. return
  655. }
  656. go func() {
  657. nb := make([]byte, 12, 12)
  658. out := make([]byte, mtu)
  659. for {
  660. select {
  661. case <-lh.ctx.Done():
  662. return
  663. case addr := <-lh.queryChan:
  664. lh.innerQueryServer(addr, nb, out)
  665. }
  666. }
  667. }()
  668. }
  669. func (lh *LightHouse) innerQueryServer(addr netip.Addr, nb, out []byte) {
  670. if lh.IsLighthouseAddr(addr) {
  671. return
  672. }
  673. msg := &NebulaMeta{
  674. Type: NebulaMeta_HostQuery,
  675. Details: &NebulaMetaDetails{},
  676. }
  677. var v1Query, v2Query []byte
  678. var err error
  679. var v cert.Version
  680. queried := 0
  681. lighthouses := lh.GetLighthouses()
  682. for _, lhVpnAddr := range lighthouses {
  683. hi := lh.ifce.GetHostInfo(lhVpnAddr)
  684. if hi != nil {
  685. v = hi.ConnectionState.myCert.Version()
  686. } else {
  687. v = lh.ifce.GetCertState().initiatingVersion
  688. }
  689. if v == cert.Version1 {
  690. if !addr.Is4() {
  691. lh.l.Error("Can't query lighthouse for v6 address using a v1 protocol",
  692. "queryVpnAddr", addr,
  693. "lighthouseAddr", lhVpnAddr,
  694. )
  695. continue
  696. }
  697. if v1Query == nil {
  698. b := addr.As4()
  699. msg.Details.VpnAddr = nil
  700. msg.Details.OldVpnAddr = binary.BigEndian.Uint32(b[:])
  701. v1Query, err = msg.Marshal()
  702. if err != nil {
  703. lh.l.Error("Failed to marshal lighthouse v1 query payload",
  704. "error", err,
  705. "queryVpnAddr", addr,
  706. "lighthouseAddr", lhVpnAddr,
  707. )
  708. continue
  709. }
  710. }
  711. lh.ifce.SendMessageToVpnAddr(header.LightHouse, 0, lhVpnAddr, v1Query, nb, out)
  712. queried++
  713. } else if v == cert.Version2 {
  714. if v2Query == nil {
  715. msg.Details.OldVpnAddr = 0
  716. msg.Details.VpnAddr = netAddrToProtoAddr(addr)
  717. v2Query, err = msg.Marshal()
  718. if err != nil {
  719. lh.l.Error("Failed to marshal lighthouse v2 query payload",
  720. "error", err,
  721. "queryVpnAddr", addr,
  722. "lighthouseAddr", lhVpnAddr,
  723. )
  724. continue
  725. }
  726. }
  727. lh.ifce.SendMessageToVpnAddr(header.LightHouse, 0, lhVpnAddr, v2Query, nb, out)
  728. queried++
  729. } else {
  730. lh.l.Debug("unsupported protocol version",
  731. "op", "query",
  732. "queryVpnAddr", addr,
  733. "version", v,
  734. )
  735. continue
  736. }
  737. }
  738. lh.metricTx(NebulaMeta_HostQuery, int64(queried))
  739. }
  740. func (lh *LightHouse) StartUpdateWorker() {
  741. interval := lh.GetUpdateInterval()
  742. if lh.amLighthouse || interval == 0 {
  743. return
  744. }
  745. clockSource := time.NewTicker(time.Second * time.Duration(interval))
  746. updateCtx, cancel := context.WithCancel(lh.ctx)
  747. lh.updateCancel = cancel
  748. go func() {
  749. defer clockSource.Stop()
  750. for {
  751. lh.SendUpdate()
  752. select {
  753. case <-updateCtx.Done():
  754. return
  755. case <-clockSource.C:
  756. continue
  757. case <-lh.updateTrigger:
  758. continue
  759. }
  760. }
  761. }()
  762. }
  763. // TriggerUpdate requests an immediate lighthouse update. This is a non-blocking
  764. // operation intended to be called after a handshake completes with a lighthouse,
  765. // so the lighthouse has our current addresses without waiting for the next
  766. // periodic update.
  767. func (lh *LightHouse) TriggerUpdate() {
  768. select {
  769. case lh.updateTrigger <- struct{}{}:
  770. default:
  771. }
  772. }
  773. func (lh *LightHouse) SendUpdate() {
  774. var v4 []*V4AddrPort
  775. var v6 []*V6AddrPort
  776. for _, e := range lh.GetAdvertiseAddrs() {
  777. if e.Addr().Is4() {
  778. v4 = append(v4, netAddrToProtoV4AddrPort(e.Addr(), e.Port()))
  779. } else {
  780. v6 = append(v6, netAddrToProtoV6AddrPort(e.Addr(), e.Port()))
  781. }
  782. }
  783. lal := lh.GetLocalAllowList()
  784. for _, e := range localAddrs(lh.l, lal) {
  785. if lh.myVpnNetworksTable.Contains(e) {
  786. continue
  787. }
  788. // Only add addrs that aren't my VPN/tun networks
  789. if e.Is4() {
  790. v4 = append(v4, netAddrToProtoV4AddrPort(e, uint16(lh.nebulaPort)))
  791. } else {
  792. v6 = append(v6, netAddrToProtoV6AddrPort(e, uint16(lh.nebulaPort)))
  793. }
  794. }
  795. nb := make([]byte, 12, 12)
  796. out := make([]byte, mtu)
  797. var v1Update, v2Update []byte
  798. var err error
  799. updated := 0
  800. lighthouses := lh.GetLighthouses()
  801. for _, lhVpnAddr := range lighthouses {
  802. var v cert.Version
  803. hi := lh.ifce.GetHostInfo(lhVpnAddr)
  804. if hi != nil {
  805. v = hi.ConnectionState.myCert.Version()
  806. } else {
  807. v = lh.ifce.GetCertState().initiatingVersion
  808. }
  809. if v == cert.Version1 {
  810. if v1Update == nil {
  811. if !lh.myVpnNetworks[0].Addr().Is4() {
  812. lh.l.Warn("cannot update lighthouse using v1 protocol without an IPv4 address",
  813. "lighthouseAddr", lhVpnAddr,
  814. )
  815. continue
  816. }
  817. var relays []uint32
  818. for _, r := range lh.GetRelaysForMe() {
  819. if !r.Is4() {
  820. continue
  821. }
  822. b := r.As4()
  823. relays = append(relays, binary.BigEndian.Uint32(b[:]))
  824. }
  825. b := lh.myVpnNetworks[0].Addr().As4()
  826. msg := NebulaMeta{
  827. Type: NebulaMeta_HostUpdateNotification,
  828. Details: &NebulaMetaDetails{
  829. V4AddrPorts: v4,
  830. V6AddrPorts: v6,
  831. OldRelayVpnAddrs: relays,
  832. OldVpnAddr: binary.BigEndian.Uint32(b[:]),
  833. },
  834. }
  835. v1Update, err = msg.Marshal()
  836. if err != nil {
  837. lh.l.Error("Error while marshaling for lighthouse v1 update",
  838. "error", err,
  839. "lighthouseAddr", lhVpnAddr,
  840. )
  841. continue
  842. }
  843. }
  844. lh.ifce.SendMessageToVpnAddr(header.LightHouse, 0, lhVpnAddr, v1Update, nb, out)
  845. updated++
  846. } else if v == cert.Version2 {
  847. if v2Update == nil {
  848. var relays []*Addr
  849. for _, r := range lh.GetRelaysForMe() {
  850. relays = append(relays, netAddrToProtoAddr(r))
  851. }
  852. msg := NebulaMeta{
  853. Type: NebulaMeta_HostUpdateNotification,
  854. Details: &NebulaMetaDetails{
  855. V4AddrPorts: v4,
  856. V6AddrPorts: v6,
  857. RelayVpnAddrs: relays,
  858. },
  859. }
  860. v2Update, err = msg.Marshal()
  861. if err != nil {
  862. lh.l.Error("Error while marshaling for lighthouse v2 update",
  863. "error", err,
  864. "lighthouseAddr", lhVpnAddr,
  865. )
  866. continue
  867. }
  868. }
  869. lh.ifce.SendMessageToVpnAddr(header.LightHouse, 0, lhVpnAddr, v2Update, nb, out)
  870. updated++
  871. } else {
  872. lh.l.Debug("unsupported protocol version",
  873. "op", "update",
  874. "version", v,
  875. )
  876. continue
  877. }
  878. }
  879. lh.metricTx(NebulaMeta_HostUpdateNotification, int64(updated))
  880. }
  881. type LightHouseHandler struct {
  882. lh *LightHouse
  883. nb []byte
  884. out []byte
  885. pb []byte
  886. meta *NebulaMeta
  887. l *slog.Logger
  888. }
  889. func (lh *LightHouse) NewRequestHandler() *LightHouseHandler {
  890. lhh := &LightHouseHandler{
  891. lh: lh,
  892. nb: make([]byte, 12, 12),
  893. out: make([]byte, mtu),
  894. l: lh.l,
  895. pb: make([]byte, mtu),
  896. meta: &NebulaMeta{
  897. Details: &NebulaMetaDetails{},
  898. },
  899. }
  900. return lhh
  901. }
  902. func (lh *LightHouse) metricRx(t NebulaMeta_MessageType, i int64) {
  903. lh.metrics.Rx(header.MessageType(t), 0, i)
  904. }
  905. func (lh *LightHouse) metricTx(t NebulaMeta_MessageType, i int64) {
  906. lh.metrics.Tx(header.MessageType(t), 0, i)
  907. }
  908. // This method is similar to Reset(), but it re-uses the pointer structs
  909. // so that we don't have to re-allocate them
  910. func (lhh *LightHouseHandler) resetMeta() *NebulaMeta {
  911. details := lhh.meta.Details
  912. lhh.meta.Reset()
  913. // Keep the array memory around
  914. details.V4AddrPorts = details.V4AddrPorts[:0]
  915. details.V6AddrPorts = details.V6AddrPorts[:0]
  916. details.RelayVpnAddrs = details.RelayVpnAddrs[:0]
  917. details.OldRelayVpnAddrs = details.OldRelayVpnAddrs[:0]
  918. details.OldVpnAddr = 0
  919. details.VpnAddr = nil
  920. lhh.meta.Details = details
  921. return lhh.meta
  922. }
  923. func (lhh *LightHouseHandler) HandleRequest(rAddr netip.AddrPort, fromVpnAddrs []netip.Addr, p []byte, w EncWriter) {
  924. n := lhh.resetMeta()
  925. err := n.Unmarshal(p)
  926. if err != nil {
  927. lhh.l.Error("Failed to unmarshal lighthouse packet",
  928. "error", err,
  929. "vpnAddrs", fromVpnAddrs,
  930. "udpAddr", rAddr,
  931. )
  932. return
  933. }
  934. if n.Details == nil {
  935. lhh.l.Error("Invalid lighthouse update",
  936. "vpnAddrs", fromVpnAddrs,
  937. "udpAddr", rAddr,
  938. )
  939. return
  940. }
  941. lhh.lh.metricRx(n.Type, 1)
  942. switch n.Type {
  943. case NebulaMeta_HostQuery:
  944. lhh.handleHostQuery(n, fromVpnAddrs, rAddr, w)
  945. case NebulaMeta_HostQueryReply:
  946. lhh.handleHostQueryReply(n, fromVpnAddrs)
  947. case NebulaMeta_HostUpdateNotification:
  948. lhh.handleHostUpdateNotification(n, fromVpnAddrs, w)
  949. case NebulaMeta_HostMovedNotification:
  950. case NebulaMeta_HostPunchNotification:
  951. lhh.handleHostPunchNotification(n, fromVpnAddrs, w)
  952. case NebulaMeta_HostUpdateNotificationAck:
  953. // noop
  954. }
  955. }
  956. func (lhh *LightHouseHandler) handleHostQuery(n *NebulaMeta, fromVpnAddrs []netip.Addr, addr netip.AddrPort, w EncWriter) {
  957. // Exit if we don't answer queries
  958. if !lhh.lh.amLighthouse {
  959. if lhh.l.Enabled(context.Background(), slog.LevelDebug) {
  960. lhh.l.Debug("I don't answer queries, but received one", "from", addr)
  961. }
  962. return
  963. }
  964. queryVpnAddr, useVersion, err := n.Details.GetVpnAddrAndVersion()
  965. if err != nil {
  966. if lhh.l.Enabled(context.Background(), slog.LevelDebug) {
  967. lhh.l.Debug("Dropping malformed HostQuery",
  968. "from", fromVpnAddrs,
  969. "details", n.Details,
  970. )
  971. }
  972. return
  973. }
  974. if useVersion == cert.Version1 && queryVpnAddr.Is6() {
  975. // this case really shouldn't be possible to represent, but reject it anyway.
  976. if lhh.l.Enabled(context.Background(), slog.LevelDebug) {
  977. lhh.l.Debug("invalid vpn addr for v1 handleHostQuery",
  978. "vpnAddrs", fromVpnAddrs,
  979. "queryVpnAddr", queryVpnAddr,
  980. )
  981. }
  982. return
  983. }
  984. found, ln, err := lhh.lh.queryAndPrepMessage(queryVpnAddr, func(c *cache) (int, error) {
  985. n = lhh.resetMeta()
  986. n.Type = NebulaMeta_HostQueryReply
  987. if useVersion == cert.Version1 {
  988. b := queryVpnAddr.As4()
  989. n.Details.OldVpnAddr = binary.BigEndian.Uint32(b[:])
  990. } else {
  991. n.Details.VpnAddr = netAddrToProtoAddr(queryVpnAddr)
  992. }
  993. lhh.coalesceAnswers(useVersion, c, n)
  994. return n.MarshalTo(lhh.pb)
  995. })
  996. if !found {
  997. return
  998. }
  999. if err != nil {
  1000. lhh.l.Error("Failed to marshal lighthouse host query reply",
  1001. "error", err,
  1002. "vpnAddrs", fromVpnAddrs,
  1003. )
  1004. return
  1005. }
  1006. lhh.lh.metricTx(NebulaMeta_HostQueryReply, 1)
  1007. w.SendMessageToVpnAddr(header.LightHouse, 0, fromVpnAddrs[0], lhh.pb[:ln], lhh.nb, lhh.out[:0])
  1008. lhh.sendHostPunchNotification(n, fromVpnAddrs, queryVpnAddr, w)
  1009. }
  1010. // sendHostPunchNotification signals the other side to punch some zero byte udp packets
  1011. func (lhh *LightHouseHandler) sendHostPunchNotification(n *NebulaMeta, fromVpnAddrs []netip.Addr, punchNotifDest netip.Addr, w EncWriter) {
  1012. whereToPunch := fromVpnAddrs[0]
  1013. found, ln, err := lhh.lh.queryAndPrepMessage(whereToPunch, func(c *cache) (int, error) {
  1014. n = lhh.resetMeta()
  1015. n.Type = NebulaMeta_HostPunchNotification
  1016. targetHI := lhh.lh.ifce.GetHostInfo(punchNotifDest)
  1017. var useVersion cert.Version
  1018. if targetHI == nil {
  1019. useVersion = lhh.lh.ifce.GetCertState().initiatingVersion
  1020. } else {
  1021. crt := targetHI.GetCert().Certificate
  1022. useVersion = crt.Version()
  1023. // we can only retarget if we have a hostinfo
  1024. newDest, ok := findNetworkUnion(crt.Networks(), fromVpnAddrs)
  1025. if ok {
  1026. whereToPunch = newDest
  1027. } else {
  1028. if lhh.l.Enabled(context.Background(), slog.LevelDebug) {
  1029. lhh.l.Debug("unable to punch to host, no addresses in common",
  1030. "to", crt.Networks(),
  1031. )
  1032. }
  1033. }
  1034. }
  1035. if useVersion == cert.Version1 {
  1036. if !whereToPunch.Is4() {
  1037. return 0, fmt.Errorf("invalid vpn addr for v1 handleHostQuery")
  1038. }
  1039. b := whereToPunch.As4()
  1040. n.Details.OldVpnAddr = binary.BigEndian.Uint32(b[:])
  1041. } else if useVersion == cert.Version2 {
  1042. n.Details.VpnAddr = netAddrToProtoAddr(whereToPunch)
  1043. } else {
  1044. return 0, errors.New("unsupported version")
  1045. }
  1046. lhh.coalesceAnswers(useVersion, c, n)
  1047. return n.MarshalTo(lhh.pb)
  1048. })
  1049. if !found {
  1050. return
  1051. }
  1052. if err != nil {
  1053. lhh.l.Error("Failed to marshal lighthouse host was queried for",
  1054. "error", err,
  1055. "vpnAddrs", fromVpnAddrs,
  1056. )
  1057. return
  1058. }
  1059. lhh.lh.metricTx(NebulaMeta_HostPunchNotification, 1)
  1060. w.SendMessageToVpnAddr(header.LightHouse, 0, punchNotifDest, lhh.pb[:ln], lhh.nb, lhh.out[:0])
  1061. }
  1062. func (lhh *LightHouseHandler) coalesceAnswers(v cert.Version, c *cache, n *NebulaMeta) {
  1063. if c.v4 != nil {
  1064. if c.v4.learned != nil {
  1065. n.Details.V4AddrPorts = append(n.Details.V4AddrPorts, c.v4.learned)
  1066. }
  1067. if c.v4.reported != nil && len(c.v4.reported) > 0 {
  1068. n.Details.V4AddrPorts = append(n.Details.V4AddrPorts, c.v4.reported...)
  1069. }
  1070. }
  1071. if c.v6 != nil {
  1072. if c.v6.learned != nil {
  1073. n.Details.V6AddrPorts = append(n.Details.V6AddrPorts, c.v6.learned)
  1074. }
  1075. if c.v6.reported != nil && len(c.v6.reported) > 0 {
  1076. n.Details.V6AddrPorts = append(n.Details.V6AddrPorts, c.v6.reported...)
  1077. }
  1078. }
  1079. if c.relay != nil {
  1080. if v == cert.Version1 {
  1081. b := [4]byte{}
  1082. for _, r := range c.relay.relay {
  1083. if !r.Is4() {
  1084. continue
  1085. }
  1086. b = r.As4()
  1087. n.Details.OldRelayVpnAddrs = append(n.Details.OldRelayVpnAddrs, binary.BigEndian.Uint32(b[:]))
  1088. }
  1089. } else if v == cert.Version2 {
  1090. for _, r := range c.relay.relay {
  1091. n.Details.RelayVpnAddrs = append(n.Details.RelayVpnAddrs, netAddrToProtoAddr(r))
  1092. }
  1093. } else {
  1094. if lhh.l.Enabled(context.Background(), slog.LevelDebug) {
  1095. lhh.l.Debug("unsupported protocol version",
  1096. "op", "coalesceAnswers",
  1097. "version", v,
  1098. )
  1099. }
  1100. }
  1101. }
  1102. }
  1103. func (lhh *LightHouseHandler) handleHostQueryReply(n *NebulaMeta, fromVpnAddrs []netip.Addr) {
  1104. if !lhh.lh.IsAnyLighthouseAddr(fromVpnAddrs) {
  1105. return
  1106. }
  1107. certVpnAddr, _, err := n.Details.GetVpnAddrAndVersion()
  1108. if err != nil {
  1109. if lhh.l.Enabled(context.Background(), slog.LevelDebug) {
  1110. lhh.l.Error("dropping malformed HostQueryReply",
  1111. "error", err,
  1112. "vpnAddrs", fromVpnAddrs,
  1113. )
  1114. }
  1115. return
  1116. }
  1117. relays := n.Details.GetRelays()
  1118. lhh.lh.Lock()
  1119. am := lhh.lh.unlockedGetRemoteList([]netip.Addr{certVpnAddr})
  1120. am.Lock()
  1121. lhh.lh.Unlock()
  1122. am.unlockedSetV4(fromVpnAddrs[0], certVpnAddr, n.Details.V4AddrPorts, lhh.lh.unlockedShouldAddV4)
  1123. am.unlockedSetV6(fromVpnAddrs[0], certVpnAddr, n.Details.V6AddrPorts, lhh.lh.unlockedShouldAddV6)
  1124. am.unlockedSetRelay(fromVpnAddrs[0], relays)
  1125. am.Unlock()
  1126. // Non-blocking attempt to trigger, skip if it would block
  1127. select {
  1128. case lhh.lh.handshakeTrigger <- certVpnAddr:
  1129. default:
  1130. }
  1131. }
  1132. func (lhh *LightHouseHandler) handleHostUpdateNotification(n *NebulaMeta, fromVpnAddrs []netip.Addr, w EncWriter) {
  1133. if !lhh.lh.amLighthouse {
  1134. if lhh.l.Enabled(context.Background(), slog.LevelDebug) {
  1135. lhh.l.Debug("I am not a lighthouse, do not take host updates", "from", fromVpnAddrs)
  1136. }
  1137. return
  1138. }
  1139. // not using GetVpnAddrAndVersion because we don't want to error on a blank detailsVpnAddr
  1140. var detailsVpnAddr netip.Addr
  1141. var useVersion cert.Version
  1142. if n.Details.OldVpnAddr != 0 { //v1 always sets this field
  1143. b := [4]byte{}
  1144. binary.BigEndian.PutUint32(b[:], n.Details.OldVpnAddr)
  1145. detailsVpnAddr = netip.AddrFrom4(b)
  1146. useVersion = cert.Version1
  1147. } else if n.Details.VpnAddr != nil { //this field is "optional" in v2, but if it's set, we should enforce it
  1148. detailsVpnAddr = protoAddrToNetAddr(n.Details.VpnAddr)
  1149. useVersion = cert.Version2
  1150. } else {
  1151. detailsVpnAddr = netip.Addr{}
  1152. useVersion = cert.Version2
  1153. }
  1154. //Simple check that the host sent this not someone else, if detailsVpnAddr is filled
  1155. if detailsVpnAddr.IsValid() && !slices.Contains(fromVpnAddrs, detailsVpnAddr) {
  1156. if lhh.l.Enabled(context.Background(), slog.LevelDebug) {
  1157. lhh.l.Debug("Host sent invalid update",
  1158. "vpnAddrs", fromVpnAddrs,
  1159. "answer", detailsVpnAddr,
  1160. )
  1161. }
  1162. return
  1163. }
  1164. relays := n.Details.GetRelays()
  1165. lhh.lh.Lock()
  1166. am := lhh.lh.unlockedGetRemoteList(fromVpnAddrs)
  1167. am.Lock()
  1168. lhh.lh.Unlock()
  1169. am.unlockedSetV4(fromVpnAddrs[0], fromVpnAddrs[0], n.Details.V4AddrPorts, lhh.lh.unlockedShouldAddV4)
  1170. am.unlockedSetV6(fromVpnAddrs[0], fromVpnAddrs[0], n.Details.V6AddrPorts, lhh.lh.unlockedShouldAddV6)
  1171. am.unlockedSetRelay(fromVpnAddrs[0], relays)
  1172. am.Unlock()
  1173. n = lhh.resetMeta()
  1174. n.Type = NebulaMeta_HostUpdateNotificationAck
  1175. switch useVersion {
  1176. case cert.Version1:
  1177. if !fromVpnAddrs[0].Is4() {
  1178. lhh.l.Error("Can not send HostUpdateNotificationAck for a ipv6 vpn ip in a v1 message",
  1179. "vpnAddrs", fromVpnAddrs,
  1180. )
  1181. return
  1182. }
  1183. vpnAddrB := fromVpnAddrs[0].As4()
  1184. n.Details.OldVpnAddr = binary.BigEndian.Uint32(vpnAddrB[:])
  1185. case cert.Version2:
  1186. // do nothing, we want to send a blank message
  1187. default:
  1188. lhh.l.Error("invalid protocol version", "useVersion", useVersion)
  1189. return
  1190. }
  1191. ln, err := n.MarshalTo(lhh.pb)
  1192. if err != nil {
  1193. lhh.l.Error("Failed to marshal lighthouse host update ack",
  1194. "error", err,
  1195. "vpnAddrs", fromVpnAddrs,
  1196. )
  1197. return
  1198. }
  1199. lhh.lh.metricTx(NebulaMeta_HostUpdateNotificationAck, 1)
  1200. w.SendMessageToVpnAddr(header.LightHouse, 0, fromVpnAddrs[0], lhh.pb[:ln], lhh.nb, lhh.out[:0])
  1201. }
  1202. func (lhh *LightHouseHandler) handleHostPunchNotification(n *NebulaMeta, fromVpnAddrs []netip.Addr, w EncWriter) {
  1203. //It's possible the lighthouse is communicating with us using a non primary vpn addr,
  1204. //which means we need to compare all fromVpnAddrs against all configured lighthouse vpn addrs.
  1205. if !lhh.lh.IsAnyLighthouseAddr(fromVpnAddrs) {
  1206. return
  1207. }
  1208. detailsVpnAddr, _, err := n.Details.GetVpnAddrAndVersion()
  1209. if err != nil {
  1210. if lhh.l.Enabled(context.Background(), slog.LevelDebug) {
  1211. lhh.l.Debug("dropping invalid HostPunchNotification",
  1212. "details", n.Details,
  1213. "error", err,
  1214. )
  1215. }
  1216. return
  1217. }
  1218. remoteAllowList := lhh.lh.GetRemoteAllowList()
  1219. for _, a := range n.Details.V4AddrPorts {
  1220. if a == nil {
  1221. continue
  1222. }
  1223. b := protoV4AddrPortToNetAddrPort(a)
  1224. if remoteAllowList.Allow(detailsVpnAddr, b.Addr()) {
  1225. lhh.lh.punchy.Schedule(b, detailsVpnAddr)
  1226. }
  1227. }
  1228. for _, a := range n.Details.V6AddrPorts {
  1229. if a == nil {
  1230. continue
  1231. }
  1232. b := protoV6AddrPortToNetAddrPort(a)
  1233. if remoteAllowList.Allow(detailsVpnAddr, b.Addr()) {
  1234. lhh.lh.punchy.Schedule(b, detailsVpnAddr)
  1235. }
  1236. }
  1237. // This sends a nebula test packet to the host trying to contact us. In the case
  1238. // of a double nat or other difficult scenario, this may help establish
  1239. // a tunnel. ScheduleRespond is a no-op when punchy.respond is disabled.
  1240. lhh.lh.punchy.ScheduleRespond(detailsVpnAddr)
  1241. }
  1242. func protoAddrToNetAddr(addr *Addr) netip.Addr {
  1243. b := [16]byte{}
  1244. binary.BigEndian.PutUint64(b[:8], addr.Hi)
  1245. binary.BigEndian.PutUint64(b[8:], addr.Lo)
  1246. return netip.AddrFrom16(b).Unmap()
  1247. }
  1248. func protoV4AddrPortToNetAddrPort(ap *V4AddrPort) netip.AddrPort {
  1249. b := [4]byte{}
  1250. binary.BigEndian.PutUint32(b[:], ap.Addr)
  1251. return netip.AddrPortFrom(netip.AddrFrom4(b), uint16(ap.Port))
  1252. }
  1253. func protoV6AddrPortToNetAddrPort(ap *V6AddrPort) netip.AddrPort {
  1254. b := [16]byte{}
  1255. binary.BigEndian.PutUint64(b[:8], ap.Hi)
  1256. binary.BigEndian.PutUint64(b[8:], ap.Lo)
  1257. return netip.AddrPortFrom(netip.AddrFrom16(b).Unmap(), uint16(ap.Port))
  1258. }
  1259. func netAddrToProtoAddr(addr netip.Addr) *Addr {
  1260. b := addr.As16()
  1261. return &Addr{
  1262. Hi: binary.BigEndian.Uint64(b[:8]),
  1263. Lo: binary.BigEndian.Uint64(b[8:]),
  1264. }
  1265. }
  1266. func netAddrToProtoV4AddrPort(addr netip.Addr, port uint16) *V4AddrPort {
  1267. v4Addr := addr.As4()
  1268. return &V4AddrPort{
  1269. Addr: binary.BigEndian.Uint32(v4Addr[:]),
  1270. Port: uint32(port),
  1271. }
  1272. }
  1273. func netAddrToProtoV6AddrPort(addr netip.Addr, port uint16) *V6AddrPort {
  1274. v6Addr := addr.As16()
  1275. return &V6AddrPort{
  1276. Hi: binary.BigEndian.Uint64(v6Addr[:8]),
  1277. Lo: binary.BigEndian.Uint64(v6Addr[8:]),
  1278. Port: uint32(port),
  1279. }
  1280. }
  1281. func (d *NebulaMetaDetails) GetRelays() []netip.Addr {
  1282. var relays []netip.Addr
  1283. if len(d.OldRelayVpnAddrs) > 0 {
  1284. b := [4]byte{}
  1285. for _, r := range d.OldRelayVpnAddrs {
  1286. binary.BigEndian.PutUint32(b[:], r)
  1287. relays = append(relays, netip.AddrFrom4(b))
  1288. }
  1289. }
  1290. if len(d.RelayVpnAddrs) > 0 {
  1291. for _, r := range d.RelayVpnAddrs {
  1292. if r != nil {
  1293. relays = append(relays, protoAddrToNetAddr(r))
  1294. }
  1295. }
  1296. }
  1297. return relays
  1298. }
  1299. // FindNetworkUnion returns the first netip.Addr contained in the list of provided netip.Prefix, if able
  1300. func findNetworkUnion(prefixes []netip.Prefix, addrs []netip.Addr) (netip.Addr, bool) {
  1301. for i := range prefixes {
  1302. for j := range addrs {
  1303. if prefixes[i].Contains(addrs[j]) {
  1304. return addrs[j], true
  1305. }
  1306. }
  1307. }
  1308. return netip.Addr{}, false
  1309. }
  1310. func (d *NebulaMetaDetails) GetVpnAddrAndVersion() (netip.Addr, cert.Version, error) {
  1311. if d.OldVpnAddr != 0 {
  1312. b := [4]byte{}
  1313. binary.BigEndian.PutUint32(b[:], d.OldVpnAddr)
  1314. detailsVpnAddr := netip.AddrFrom4(b)
  1315. return detailsVpnAddr, cert.Version1, nil
  1316. } else if d.VpnAddr != nil {
  1317. detailsVpnAddr := protoAddrToNetAddr(d.VpnAddr)
  1318. return detailsVpnAddr, cert.Version2, nil
  1319. } else {
  1320. return netip.Addr{}, cert.Version1, ErrBadDetailsVpnAddr
  1321. }
  1322. }