lighthouse.go 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119
  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. staticList := make(map[iputil.VpnIp]struct{})
  217. err := lh.loadStaticMap(c, lh.myVpnNet, staticList)
  218. if err != nil {
  219. return err
  220. }
  221. lh.staticList.Store(&staticList)
  222. if !initial {
  223. //TODO: we should remove any remote list entries for static hosts that were removed/modified?
  224. if c.HasChanged("static_host_map") {
  225. lh.l.Info("static_host_map has changed")
  226. }
  227. if c.HasChanged("static_map.cadence") {
  228. lh.l.Info("static_map.cadence has changed")
  229. }
  230. if c.HasChanged("static_map.network") {
  231. lh.l.Info("static_map.network has changed")
  232. }
  233. if c.HasChanged("static_map.lookup_timeout") {
  234. lh.l.Info("static_map.lookup_timeout has changed")
  235. }
  236. }
  237. }
  238. if initial || c.HasChanged("lighthouse.hosts") {
  239. lhMap := make(map[iputil.VpnIp]struct{})
  240. err := lh.parseLighthouses(c, lh.myVpnNet, lhMap)
  241. if err != nil {
  242. return err
  243. }
  244. lh.lighthouses.Store(&lhMap)
  245. if !initial {
  246. //NOTE: we are not tearing down existing lighthouse connections because they might be used for non lighthouse traffic
  247. lh.l.Info("lighthouse.hosts has changed")
  248. }
  249. }
  250. if initial || c.HasChanged("relay.relays") {
  251. switch c.GetBool("relay.am_relay", false) {
  252. case true:
  253. // Relays aren't allowed to specify other relays
  254. if len(c.GetStringSlice("relay.relays", nil)) > 0 {
  255. lh.l.Info("Ignoring relays from config because am_relay is true")
  256. }
  257. relaysForMe := []iputil.VpnIp{}
  258. lh.relaysForMe.Store(&relaysForMe)
  259. case false:
  260. relaysForMe := []iputil.VpnIp{}
  261. for _, v := range c.GetStringSlice("relay.relays", nil) {
  262. lh.l.WithField("relay", v).Info("Read relay from config")
  263. configRIP := net.ParseIP(v)
  264. if configRIP != nil {
  265. relaysForMe = append(relaysForMe, iputil.Ip2VpnIp(configRIP))
  266. }
  267. }
  268. lh.relaysForMe.Store(&relaysForMe)
  269. }
  270. }
  271. return nil
  272. }
  273. func (lh *LightHouse) parseLighthouses(c *config.C, tunCidr *net.IPNet, lhMap map[iputil.VpnIp]struct{}) error {
  274. lhs := c.GetStringSlice("lighthouse.hosts", []string{})
  275. if lh.amLighthouse && len(lhs) != 0 {
  276. lh.l.Warn("lighthouse.am_lighthouse enabled on node but upstream lighthouses exist in config")
  277. }
  278. for i, host := range lhs {
  279. ip := net.ParseIP(host)
  280. if ip == nil {
  281. return util.NewContextualError("Unable to parse lighthouse host entry", m{"host": host, "entry": i + 1}, nil)
  282. }
  283. if !tunCidr.Contains(ip) {
  284. return util.NewContextualError("lighthouse host is not in our subnet, invalid", m{"vpnIp": ip, "network": tunCidr.String()}, nil)
  285. }
  286. lhMap[iputil.Ip2VpnIp(ip)] = struct{}{}
  287. }
  288. if !lh.amLighthouse && len(lhMap) == 0 {
  289. lh.l.Warn("No lighthouse.hosts configured, this host will only be able to initiate tunnels with static_host_map entries")
  290. }
  291. staticList := lh.GetStaticHostList()
  292. for lhIP, _ := range lhMap {
  293. if _, ok := staticList[lhIP]; !ok {
  294. return fmt.Errorf("lighthouse %s does not have a static_host_map entry", lhIP)
  295. }
  296. }
  297. return nil
  298. }
  299. func getStaticMapCadence(c *config.C) (time.Duration, error) {
  300. cadence := c.GetString("static_map.cadence", "30s")
  301. d, err := time.ParseDuration(cadence)
  302. if err != nil {
  303. return 0, err
  304. }
  305. return d, nil
  306. }
  307. func getStaticMapLookupTimeout(c *config.C) (time.Duration, error) {
  308. lookupTimeout := c.GetString("static_map.lookup_timeout", "250ms")
  309. d, err := time.ParseDuration(lookupTimeout)
  310. if err != nil {
  311. return 0, err
  312. }
  313. return d, nil
  314. }
  315. func getStaticMapNetwork(c *config.C) (string, error) {
  316. network := c.GetString("static_map.network", "ip4")
  317. if network != "ip" && network != "ip4" && network != "ip6" {
  318. return "", fmt.Errorf("static_map.network must be one of ip, ip4, or ip6")
  319. }
  320. return network, nil
  321. }
  322. func (lh *LightHouse) loadStaticMap(c *config.C, tunCidr *net.IPNet, staticList map[iputil.VpnIp]struct{}) error {
  323. d, err := getStaticMapCadence(c)
  324. if err != nil {
  325. return err
  326. }
  327. network, err := getStaticMapNetwork(c)
  328. if err != nil {
  329. return err
  330. }
  331. lookup_timeout, err := getStaticMapLookupTimeout(c)
  332. if err != nil {
  333. return err
  334. }
  335. shm := c.GetMap("static_host_map", map[interface{}]interface{}{})
  336. i := 0
  337. for k, v := range shm {
  338. rip := net.ParseIP(fmt.Sprintf("%v", k))
  339. if rip == nil {
  340. return util.NewContextualError("Unable to parse static_host_map entry", m{"host": k, "entry": i + 1}, nil)
  341. }
  342. if !tunCidr.Contains(rip) {
  343. return util.NewContextualError("static_host_map key is not in our subnet, invalid", m{"vpnIp": rip, "network": tunCidr.String(), "entry": i + 1}, nil)
  344. }
  345. vpnIp := iputil.Ip2VpnIp(rip)
  346. vals, ok := v.([]interface{})
  347. if !ok {
  348. vals = []interface{}{v}
  349. }
  350. remoteAddrs := []string{}
  351. for _, v := range vals {
  352. remoteAddrs = append(remoteAddrs, fmt.Sprintf("%v", v))
  353. }
  354. err := lh.addStaticRemotes(i, d, network, lookup_timeout, vpnIp, remoteAddrs, staticList)
  355. if err != nil {
  356. return err
  357. }
  358. i++
  359. }
  360. return nil
  361. }
  362. func (lh *LightHouse) Query(ip iputil.VpnIp, f EncWriter) *RemoteList {
  363. if !lh.IsLighthouseIP(ip) {
  364. lh.QueryServer(ip, f)
  365. }
  366. lh.RLock()
  367. if v, ok := lh.addrMap[ip]; ok {
  368. lh.RUnlock()
  369. return v
  370. }
  371. lh.RUnlock()
  372. return nil
  373. }
  374. // This is asynchronous so no reply should be expected
  375. func (lh *LightHouse) QueryServer(ip iputil.VpnIp, f EncWriter) {
  376. if lh.amLighthouse {
  377. return
  378. }
  379. if lh.IsLighthouseIP(ip) {
  380. return
  381. }
  382. // Send a query to the lighthouses and hope for the best next time
  383. query, err := NewLhQueryByInt(ip).Marshal()
  384. if err != nil {
  385. lh.l.WithError(err).WithField("vpnIp", ip).Error("Failed to marshal lighthouse query payload")
  386. return
  387. }
  388. lighthouses := lh.GetLighthouses()
  389. lh.metricTx(NebulaMeta_HostQuery, int64(len(lighthouses)))
  390. nb := make([]byte, 12, 12)
  391. out := make([]byte, mtu)
  392. for n := range lighthouses {
  393. f.SendMessageToVpnIp(header.LightHouse, 0, n, query, nb, out)
  394. }
  395. }
  396. func (lh *LightHouse) QueryCache(ip iputil.VpnIp) *RemoteList {
  397. lh.RLock()
  398. if v, ok := lh.addrMap[ip]; ok {
  399. lh.RUnlock()
  400. return v
  401. }
  402. lh.RUnlock()
  403. lh.Lock()
  404. defer lh.Unlock()
  405. // Add an entry if we don't already have one
  406. return lh.unlockedGetRemoteList(ip)
  407. }
  408. // queryAndPrepMessage is a lock helper on RemoteList, assisting the caller to build a lighthouse message containing
  409. // details from the remote list. It looks for a hit in the addrMap and a hit in the RemoteList under the owner vpnIp
  410. // If one is found then f() is called with proper locking, f() must return result of n.MarshalTo()
  411. func (lh *LightHouse) queryAndPrepMessage(vpnIp iputil.VpnIp, f func(*cache) (int, error)) (bool, int, error) {
  412. lh.RLock()
  413. // Do we have an entry in the main cache?
  414. if v, ok := lh.addrMap[vpnIp]; ok {
  415. // Swap lh lock for remote list lock
  416. v.RLock()
  417. defer v.RUnlock()
  418. lh.RUnlock()
  419. // vpnIp should also be the owner here since we are a lighthouse.
  420. c := v.cache[vpnIp]
  421. // Make sure we have
  422. if c != nil {
  423. n, err := f(c)
  424. return true, n, err
  425. }
  426. return false, 0, nil
  427. }
  428. lh.RUnlock()
  429. return false, 0, nil
  430. }
  431. func (lh *LightHouse) DeleteVpnIp(vpnIp iputil.VpnIp) {
  432. // First we check the static mapping
  433. // and do nothing if it is there
  434. if _, ok := lh.GetStaticHostList()[vpnIp]; ok {
  435. return
  436. }
  437. lh.Lock()
  438. //l.Debugln(lh.addrMap)
  439. delete(lh.addrMap, vpnIp)
  440. if lh.l.Level >= logrus.DebugLevel {
  441. lh.l.Debugf("deleting %s from lighthouse.", vpnIp)
  442. }
  443. lh.Unlock()
  444. }
  445. // AddStaticRemote adds a static host entry for vpnIp as ourselves as the owner
  446. // We are the owner because we don't want a lighthouse server to advertise for static hosts it was configured with
  447. // And we don't want a lighthouse query reply to interfere with our learned cache if we are a client
  448. // NOTE: this function should not interact with any hot path objects, like lh.staticList, the caller should handle it
  449. 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 {
  450. lh.Lock()
  451. am := lh.unlockedGetRemoteList(vpnIp)
  452. am.Lock()
  453. defer am.Unlock()
  454. ctx := lh.ctx
  455. lh.Unlock()
  456. hr, err := NewHostnameResults(ctx, lh.l, d, network, timeout, toAddrs, func() {
  457. // This callback runs whenever the DNS hostname resolver finds a different set of IP's
  458. // in its resolution for hostnames.
  459. am.Lock()
  460. defer am.Unlock()
  461. am.shouldRebuild = true
  462. })
  463. if err != nil {
  464. return util.NewContextualError("Static host address could not be parsed", m{"vpnIp": vpnIp, "entry": i + 1}, err)
  465. }
  466. am.unlockedSetHostnamesResults(hr)
  467. for _, addrPort := range hr.GetIPs() {
  468. switch {
  469. case addrPort.Addr().Is4():
  470. to := NewIp4AndPortFromNetIP(addrPort.Addr(), addrPort.Port())
  471. if !lh.unlockedShouldAddV4(vpnIp, to) {
  472. continue
  473. }
  474. am.unlockedPrependV4(lh.myVpnIp, to)
  475. case addrPort.Addr().Is6():
  476. to := NewIp6AndPortFromNetIP(addrPort.Addr(), addrPort.Port())
  477. if !lh.unlockedShouldAddV6(vpnIp, to) {
  478. continue
  479. }
  480. am.unlockedPrependV6(lh.myVpnIp, to)
  481. }
  482. }
  483. // Mark it as static in the caller provided map
  484. staticList[vpnIp] = struct{}{}
  485. return nil
  486. }
  487. // addCalculatedRemotes adds any calculated remotes based on the
  488. // lighthouse.calculated_remotes configuration. It returns true if any
  489. // calculated remotes were added
  490. func (lh *LightHouse) addCalculatedRemotes(vpnIp iputil.VpnIp) bool {
  491. tree := lh.getCalculatedRemotes()
  492. if tree == nil {
  493. return false
  494. }
  495. value := tree.MostSpecificContains(vpnIp)
  496. if value == nil {
  497. return false
  498. }
  499. calculatedRemotes := value.([]*calculatedRemote)
  500. var calculated []*Ip4AndPort
  501. for _, cr := range calculatedRemotes {
  502. c := cr.Apply(vpnIp)
  503. if c != nil {
  504. calculated = append(calculated, c)
  505. }
  506. }
  507. lh.Lock()
  508. am := lh.unlockedGetRemoteList(vpnIp)
  509. am.Lock()
  510. defer am.Unlock()
  511. lh.Unlock()
  512. am.unlockedSetV4(lh.myVpnIp, vpnIp, calculated, lh.unlockedShouldAddV4)
  513. return len(calculated) > 0
  514. }
  515. // unlockedGetRemoteList assumes you have the lh lock
  516. func (lh *LightHouse) unlockedGetRemoteList(vpnIp iputil.VpnIp) *RemoteList {
  517. am, ok := lh.addrMap[vpnIp]
  518. if !ok {
  519. am = NewRemoteList(func(a netip.Addr) bool { return lh.shouldAdd(vpnIp, a) })
  520. lh.addrMap[vpnIp] = am
  521. }
  522. return am
  523. }
  524. func (lh *LightHouse) shouldAdd(vpnIp iputil.VpnIp, to netip.Addr) bool {
  525. switch {
  526. case to.Is4():
  527. ipBytes := to.As4()
  528. ip := iputil.Ip2VpnIp(ipBytes[:])
  529. allow := lh.GetRemoteAllowList().AllowIpV4(vpnIp, ip)
  530. if lh.l.Level >= logrus.TraceLevel {
  531. lh.l.WithField("remoteIp", vpnIp).WithField("allow", allow).Trace("remoteAllowList.Allow")
  532. }
  533. if !allow || ipMaskContains(lh.myVpnIp, lh.myVpnZeros, ip) {
  534. return false
  535. }
  536. case to.Is6():
  537. ipBytes := to.As16()
  538. hi := binary.BigEndian.Uint64(ipBytes[:8])
  539. lo := binary.BigEndian.Uint64(ipBytes[8:])
  540. allow := lh.GetRemoteAllowList().AllowIpV6(vpnIp, hi, lo)
  541. if lh.l.Level >= logrus.TraceLevel {
  542. lh.l.WithField("remoteIp", to).WithField("allow", allow).Trace("remoteAllowList.Allow")
  543. }
  544. // We don't check our vpn network here because nebula does not support ipv6 on the inside
  545. if !allow {
  546. return false
  547. }
  548. }
  549. return true
  550. }
  551. // unlockedShouldAddV4 checks if to is allowed by our allow list
  552. func (lh *LightHouse) unlockedShouldAddV4(vpnIp iputil.VpnIp, to *Ip4AndPort) bool {
  553. allow := lh.GetRemoteAllowList().AllowIpV4(vpnIp, iputil.VpnIp(to.Ip))
  554. if lh.l.Level >= logrus.TraceLevel {
  555. lh.l.WithField("remoteIp", vpnIp).WithField("allow", allow).Trace("remoteAllowList.Allow")
  556. }
  557. if !allow || ipMaskContains(lh.myVpnIp, lh.myVpnZeros, iputil.VpnIp(to.Ip)) {
  558. return false
  559. }
  560. return true
  561. }
  562. // unlockedShouldAddV6 checks if to is allowed by our allow list
  563. func (lh *LightHouse) unlockedShouldAddV6(vpnIp iputil.VpnIp, to *Ip6AndPort) bool {
  564. allow := lh.GetRemoteAllowList().AllowIpV6(vpnIp, to.Hi, to.Lo)
  565. if lh.l.Level >= logrus.TraceLevel {
  566. lh.l.WithField("remoteIp", lhIp6ToIp(to)).WithField("allow", allow).Trace("remoteAllowList.Allow")
  567. }
  568. // We don't check our vpn network here because nebula does not support ipv6 on the inside
  569. if !allow {
  570. return false
  571. }
  572. return true
  573. }
  574. func lhIp6ToIp(v *Ip6AndPort) net.IP {
  575. ip := make(net.IP, 16)
  576. binary.BigEndian.PutUint64(ip[:8], v.Hi)
  577. binary.BigEndian.PutUint64(ip[8:], v.Lo)
  578. return ip
  579. }
  580. func (lh *LightHouse) IsLighthouseIP(vpnIp iputil.VpnIp) bool {
  581. if _, ok := lh.GetLighthouses()[vpnIp]; ok {
  582. return true
  583. }
  584. return false
  585. }
  586. func NewLhQueryByInt(VpnIp iputil.VpnIp) *NebulaMeta {
  587. return &NebulaMeta{
  588. Type: NebulaMeta_HostQuery,
  589. Details: &NebulaMetaDetails{
  590. VpnIp: uint32(VpnIp),
  591. },
  592. }
  593. }
  594. func NewIp4AndPort(ip net.IP, port uint32) *Ip4AndPort {
  595. ipp := Ip4AndPort{Port: port}
  596. ipp.Ip = uint32(iputil.Ip2VpnIp(ip))
  597. return &ipp
  598. }
  599. func NewIp4AndPortFromNetIP(ip netip.Addr, port uint16) *Ip4AndPort {
  600. v4Addr := ip.As4()
  601. return &Ip4AndPort{
  602. Ip: binary.BigEndian.Uint32(v4Addr[:]),
  603. Port: uint32(port),
  604. }
  605. }
  606. func NewIp6AndPort(ip net.IP, port uint32) *Ip6AndPort {
  607. return &Ip6AndPort{
  608. Hi: binary.BigEndian.Uint64(ip[:8]),
  609. Lo: binary.BigEndian.Uint64(ip[8:]),
  610. Port: port,
  611. }
  612. }
  613. func NewIp6AndPortFromNetIP(ip netip.Addr, port uint16) *Ip6AndPort {
  614. ip6Addr := ip.As16()
  615. return &Ip6AndPort{
  616. Hi: binary.BigEndian.Uint64(ip6Addr[:8]),
  617. Lo: binary.BigEndian.Uint64(ip6Addr[8:]),
  618. Port: uint32(port),
  619. }
  620. }
  621. func NewUDPAddrFromLH4(ipp *Ip4AndPort) *udp.Addr {
  622. ip := ipp.Ip
  623. return udp.NewAddr(
  624. net.IPv4(byte(ip&0xff000000>>24), byte(ip&0x00ff0000>>16), byte(ip&0x0000ff00>>8), byte(ip&0x000000ff)),
  625. uint16(ipp.Port),
  626. )
  627. }
  628. func NewUDPAddrFromLH6(ipp *Ip6AndPort) *udp.Addr {
  629. return udp.NewAddr(lhIp6ToIp(ipp), uint16(ipp.Port))
  630. }
  631. func (lh *LightHouse) LhUpdateWorker(ctx context.Context, f EncWriter) {
  632. lh.updateParentCtx = ctx
  633. lh.updateUdp = f
  634. interval := lh.GetUpdateInterval()
  635. if lh.amLighthouse || interval == 0 {
  636. return
  637. }
  638. clockSource := time.NewTicker(time.Second * time.Duration(interval))
  639. updateCtx, cancel := context.WithCancel(ctx)
  640. lh.updateCancel = cancel
  641. defer clockSource.Stop()
  642. for {
  643. lh.SendUpdate(f)
  644. select {
  645. case <-updateCtx.Done():
  646. return
  647. case <-clockSource.C:
  648. continue
  649. }
  650. }
  651. }
  652. func (lh *LightHouse) SendUpdate(f EncWriter) {
  653. var v4 []*Ip4AndPort
  654. var v6 []*Ip6AndPort
  655. for _, e := range lh.GetAdvertiseAddrs() {
  656. if ip := e.ip.To4(); ip != nil {
  657. v4 = append(v4, NewIp4AndPort(e.ip, uint32(e.port)))
  658. } else {
  659. v6 = append(v6, NewIp6AndPort(e.ip, uint32(e.port)))
  660. }
  661. }
  662. lal := lh.GetLocalAllowList()
  663. for _, e := range *localIps(lh.l, lal) {
  664. if ip4 := e.To4(); ip4 != nil && ipMaskContains(lh.myVpnIp, lh.myVpnZeros, iputil.Ip2VpnIp(ip4)) {
  665. continue
  666. }
  667. // Only add IPs that aren't my VPN/tun IP
  668. if ip := e.To4(); ip != nil {
  669. v4 = append(v4, NewIp4AndPort(e, lh.nebulaPort))
  670. } else {
  671. v6 = append(v6, NewIp6AndPort(e, lh.nebulaPort))
  672. }
  673. }
  674. var relays []uint32
  675. for _, r := range lh.GetRelaysForMe() {
  676. relays = append(relays, (uint32)(r))
  677. }
  678. m := &NebulaMeta{
  679. Type: NebulaMeta_HostUpdateNotification,
  680. Details: &NebulaMetaDetails{
  681. VpnIp: uint32(lh.myVpnIp),
  682. Ip4AndPorts: v4,
  683. Ip6AndPorts: v6,
  684. RelayVpnIp: relays,
  685. },
  686. }
  687. lighthouses := lh.GetLighthouses()
  688. lh.metricTx(NebulaMeta_HostUpdateNotification, int64(len(lighthouses)))
  689. nb := make([]byte, 12, 12)
  690. out := make([]byte, mtu)
  691. mm, err := m.Marshal()
  692. if err != nil {
  693. lh.l.WithError(err).Error("Error while marshaling for lighthouse update")
  694. return
  695. }
  696. for vpnIp := range lighthouses {
  697. f.SendMessageToVpnIp(header.LightHouse, 0, vpnIp, mm, nb, out)
  698. }
  699. }
  700. type LightHouseHandler struct {
  701. lh *LightHouse
  702. nb []byte
  703. out []byte
  704. pb []byte
  705. meta *NebulaMeta
  706. l *logrus.Logger
  707. }
  708. func (lh *LightHouse) NewRequestHandler() *LightHouseHandler {
  709. lhh := &LightHouseHandler{
  710. lh: lh,
  711. nb: make([]byte, 12, 12),
  712. out: make([]byte, mtu),
  713. l: lh.l,
  714. pb: make([]byte, mtu),
  715. meta: &NebulaMeta{
  716. Details: &NebulaMetaDetails{},
  717. },
  718. }
  719. return lhh
  720. }
  721. func (lh *LightHouse) metricRx(t NebulaMeta_MessageType, i int64) {
  722. lh.metrics.Rx(header.MessageType(t), 0, i)
  723. }
  724. func (lh *LightHouse) metricTx(t NebulaMeta_MessageType, i int64) {
  725. lh.metrics.Tx(header.MessageType(t), 0, i)
  726. }
  727. // This method is similar to Reset(), but it re-uses the pointer structs
  728. // so that we don't have to re-allocate them
  729. func (lhh *LightHouseHandler) resetMeta() *NebulaMeta {
  730. details := lhh.meta.Details
  731. lhh.meta.Reset()
  732. // Keep the array memory around
  733. details.Ip4AndPorts = details.Ip4AndPorts[:0]
  734. details.Ip6AndPorts = details.Ip6AndPorts[:0]
  735. details.RelayVpnIp = details.RelayVpnIp[:0]
  736. lhh.meta.Details = details
  737. return lhh.meta
  738. }
  739. func lhHandleRequest(lhh *LightHouseHandler, f *Interface) udp.LightHouseHandlerFunc {
  740. return func(rAddr *udp.Addr, vpnIp iputil.VpnIp, p []byte) {
  741. lhh.HandleRequest(rAddr, vpnIp, p, f)
  742. }
  743. }
  744. func (lhh *LightHouseHandler) HandleRequest(rAddr *udp.Addr, vpnIp iputil.VpnIp, p []byte, w EncWriter) {
  745. n := lhh.resetMeta()
  746. err := n.Unmarshal(p)
  747. if err != nil {
  748. lhh.l.WithError(err).WithField("vpnIp", vpnIp).WithField("udpAddr", rAddr).
  749. Error("Failed to unmarshal lighthouse packet")
  750. //TODO: send recv_error?
  751. return
  752. }
  753. if n.Details == nil {
  754. lhh.l.WithField("vpnIp", vpnIp).WithField("udpAddr", rAddr).
  755. Error("Invalid lighthouse update")
  756. //TODO: send recv_error?
  757. return
  758. }
  759. lhh.lh.metricRx(n.Type, 1)
  760. switch n.Type {
  761. case NebulaMeta_HostQuery:
  762. lhh.handleHostQuery(n, vpnIp, rAddr, w)
  763. case NebulaMeta_HostQueryReply:
  764. lhh.handleHostQueryReply(n, vpnIp)
  765. case NebulaMeta_HostUpdateNotification:
  766. lhh.handleHostUpdateNotification(n, vpnIp, w)
  767. case NebulaMeta_HostMovedNotification:
  768. case NebulaMeta_HostPunchNotification:
  769. lhh.handleHostPunchNotification(n, vpnIp, w)
  770. case NebulaMeta_HostUpdateNotificationAck:
  771. // noop
  772. }
  773. }
  774. func (lhh *LightHouseHandler) handleHostQuery(n *NebulaMeta, vpnIp iputil.VpnIp, addr *udp.Addr, w EncWriter) {
  775. // Exit if we don't answer queries
  776. if !lhh.lh.amLighthouse {
  777. if lhh.l.Level >= logrus.DebugLevel {
  778. lhh.l.Debugln("I don't answer queries, but received from: ", addr)
  779. }
  780. return
  781. }
  782. //TODO: we can DRY this further
  783. reqVpnIp := n.Details.VpnIp
  784. //TODO: Maybe instead of marshalling into n we marshal into a new `r` to not nuke our current request data
  785. found, ln, err := lhh.lh.queryAndPrepMessage(iputil.VpnIp(n.Details.VpnIp), func(c *cache) (int, error) {
  786. n = lhh.resetMeta()
  787. n.Type = NebulaMeta_HostQueryReply
  788. n.Details.VpnIp = reqVpnIp
  789. lhh.coalesceAnswers(c, n)
  790. return n.MarshalTo(lhh.pb)
  791. })
  792. if !found {
  793. return
  794. }
  795. if err != nil {
  796. lhh.l.WithError(err).WithField("vpnIp", vpnIp).Error("Failed to marshal lighthouse host query reply")
  797. return
  798. }
  799. lhh.lh.metricTx(NebulaMeta_HostQueryReply, 1)
  800. w.SendMessageToVpnIp(header.LightHouse, 0, vpnIp, lhh.pb[:ln], lhh.nb, lhh.out[:0])
  801. // This signals the other side to punch some zero byte udp packets
  802. found, ln, err = lhh.lh.queryAndPrepMessage(vpnIp, func(c *cache) (int, error) {
  803. n = lhh.resetMeta()
  804. n.Type = NebulaMeta_HostPunchNotification
  805. n.Details.VpnIp = uint32(vpnIp)
  806. lhh.coalesceAnswers(c, n)
  807. return n.MarshalTo(lhh.pb)
  808. })
  809. if !found {
  810. return
  811. }
  812. if err != nil {
  813. lhh.l.WithError(err).WithField("vpnIp", vpnIp).Error("Failed to marshal lighthouse host was queried for")
  814. return
  815. }
  816. lhh.lh.metricTx(NebulaMeta_HostPunchNotification, 1)
  817. w.SendMessageToVpnIp(header.LightHouse, 0, iputil.VpnIp(reqVpnIp), lhh.pb[:ln], lhh.nb, lhh.out[:0])
  818. }
  819. func (lhh *LightHouseHandler) coalesceAnswers(c *cache, n *NebulaMeta) {
  820. if c.v4 != nil {
  821. if c.v4.learned != nil {
  822. n.Details.Ip4AndPorts = append(n.Details.Ip4AndPorts, c.v4.learned)
  823. }
  824. if c.v4.reported != nil && len(c.v4.reported) > 0 {
  825. n.Details.Ip4AndPorts = append(n.Details.Ip4AndPorts, c.v4.reported...)
  826. }
  827. }
  828. if c.v6 != nil {
  829. if c.v6.learned != nil {
  830. n.Details.Ip6AndPorts = append(n.Details.Ip6AndPorts, c.v6.learned)
  831. }
  832. if c.v6.reported != nil && len(c.v6.reported) > 0 {
  833. n.Details.Ip6AndPorts = append(n.Details.Ip6AndPorts, c.v6.reported...)
  834. }
  835. }
  836. if c.relay != nil {
  837. n.Details.RelayVpnIp = append(n.Details.RelayVpnIp, c.relay.relay...)
  838. }
  839. }
  840. func (lhh *LightHouseHandler) handleHostQueryReply(n *NebulaMeta, vpnIp iputil.VpnIp) {
  841. if !lhh.lh.IsLighthouseIP(vpnIp) {
  842. return
  843. }
  844. lhh.lh.Lock()
  845. am := lhh.lh.unlockedGetRemoteList(iputil.VpnIp(n.Details.VpnIp))
  846. am.Lock()
  847. lhh.lh.Unlock()
  848. certVpnIp := iputil.VpnIp(n.Details.VpnIp)
  849. am.unlockedSetV4(vpnIp, certVpnIp, n.Details.Ip4AndPorts, lhh.lh.unlockedShouldAddV4)
  850. am.unlockedSetV6(vpnIp, certVpnIp, n.Details.Ip6AndPorts, lhh.lh.unlockedShouldAddV6)
  851. am.unlockedSetRelay(vpnIp, certVpnIp, n.Details.RelayVpnIp)
  852. am.Unlock()
  853. // Non-blocking attempt to trigger, skip if it would block
  854. select {
  855. case lhh.lh.handshakeTrigger <- iputil.VpnIp(n.Details.VpnIp):
  856. default:
  857. }
  858. }
  859. func (lhh *LightHouseHandler) handleHostUpdateNotification(n *NebulaMeta, vpnIp iputil.VpnIp, w EncWriter) {
  860. if !lhh.lh.amLighthouse {
  861. if lhh.l.Level >= logrus.DebugLevel {
  862. lhh.l.Debugln("I am not a lighthouse, do not take host updates: ", vpnIp)
  863. }
  864. return
  865. }
  866. //Simple check that the host sent this not someone else
  867. if n.Details.VpnIp != uint32(vpnIp) {
  868. if lhh.l.Level >= logrus.DebugLevel {
  869. lhh.l.WithField("vpnIp", vpnIp).WithField("answer", iputil.VpnIp(n.Details.VpnIp)).Debugln("Host sent invalid update")
  870. }
  871. return
  872. }
  873. lhh.lh.Lock()
  874. am := lhh.lh.unlockedGetRemoteList(vpnIp)
  875. am.Lock()
  876. lhh.lh.Unlock()
  877. certVpnIp := iputil.VpnIp(n.Details.VpnIp)
  878. am.unlockedSetV4(vpnIp, certVpnIp, n.Details.Ip4AndPorts, lhh.lh.unlockedShouldAddV4)
  879. am.unlockedSetV6(vpnIp, certVpnIp, n.Details.Ip6AndPorts, lhh.lh.unlockedShouldAddV6)
  880. am.unlockedSetRelay(vpnIp, certVpnIp, n.Details.RelayVpnIp)
  881. am.Unlock()
  882. n = lhh.resetMeta()
  883. n.Type = NebulaMeta_HostUpdateNotificationAck
  884. n.Details.VpnIp = uint32(vpnIp)
  885. ln, err := n.MarshalTo(lhh.pb)
  886. if err != nil {
  887. lhh.l.WithError(err).WithField("vpnIp", vpnIp).Error("Failed to marshal lighthouse host update ack")
  888. return
  889. }
  890. lhh.lh.metricTx(NebulaMeta_HostUpdateNotificationAck, 1)
  891. w.SendMessageToVpnIp(header.LightHouse, 0, vpnIp, lhh.pb[:ln], lhh.nb, lhh.out[:0])
  892. }
  893. func (lhh *LightHouseHandler) handleHostPunchNotification(n *NebulaMeta, vpnIp iputil.VpnIp, w EncWriter) {
  894. if !lhh.lh.IsLighthouseIP(vpnIp) {
  895. return
  896. }
  897. empty := []byte{0}
  898. punch := func(vpnPeer *udp.Addr) {
  899. if vpnPeer == nil {
  900. return
  901. }
  902. go func() {
  903. time.Sleep(lhh.lh.punchy.GetDelay())
  904. lhh.lh.metricHolepunchTx.Inc(1)
  905. lhh.lh.punchConn.WriteTo(empty, vpnPeer)
  906. }()
  907. if lhh.l.Level >= logrus.DebugLevel {
  908. //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))
  909. lhh.l.Debugf("Punching on %d for %s", vpnPeer.Port, iputil.VpnIp(n.Details.VpnIp))
  910. }
  911. }
  912. for _, a := range n.Details.Ip4AndPorts {
  913. punch(NewUDPAddrFromLH4(a))
  914. }
  915. for _, a := range n.Details.Ip6AndPorts {
  916. punch(NewUDPAddrFromLH6(a))
  917. }
  918. // This sends a nebula test packet to the host trying to contact us. In the case
  919. // of a double nat or other difficult scenario, this may help establish
  920. // a tunnel.
  921. if lhh.lh.punchy.GetRespond() {
  922. queryVpnIp := iputil.VpnIp(n.Details.VpnIp)
  923. go func() {
  924. time.Sleep(lhh.lh.punchy.GetRespondDelay())
  925. if lhh.l.Level >= logrus.DebugLevel {
  926. lhh.l.Debugf("Sending a nebula test packet to vpn ip %s", queryVpnIp)
  927. }
  928. //NOTE: we have to allocate a new output buffer here since we are spawning a new goroutine
  929. // for each punchBack packet. We should move this into a timerwheel or a single goroutine
  930. // managed by a channel.
  931. w.SendMessageToVpnIp(header.Test, header.TestRequest, queryVpnIp, []byte(""), make([]byte, 12, 12), make([]byte, mtu))
  932. }()
  933. }
  934. }
  935. // ipMaskContains checks if testIp is contained by ip after applying a cidr
  936. // zeros is 32 - bits from net.IPMask.Size()
  937. func ipMaskContains(ip iputil.VpnIp, zeros iputil.VpnIp, testIp iputil.VpnIp) bool {
  938. return (testIp^ip)>>zeros == 0
  939. }