lighthouse.go 44 KB

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