lighthouse.go 44 KB

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