lighthouse.go 45 KB

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