1
0

lighthouse.go 44 KB

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