2
0

lighthouse.go 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434
  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[map[netip.Addr]struct{}]
  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(map[netip.Addr]struct{})
  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() map[netip.Addr]struct{} {
  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. lhMap := make(map[netip.Addr]struct{})
  257. err := lh.parseLighthouses(c, lhMap)
  258. if err != nil {
  259. return err
  260. }
  261. lh.lighthouses.Store(&lhMap)
  262. if !initial {
  263. //NOTE: we are not tearing down existing lighthouse connections because they might be used for non lighthouse traffic
  264. lh.l.Info("lighthouse.hosts has changed")
  265. }
  266. }
  267. if initial || c.HasChanged("relay.relays") {
  268. switch c.GetBool("relay.am_relay", false) {
  269. case true:
  270. // Relays aren't allowed to specify other relays
  271. if len(c.GetStringSlice("relay.relays", nil)) > 0 {
  272. lh.l.Info("Ignoring relays from config because am_relay is true")
  273. }
  274. relaysForMe := []netip.Addr{}
  275. lh.relaysForMe.Store(&relaysForMe)
  276. case false:
  277. relaysForMe := []netip.Addr{}
  278. for _, v := range c.GetStringSlice("relay.relays", nil) {
  279. configRIP, err := netip.ParseAddr(v)
  280. if err != nil {
  281. lh.l.WithField("relay", v).WithError(err).Warn("Parse relay from config failed")
  282. } else {
  283. lh.l.WithField("relay", v).Info("Read relay from config")
  284. relaysForMe = append(relaysForMe, configRIP)
  285. }
  286. }
  287. lh.relaysForMe.Store(&relaysForMe)
  288. }
  289. }
  290. return nil
  291. }
  292. func (lh *LightHouse) parseLighthouses(c *config.C, lhMap map[netip.Addr]struct{}) error {
  293. lhs := c.GetStringSlice("lighthouse.hosts", []string{})
  294. if lh.amLighthouse && len(lhs) != 0 {
  295. lh.l.Warn("lighthouse.am_lighthouse enabled on node but upstream lighthouses exist in config")
  296. }
  297. for i, host := range lhs {
  298. addr, err := netip.ParseAddr(host)
  299. if err != nil {
  300. return util.NewContextualError("Unable to parse lighthouse host entry", m{"host": host, "entry": i + 1}, err)
  301. }
  302. if !lh.myVpnNetworksTable.Contains(addr) {
  303. return util.NewContextualError("lighthouse host is not in our networks, invalid", m{"vpnAddr": addr, "networks": lh.myVpnNetworks}, nil)
  304. }
  305. lhMap[addr] = struct{}{}
  306. }
  307. if !lh.amLighthouse && len(lhMap) == 0 {
  308. lh.l.Warn("No lighthouse.hosts configured, this host will only be able to initiate tunnels with static_host_map entries")
  309. }
  310. staticList := lh.GetStaticHostList()
  311. for lhAddr, _ := range lhMap {
  312. if _, ok := staticList[lhAddr]; !ok {
  313. return fmt.Errorf("lighthouse %s does not have a static_host_map entry", lhAddr)
  314. }
  315. }
  316. return nil
  317. }
  318. func getStaticMapCadence(c *config.C) (time.Duration, error) {
  319. cadence := c.GetString("static_map.cadence", "30s")
  320. d, err := time.ParseDuration(cadence)
  321. if err != nil {
  322. return 0, err
  323. }
  324. return d, nil
  325. }
  326. func getStaticMapLookupTimeout(c *config.C) (time.Duration, error) {
  327. lookupTimeout := c.GetString("static_map.lookup_timeout", "250ms")
  328. d, err := time.ParseDuration(lookupTimeout)
  329. if err != nil {
  330. return 0, err
  331. }
  332. return d, nil
  333. }
  334. func getStaticMapNetwork(c *config.C) (string, error) {
  335. network := c.GetString("static_map.network", "ip4")
  336. if network != "ip" && network != "ip4" && network != "ip6" {
  337. return "", fmt.Errorf("static_map.network must be one of ip, ip4, or ip6")
  338. }
  339. return network, nil
  340. }
  341. func (lh *LightHouse) loadStaticMap(c *config.C, staticList map[netip.Addr]struct{}) error {
  342. d, err := getStaticMapCadence(c)
  343. if err != nil {
  344. return err
  345. }
  346. network, err := getStaticMapNetwork(c)
  347. if err != nil {
  348. return err
  349. }
  350. lookupTimeout, err := getStaticMapLookupTimeout(c)
  351. if err != nil {
  352. return err
  353. }
  354. shm := c.GetMap("static_host_map", map[string]any{})
  355. i := 0
  356. for k, v := range shm {
  357. vpnAddr, err := netip.ParseAddr(fmt.Sprintf("%v", k))
  358. if err != nil {
  359. return util.NewContextualError("Unable to parse static_host_map entry", m{"host": k, "entry": i + 1}, err)
  360. }
  361. if !lh.myVpnNetworksTable.Contains(vpnAddr) {
  362. return util.NewContextualError("static_host_map key is not in our network, invalid", m{"vpnAddr": vpnAddr, "networks": lh.myVpnNetworks, "entry": i + 1}, nil)
  363. }
  364. vals, ok := v.([]any)
  365. if !ok {
  366. vals = []any{v}
  367. }
  368. remoteAddrs := []string{}
  369. for _, v := range vals {
  370. remoteAddrs = append(remoteAddrs, fmt.Sprintf("%v", v))
  371. }
  372. err = lh.addStaticRemotes(i, d, network, lookupTimeout, vpnAddr, remoteAddrs, staticList)
  373. if err != nil {
  374. return err
  375. }
  376. i++
  377. }
  378. return nil
  379. }
  380. func (lh *LightHouse) Query(vpnAddr netip.Addr) *RemoteList {
  381. if !lh.IsLighthouseAddr(vpnAddr) {
  382. lh.QueryServer(vpnAddr)
  383. }
  384. lh.RLock()
  385. if v, ok := lh.addrMap[vpnAddr]; ok {
  386. lh.RUnlock()
  387. return v
  388. }
  389. lh.RUnlock()
  390. return nil
  391. }
  392. // QueryServer is asynchronous so no reply should be expected
  393. func (lh *LightHouse) QueryServer(vpnAddr netip.Addr) {
  394. // Don't put lighthouse addrs in the query channel because we can't query lighthouses about lighthouses
  395. if lh.amLighthouse || lh.IsLighthouseAddr(vpnAddr) {
  396. return
  397. }
  398. lh.queryChan <- vpnAddr
  399. }
  400. func (lh *LightHouse) QueryCache(vpnAddrs []netip.Addr) *RemoteList {
  401. lh.RLock()
  402. if v, ok := lh.addrMap[vpnAddrs[0]]; ok {
  403. lh.RUnlock()
  404. return v
  405. }
  406. lh.RUnlock()
  407. lh.Lock()
  408. defer lh.Unlock()
  409. // Add an entry if we don't already have one
  410. return lh.unlockedGetRemoteList(vpnAddrs)
  411. }
  412. // queryAndPrepMessage is a lock helper on RemoteList, assisting the caller to build a lighthouse message containing
  413. // details from the remote list. It looks for a hit in the addrMap and a hit in the RemoteList under the owner vpnAddr
  414. // If one is found then f() is called with proper locking, f() must return result of n.MarshalTo()
  415. func (lh *LightHouse) queryAndPrepMessage(vpnAddr netip.Addr, f func(*cache) (int, error)) (bool, int, error) {
  416. lh.RLock()
  417. // Do we have an entry in the main cache?
  418. if v, ok := lh.addrMap[vpnAddr]; ok {
  419. // Swap lh lock for remote list lock
  420. v.RLock()
  421. defer v.RUnlock()
  422. lh.RUnlock()
  423. // We may be asking about a non primary address so lets get the primary address
  424. if slices.Contains(v.vpnAddrs, vpnAddr) {
  425. vpnAddr = v.vpnAddrs[0]
  426. }
  427. c := v.cache[vpnAddr]
  428. // Make sure we have
  429. if c != nil {
  430. n, err := f(c)
  431. return true, n, err
  432. }
  433. return false, 0, nil
  434. }
  435. lh.RUnlock()
  436. return false, 0, nil
  437. }
  438. func (lh *LightHouse) DeleteVpnAddrs(allVpnAddrs []netip.Addr) {
  439. // First we check the static host map. If any of the VpnAddrs to be deleted are present, do nothing.
  440. staticList := lh.GetStaticHostList()
  441. for _, addr := range allVpnAddrs {
  442. if _, ok := staticList[addr]; ok {
  443. return
  444. }
  445. }
  446. // None of the VpnAddrs were present. Now we can do the deletes.
  447. lh.Lock()
  448. rm, ok := lh.addrMap[allVpnAddrs[0]]
  449. if ok {
  450. for _, addr := range allVpnAddrs {
  451. srm := lh.addrMap[addr]
  452. if srm == rm {
  453. delete(lh.addrMap, addr)
  454. if lh.l.Level >= logrus.DebugLevel {
  455. lh.l.Debugf("deleting %s from lighthouse.", addr)
  456. }
  457. }
  458. }
  459. }
  460. lh.Unlock()
  461. }
  462. // AddStaticRemote adds a static host entry for vpnAddr as ourselves as the owner
  463. // We are the owner because we don't want a lighthouse server to advertise for static hosts it was configured with
  464. // And we don't want a lighthouse query reply to interfere with our learned cache if we are a client
  465. // NOTE: this function should not interact with any hot path objects, like lh.staticList, the caller should handle it
  466. 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 {
  467. lh.Lock()
  468. am := lh.unlockedGetRemoteList([]netip.Addr{vpnAddr})
  469. am.Lock()
  470. defer am.Unlock()
  471. ctx := lh.ctx
  472. lh.Unlock()
  473. hr, err := NewHostnameResults(ctx, lh.l, d, network, timeout, toAddrs, func() {
  474. // This callback runs whenever the DNS hostname resolver finds a different set of addr's
  475. // in its resolution for hostnames.
  476. am.Lock()
  477. defer am.Unlock()
  478. am.shouldRebuild = true
  479. })
  480. if err != nil {
  481. return util.NewContextualError("Static host address could not be parsed", m{"vpnAddr": vpnAddr, "entry": i + 1}, err)
  482. }
  483. am.unlockedSetHostnamesResults(hr)
  484. for _, addrPort := range hr.GetAddrs() {
  485. if !lh.shouldAdd(vpnAddr, addrPort.Addr()) {
  486. continue
  487. }
  488. switch {
  489. case addrPort.Addr().Is4():
  490. am.unlockedPrependV4(lh.myVpnNetworks[0].Addr(), netAddrToProtoV4AddrPort(addrPort.Addr(), addrPort.Port()))
  491. case addrPort.Addr().Is6():
  492. am.unlockedPrependV6(lh.myVpnNetworks[0].Addr(), netAddrToProtoV6AddrPort(addrPort.Addr(), addrPort.Port()))
  493. }
  494. }
  495. // Mark it as static in the caller provided map
  496. staticList[vpnAddr] = struct{}{}
  497. return nil
  498. }
  499. // addCalculatedRemotes adds any calculated remotes based on the
  500. // lighthouse.calculated_remotes configuration. It returns true if any
  501. // calculated remotes were added
  502. func (lh *LightHouse) addCalculatedRemotes(vpnAddr netip.Addr) bool {
  503. tree := lh.getCalculatedRemotes()
  504. if tree == nil {
  505. return false
  506. }
  507. calculatedRemotes, ok := tree.Lookup(vpnAddr)
  508. if !ok {
  509. return false
  510. }
  511. var calculatedV4 []*V4AddrPort
  512. var calculatedV6 []*V6AddrPort
  513. for _, cr := range calculatedRemotes {
  514. if vpnAddr.Is4() {
  515. c := cr.ApplyV4(vpnAddr)
  516. if c != nil {
  517. calculatedV4 = append(calculatedV4, c)
  518. }
  519. } else if vpnAddr.Is6() {
  520. c := cr.ApplyV6(vpnAddr)
  521. if c != nil {
  522. calculatedV6 = append(calculatedV6, c)
  523. }
  524. }
  525. }
  526. lh.Lock()
  527. am := lh.unlockedGetRemoteList([]netip.Addr{vpnAddr})
  528. am.Lock()
  529. defer am.Unlock()
  530. lh.Unlock()
  531. if len(calculatedV4) > 0 {
  532. am.unlockedSetV4(lh.myVpnNetworks[0].Addr(), vpnAddr, calculatedV4, lh.unlockedShouldAddV4)
  533. }
  534. if len(calculatedV6) > 0 {
  535. am.unlockedSetV6(lh.myVpnNetworks[0].Addr(), vpnAddr, calculatedV6, lh.unlockedShouldAddV6)
  536. }
  537. return len(calculatedV4) > 0 || len(calculatedV6) > 0
  538. }
  539. // unlockedGetRemoteList assumes you have the lh lock
  540. func (lh *LightHouse) unlockedGetRemoteList(allAddrs []netip.Addr) *RemoteList {
  541. // 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
  542. for i, addr := range allAddrs {
  543. am, ok := lh.addrMap[addr]
  544. if ok {
  545. if i != 0 {
  546. lh.addrMap[allAddrs[0]] = am
  547. }
  548. return am
  549. }
  550. }
  551. //TODO lighthouse.remote_allow_ranges is almost certainly broken in a multiple-address-per-cert scenario
  552. am := NewRemoteList(allAddrs, func(a netip.Addr) bool { return lh.shouldAdd(allAddrs[0], a) })
  553. for _, addr := range allAddrs {
  554. lh.addrMap[addr] = am
  555. }
  556. return am
  557. }
  558. func (lh *LightHouse) shouldAdd(vpnAddr netip.Addr, to netip.Addr) bool {
  559. allow := lh.GetRemoteAllowList().Allow(vpnAddr, to)
  560. if lh.l.Level >= logrus.TraceLevel {
  561. lh.l.WithField("vpnAddr", vpnAddr).WithField("udpAddr", to).WithField("allow", allow).
  562. Trace("remoteAllowList.Allow")
  563. }
  564. if !allow {
  565. return false
  566. }
  567. if lh.myVpnNetworksTable.Contains(to) {
  568. return false
  569. }
  570. return true
  571. }
  572. // unlockedShouldAddV4 checks if to is allowed by our allow list
  573. func (lh *LightHouse) unlockedShouldAddV4(vpnAddr netip.Addr, to *V4AddrPort) bool {
  574. udpAddr := protoV4AddrPortToNetAddrPort(to)
  575. allow := lh.GetRemoteAllowList().Allow(vpnAddr, udpAddr.Addr())
  576. if lh.l.Level >= logrus.TraceLevel {
  577. lh.l.WithField("vpnAddr", vpnAddr).WithField("udpAddr", udpAddr).WithField("allow", allow).
  578. Trace("remoteAllowList.Allow")
  579. }
  580. if !allow {
  581. return false
  582. }
  583. if lh.myVpnNetworksTable.Contains(udpAddr.Addr()) {
  584. return false
  585. }
  586. return true
  587. }
  588. // unlockedShouldAddV6 checks if to is allowed by our allow list
  589. func (lh *LightHouse) unlockedShouldAddV6(vpnAddr netip.Addr, to *V6AddrPort) bool {
  590. udpAddr := protoV6AddrPortToNetAddrPort(to)
  591. allow := lh.GetRemoteAllowList().Allow(vpnAddr, udpAddr.Addr())
  592. if lh.l.Level >= logrus.TraceLevel {
  593. lh.l.WithField("vpnAddr", vpnAddr).WithField("udpAddr", udpAddr).WithField("allow", allow).
  594. Trace("remoteAllowList.Allow")
  595. }
  596. if !allow {
  597. return false
  598. }
  599. if lh.myVpnNetworksTable.Contains(udpAddr.Addr()) {
  600. return false
  601. }
  602. return true
  603. }
  604. func (lh *LightHouse) IsLighthouseAddr(vpnAddr netip.Addr) bool {
  605. _, ok := lh.GetLighthouses()[vpnAddr]
  606. return ok
  607. }
  608. func (lh *LightHouse) IsAnyLighthouseAddr(vpnAddr []netip.Addr) bool {
  609. l := lh.GetLighthouses()
  610. for _, a := range vpnAddr {
  611. if _, ok := l[a]; ok {
  612. return true
  613. }
  614. }
  615. return false
  616. }
  617. func (lh *LightHouse) startQueryWorker() {
  618. if lh.amLighthouse {
  619. return
  620. }
  621. go func() {
  622. nb := make([]byte, 12, 12)
  623. out := make([]byte, mtu)
  624. for {
  625. select {
  626. case <-lh.ctx.Done():
  627. return
  628. case addr := <-lh.queryChan:
  629. lh.innerQueryServer(addr, nb, out)
  630. }
  631. }
  632. }()
  633. }
  634. func (lh *LightHouse) innerQueryServer(addr netip.Addr, nb, out []byte) {
  635. if lh.IsLighthouseAddr(addr) {
  636. return
  637. }
  638. msg := &NebulaMeta{
  639. Type: NebulaMeta_HostQuery,
  640. Details: &NebulaMetaDetails{},
  641. }
  642. var v1Query, v2Query []byte
  643. var err error
  644. var v cert.Version
  645. queried := 0
  646. lighthouses := lh.GetLighthouses()
  647. for lhVpnAddr := range lighthouses {
  648. hi := lh.ifce.GetHostInfo(lhVpnAddr)
  649. if hi != nil {
  650. v = hi.ConnectionState.myCert.Version()
  651. } else {
  652. v = lh.ifce.GetCertState().initiatingVersion
  653. }
  654. if v == cert.Version1 {
  655. if !addr.Is4() {
  656. lh.l.WithField("queryVpnAddr", addr).WithField("lighthouseAddr", lhVpnAddr).
  657. Error("Can't query lighthouse for v6 address using a v1 protocol")
  658. continue
  659. }
  660. if v1Query == nil {
  661. b := addr.As4()
  662. msg.Details.VpnAddr = nil
  663. msg.Details.OldVpnAddr = binary.BigEndian.Uint32(b[:])
  664. v1Query, err = msg.Marshal()
  665. if err != nil {
  666. lh.l.WithError(err).WithField("queryVpnAddr", addr).
  667. WithField("lighthouseAddr", lhVpnAddr).
  668. Error("Failed to marshal lighthouse v1 query payload")
  669. continue
  670. }
  671. }
  672. lh.ifce.SendMessageToVpnAddr(header.LightHouse, 0, lhVpnAddr, v1Query, nb, out)
  673. queried++
  674. } else if v == cert.Version2 {
  675. if v2Query == nil {
  676. msg.Details.OldVpnAddr = 0
  677. msg.Details.VpnAddr = netAddrToProtoAddr(addr)
  678. v2Query, err = msg.Marshal()
  679. if err != nil {
  680. lh.l.WithError(err).WithField("queryVpnAddr", addr).
  681. WithField("lighthouseAddr", lhVpnAddr).
  682. Error("Failed to marshal lighthouse v2 query payload")
  683. continue
  684. }
  685. }
  686. lh.ifce.SendMessageToVpnAddr(header.LightHouse, 0, lhVpnAddr, v2Query, nb, out)
  687. queried++
  688. } else {
  689. lh.l.Debugf("Can not query lighthouse for %v using unknown protocol version: %v", addr, v)
  690. continue
  691. }
  692. }
  693. lh.metricTx(NebulaMeta_HostQuery, int64(queried))
  694. }
  695. func (lh *LightHouse) StartUpdateWorker() {
  696. interval := lh.GetUpdateInterval()
  697. if lh.amLighthouse || interval == 0 {
  698. return
  699. }
  700. clockSource := time.NewTicker(time.Second * time.Duration(interval))
  701. updateCtx, cancel := context.WithCancel(lh.ctx)
  702. lh.updateCancel = cancel
  703. go func() {
  704. defer clockSource.Stop()
  705. for {
  706. lh.SendUpdate()
  707. select {
  708. case <-updateCtx.Done():
  709. return
  710. case <-clockSource.C:
  711. continue
  712. }
  713. }
  714. }()
  715. }
  716. func (lh *LightHouse) SendUpdate() {
  717. var v4 []*V4AddrPort
  718. var v6 []*V6AddrPort
  719. for _, e := range lh.GetAdvertiseAddrs() {
  720. if e.Addr().Is4() {
  721. v4 = append(v4, netAddrToProtoV4AddrPort(e.Addr(), e.Port()))
  722. } else {
  723. v6 = append(v6, netAddrToProtoV6AddrPort(e.Addr(), e.Port()))
  724. }
  725. }
  726. lal := lh.GetLocalAllowList()
  727. for _, e := range localAddrs(lh.l, lal) {
  728. if lh.myVpnNetworksTable.Contains(e) {
  729. continue
  730. }
  731. // Only add addrs that aren't my VPN/tun networks
  732. if e.Is4() {
  733. v4 = append(v4, netAddrToProtoV4AddrPort(e, uint16(lh.nebulaPort)))
  734. } else {
  735. v6 = append(v6, netAddrToProtoV6AddrPort(e, uint16(lh.nebulaPort)))
  736. }
  737. }
  738. nb := make([]byte, 12, 12)
  739. out := make([]byte, mtu)
  740. var v1Update, v2Update []byte
  741. var err error
  742. updated := 0
  743. lighthouses := lh.GetLighthouses()
  744. for lhVpnAddr := range lighthouses {
  745. var v cert.Version
  746. hi := lh.ifce.GetHostInfo(lhVpnAddr)
  747. if hi != nil {
  748. v = hi.ConnectionState.myCert.Version()
  749. } else {
  750. v = lh.ifce.GetCertState().initiatingVersion
  751. }
  752. if v == cert.Version1 {
  753. if v1Update == nil {
  754. if !lh.myVpnNetworks[0].Addr().Is4() {
  755. lh.l.WithField("lighthouseAddr", lhVpnAddr).
  756. Warn("cannot update lighthouse using v1 protocol without an IPv4 address")
  757. continue
  758. }
  759. var relays []uint32
  760. for _, r := range lh.GetRelaysForMe() {
  761. if !r.Is4() {
  762. continue
  763. }
  764. b := r.As4()
  765. relays = append(relays, binary.BigEndian.Uint32(b[:]))
  766. }
  767. b := lh.myVpnNetworks[0].Addr().As4()
  768. msg := NebulaMeta{
  769. Type: NebulaMeta_HostUpdateNotification,
  770. Details: &NebulaMetaDetails{
  771. V4AddrPorts: v4,
  772. V6AddrPorts: v6,
  773. OldRelayVpnAddrs: relays,
  774. OldVpnAddr: binary.BigEndian.Uint32(b[:]),
  775. },
  776. }
  777. v1Update, err = msg.Marshal()
  778. if err != nil {
  779. lh.l.WithError(err).WithField("lighthouseAddr", lhVpnAddr).
  780. Error("Error while marshaling for lighthouse v1 update")
  781. continue
  782. }
  783. }
  784. lh.ifce.SendMessageToVpnAddr(header.LightHouse, 0, lhVpnAddr, v1Update, nb, out)
  785. updated++
  786. } else if v == cert.Version2 {
  787. if v2Update == nil {
  788. var relays []*Addr
  789. for _, r := range lh.GetRelaysForMe() {
  790. relays = append(relays, netAddrToProtoAddr(r))
  791. }
  792. msg := NebulaMeta{
  793. Type: NebulaMeta_HostUpdateNotification,
  794. Details: &NebulaMetaDetails{
  795. V4AddrPorts: v4,
  796. V6AddrPorts: v6,
  797. RelayVpnAddrs: relays,
  798. VpnAddr: netAddrToProtoAddr(lh.myVpnNetworks[0].Addr()),
  799. },
  800. }
  801. v2Update, err = msg.Marshal()
  802. if err != nil {
  803. lh.l.WithError(err).WithField("lighthouseAddr", lhVpnAddr).
  804. Error("Error while marshaling for lighthouse v2 update")
  805. continue
  806. }
  807. }
  808. lh.ifce.SendMessageToVpnAddr(header.LightHouse, 0, lhVpnAddr, v2Update, nb, out)
  809. updated++
  810. } else {
  811. lh.l.Debugf("Can not update lighthouse using unknown protocol version: %v", v)
  812. continue
  813. }
  814. }
  815. lh.metricTx(NebulaMeta_HostUpdateNotification, int64(updated))
  816. }
  817. type LightHouseHandler struct {
  818. lh *LightHouse
  819. nb []byte
  820. out []byte
  821. pb []byte
  822. meta *NebulaMeta
  823. l *logrus.Logger
  824. }
  825. func (lh *LightHouse) NewRequestHandler() *LightHouseHandler {
  826. lhh := &LightHouseHandler{
  827. lh: lh,
  828. nb: make([]byte, 12, 12),
  829. out: make([]byte, mtu),
  830. l: lh.l,
  831. pb: make([]byte, mtu),
  832. meta: &NebulaMeta{
  833. Details: &NebulaMetaDetails{},
  834. },
  835. }
  836. return lhh
  837. }
  838. func (lh *LightHouse) metricRx(t NebulaMeta_MessageType, i int64) {
  839. lh.metrics.Rx(header.MessageType(t), 0, i)
  840. }
  841. func (lh *LightHouse) metricTx(t NebulaMeta_MessageType, i int64) {
  842. lh.metrics.Tx(header.MessageType(t), 0, i)
  843. }
  844. // This method is similar to Reset(), but it re-uses the pointer structs
  845. // so that we don't have to re-allocate them
  846. func (lhh *LightHouseHandler) resetMeta() *NebulaMeta {
  847. details := lhh.meta.Details
  848. lhh.meta.Reset()
  849. // Keep the array memory around
  850. details.V4AddrPorts = details.V4AddrPorts[:0]
  851. details.V6AddrPorts = details.V6AddrPorts[:0]
  852. details.RelayVpnAddrs = details.RelayVpnAddrs[:0]
  853. details.OldRelayVpnAddrs = details.OldRelayVpnAddrs[:0]
  854. details.OldVpnAddr = 0
  855. details.VpnAddr = nil
  856. lhh.meta.Details = details
  857. return lhh.meta
  858. }
  859. func (lhh *LightHouseHandler) HandleRequest(rAddr netip.AddrPort, fromVpnAddrs []netip.Addr, p []byte, w EncWriter) {
  860. n := lhh.resetMeta()
  861. err := n.Unmarshal(p)
  862. if err != nil {
  863. lhh.l.WithError(err).WithField("vpnAddrs", fromVpnAddrs).WithField("udpAddr", rAddr).
  864. Error("Failed to unmarshal lighthouse packet")
  865. return
  866. }
  867. if n.Details == nil {
  868. lhh.l.WithField("vpnAddrs", fromVpnAddrs).WithField("udpAddr", rAddr).
  869. Error("Invalid lighthouse update")
  870. return
  871. }
  872. lhh.lh.metricRx(n.Type, 1)
  873. switch n.Type {
  874. case NebulaMeta_HostQuery:
  875. lhh.handleHostQuery(n, fromVpnAddrs, rAddr, w)
  876. case NebulaMeta_HostQueryReply:
  877. lhh.handleHostQueryReply(n, fromVpnAddrs)
  878. case NebulaMeta_HostUpdateNotification:
  879. lhh.handleHostUpdateNotification(n, fromVpnAddrs, w)
  880. case NebulaMeta_HostMovedNotification:
  881. case NebulaMeta_HostPunchNotification:
  882. lhh.handleHostPunchNotification(n, fromVpnAddrs, w)
  883. case NebulaMeta_HostUpdateNotificationAck:
  884. // noop
  885. }
  886. }
  887. func (lhh *LightHouseHandler) handleHostQuery(n *NebulaMeta, fromVpnAddrs []netip.Addr, addr netip.AddrPort, w EncWriter) {
  888. // Exit if we don't answer queries
  889. if !lhh.lh.amLighthouse {
  890. if lhh.l.Level >= logrus.DebugLevel {
  891. lhh.l.Debugln("I don't answer queries, but received from: ", addr)
  892. }
  893. return
  894. }
  895. queryVpnAddr, useVersion, err := n.Details.GetVpnAddrAndVersion()
  896. if err != nil {
  897. if lhh.l.Level >= logrus.DebugLevel {
  898. lhh.l.WithField("from", fromVpnAddrs).WithField("details", n.Details).Debugln("Dropping malformed HostQuery")
  899. }
  900. return
  901. }
  902. found, ln, err := lhh.lh.queryAndPrepMessage(queryVpnAddr, func(c *cache) (int, error) {
  903. n = lhh.resetMeta()
  904. n.Type = NebulaMeta_HostQueryReply
  905. if useVersion == cert.Version1 {
  906. if !queryVpnAddr.Is4() {
  907. return 0, fmt.Errorf("invalid vpn addr for v1 handleHostQuery")
  908. }
  909. b := queryVpnAddr.As4()
  910. n.Details.OldVpnAddr = binary.BigEndian.Uint32(b[:])
  911. } else {
  912. n.Details.VpnAddr = netAddrToProtoAddr(queryVpnAddr)
  913. }
  914. lhh.coalesceAnswers(useVersion, c, n)
  915. return n.MarshalTo(lhh.pb)
  916. })
  917. if !found {
  918. return
  919. }
  920. if err != nil {
  921. lhh.l.WithError(err).WithField("vpnAddrs", fromVpnAddrs).Error("Failed to marshal lighthouse host query reply")
  922. return
  923. }
  924. lhh.lh.metricTx(NebulaMeta_HostQueryReply, 1)
  925. w.SendMessageToVpnAddr(header.LightHouse, 0, fromVpnAddrs[0], lhh.pb[:ln], lhh.nb, lhh.out[:0])
  926. lhh.sendHostPunchNotification(n, fromVpnAddrs, queryVpnAddr, w)
  927. }
  928. // sendHostPunchNotification signals the other side to punch some zero byte udp packets
  929. func (lhh *LightHouseHandler) sendHostPunchNotification(n *NebulaMeta, fromVpnAddrs []netip.Addr, punchNotifDest netip.Addr, w EncWriter) {
  930. whereToPunch := fromVpnAddrs[0]
  931. found, ln, err := lhh.lh.queryAndPrepMessage(whereToPunch, func(c *cache) (int, error) {
  932. n = lhh.resetMeta()
  933. n.Type = NebulaMeta_HostPunchNotification
  934. targetHI := lhh.lh.ifce.GetHostInfo(punchNotifDest)
  935. var useVersion cert.Version
  936. if targetHI == nil {
  937. useVersion = lhh.lh.ifce.GetCertState().initiatingVersion
  938. } else {
  939. crt := targetHI.GetCert().Certificate
  940. useVersion = crt.Version()
  941. // we can only retarget if we have a hostinfo
  942. newDest, ok := findNetworkUnion(crt.Networks(), fromVpnAddrs)
  943. if ok {
  944. whereToPunch = newDest
  945. } else {
  946. if lhh.l.Level >= logrus.DebugLevel {
  947. lhh.l.WithField("to", crt.Networks()).Debugln("unable to punch to host, no addresses in common")
  948. }
  949. }
  950. }
  951. if useVersion == cert.Version1 {
  952. if !whereToPunch.Is4() {
  953. return 0, fmt.Errorf("invalid vpn addr for v1 handleHostQuery")
  954. }
  955. b := whereToPunch.As4()
  956. n.Details.OldVpnAddr = binary.BigEndian.Uint32(b[:])
  957. } else if useVersion == cert.Version2 {
  958. n.Details.VpnAddr = netAddrToProtoAddr(whereToPunch)
  959. } else {
  960. return 0, errors.New("unsupported version")
  961. }
  962. lhh.coalesceAnswers(useVersion, c, n)
  963. return n.MarshalTo(lhh.pb)
  964. })
  965. if !found {
  966. return
  967. }
  968. if err != nil {
  969. lhh.l.WithError(err).WithField("vpnAddrs", fromVpnAddrs).Error("Failed to marshal lighthouse host was queried for")
  970. return
  971. }
  972. lhh.lh.metricTx(NebulaMeta_HostPunchNotification, 1)
  973. w.SendMessageToVpnAddr(header.LightHouse, 0, punchNotifDest, lhh.pb[:ln], lhh.nb, lhh.out[:0])
  974. }
  975. func (lhh *LightHouseHandler) coalesceAnswers(v cert.Version, c *cache, n *NebulaMeta) {
  976. if c.v4 != nil {
  977. if c.v4.learned != nil {
  978. n.Details.V4AddrPorts = append(n.Details.V4AddrPorts, c.v4.learned)
  979. }
  980. if c.v4.reported != nil && len(c.v4.reported) > 0 {
  981. n.Details.V4AddrPorts = append(n.Details.V4AddrPorts, c.v4.reported...)
  982. }
  983. }
  984. if c.v6 != nil {
  985. if c.v6.learned != nil {
  986. n.Details.V6AddrPorts = append(n.Details.V6AddrPorts, c.v6.learned)
  987. }
  988. if c.v6.reported != nil && len(c.v6.reported) > 0 {
  989. n.Details.V6AddrPorts = append(n.Details.V6AddrPorts, c.v6.reported...)
  990. }
  991. }
  992. if c.relay != nil {
  993. if v == cert.Version1 {
  994. b := [4]byte{}
  995. for _, r := range c.relay.relay {
  996. if !r.Is4() {
  997. continue
  998. }
  999. b = r.As4()
  1000. n.Details.OldRelayVpnAddrs = append(n.Details.OldRelayVpnAddrs, binary.BigEndian.Uint32(b[:]))
  1001. }
  1002. } else if v == cert.Version2 {
  1003. for _, r := range c.relay.relay {
  1004. n.Details.RelayVpnAddrs = append(n.Details.RelayVpnAddrs, netAddrToProtoAddr(r))
  1005. }
  1006. } else {
  1007. if lhh.l.Level >= logrus.DebugLevel {
  1008. lhh.l.WithField("version", v).Debug("unsupported protocol version")
  1009. }
  1010. }
  1011. }
  1012. }
  1013. func (lhh *LightHouseHandler) handleHostQueryReply(n *NebulaMeta, fromVpnAddrs []netip.Addr) {
  1014. if !lhh.lh.IsAnyLighthouseAddr(fromVpnAddrs) {
  1015. return
  1016. }
  1017. certVpnAddr, _, err := n.Details.GetVpnAddrAndVersion()
  1018. if err != nil {
  1019. if lhh.l.Level >= logrus.DebugLevel {
  1020. lhh.l.WithError(err).WithField("vpnAddrs", fromVpnAddrs).Error("dropping malformed HostQueryReply")
  1021. }
  1022. return
  1023. }
  1024. relays := n.Details.GetRelays()
  1025. lhh.lh.Lock()
  1026. am := lhh.lh.unlockedGetRemoteList([]netip.Addr{certVpnAddr})
  1027. am.Lock()
  1028. lhh.lh.Unlock()
  1029. am.unlockedSetV4(fromVpnAddrs[0], certVpnAddr, n.Details.V4AddrPorts, lhh.lh.unlockedShouldAddV4)
  1030. am.unlockedSetV6(fromVpnAddrs[0], certVpnAddr, n.Details.V6AddrPorts, lhh.lh.unlockedShouldAddV6)
  1031. am.unlockedSetRelay(fromVpnAddrs[0], relays)
  1032. am.Unlock()
  1033. // Non-blocking attempt to trigger, skip if it would block
  1034. select {
  1035. case lhh.lh.handshakeTrigger <- certVpnAddr:
  1036. default:
  1037. }
  1038. }
  1039. func (lhh *LightHouseHandler) handleHostUpdateNotification(n *NebulaMeta, fromVpnAddrs []netip.Addr, w EncWriter) {
  1040. if !lhh.lh.amLighthouse {
  1041. if lhh.l.Level >= logrus.DebugLevel {
  1042. lhh.l.Debugln("I am not a lighthouse, do not take host updates: ", fromVpnAddrs)
  1043. }
  1044. return
  1045. }
  1046. detailsVpnAddr, useVersion, err := n.Details.GetVpnAddrAndVersion()
  1047. if err != nil {
  1048. if lhh.l.Level >= logrus.DebugLevel {
  1049. lhh.l.WithField("details", n.Details).WithError(err).Debugln("dropping invalid HostUpdateNotification")
  1050. }
  1051. }
  1052. //TODO: CERT-V2 why do we care about the vpnAddr in the packet? We know where it came from, right?
  1053. //Simple check that the host sent this not someone else
  1054. if !slices.Contains(fromVpnAddrs, detailsVpnAddr) {
  1055. if lhh.l.Level >= logrus.DebugLevel {
  1056. lhh.l.WithField("vpnAddrs", fromVpnAddrs).WithField("answer", detailsVpnAddr).Debugln("Host sent invalid update")
  1057. }
  1058. return
  1059. }
  1060. relays := n.Details.GetRelays()
  1061. lhh.lh.Lock()
  1062. am := lhh.lh.unlockedGetRemoteList(fromVpnAddrs)
  1063. am.Lock()
  1064. lhh.lh.Unlock()
  1065. am.unlockedSetV4(fromVpnAddrs[0], detailsVpnAddr, n.Details.V4AddrPorts, lhh.lh.unlockedShouldAddV4)
  1066. am.unlockedSetV6(fromVpnAddrs[0], detailsVpnAddr, n.Details.V6AddrPorts, lhh.lh.unlockedShouldAddV6)
  1067. am.unlockedSetRelay(fromVpnAddrs[0], relays)
  1068. am.Unlock()
  1069. n = lhh.resetMeta()
  1070. n.Type = NebulaMeta_HostUpdateNotificationAck
  1071. if useVersion == cert.Version1 {
  1072. if !fromVpnAddrs[0].Is4() {
  1073. lhh.l.WithField("vpnAddrs", fromVpnAddrs).Error("Can not send HostUpdateNotificationAck for a ipv6 vpn ip in a v1 message")
  1074. return
  1075. }
  1076. vpnAddrB := fromVpnAddrs[0].As4()
  1077. n.Details.OldVpnAddr = binary.BigEndian.Uint32(vpnAddrB[:])
  1078. } else if useVersion == cert.Version2 {
  1079. n.Details.VpnAddr = netAddrToProtoAddr(fromVpnAddrs[0])
  1080. } else {
  1081. lhh.l.WithField("useVersion", useVersion).Error("invalid protocol version")
  1082. return
  1083. }
  1084. ln, err := n.MarshalTo(lhh.pb)
  1085. if err != nil {
  1086. lhh.l.WithError(err).WithField("vpnAddrs", fromVpnAddrs).Error("Failed to marshal lighthouse host update ack")
  1087. return
  1088. }
  1089. lhh.lh.metricTx(NebulaMeta_HostUpdateNotificationAck, 1)
  1090. w.SendMessageToVpnAddr(header.LightHouse, 0, fromVpnAddrs[0], lhh.pb[:ln], lhh.nb, lhh.out[:0])
  1091. }
  1092. func (lhh *LightHouseHandler) handleHostPunchNotification(n *NebulaMeta, fromVpnAddrs []netip.Addr, w EncWriter) {
  1093. //It's possible the lighthouse is communicating with us using a non primary vpn addr,
  1094. //which means we need to compare all fromVpnAddrs against all configured lighthouse vpn addrs.
  1095. //maybe one day we'll have a better idea, if it matters.
  1096. if !lhh.lh.IsAnyLighthouseAddr(fromVpnAddrs) {
  1097. return
  1098. }
  1099. detailsVpnAddr, _, err := n.Details.GetVpnAddrAndVersion()
  1100. if err != nil {
  1101. if lhh.l.Level >= logrus.DebugLevel {
  1102. lhh.l.WithField("details", n.Details).WithError(err).Debugln("dropping invalid HostPunchNotification")
  1103. }
  1104. return
  1105. }
  1106. empty := []byte{0}
  1107. punch := func(vpnPeer netip.AddrPort, logVpnAddr netip.Addr) {
  1108. if !vpnPeer.IsValid() {
  1109. return
  1110. }
  1111. go func() {
  1112. time.Sleep(lhh.lh.punchy.GetDelay())
  1113. lhh.lh.metricHolepunchTx.Inc(1)
  1114. lhh.lh.punchConn.WriteTo(empty, vpnPeer)
  1115. }()
  1116. if lhh.l.Level >= logrus.DebugLevel {
  1117. lhh.l.Debugf("Punching on %v for %v", vpnPeer, logVpnAddr)
  1118. }
  1119. }
  1120. for _, a := range n.Details.V4AddrPorts {
  1121. punch(protoV4AddrPortToNetAddrPort(a), detailsVpnAddr)
  1122. }
  1123. for _, a := range n.Details.V6AddrPorts {
  1124. punch(protoV6AddrPortToNetAddrPort(a), detailsVpnAddr)
  1125. }
  1126. // This sends a nebula test packet to the host trying to contact us. In the case
  1127. // of a double nat or other difficult scenario, this may help establish
  1128. // a tunnel.
  1129. if lhh.lh.punchy.GetRespond() {
  1130. go func() {
  1131. time.Sleep(lhh.lh.punchy.GetRespondDelay())
  1132. if lhh.l.Level >= logrus.DebugLevel {
  1133. lhh.l.Debugf("Sending a nebula test packet to vpn addr %s", detailsVpnAddr)
  1134. }
  1135. //NOTE: we have to allocate a new output buffer here since we are spawning a new goroutine
  1136. // for each punchBack packet. We should move this into a timerwheel or a single goroutine
  1137. // managed by a channel.
  1138. w.SendMessageToVpnAddr(header.Test, header.TestRequest, detailsVpnAddr, []byte(""), make([]byte, 12, 12), make([]byte, mtu))
  1139. }()
  1140. }
  1141. }
  1142. func protoAddrToNetAddr(addr *Addr) netip.Addr {
  1143. b := [16]byte{}
  1144. binary.BigEndian.PutUint64(b[:8], addr.Hi)
  1145. binary.BigEndian.PutUint64(b[8:], addr.Lo)
  1146. return netip.AddrFrom16(b).Unmap()
  1147. }
  1148. func protoV4AddrPortToNetAddrPort(ap *V4AddrPort) netip.AddrPort {
  1149. b := [4]byte{}
  1150. binary.BigEndian.PutUint32(b[:], ap.Addr)
  1151. return netip.AddrPortFrom(netip.AddrFrom4(b), uint16(ap.Port))
  1152. }
  1153. func protoV6AddrPortToNetAddrPort(ap *V6AddrPort) netip.AddrPort {
  1154. b := [16]byte{}
  1155. binary.BigEndian.PutUint64(b[:8], ap.Hi)
  1156. binary.BigEndian.PutUint64(b[8:], ap.Lo)
  1157. return netip.AddrPortFrom(netip.AddrFrom16(b), uint16(ap.Port))
  1158. }
  1159. func netAddrToProtoAddr(addr netip.Addr) *Addr {
  1160. b := addr.As16()
  1161. return &Addr{
  1162. Hi: binary.BigEndian.Uint64(b[:8]),
  1163. Lo: binary.BigEndian.Uint64(b[8:]),
  1164. }
  1165. }
  1166. func netAddrToProtoV4AddrPort(addr netip.Addr, port uint16) *V4AddrPort {
  1167. v4Addr := addr.As4()
  1168. return &V4AddrPort{
  1169. Addr: binary.BigEndian.Uint32(v4Addr[:]),
  1170. Port: uint32(port),
  1171. }
  1172. }
  1173. func netAddrToProtoV6AddrPort(addr netip.Addr, port uint16) *V6AddrPort {
  1174. v6Addr := addr.As16()
  1175. return &V6AddrPort{
  1176. Hi: binary.BigEndian.Uint64(v6Addr[:8]),
  1177. Lo: binary.BigEndian.Uint64(v6Addr[8:]),
  1178. Port: uint32(port),
  1179. }
  1180. }
  1181. func (d *NebulaMetaDetails) GetRelays() []netip.Addr {
  1182. var relays []netip.Addr
  1183. if len(d.OldRelayVpnAddrs) > 0 {
  1184. b := [4]byte{}
  1185. for _, r := range d.OldRelayVpnAddrs {
  1186. binary.BigEndian.PutUint32(b[:], r)
  1187. relays = append(relays, netip.AddrFrom4(b))
  1188. }
  1189. }
  1190. if len(d.RelayVpnAddrs) > 0 {
  1191. for _, r := range d.RelayVpnAddrs {
  1192. relays = append(relays, protoAddrToNetAddr(r))
  1193. }
  1194. }
  1195. return relays
  1196. }
  1197. // FindNetworkUnion returns the first netip.Addr contained in the list of provided netip.Prefix, if able
  1198. func findNetworkUnion(prefixes []netip.Prefix, addrs []netip.Addr) (netip.Addr, bool) {
  1199. for i := range prefixes {
  1200. for j := range addrs {
  1201. if prefixes[i].Contains(addrs[j]) {
  1202. return addrs[j], true
  1203. }
  1204. }
  1205. }
  1206. return netip.Addr{}, false
  1207. }
  1208. func (d *NebulaMetaDetails) GetVpnAddrAndVersion() (netip.Addr, cert.Version, error) {
  1209. if d.OldVpnAddr != 0 {
  1210. b := [4]byte{}
  1211. binary.BigEndian.PutUint32(b[:], d.OldVpnAddr)
  1212. detailsVpnAddr := netip.AddrFrom4(b)
  1213. return detailsVpnAddr, cert.Version1, nil
  1214. } else if d.VpnAddr != nil {
  1215. detailsVpnAddr := protoAddrToNetAddr(d.VpnAddr)
  1216. return detailsVpnAddr, cert.Version2, nil
  1217. } else {
  1218. return netip.Addr{}, cert.Version1, ErrBadDetailsVpnAddr
  1219. }
  1220. }