lighthouse.go 24 KB

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