lighthouse.go 41 KB

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