1
0

lighthouse.go 43 KB

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