1
0

lighthouse.go 44 KB

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