lighthouse.go 42 KB

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