lighthouse.go 44 KB

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