lighthouse.go 43 KB

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