lighthouse.go 17 KB

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