lighthouse.go 28 KB

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