lighthouse.go 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131
  1. package nebula
  2. import (
  3. "context"
  4. "encoding/binary"
  5. "errors"
  6. "fmt"
  7. "net"
  8. "net/netip"
  9. "sync"
  10. "sync/atomic"
  11. "time"
  12. "github.com/rcrowley/go-metrics"
  13. "github.com/sirupsen/logrus"
  14. "github.com/slackhq/nebula/cidr"
  15. "github.com/slackhq/nebula/config"
  16. "github.com/slackhq/nebula/header"
  17. "github.com/slackhq/nebula/iputil"
  18. "github.com/slackhq/nebula/udp"
  19. "github.com/slackhq/nebula/util"
  20. )
  21. //TODO: if a lighthouse doesn't have an answer, clients AGGRESSIVELY REQUERY.. why? handshake manager and/or getOrHandshake?
  22. //TODO: nodes are roaming lighthouses, this is bad. How are they learning?
  23. var ErrHostNotKnown = errors.New("host not known")
  24. type netIpAndPort struct {
  25. ip net.IP
  26. port uint16
  27. }
  28. type LightHouse struct {
  29. //TODO: We need a timer wheel to kick out vpnIps that haven't reported in a long time
  30. sync.RWMutex //Because we concurrently read and write to our maps
  31. ctx context.Context
  32. amLighthouse bool
  33. myVpnIp iputil.VpnIp
  34. myVpnZeros iputil.VpnIp
  35. myVpnNet *net.IPNet
  36. punchConn udp.Conn
  37. punchy *Punchy
  38. // Local cache of answers from light houses
  39. // map of vpn Ip to answers
  40. addrMap map[iputil.VpnIp]*RemoteList
  41. // filters remote addresses allowed for each host
  42. // - When we are a lighthouse, this filters what addresses we store and
  43. // respond with.
  44. // - When we are not a lighthouse, this filters which addresses we accept
  45. // from lighthouses.
  46. remoteAllowList atomic.Pointer[RemoteAllowList]
  47. // filters local addresses that we advertise to lighthouses
  48. localAllowList atomic.Pointer[LocalAllowList]
  49. // used to trigger the HandshakeManager when we receive HostQueryReply
  50. handshakeTrigger chan<- iputil.VpnIp
  51. // staticList exists to avoid having a bool in each addrMap entry
  52. // since static should be rare
  53. staticList atomic.Pointer[map[iputil.VpnIp]struct{}]
  54. lighthouses atomic.Pointer[map[iputil.VpnIp]struct{}]
  55. interval atomic.Int64
  56. updateCancel context.CancelFunc
  57. updateParentCtx context.Context
  58. updateUdp EncWriter
  59. nebulaPort uint32 // 32 bits because protobuf does not have a uint16
  60. advertiseAddrs atomic.Pointer[[]netIpAndPort]
  61. // IP's of relays that can be used by peers to access me
  62. relaysForMe atomic.Pointer[[]iputil.VpnIp]
  63. calculatedRemotes atomic.Pointer[cidr.Tree4] // Maps VpnIp to []*calculatedRemote
  64. metrics *MessageMetrics
  65. metricHolepunchTx metrics.Counter
  66. l *logrus.Logger
  67. }
  68. // NewLightHouseFromConfig will build a Lighthouse struct from the values provided in the config object
  69. // addrMap should be nil unless this is during a config reload
  70. func NewLightHouseFromConfig(ctx context.Context, l *logrus.Logger, c *config.C, myVpnNet *net.IPNet, pc udp.Conn, p *Punchy) (*LightHouse, error) {
  71. amLighthouse := c.GetBool("lighthouse.am_lighthouse", false)
  72. nebulaPort := uint32(c.GetInt("listen.port", 0))
  73. if amLighthouse && nebulaPort == 0 {
  74. return nil, util.NewContextualError("lighthouse.am_lighthouse enabled on node but no port number is set in config", nil, nil)
  75. }
  76. // If port is dynamic, discover it
  77. if nebulaPort == 0 && pc != nil {
  78. uPort, err := pc.LocalAddr()
  79. if err != nil {
  80. return nil, util.NewContextualError("Failed to get listening port", nil, err)
  81. }
  82. nebulaPort = uint32(uPort.Port)
  83. }
  84. ones, _ := myVpnNet.Mask.Size()
  85. h := LightHouse{
  86. ctx: ctx,
  87. amLighthouse: amLighthouse,
  88. myVpnIp: iputil.Ip2VpnIp(myVpnNet.IP),
  89. myVpnZeros: iputil.VpnIp(32 - ones),
  90. myVpnNet: myVpnNet,
  91. addrMap: make(map[iputil.VpnIp]*RemoteList),
  92. nebulaPort: nebulaPort,
  93. punchConn: pc,
  94. punchy: p,
  95. l: l,
  96. }
  97. lighthouses := make(map[iputil.VpnIp]struct{})
  98. h.lighthouses.Store(&lighthouses)
  99. staticList := make(map[iputil.VpnIp]struct{})
  100. h.staticList.Store(&staticList)
  101. if c.GetBool("stats.lighthouse_metrics", false) {
  102. h.metrics = newLighthouseMetrics()
  103. h.metricHolepunchTx = metrics.GetOrRegisterCounter("messages.tx.holepunch", nil)
  104. } else {
  105. h.metricHolepunchTx = metrics.NilCounter{}
  106. }
  107. err := h.reload(c, true)
  108. if err != nil {
  109. return nil, err
  110. }
  111. c.RegisterReloadCallback(func(c *config.C) {
  112. err := h.reload(c, false)
  113. switch v := err.(type) {
  114. case util.ContextualError:
  115. v.Log(l)
  116. case error:
  117. l.WithError(err).Error("failed to reload lighthouse")
  118. }
  119. })
  120. return &h, nil
  121. }
  122. func (lh *LightHouse) GetStaticHostList() map[iputil.VpnIp]struct{} {
  123. return *lh.staticList.Load()
  124. }
  125. func (lh *LightHouse) GetLighthouses() map[iputil.VpnIp]struct{} {
  126. return *lh.lighthouses.Load()
  127. }
  128. func (lh *LightHouse) GetRemoteAllowList() *RemoteAllowList {
  129. return lh.remoteAllowList.Load()
  130. }
  131. func (lh *LightHouse) GetLocalAllowList() *LocalAllowList {
  132. return lh.localAllowList.Load()
  133. }
  134. func (lh *LightHouse) GetAdvertiseAddrs() []netIpAndPort {
  135. return *lh.advertiseAddrs.Load()
  136. }
  137. func (lh *LightHouse) GetRelaysForMe() []iputil.VpnIp {
  138. return *lh.relaysForMe.Load()
  139. }
  140. func (lh *LightHouse) getCalculatedRemotes() *cidr.Tree4 {
  141. return lh.calculatedRemotes.Load()
  142. }
  143. func (lh *LightHouse) GetUpdateInterval() int64 {
  144. return lh.interval.Load()
  145. }
  146. func (lh *LightHouse) reload(c *config.C, initial bool) error {
  147. if initial || c.HasChanged("lighthouse.advertise_addrs") {
  148. rawAdvAddrs := c.GetStringSlice("lighthouse.advertise_addrs", []string{})
  149. advAddrs := make([]netIpAndPort, 0)
  150. for i, rawAddr := range rawAdvAddrs {
  151. fIp, fPort, err := udp.ParseIPAndPort(rawAddr)
  152. if err != nil {
  153. return util.NewContextualError("Unable to parse lighthouse.advertise_addrs entry", m{"addr": rawAddr, "entry": i + 1}, err)
  154. }
  155. if fPort == 0 {
  156. fPort = uint16(lh.nebulaPort)
  157. }
  158. if ip4 := fIp.To4(); ip4 != nil && lh.myVpnNet.Contains(fIp) {
  159. lh.l.WithField("addr", rawAddr).WithField("entry", i+1).
  160. Warn("Ignoring lighthouse.advertise_addrs report because it is within the nebula network range")
  161. continue
  162. }
  163. advAddrs = append(advAddrs, netIpAndPort{ip: fIp, port: fPort})
  164. }
  165. lh.advertiseAddrs.Store(&advAddrs)
  166. if !initial {
  167. lh.l.Info("lighthouse.advertise_addrs has changed")
  168. }
  169. }
  170. if initial || c.HasChanged("lighthouse.interval") {
  171. lh.interval.Store(int64(c.GetInt("lighthouse.interval", 10)))
  172. if !initial {
  173. lh.l.Infof("lighthouse.interval changed to %v", lh.interval.Load())
  174. if lh.updateCancel != nil {
  175. // May not always have a running routine
  176. lh.updateCancel()
  177. }
  178. lh.LhUpdateWorker(lh.updateParentCtx, lh.updateUdp)
  179. }
  180. }
  181. if initial || c.HasChanged("lighthouse.remote_allow_list") || c.HasChanged("lighthouse.remote_allow_ranges") {
  182. ral, err := NewRemoteAllowListFromConfig(c, "lighthouse.remote_allow_list", "lighthouse.remote_allow_ranges")
  183. if err != nil {
  184. return util.NewContextualError("Invalid lighthouse.remote_allow_list", nil, err)
  185. }
  186. lh.remoteAllowList.Store(ral)
  187. if !initial {
  188. //TODO: a diff will be annoyingly difficult
  189. lh.l.Info("lighthouse.remote_allow_list and/or lighthouse.remote_allow_ranges has changed")
  190. }
  191. }
  192. if initial || c.HasChanged("lighthouse.local_allow_list") {
  193. lal, err := NewLocalAllowListFromConfig(c, "lighthouse.local_allow_list")
  194. if err != nil {
  195. return util.NewContextualError("Invalid lighthouse.local_allow_list", nil, err)
  196. }
  197. lh.localAllowList.Store(lal)
  198. if !initial {
  199. //TODO: a diff will be annoyingly difficult
  200. lh.l.Info("lighthouse.local_allow_list has changed")
  201. }
  202. }
  203. if initial || c.HasChanged("lighthouse.calculated_remotes") {
  204. cr, err := NewCalculatedRemotesFromConfig(c, "lighthouse.calculated_remotes")
  205. if err != nil {
  206. return util.NewContextualError("Invalid lighthouse.calculated_remotes", nil, err)
  207. }
  208. lh.calculatedRemotes.Store(cr)
  209. if !initial {
  210. //TODO: a diff will be annoyingly difficult
  211. lh.l.Info("lighthouse.calculated_remotes has changed")
  212. }
  213. }
  214. //NOTE: many things will get much simpler when we combine static_host_map and lighthouse.hosts in config
  215. if initial || c.HasChanged("static_host_map") || c.HasChanged("static_map.cadence") || c.HasChanged("static_map.network") || c.HasChanged("static_map.lookup_timeout") {
  216. // Clean up. Entries still in the static_host_map will be re-built.
  217. // Entries no longer present must have their (possible) background DNS goroutines stopped.
  218. if existingStaticList := lh.staticList.Load(); existingStaticList != nil {
  219. lh.RLock()
  220. for staticVpnIp := range *existingStaticList {
  221. if am, ok := lh.addrMap[staticVpnIp]; ok && am != nil {
  222. am.hr.Cancel()
  223. }
  224. }
  225. lh.RUnlock()
  226. }
  227. // Build a new list based on current config.
  228. staticList := make(map[iputil.VpnIp]struct{})
  229. err := lh.loadStaticMap(c, lh.myVpnNet, staticList)
  230. if err != nil {
  231. return err
  232. }
  233. lh.staticList.Store(&staticList)
  234. if !initial {
  235. //TODO: we should remove any remote list entries for static hosts that were removed/modified?
  236. if c.HasChanged("static_host_map") {
  237. lh.l.Info("static_host_map has changed")
  238. }
  239. if c.HasChanged("static_map.cadence") {
  240. lh.l.Info("static_map.cadence has changed")
  241. }
  242. if c.HasChanged("static_map.network") {
  243. lh.l.Info("static_map.network has changed")
  244. }
  245. if c.HasChanged("static_map.lookup_timeout") {
  246. lh.l.Info("static_map.lookup_timeout has changed")
  247. }
  248. }
  249. }
  250. if initial || c.HasChanged("lighthouse.hosts") {
  251. lhMap := make(map[iputil.VpnIp]struct{})
  252. err := lh.parseLighthouses(c, lh.myVpnNet, lhMap)
  253. if err != nil {
  254. return err
  255. }
  256. lh.lighthouses.Store(&lhMap)
  257. if !initial {
  258. //NOTE: we are not tearing down existing lighthouse connections because they might be used for non lighthouse traffic
  259. lh.l.Info("lighthouse.hosts has changed")
  260. }
  261. }
  262. if initial || c.HasChanged("relay.relays") {
  263. switch c.GetBool("relay.am_relay", false) {
  264. case true:
  265. // Relays aren't allowed to specify other relays
  266. if len(c.GetStringSlice("relay.relays", nil)) > 0 {
  267. lh.l.Info("Ignoring relays from config because am_relay is true")
  268. }
  269. relaysForMe := []iputil.VpnIp{}
  270. lh.relaysForMe.Store(&relaysForMe)
  271. case false:
  272. relaysForMe := []iputil.VpnIp{}
  273. for _, v := range c.GetStringSlice("relay.relays", nil) {
  274. lh.l.WithField("relay", v).Info("Read relay from config")
  275. configRIP := net.ParseIP(v)
  276. if configRIP != nil {
  277. relaysForMe = append(relaysForMe, iputil.Ip2VpnIp(configRIP))
  278. }
  279. }
  280. lh.relaysForMe.Store(&relaysForMe)
  281. }
  282. }
  283. return nil
  284. }
  285. func (lh *LightHouse) parseLighthouses(c *config.C, tunCidr *net.IPNet, lhMap map[iputil.VpnIp]struct{}) error {
  286. lhs := c.GetStringSlice("lighthouse.hosts", []string{})
  287. if lh.amLighthouse && len(lhs) != 0 {
  288. lh.l.Warn("lighthouse.am_lighthouse enabled on node but upstream lighthouses exist in config")
  289. }
  290. for i, host := range lhs {
  291. ip := net.ParseIP(host)
  292. if ip == nil {
  293. return util.NewContextualError("Unable to parse lighthouse host entry", m{"host": host, "entry": i + 1}, nil)
  294. }
  295. if !tunCidr.Contains(ip) {
  296. return util.NewContextualError("lighthouse host is not in our subnet, invalid", m{"vpnIp": ip, "network": tunCidr.String()}, nil)
  297. }
  298. lhMap[iputil.Ip2VpnIp(ip)] = struct{}{}
  299. }
  300. if !lh.amLighthouse && len(lhMap) == 0 {
  301. lh.l.Warn("No lighthouse.hosts configured, this host will only be able to initiate tunnels with static_host_map entries")
  302. }
  303. staticList := lh.GetStaticHostList()
  304. for lhIP, _ := range lhMap {
  305. if _, ok := staticList[lhIP]; !ok {
  306. return fmt.Errorf("lighthouse %s does not have a static_host_map entry", lhIP)
  307. }
  308. }
  309. return nil
  310. }
  311. func getStaticMapCadence(c *config.C) (time.Duration, error) {
  312. cadence := c.GetString("static_map.cadence", "30s")
  313. d, err := time.ParseDuration(cadence)
  314. if err != nil {
  315. return 0, err
  316. }
  317. return d, nil
  318. }
  319. func getStaticMapLookupTimeout(c *config.C) (time.Duration, error) {
  320. lookupTimeout := c.GetString("static_map.lookup_timeout", "250ms")
  321. d, err := time.ParseDuration(lookupTimeout)
  322. if err != nil {
  323. return 0, err
  324. }
  325. return d, nil
  326. }
  327. func getStaticMapNetwork(c *config.C) (string, error) {
  328. network := c.GetString("static_map.network", "ip4")
  329. if network != "ip" && network != "ip4" && network != "ip6" {
  330. return "", fmt.Errorf("static_map.network must be one of ip, ip4, or ip6")
  331. }
  332. return network, nil
  333. }
  334. func (lh *LightHouse) loadStaticMap(c *config.C, tunCidr *net.IPNet, staticList map[iputil.VpnIp]struct{}) error {
  335. d, err := getStaticMapCadence(c)
  336. if err != nil {
  337. return err
  338. }
  339. network, err := getStaticMapNetwork(c)
  340. if err != nil {
  341. return err
  342. }
  343. lookup_timeout, err := getStaticMapLookupTimeout(c)
  344. if err != nil {
  345. return err
  346. }
  347. shm := c.GetMap("static_host_map", map[interface{}]interface{}{})
  348. i := 0
  349. for k, v := range shm {
  350. rip := net.ParseIP(fmt.Sprintf("%v", k))
  351. if rip == nil {
  352. return util.NewContextualError("Unable to parse static_host_map entry", m{"host": k, "entry": i + 1}, nil)
  353. }
  354. if !tunCidr.Contains(rip) {
  355. return util.NewContextualError("static_host_map key is not in our subnet, invalid", m{"vpnIp": rip, "network": tunCidr.String(), "entry": i + 1}, nil)
  356. }
  357. vpnIp := iputil.Ip2VpnIp(rip)
  358. vals, ok := v.([]interface{})
  359. if !ok {
  360. vals = []interface{}{v}
  361. }
  362. remoteAddrs := []string{}
  363. for _, v := range vals {
  364. remoteAddrs = append(remoteAddrs, fmt.Sprintf("%v", v))
  365. }
  366. err := lh.addStaticRemotes(i, d, network, lookup_timeout, vpnIp, remoteAddrs, staticList)
  367. if err != nil {
  368. return err
  369. }
  370. i++
  371. }
  372. return nil
  373. }
  374. func (lh *LightHouse) Query(ip iputil.VpnIp, f EncWriter) *RemoteList {
  375. if !lh.IsLighthouseIP(ip) {
  376. lh.QueryServer(ip, f)
  377. }
  378. lh.RLock()
  379. if v, ok := lh.addrMap[ip]; ok {
  380. lh.RUnlock()
  381. return v
  382. }
  383. lh.RUnlock()
  384. return nil
  385. }
  386. // This is asynchronous so no reply should be expected
  387. func (lh *LightHouse) QueryServer(ip iputil.VpnIp, f EncWriter) {
  388. if lh.amLighthouse {
  389. return
  390. }
  391. if lh.IsLighthouseIP(ip) {
  392. return
  393. }
  394. // Send a query to the lighthouses and hope for the best next time
  395. query, err := NewLhQueryByInt(ip).Marshal()
  396. if err != nil {
  397. lh.l.WithError(err).WithField("vpnIp", ip).Error("Failed to marshal lighthouse query payload")
  398. return
  399. }
  400. lighthouses := lh.GetLighthouses()
  401. lh.metricTx(NebulaMeta_HostQuery, int64(len(lighthouses)))
  402. nb := make([]byte, 12, 12)
  403. out := make([]byte, mtu)
  404. for n := range lighthouses {
  405. f.SendMessageToVpnIp(header.LightHouse, 0, n, query, nb, out)
  406. }
  407. }
  408. func (lh *LightHouse) QueryCache(ip iputil.VpnIp) *RemoteList {
  409. lh.RLock()
  410. if v, ok := lh.addrMap[ip]; ok {
  411. lh.RUnlock()
  412. return v
  413. }
  414. lh.RUnlock()
  415. lh.Lock()
  416. defer lh.Unlock()
  417. // Add an entry if we don't already have one
  418. return lh.unlockedGetRemoteList(ip)
  419. }
  420. // queryAndPrepMessage is a lock helper on RemoteList, assisting the caller to build a lighthouse message containing
  421. // details from the remote list. It looks for a hit in the addrMap and a hit in the RemoteList under the owner vpnIp
  422. // If one is found then f() is called with proper locking, f() must return result of n.MarshalTo()
  423. func (lh *LightHouse) queryAndPrepMessage(vpnIp iputil.VpnIp, f func(*cache) (int, error)) (bool, int, error) {
  424. lh.RLock()
  425. // Do we have an entry in the main cache?
  426. if v, ok := lh.addrMap[vpnIp]; ok {
  427. // Swap lh lock for remote list lock
  428. v.RLock()
  429. defer v.RUnlock()
  430. lh.RUnlock()
  431. // vpnIp should also be the owner here since we are a lighthouse.
  432. c := v.cache[vpnIp]
  433. // Make sure we have
  434. if c != nil {
  435. n, err := f(c)
  436. return true, n, err
  437. }
  438. return false, 0, nil
  439. }
  440. lh.RUnlock()
  441. return false, 0, nil
  442. }
  443. func (lh *LightHouse) DeleteVpnIp(vpnIp iputil.VpnIp) {
  444. // First we check the static mapping
  445. // and do nothing if it is there
  446. if _, ok := lh.GetStaticHostList()[vpnIp]; ok {
  447. return
  448. }
  449. lh.Lock()
  450. //l.Debugln(lh.addrMap)
  451. delete(lh.addrMap, vpnIp)
  452. if lh.l.Level >= logrus.DebugLevel {
  453. lh.l.Debugf("deleting %s from lighthouse.", vpnIp)
  454. }
  455. lh.Unlock()
  456. }
  457. // AddStaticRemote adds a static host entry for vpnIp as ourselves as the owner
  458. // We are the owner because we don't want a lighthouse server to advertise for static hosts it was configured with
  459. // And we don't want a lighthouse query reply to interfere with our learned cache if we are a client
  460. // NOTE: this function should not interact with any hot path objects, like lh.staticList, the caller should handle it
  461. func (lh *LightHouse) addStaticRemotes(i int, d time.Duration, network string, timeout time.Duration, vpnIp iputil.VpnIp, toAddrs []string, staticList map[iputil.VpnIp]struct{}) error {
  462. lh.Lock()
  463. am := lh.unlockedGetRemoteList(vpnIp)
  464. am.Lock()
  465. defer am.Unlock()
  466. ctx := lh.ctx
  467. lh.Unlock()
  468. hr, err := NewHostnameResults(ctx, lh.l, d, network, timeout, toAddrs, func() {
  469. // This callback runs whenever the DNS hostname resolver finds a different set of IP's
  470. // in its resolution for hostnames.
  471. am.Lock()
  472. defer am.Unlock()
  473. am.shouldRebuild = true
  474. })
  475. if err != nil {
  476. return util.NewContextualError("Static host address could not be parsed", m{"vpnIp": vpnIp, "entry": i + 1}, err)
  477. }
  478. am.unlockedSetHostnamesResults(hr)
  479. for _, addrPort := range hr.GetIPs() {
  480. switch {
  481. case addrPort.Addr().Is4():
  482. to := NewIp4AndPortFromNetIP(addrPort.Addr(), addrPort.Port())
  483. if !lh.unlockedShouldAddV4(vpnIp, to) {
  484. continue
  485. }
  486. am.unlockedPrependV4(lh.myVpnIp, to)
  487. case addrPort.Addr().Is6():
  488. to := NewIp6AndPortFromNetIP(addrPort.Addr(), addrPort.Port())
  489. if !lh.unlockedShouldAddV6(vpnIp, to) {
  490. continue
  491. }
  492. am.unlockedPrependV6(lh.myVpnIp, to)
  493. }
  494. }
  495. // Mark it as static in the caller provided map
  496. staticList[vpnIp] = 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(vpnIp iputil.VpnIp) bool {
  503. tree := lh.getCalculatedRemotes()
  504. if tree == nil {
  505. return false
  506. }
  507. value := tree.MostSpecificContains(vpnIp)
  508. if value == nil {
  509. return false
  510. }
  511. calculatedRemotes := value.([]*calculatedRemote)
  512. var calculated []*Ip4AndPort
  513. for _, cr := range calculatedRemotes {
  514. c := cr.Apply(vpnIp)
  515. if c != nil {
  516. calculated = append(calculated, c)
  517. }
  518. }
  519. lh.Lock()
  520. am := lh.unlockedGetRemoteList(vpnIp)
  521. am.Lock()
  522. defer am.Unlock()
  523. lh.Unlock()
  524. am.unlockedSetV4(lh.myVpnIp, vpnIp, calculated, lh.unlockedShouldAddV4)
  525. return len(calculated) > 0
  526. }
  527. // unlockedGetRemoteList assumes you have the lh lock
  528. func (lh *LightHouse) unlockedGetRemoteList(vpnIp iputil.VpnIp) *RemoteList {
  529. am, ok := lh.addrMap[vpnIp]
  530. if !ok {
  531. am = NewRemoteList(func(a netip.Addr) bool { return lh.shouldAdd(vpnIp, a) })
  532. lh.addrMap[vpnIp] = am
  533. }
  534. return am
  535. }
  536. func (lh *LightHouse) shouldAdd(vpnIp iputil.VpnIp, to netip.Addr) bool {
  537. switch {
  538. case to.Is4():
  539. ipBytes := to.As4()
  540. ip := iputil.Ip2VpnIp(ipBytes[:])
  541. allow := lh.GetRemoteAllowList().AllowIpV4(vpnIp, ip)
  542. if lh.l.Level >= logrus.TraceLevel {
  543. lh.l.WithField("remoteIp", vpnIp).WithField("allow", allow).Trace("remoteAllowList.Allow")
  544. }
  545. if !allow || ipMaskContains(lh.myVpnIp, lh.myVpnZeros, ip) {
  546. return false
  547. }
  548. case to.Is6():
  549. ipBytes := to.As16()
  550. hi := binary.BigEndian.Uint64(ipBytes[:8])
  551. lo := binary.BigEndian.Uint64(ipBytes[8:])
  552. allow := lh.GetRemoteAllowList().AllowIpV6(vpnIp, hi, lo)
  553. if lh.l.Level >= logrus.TraceLevel {
  554. lh.l.WithField("remoteIp", to).WithField("allow", allow).Trace("remoteAllowList.Allow")
  555. }
  556. // We don't check our vpn network here because nebula does not support ipv6 on the inside
  557. if !allow {
  558. return false
  559. }
  560. }
  561. return true
  562. }
  563. // unlockedShouldAddV4 checks if to is allowed by our allow list
  564. func (lh *LightHouse) unlockedShouldAddV4(vpnIp iputil.VpnIp, to *Ip4AndPort) bool {
  565. allow := lh.GetRemoteAllowList().AllowIpV4(vpnIp, iputil.VpnIp(to.Ip))
  566. if lh.l.Level >= logrus.TraceLevel {
  567. lh.l.WithField("remoteIp", vpnIp).WithField("allow", allow).Trace("remoteAllowList.Allow")
  568. }
  569. if !allow || ipMaskContains(lh.myVpnIp, lh.myVpnZeros, iputil.VpnIp(to.Ip)) {
  570. return false
  571. }
  572. return true
  573. }
  574. // unlockedShouldAddV6 checks if to is allowed by our allow list
  575. func (lh *LightHouse) unlockedShouldAddV6(vpnIp iputil.VpnIp, to *Ip6AndPort) bool {
  576. allow := lh.GetRemoteAllowList().AllowIpV6(vpnIp, to.Hi, to.Lo)
  577. if lh.l.Level >= logrus.TraceLevel {
  578. lh.l.WithField("remoteIp", lhIp6ToIp(to)).WithField("allow", allow).Trace("remoteAllowList.Allow")
  579. }
  580. // We don't check our vpn network here because nebula does not support ipv6 on the inside
  581. if !allow {
  582. return false
  583. }
  584. return true
  585. }
  586. func lhIp6ToIp(v *Ip6AndPort) net.IP {
  587. ip := make(net.IP, 16)
  588. binary.BigEndian.PutUint64(ip[:8], v.Hi)
  589. binary.BigEndian.PutUint64(ip[8:], v.Lo)
  590. return ip
  591. }
  592. func (lh *LightHouse) IsLighthouseIP(vpnIp iputil.VpnIp) bool {
  593. if _, ok := lh.GetLighthouses()[vpnIp]; ok {
  594. return true
  595. }
  596. return false
  597. }
  598. func NewLhQueryByInt(VpnIp iputil.VpnIp) *NebulaMeta {
  599. return &NebulaMeta{
  600. Type: NebulaMeta_HostQuery,
  601. Details: &NebulaMetaDetails{
  602. VpnIp: uint32(VpnIp),
  603. },
  604. }
  605. }
  606. func NewIp4AndPort(ip net.IP, port uint32) *Ip4AndPort {
  607. ipp := Ip4AndPort{Port: port}
  608. ipp.Ip = uint32(iputil.Ip2VpnIp(ip))
  609. return &ipp
  610. }
  611. func NewIp4AndPortFromNetIP(ip netip.Addr, port uint16) *Ip4AndPort {
  612. v4Addr := ip.As4()
  613. return &Ip4AndPort{
  614. Ip: binary.BigEndian.Uint32(v4Addr[:]),
  615. Port: uint32(port),
  616. }
  617. }
  618. func NewIp6AndPort(ip net.IP, port uint32) *Ip6AndPort {
  619. return &Ip6AndPort{
  620. Hi: binary.BigEndian.Uint64(ip[:8]),
  621. Lo: binary.BigEndian.Uint64(ip[8:]),
  622. Port: port,
  623. }
  624. }
  625. func NewIp6AndPortFromNetIP(ip netip.Addr, port uint16) *Ip6AndPort {
  626. ip6Addr := ip.As16()
  627. return &Ip6AndPort{
  628. Hi: binary.BigEndian.Uint64(ip6Addr[:8]),
  629. Lo: binary.BigEndian.Uint64(ip6Addr[8:]),
  630. Port: uint32(port),
  631. }
  632. }
  633. func NewUDPAddrFromLH4(ipp *Ip4AndPort) *udp.Addr {
  634. ip := ipp.Ip
  635. return udp.NewAddr(
  636. net.IPv4(byte(ip&0xff000000>>24), byte(ip&0x00ff0000>>16), byte(ip&0x0000ff00>>8), byte(ip&0x000000ff)),
  637. uint16(ipp.Port),
  638. )
  639. }
  640. func NewUDPAddrFromLH6(ipp *Ip6AndPort) *udp.Addr {
  641. return udp.NewAddr(lhIp6ToIp(ipp), uint16(ipp.Port))
  642. }
  643. func (lh *LightHouse) LhUpdateWorker(ctx context.Context, f EncWriter) {
  644. lh.updateParentCtx = ctx
  645. lh.updateUdp = f
  646. interval := lh.GetUpdateInterval()
  647. if lh.amLighthouse || interval == 0 {
  648. return
  649. }
  650. clockSource := time.NewTicker(time.Second * time.Duration(interval))
  651. updateCtx, cancel := context.WithCancel(ctx)
  652. lh.updateCancel = cancel
  653. defer clockSource.Stop()
  654. for {
  655. lh.SendUpdate(f)
  656. select {
  657. case <-updateCtx.Done():
  658. return
  659. case <-clockSource.C:
  660. continue
  661. }
  662. }
  663. }
  664. func (lh *LightHouse) SendUpdate(f EncWriter) {
  665. var v4 []*Ip4AndPort
  666. var v6 []*Ip6AndPort
  667. for _, e := range lh.GetAdvertiseAddrs() {
  668. if ip := e.ip.To4(); ip != nil {
  669. v4 = append(v4, NewIp4AndPort(e.ip, uint32(e.port)))
  670. } else {
  671. v6 = append(v6, NewIp6AndPort(e.ip, uint32(e.port)))
  672. }
  673. }
  674. lal := lh.GetLocalAllowList()
  675. for _, e := range *localIps(lh.l, lal) {
  676. if ip4 := e.To4(); ip4 != nil && ipMaskContains(lh.myVpnIp, lh.myVpnZeros, iputil.Ip2VpnIp(ip4)) {
  677. continue
  678. }
  679. // Only add IPs that aren't my VPN/tun IP
  680. if ip := e.To4(); ip != nil {
  681. v4 = append(v4, NewIp4AndPort(e, lh.nebulaPort))
  682. } else {
  683. v6 = append(v6, NewIp6AndPort(e, lh.nebulaPort))
  684. }
  685. }
  686. var relays []uint32
  687. for _, r := range lh.GetRelaysForMe() {
  688. relays = append(relays, (uint32)(r))
  689. }
  690. m := &NebulaMeta{
  691. Type: NebulaMeta_HostUpdateNotification,
  692. Details: &NebulaMetaDetails{
  693. VpnIp: uint32(lh.myVpnIp),
  694. Ip4AndPorts: v4,
  695. Ip6AndPorts: v6,
  696. RelayVpnIp: relays,
  697. },
  698. }
  699. lighthouses := lh.GetLighthouses()
  700. lh.metricTx(NebulaMeta_HostUpdateNotification, int64(len(lighthouses)))
  701. nb := make([]byte, 12, 12)
  702. out := make([]byte, mtu)
  703. mm, err := m.Marshal()
  704. if err != nil {
  705. lh.l.WithError(err).Error("Error while marshaling for lighthouse update")
  706. return
  707. }
  708. for vpnIp := range lighthouses {
  709. f.SendMessageToVpnIp(header.LightHouse, 0, vpnIp, mm, nb, out)
  710. }
  711. }
  712. type LightHouseHandler struct {
  713. lh *LightHouse
  714. nb []byte
  715. out []byte
  716. pb []byte
  717. meta *NebulaMeta
  718. l *logrus.Logger
  719. }
  720. func (lh *LightHouse) NewRequestHandler() *LightHouseHandler {
  721. lhh := &LightHouseHandler{
  722. lh: lh,
  723. nb: make([]byte, 12, 12),
  724. out: make([]byte, mtu),
  725. l: lh.l,
  726. pb: make([]byte, mtu),
  727. meta: &NebulaMeta{
  728. Details: &NebulaMetaDetails{},
  729. },
  730. }
  731. return lhh
  732. }
  733. func (lh *LightHouse) metricRx(t NebulaMeta_MessageType, i int64) {
  734. lh.metrics.Rx(header.MessageType(t), 0, i)
  735. }
  736. func (lh *LightHouse) metricTx(t NebulaMeta_MessageType, i int64) {
  737. lh.metrics.Tx(header.MessageType(t), 0, i)
  738. }
  739. // This method is similar to Reset(), but it re-uses the pointer structs
  740. // so that we don't have to re-allocate them
  741. func (lhh *LightHouseHandler) resetMeta() *NebulaMeta {
  742. details := lhh.meta.Details
  743. lhh.meta.Reset()
  744. // Keep the array memory around
  745. details.Ip4AndPorts = details.Ip4AndPorts[:0]
  746. details.Ip6AndPorts = details.Ip6AndPorts[:0]
  747. details.RelayVpnIp = details.RelayVpnIp[:0]
  748. lhh.meta.Details = details
  749. return lhh.meta
  750. }
  751. func lhHandleRequest(lhh *LightHouseHandler, f *Interface) udp.LightHouseHandlerFunc {
  752. return func(rAddr *udp.Addr, vpnIp iputil.VpnIp, p []byte) {
  753. lhh.HandleRequest(rAddr, vpnIp, p, f)
  754. }
  755. }
  756. func (lhh *LightHouseHandler) HandleRequest(rAddr *udp.Addr, vpnIp iputil.VpnIp, p []byte, w EncWriter) {
  757. n := lhh.resetMeta()
  758. err := n.Unmarshal(p)
  759. if err != nil {
  760. lhh.l.WithError(err).WithField("vpnIp", vpnIp).WithField("udpAddr", rAddr).
  761. Error("Failed to unmarshal lighthouse packet")
  762. //TODO: send recv_error?
  763. return
  764. }
  765. if n.Details == nil {
  766. lhh.l.WithField("vpnIp", vpnIp).WithField("udpAddr", rAddr).
  767. Error("Invalid lighthouse update")
  768. //TODO: send recv_error?
  769. return
  770. }
  771. lhh.lh.metricRx(n.Type, 1)
  772. switch n.Type {
  773. case NebulaMeta_HostQuery:
  774. lhh.handleHostQuery(n, vpnIp, rAddr, w)
  775. case NebulaMeta_HostQueryReply:
  776. lhh.handleHostQueryReply(n, vpnIp)
  777. case NebulaMeta_HostUpdateNotification:
  778. lhh.handleHostUpdateNotification(n, vpnIp, w)
  779. case NebulaMeta_HostMovedNotification:
  780. case NebulaMeta_HostPunchNotification:
  781. lhh.handleHostPunchNotification(n, vpnIp, w)
  782. case NebulaMeta_HostUpdateNotificationAck:
  783. // noop
  784. }
  785. }
  786. func (lhh *LightHouseHandler) handleHostQuery(n *NebulaMeta, vpnIp iputil.VpnIp, addr *udp.Addr, w EncWriter) {
  787. // Exit if we don't answer queries
  788. if !lhh.lh.amLighthouse {
  789. if lhh.l.Level >= logrus.DebugLevel {
  790. lhh.l.Debugln("I don't answer queries, but received from: ", addr)
  791. }
  792. return
  793. }
  794. //TODO: we can DRY this further
  795. reqVpnIp := n.Details.VpnIp
  796. //TODO: Maybe instead of marshalling into n we marshal into a new `r` to not nuke our current request data
  797. found, ln, err := lhh.lh.queryAndPrepMessage(iputil.VpnIp(n.Details.VpnIp), func(c *cache) (int, error) {
  798. n = lhh.resetMeta()
  799. n.Type = NebulaMeta_HostQueryReply
  800. n.Details.VpnIp = reqVpnIp
  801. lhh.coalesceAnswers(c, n)
  802. return n.MarshalTo(lhh.pb)
  803. })
  804. if !found {
  805. return
  806. }
  807. if err != nil {
  808. lhh.l.WithError(err).WithField("vpnIp", vpnIp).Error("Failed to marshal lighthouse host query reply")
  809. return
  810. }
  811. lhh.lh.metricTx(NebulaMeta_HostQueryReply, 1)
  812. w.SendMessageToVpnIp(header.LightHouse, 0, vpnIp, lhh.pb[:ln], lhh.nb, lhh.out[:0])
  813. // This signals the other side to punch some zero byte udp packets
  814. found, ln, err = lhh.lh.queryAndPrepMessage(vpnIp, func(c *cache) (int, error) {
  815. n = lhh.resetMeta()
  816. n.Type = NebulaMeta_HostPunchNotification
  817. n.Details.VpnIp = uint32(vpnIp)
  818. lhh.coalesceAnswers(c, n)
  819. return n.MarshalTo(lhh.pb)
  820. })
  821. if !found {
  822. return
  823. }
  824. if err != nil {
  825. lhh.l.WithError(err).WithField("vpnIp", vpnIp).Error("Failed to marshal lighthouse host was queried for")
  826. return
  827. }
  828. lhh.lh.metricTx(NebulaMeta_HostPunchNotification, 1)
  829. w.SendMessageToVpnIp(header.LightHouse, 0, iputil.VpnIp(reqVpnIp), lhh.pb[:ln], lhh.nb, lhh.out[:0])
  830. }
  831. func (lhh *LightHouseHandler) coalesceAnswers(c *cache, n *NebulaMeta) {
  832. if c.v4 != nil {
  833. if c.v4.learned != nil {
  834. n.Details.Ip4AndPorts = append(n.Details.Ip4AndPorts, c.v4.learned)
  835. }
  836. if c.v4.reported != nil && len(c.v4.reported) > 0 {
  837. n.Details.Ip4AndPorts = append(n.Details.Ip4AndPorts, c.v4.reported...)
  838. }
  839. }
  840. if c.v6 != nil {
  841. if c.v6.learned != nil {
  842. n.Details.Ip6AndPorts = append(n.Details.Ip6AndPorts, c.v6.learned)
  843. }
  844. if c.v6.reported != nil && len(c.v6.reported) > 0 {
  845. n.Details.Ip6AndPorts = append(n.Details.Ip6AndPorts, c.v6.reported...)
  846. }
  847. }
  848. if c.relay != nil {
  849. n.Details.RelayVpnIp = append(n.Details.RelayVpnIp, c.relay.relay...)
  850. }
  851. }
  852. func (lhh *LightHouseHandler) handleHostQueryReply(n *NebulaMeta, vpnIp iputil.VpnIp) {
  853. if !lhh.lh.IsLighthouseIP(vpnIp) {
  854. return
  855. }
  856. lhh.lh.Lock()
  857. am := lhh.lh.unlockedGetRemoteList(iputil.VpnIp(n.Details.VpnIp))
  858. am.Lock()
  859. lhh.lh.Unlock()
  860. certVpnIp := iputil.VpnIp(n.Details.VpnIp)
  861. am.unlockedSetV4(vpnIp, certVpnIp, n.Details.Ip4AndPorts, lhh.lh.unlockedShouldAddV4)
  862. am.unlockedSetV6(vpnIp, certVpnIp, n.Details.Ip6AndPorts, lhh.lh.unlockedShouldAddV6)
  863. am.unlockedSetRelay(vpnIp, certVpnIp, n.Details.RelayVpnIp)
  864. am.Unlock()
  865. // Non-blocking attempt to trigger, skip if it would block
  866. select {
  867. case lhh.lh.handshakeTrigger <- iputil.VpnIp(n.Details.VpnIp):
  868. default:
  869. }
  870. }
  871. func (lhh *LightHouseHandler) handleHostUpdateNotification(n *NebulaMeta, vpnIp iputil.VpnIp, w EncWriter) {
  872. if !lhh.lh.amLighthouse {
  873. if lhh.l.Level >= logrus.DebugLevel {
  874. lhh.l.Debugln("I am not a lighthouse, do not take host updates: ", vpnIp)
  875. }
  876. return
  877. }
  878. //Simple check that the host sent this not someone else
  879. if n.Details.VpnIp != uint32(vpnIp) {
  880. if lhh.l.Level >= logrus.DebugLevel {
  881. lhh.l.WithField("vpnIp", vpnIp).WithField("answer", iputil.VpnIp(n.Details.VpnIp)).Debugln("Host sent invalid update")
  882. }
  883. return
  884. }
  885. lhh.lh.Lock()
  886. am := lhh.lh.unlockedGetRemoteList(vpnIp)
  887. am.Lock()
  888. lhh.lh.Unlock()
  889. certVpnIp := iputil.VpnIp(n.Details.VpnIp)
  890. am.unlockedSetV4(vpnIp, certVpnIp, n.Details.Ip4AndPorts, lhh.lh.unlockedShouldAddV4)
  891. am.unlockedSetV6(vpnIp, certVpnIp, n.Details.Ip6AndPorts, lhh.lh.unlockedShouldAddV6)
  892. am.unlockedSetRelay(vpnIp, certVpnIp, n.Details.RelayVpnIp)
  893. am.Unlock()
  894. n = lhh.resetMeta()
  895. n.Type = NebulaMeta_HostUpdateNotificationAck
  896. n.Details.VpnIp = uint32(vpnIp)
  897. ln, err := n.MarshalTo(lhh.pb)
  898. if err != nil {
  899. lhh.l.WithError(err).WithField("vpnIp", vpnIp).Error("Failed to marshal lighthouse host update ack")
  900. return
  901. }
  902. lhh.lh.metricTx(NebulaMeta_HostUpdateNotificationAck, 1)
  903. w.SendMessageToVpnIp(header.LightHouse, 0, vpnIp, lhh.pb[:ln], lhh.nb, lhh.out[:0])
  904. }
  905. func (lhh *LightHouseHandler) handleHostPunchNotification(n *NebulaMeta, vpnIp iputil.VpnIp, w EncWriter) {
  906. if !lhh.lh.IsLighthouseIP(vpnIp) {
  907. return
  908. }
  909. empty := []byte{0}
  910. punch := func(vpnPeer *udp.Addr) {
  911. if vpnPeer == nil {
  912. return
  913. }
  914. go func() {
  915. time.Sleep(lhh.lh.punchy.GetDelay())
  916. lhh.lh.metricHolepunchTx.Inc(1)
  917. lhh.lh.punchConn.WriteTo(empty, vpnPeer)
  918. }()
  919. if lhh.l.Level >= logrus.DebugLevel {
  920. //TODO: lacking the ip we are actually punching on, old: l.Debugf("Punching %s on %d for %s", IntIp(a.Ip), a.Port, IntIp(n.Details.VpnIp))
  921. lhh.l.Debugf("Punching on %d for %s", vpnPeer.Port, iputil.VpnIp(n.Details.VpnIp))
  922. }
  923. }
  924. for _, a := range n.Details.Ip4AndPorts {
  925. punch(NewUDPAddrFromLH4(a))
  926. }
  927. for _, a := range n.Details.Ip6AndPorts {
  928. punch(NewUDPAddrFromLH6(a))
  929. }
  930. // This sends a nebula test packet to the host trying to contact us. In the case
  931. // of a double nat or other difficult scenario, this may help establish
  932. // a tunnel.
  933. if lhh.lh.punchy.GetRespond() {
  934. queryVpnIp := iputil.VpnIp(n.Details.VpnIp)
  935. go func() {
  936. time.Sleep(lhh.lh.punchy.GetRespondDelay())
  937. if lhh.l.Level >= logrus.DebugLevel {
  938. lhh.l.Debugf("Sending a nebula test packet to vpn ip %s", queryVpnIp)
  939. }
  940. //NOTE: we have to allocate a new output buffer here since we are spawning a new goroutine
  941. // for each punchBack packet. We should move this into a timerwheel or a single goroutine
  942. // managed by a channel.
  943. w.SendMessageToVpnIp(header.Test, header.TestRequest, queryVpnIp, []byte(""), make([]byte, 12, 12), make([]byte, mtu))
  944. }()
  945. }
  946. }
  947. // ipMaskContains checks if testIp is contained by ip after applying a cidr
  948. // zeros is 32 - bits from net.IPMask.Size()
  949. func ipMaskContains(ip iputil.VpnIp, zeros iputil.VpnIp, testIp iputil.VpnIp) bool {
  950. return (testIp^ip)>>zeros == 0
  951. }