lighthouse.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653
  1. package nebula
  2. import (
  3. "context"
  4. "encoding/binary"
  5. "errors"
  6. "fmt"
  7. "net"
  8. "sync"
  9. "time"
  10. "github.com/golang/protobuf/proto"
  11. "github.com/rcrowley/go-metrics"
  12. "github.com/sirupsen/logrus"
  13. "github.com/slackhq/nebula/header"
  14. "github.com/slackhq/nebula/iputil"
  15. "github.com/slackhq/nebula/udp"
  16. )
  17. //TODO: if a lighthouse doesn't have an answer, clients AGGRESSIVELY REQUERY.. why? handshake manager and/or getOrHandshake?
  18. //TODO: nodes are roaming lighthouses, this is bad. How are they learning?
  19. var ErrHostNotKnown = errors.New("host not known")
  20. type LightHouse struct {
  21. //TODO: We need a timer wheel to kick out vpnIps that haven't reported in a long time
  22. sync.RWMutex //Because we concurrently read and write to our maps
  23. amLighthouse bool
  24. myVpnIp iputil.VpnIp
  25. myVpnZeros iputil.VpnIp
  26. punchConn *udp.Conn
  27. // Local cache of answers from light houses
  28. // map of vpn Ip to answers
  29. addrMap map[iputil.VpnIp]*RemoteList
  30. // filters remote addresses allowed for each host
  31. // - When we are a lighthouse, this filters what addresses we store and
  32. // respond with.
  33. // - When we are not a lighthouse, this filters which addresses we accept
  34. // from lighthouses.
  35. remoteAllowList *RemoteAllowList
  36. // filters local addresses that we advertise to lighthouses
  37. localAllowList *LocalAllowList
  38. // used to trigger the HandshakeManager when we receive HostQueryReply
  39. handshakeTrigger chan<- iputil.VpnIp
  40. // staticList exists to avoid having a bool in each addrMap entry
  41. // since static should be rare
  42. staticList map[iputil.VpnIp]struct{}
  43. lighthouses map[iputil.VpnIp]struct{}
  44. interval int
  45. nebulaPort uint32 // 32 bits because protobuf does not have a uint16
  46. punchBack bool
  47. punchDelay time.Duration
  48. metrics *MessageMetrics
  49. metricHolepunchTx metrics.Counter
  50. l *logrus.Logger
  51. }
  52. func NewLightHouse(l *logrus.Logger, amLighthouse bool, myVpnIpNet *net.IPNet, ips []iputil.VpnIp, interval int, nebulaPort uint32, pc *udp.Conn, punchBack bool, punchDelay time.Duration, metricsEnabled bool) *LightHouse {
  53. ones, _ := myVpnIpNet.Mask.Size()
  54. h := LightHouse{
  55. amLighthouse: amLighthouse,
  56. myVpnIp: iputil.Ip2VpnIp(myVpnIpNet.IP),
  57. myVpnZeros: iputil.VpnIp(32 - ones),
  58. addrMap: make(map[iputil.VpnIp]*RemoteList),
  59. nebulaPort: nebulaPort,
  60. lighthouses: make(map[iputil.VpnIp]struct{}),
  61. staticList: make(map[iputil.VpnIp]struct{}),
  62. interval: interval,
  63. punchConn: pc,
  64. punchBack: punchBack,
  65. punchDelay: punchDelay,
  66. l: l,
  67. }
  68. if metricsEnabled {
  69. h.metrics = newLighthouseMetrics()
  70. h.metricHolepunchTx = metrics.GetOrRegisterCounter("messages.tx.holepunch", nil)
  71. } else {
  72. h.metricHolepunchTx = metrics.NilCounter{}
  73. }
  74. for _, ip := range ips {
  75. h.lighthouses[ip] = struct{}{}
  76. }
  77. return &h
  78. }
  79. func (lh *LightHouse) SetRemoteAllowList(allowList *RemoteAllowList) {
  80. lh.Lock()
  81. defer lh.Unlock()
  82. lh.remoteAllowList = allowList
  83. }
  84. func (lh *LightHouse) SetLocalAllowList(allowList *LocalAllowList) {
  85. lh.Lock()
  86. defer lh.Unlock()
  87. lh.localAllowList = allowList
  88. }
  89. func (lh *LightHouse) ValidateLHStaticEntries() error {
  90. for lhIP, _ := range lh.lighthouses {
  91. if _, ok := lh.staticList[lhIP]; !ok {
  92. return fmt.Errorf("Lighthouse %s does not have a static_host_map entry", lhIP)
  93. }
  94. }
  95. return nil
  96. }
  97. func (lh *LightHouse) Query(ip iputil.VpnIp, f udp.EncWriter) *RemoteList {
  98. if !lh.IsLighthouseIP(ip) {
  99. lh.QueryServer(ip, f)
  100. }
  101. lh.RLock()
  102. if v, ok := lh.addrMap[ip]; ok {
  103. lh.RUnlock()
  104. return v
  105. }
  106. lh.RUnlock()
  107. return nil
  108. }
  109. // This is asynchronous so no reply should be expected
  110. func (lh *LightHouse) QueryServer(ip iputil.VpnIp, f udp.EncWriter) {
  111. if lh.amLighthouse {
  112. return
  113. }
  114. if lh.IsLighthouseIP(ip) {
  115. return
  116. }
  117. // Send a query to the lighthouses and hope for the best next time
  118. query, err := proto.Marshal(NewLhQueryByInt(ip))
  119. if err != nil {
  120. lh.l.WithError(err).WithField("vpnIp", ip).Error("Failed to marshal lighthouse query payload")
  121. return
  122. }
  123. lh.metricTx(NebulaMeta_HostQuery, int64(len(lh.lighthouses)))
  124. nb := make([]byte, 12, 12)
  125. out := make([]byte, mtu)
  126. for n := range lh.lighthouses {
  127. f.SendMessageToVpnIp(header.LightHouse, 0, n, query, nb, out)
  128. }
  129. }
  130. func (lh *LightHouse) QueryCache(ip iputil.VpnIp) *RemoteList {
  131. lh.RLock()
  132. if v, ok := lh.addrMap[ip]; ok {
  133. lh.RUnlock()
  134. return v
  135. }
  136. lh.RUnlock()
  137. lh.Lock()
  138. defer lh.Unlock()
  139. // Add an entry if we don't already have one
  140. return lh.unlockedGetRemoteList(ip)
  141. }
  142. // queryAndPrepMessage is a lock helper on RemoteList, assisting the caller to build a lighthouse message containing
  143. // details from the remote list. It looks for a hit in the addrMap and a hit in the RemoteList under the owner vpnIp
  144. // If one is found then f() is called with proper locking, f() must return result of n.MarshalTo()
  145. func (lh *LightHouse) queryAndPrepMessage(vpnIp iputil.VpnIp, f func(*cache) (int, error)) (bool, int, error) {
  146. lh.RLock()
  147. // Do we have an entry in the main cache?
  148. if v, ok := lh.addrMap[vpnIp]; ok {
  149. // Swap lh lock for remote list lock
  150. v.RLock()
  151. defer v.RUnlock()
  152. lh.RUnlock()
  153. // vpnIp should also be the owner here since we are a lighthouse.
  154. c := v.cache[vpnIp]
  155. // Make sure we have
  156. if c != nil {
  157. n, err := f(c)
  158. return true, n, err
  159. }
  160. return false, 0, nil
  161. }
  162. lh.RUnlock()
  163. return false, 0, nil
  164. }
  165. func (lh *LightHouse) DeleteVpnIp(vpnIp iputil.VpnIp) {
  166. // First we check the static mapping
  167. // and do nothing if it is there
  168. if _, ok := lh.staticList[vpnIp]; ok {
  169. return
  170. }
  171. lh.Lock()
  172. //l.Debugln(lh.addrMap)
  173. delete(lh.addrMap, vpnIp)
  174. if lh.l.Level >= logrus.DebugLevel {
  175. lh.l.Debugf("deleting %s from lighthouse.", vpnIp)
  176. }
  177. lh.Unlock()
  178. }
  179. // AddStaticRemote adds a static host entry for vpnIp as ourselves as the owner
  180. // We are the owner because we don't want a lighthouse server to advertise for static hosts it was configured with
  181. // And we don't want a lighthouse query reply to interfere with our learned cache if we are a client
  182. func (lh *LightHouse) AddStaticRemote(vpnIp iputil.VpnIp, toAddr *udp.Addr) {
  183. lh.Lock()
  184. am := lh.unlockedGetRemoteList(vpnIp)
  185. am.Lock()
  186. defer am.Unlock()
  187. lh.Unlock()
  188. if ipv4 := toAddr.IP.To4(); ipv4 != nil {
  189. to := NewIp4AndPort(ipv4, uint32(toAddr.Port))
  190. if !lh.unlockedShouldAddV4(vpnIp, to) {
  191. return
  192. }
  193. am.unlockedPrependV4(lh.myVpnIp, to)
  194. } else {
  195. to := NewIp6AndPort(toAddr.IP, uint32(toAddr.Port))
  196. if !lh.unlockedShouldAddV6(vpnIp, to) {
  197. return
  198. }
  199. am.unlockedPrependV6(lh.myVpnIp, to)
  200. }
  201. // Mark it as static
  202. lh.staticList[vpnIp] = struct{}{}
  203. }
  204. // unlockedGetRemoteList assumes you have the lh lock
  205. func (lh *LightHouse) unlockedGetRemoteList(vpnIp iputil.VpnIp) *RemoteList {
  206. am, ok := lh.addrMap[vpnIp]
  207. if !ok {
  208. am = NewRemoteList()
  209. lh.addrMap[vpnIp] = am
  210. }
  211. return am
  212. }
  213. // unlockedShouldAddV4 checks if to is allowed by our allow list
  214. func (lh *LightHouse) unlockedShouldAddV4(vpnIp iputil.VpnIp, to *Ip4AndPort) bool {
  215. allow := lh.remoteAllowList.AllowIpV4(vpnIp, iputil.VpnIp(to.Ip))
  216. if lh.l.Level >= logrus.TraceLevel {
  217. lh.l.WithField("remoteIp", vpnIp).WithField("allow", allow).Trace("remoteAllowList.Allow")
  218. }
  219. if !allow || ipMaskContains(lh.myVpnIp, lh.myVpnZeros, iputil.VpnIp(to.Ip)) {
  220. return false
  221. }
  222. return true
  223. }
  224. // unlockedShouldAddV6 checks if to is allowed by our allow list
  225. func (lh *LightHouse) unlockedShouldAddV6(vpnIp iputil.VpnIp, to *Ip6AndPort) bool {
  226. allow := lh.remoteAllowList.AllowIpV6(vpnIp, to.Hi, to.Lo)
  227. if lh.l.Level >= logrus.TraceLevel {
  228. lh.l.WithField("remoteIp", lhIp6ToIp(to)).WithField("allow", allow).Trace("remoteAllowList.Allow")
  229. }
  230. // We don't check our vpn network here because nebula does not support ipv6 on the inside
  231. if !allow {
  232. return false
  233. }
  234. return true
  235. }
  236. func lhIp6ToIp(v *Ip6AndPort) net.IP {
  237. ip := make(net.IP, 16)
  238. binary.BigEndian.PutUint64(ip[:8], v.Hi)
  239. binary.BigEndian.PutUint64(ip[8:], v.Lo)
  240. return ip
  241. }
  242. func (lh *LightHouse) IsLighthouseIP(vpnIp iputil.VpnIp) bool {
  243. if _, ok := lh.lighthouses[vpnIp]; ok {
  244. return true
  245. }
  246. return false
  247. }
  248. func NewLhQueryByInt(VpnIp iputil.VpnIp) *NebulaMeta {
  249. return &NebulaMeta{
  250. Type: NebulaMeta_HostQuery,
  251. Details: &NebulaMetaDetails{
  252. VpnIp: uint32(VpnIp),
  253. },
  254. }
  255. }
  256. func NewIp4AndPort(ip net.IP, port uint32) *Ip4AndPort {
  257. ipp := Ip4AndPort{Port: port}
  258. ipp.Ip = uint32(iputil.Ip2VpnIp(ip))
  259. return &ipp
  260. }
  261. func NewIp6AndPort(ip net.IP, port uint32) *Ip6AndPort {
  262. return &Ip6AndPort{
  263. Hi: binary.BigEndian.Uint64(ip[:8]),
  264. Lo: binary.BigEndian.Uint64(ip[8:]),
  265. Port: port,
  266. }
  267. }
  268. func NewUDPAddrFromLH4(ipp *Ip4AndPort) *udp.Addr {
  269. ip := ipp.Ip
  270. return udp.NewAddr(
  271. net.IPv4(byte(ip&0xff000000>>24), byte(ip&0x00ff0000>>16), byte(ip&0x0000ff00>>8), byte(ip&0x000000ff)),
  272. uint16(ipp.Port),
  273. )
  274. }
  275. func NewUDPAddrFromLH6(ipp *Ip6AndPort) *udp.Addr {
  276. return udp.NewAddr(lhIp6ToIp(ipp), uint16(ipp.Port))
  277. }
  278. func (lh *LightHouse) LhUpdateWorker(ctx context.Context, f udp.EncWriter) {
  279. if lh.amLighthouse || lh.interval == 0 {
  280. return
  281. }
  282. clockSource := time.NewTicker(time.Second * time.Duration(lh.interval))
  283. defer clockSource.Stop()
  284. for {
  285. lh.SendUpdate(f)
  286. select {
  287. case <-ctx.Done():
  288. return
  289. case <-clockSource.C:
  290. continue
  291. }
  292. }
  293. }
  294. func (lh *LightHouse) SendUpdate(f udp.EncWriter) {
  295. var v4 []*Ip4AndPort
  296. var v6 []*Ip6AndPort
  297. for _, e := range *localIps(lh.l, lh.localAllowList) {
  298. if ip4 := e.To4(); ip4 != nil && ipMaskContains(lh.myVpnIp, lh.myVpnZeros, iputil.Ip2VpnIp(ip4)) {
  299. continue
  300. }
  301. // Only add IPs that aren't my VPN/tun IP
  302. if ip := e.To4(); ip != nil {
  303. v4 = append(v4, NewIp4AndPort(e, lh.nebulaPort))
  304. } else {
  305. v6 = append(v6, NewIp6AndPort(e, lh.nebulaPort))
  306. }
  307. }
  308. m := &NebulaMeta{
  309. Type: NebulaMeta_HostUpdateNotification,
  310. Details: &NebulaMetaDetails{
  311. VpnIp: uint32(lh.myVpnIp),
  312. Ip4AndPorts: v4,
  313. Ip6AndPorts: v6,
  314. },
  315. }
  316. lh.metricTx(NebulaMeta_HostUpdateNotification, int64(len(lh.lighthouses)))
  317. nb := make([]byte, 12, 12)
  318. out := make([]byte, mtu)
  319. mm, err := proto.Marshal(m)
  320. if err != nil {
  321. lh.l.WithError(err).Error("Error while marshaling for lighthouse update")
  322. return
  323. }
  324. for vpnIp := range lh.lighthouses {
  325. f.SendMessageToVpnIp(header.LightHouse, 0, vpnIp, mm, nb, out)
  326. }
  327. }
  328. type LightHouseHandler struct {
  329. lh *LightHouse
  330. nb []byte
  331. out []byte
  332. pb []byte
  333. meta *NebulaMeta
  334. l *logrus.Logger
  335. }
  336. func (lh *LightHouse) NewRequestHandler() *LightHouseHandler {
  337. lhh := &LightHouseHandler{
  338. lh: lh,
  339. nb: make([]byte, 12, 12),
  340. out: make([]byte, mtu),
  341. l: lh.l,
  342. pb: make([]byte, mtu),
  343. meta: &NebulaMeta{
  344. Details: &NebulaMetaDetails{},
  345. },
  346. }
  347. return lhh
  348. }
  349. func (lh *LightHouse) metricRx(t NebulaMeta_MessageType, i int64) {
  350. lh.metrics.Rx(header.MessageType(t), 0, i)
  351. }
  352. func (lh *LightHouse) metricTx(t NebulaMeta_MessageType, i int64) {
  353. lh.metrics.Tx(header.MessageType(t), 0, i)
  354. }
  355. // This method is similar to Reset(), but it re-uses the pointer structs
  356. // so that we don't have to re-allocate them
  357. func (lhh *LightHouseHandler) resetMeta() *NebulaMeta {
  358. details := lhh.meta.Details
  359. lhh.meta.Reset()
  360. // Keep the array memory around
  361. details.Ip4AndPorts = details.Ip4AndPorts[:0]
  362. details.Ip6AndPorts = details.Ip6AndPorts[:0]
  363. lhh.meta.Details = details
  364. return lhh.meta
  365. }
  366. func (lhh *LightHouseHandler) HandleRequest(rAddr *udp.Addr, vpnIp iputil.VpnIp, p []byte, w udp.EncWriter) {
  367. n := lhh.resetMeta()
  368. err := n.Unmarshal(p)
  369. if err != nil {
  370. lhh.l.WithError(err).WithField("vpnIp", vpnIp).WithField("udpAddr", rAddr).
  371. Error("Failed to unmarshal lighthouse packet")
  372. //TODO: send recv_error?
  373. return
  374. }
  375. if n.Details == nil {
  376. lhh.l.WithField("vpnIp", vpnIp).WithField("udpAddr", rAddr).
  377. Error("Invalid lighthouse update")
  378. //TODO: send recv_error?
  379. return
  380. }
  381. lhh.lh.metricRx(n.Type, 1)
  382. switch n.Type {
  383. case NebulaMeta_HostQuery:
  384. lhh.handleHostQuery(n, vpnIp, rAddr, w)
  385. case NebulaMeta_HostQueryReply:
  386. lhh.handleHostQueryReply(n, vpnIp)
  387. case NebulaMeta_HostUpdateNotification:
  388. lhh.handleHostUpdateNotification(n, vpnIp)
  389. case NebulaMeta_HostMovedNotification:
  390. case NebulaMeta_HostPunchNotification:
  391. lhh.handleHostPunchNotification(n, vpnIp, w)
  392. }
  393. }
  394. func (lhh *LightHouseHandler) handleHostQuery(n *NebulaMeta, vpnIp iputil.VpnIp, addr *udp.Addr, w udp.EncWriter) {
  395. // Exit if we don't answer queries
  396. if !lhh.lh.amLighthouse {
  397. if lhh.l.Level >= logrus.DebugLevel {
  398. lhh.l.Debugln("I don't answer queries, but received from: ", addr)
  399. }
  400. return
  401. }
  402. //TODO: we can DRY this further
  403. reqVpnIp := n.Details.VpnIp
  404. //TODO: Maybe instead of marshalling into n we marshal into a new `r` to not nuke our current request data
  405. found, ln, err := lhh.lh.queryAndPrepMessage(iputil.VpnIp(n.Details.VpnIp), func(c *cache) (int, error) {
  406. n = lhh.resetMeta()
  407. n.Type = NebulaMeta_HostQueryReply
  408. n.Details.VpnIp = reqVpnIp
  409. lhh.coalesceAnswers(c, n)
  410. return n.MarshalTo(lhh.pb)
  411. })
  412. if !found {
  413. return
  414. }
  415. if err != nil {
  416. lhh.l.WithError(err).WithField("vpnIp", vpnIp).Error("Failed to marshal lighthouse host query reply")
  417. return
  418. }
  419. lhh.lh.metricTx(NebulaMeta_HostQueryReply, 1)
  420. w.SendMessageToVpnIp(header.LightHouse, 0, vpnIp, lhh.pb[:ln], lhh.nb, lhh.out[:0])
  421. // This signals the other side to punch some zero byte udp packets
  422. found, ln, err = lhh.lh.queryAndPrepMessage(vpnIp, func(c *cache) (int, error) {
  423. n = lhh.resetMeta()
  424. n.Type = NebulaMeta_HostPunchNotification
  425. n.Details.VpnIp = uint32(vpnIp)
  426. lhh.coalesceAnswers(c, n)
  427. return n.MarshalTo(lhh.pb)
  428. })
  429. if !found {
  430. return
  431. }
  432. if err != nil {
  433. lhh.l.WithError(err).WithField("vpnIp", vpnIp).Error("Failed to marshal lighthouse host was queried for")
  434. return
  435. }
  436. lhh.lh.metricTx(NebulaMeta_HostPunchNotification, 1)
  437. w.SendMessageToVpnIp(header.LightHouse, 0, iputil.VpnIp(reqVpnIp), lhh.pb[:ln], lhh.nb, lhh.out[:0])
  438. }
  439. func (lhh *LightHouseHandler) coalesceAnswers(c *cache, n *NebulaMeta) {
  440. if c.v4 != nil {
  441. if c.v4.learned != nil {
  442. n.Details.Ip4AndPorts = append(n.Details.Ip4AndPorts, c.v4.learned)
  443. }
  444. if c.v4.reported != nil && len(c.v4.reported) > 0 {
  445. n.Details.Ip4AndPorts = append(n.Details.Ip4AndPorts, c.v4.reported...)
  446. }
  447. }
  448. if c.v6 != nil {
  449. if c.v6.learned != nil {
  450. n.Details.Ip6AndPorts = append(n.Details.Ip6AndPorts, c.v6.learned)
  451. }
  452. if c.v6.reported != nil && len(c.v6.reported) > 0 {
  453. n.Details.Ip6AndPorts = append(n.Details.Ip6AndPorts, c.v6.reported...)
  454. }
  455. }
  456. }
  457. func (lhh *LightHouseHandler) handleHostQueryReply(n *NebulaMeta, vpnIp iputil.VpnIp) {
  458. if !lhh.lh.IsLighthouseIP(vpnIp) {
  459. return
  460. }
  461. lhh.lh.Lock()
  462. am := lhh.lh.unlockedGetRemoteList(iputil.VpnIp(n.Details.VpnIp))
  463. am.Lock()
  464. lhh.lh.Unlock()
  465. certVpnIp := iputil.VpnIp(n.Details.VpnIp)
  466. am.unlockedSetV4(vpnIp, certVpnIp, n.Details.Ip4AndPorts, lhh.lh.unlockedShouldAddV4)
  467. am.unlockedSetV6(vpnIp, certVpnIp, n.Details.Ip6AndPorts, lhh.lh.unlockedShouldAddV6)
  468. am.Unlock()
  469. // Non-blocking attempt to trigger, skip if it would block
  470. select {
  471. case lhh.lh.handshakeTrigger <- iputil.VpnIp(n.Details.VpnIp):
  472. default:
  473. }
  474. }
  475. func (lhh *LightHouseHandler) handleHostUpdateNotification(n *NebulaMeta, vpnIp iputil.VpnIp) {
  476. if !lhh.lh.amLighthouse {
  477. if lhh.l.Level >= logrus.DebugLevel {
  478. lhh.l.Debugln("I am not a lighthouse, do not take host updates: ", vpnIp)
  479. }
  480. return
  481. }
  482. //Simple check that the host sent this not someone else
  483. if n.Details.VpnIp != uint32(vpnIp) {
  484. if lhh.l.Level >= logrus.DebugLevel {
  485. lhh.l.WithField("vpnIp", vpnIp).WithField("answer", iputil.VpnIp(n.Details.VpnIp)).Debugln("Host sent invalid update")
  486. }
  487. return
  488. }
  489. lhh.lh.Lock()
  490. am := lhh.lh.unlockedGetRemoteList(vpnIp)
  491. am.Lock()
  492. lhh.lh.Unlock()
  493. certVpnIp := iputil.VpnIp(n.Details.VpnIp)
  494. am.unlockedSetV4(vpnIp, certVpnIp, n.Details.Ip4AndPorts, lhh.lh.unlockedShouldAddV4)
  495. am.unlockedSetV6(vpnIp, certVpnIp, n.Details.Ip6AndPorts, lhh.lh.unlockedShouldAddV6)
  496. am.Unlock()
  497. }
  498. func (lhh *LightHouseHandler) handleHostPunchNotification(n *NebulaMeta, vpnIp iputil.VpnIp, w udp.EncWriter) {
  499. if !lhh.lh.IsLighthouseIP(vpnIp) {
  500. return
  501. }
  502. empty := []byte{0}
  503. punch := func(vpnPeer *udp.Addr) {
  504. if vpnPeer == nil {
  505. return
  506. }
  507. go func() {
  508. time.Sleep(lhh.lh.punchDelay)
  509. lhh.lh.metricHolepunchTx.Inc(1)
  510. lhh.lh.punchConn.WriteTo(empty, vpnPeer)
  511. }()
  512. if lhh.l.Level >= logrus.DebugLevel {
  513. //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))
  514. lhh.l.Debugf("Punching on %d for %s", vpnPeer.Port, iputil.VpnIp(n.Details.VpnIp))
  515. }
  516. }
  517. for _, a := range n.Details.Ip4AndPorts {
  518. punch(NewUDPAddrFromLH4(a))
  519. }
  520. for _, a := range n.Details.Ip6AndPorts {
  521. punch(NewUDPAddrFromLH6(a))
  522. }
  523. // This sends a nebula test packet to the host trying to contact us. In the case
  524. // of a double nat or other difficult scenario, this may help establish
  525. // a tunnel.
  526. if lhh.lh.punchBack {
  527. queryVpnIp := iputil.VpnIp(n.Details.VpnIp)
  528. go func() {
  529. time.Sleep(time.Second * 5)
  530. if lhh.l.Level >= logrus.DebugLevel {
  531. lhh.l.Debugf("Sending a nebula test packet to vpn ip %s", queryVpnIp)
  532. }
  533. //NOTE: we have to allocate a new output buffer here since we are spawning a new goroutine
  534. // for each punchBack packet. We should move this into a timerwheel or a single goroutine
  535. // managed by a channel.
  536. w.SendMessageToVpnIp(header.Test, header.TestRequest, queryVpnIp, []byte(""), make([]byte, 12, 12), make([]byte, mtu))
  537. }()
  538. }
  539. }
  540. // ipMaskContains checks if testIp is contained by ip after applying a cidr
  541. // zeros is 32 - bits from net.IPMask.Size()
  542. func ipMaskContains(ip iputil.VpnIp, zeros iputil.VpnIp, testIp iputil.VpnIp) bool {
  543. return (testIp^ip)>>zeros == 0
  544. }