lighthouse.go 41 KB

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