lighthouse.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651
  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. )
  14. //TODO: if a lighthouse doesn't have an answer, clients AGGRESSIVELY REQUERY.. why? handshake manager and/or getOrHandshake?
  15. //TODO: nodes are roaming lighthouses, this is bad. How are they learning?
  16. var ErrHostNotKnown = errors.New("host not known")
  17. type LightHouse struct {
  18. //TODO: We need a timer wheel to kick out vpnIps that haven't reported in a long time
  19. sync.RWMutex //Because we concurrently read and write to our maps
  20. amLighthouse bool
  21. myVpnIp uint32
  22. myVpnZeros uint32
  23. punchConn *udpConn
  24. // Local cache of answers from light houses
  25. // map of vpn Ip to answers
  26. addrMap map[uint32]*RemoteList
  27. // filters remote addresses allowed for each host
  28. // - When we are a lighthouse, this filters what addresses we store and
  29. // respond with.
  30. // - When we are not a lighthouse, this filters which addresses we accept
  31. // from lighthouses.
  32. remoteAllowList *RemoteAllowList
  33. // filters local addresses that we advertise to lighthouses
  34. localAllowList *LocalAllowList
  35. // used to trigger the HandshakeManager when we receive HostQueryReply
  36. handshakeTrigger chan<- uint32
  37. // staticList exists to avoid having a bool in each addrMap entry
  38. // since static should be rare
  39. staticList map[uint32]struct{}
  40. lighthouses map[uint32]struct{}
  41. interval int
  42. nebulaPort uint32 // 32 bits because protobuf does not have a uint16
  43. punchBack bool
  44. punchDelay time.Duration
  45. metrics *MessageMetrics
  46. metricHolepunchTx metrics.Counter
  47. l *logrus.Logger
  48. }
  49. type EncWriter interface {
  50. SendMessageToVpnIp(t NebulaMessageType, st NebulaMessageSubType, vpnIp uint32, p, nb, out []byte)
  51. }
  52. 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 {
  53. ones, _ := myVpnIpNet.Mask.Size()
  54. h := LightHouse{
  55. amLighthouse: amLighthouse,
  56. myVpnIp: ip2int(myVpnIpNet.IP),
  57. myVpnZeros: uint32(32 - ones),
  58. addrMap: make(map[uint32]*RemoteList),
  59. nebulaPort: nebulaPort,
  60. lighthouses: make(map[uint32]struct{}),
  61. staticList: make(map[uint32]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", IntIp(lhIP))
  93. }
  94. }
  95. return nil
  96. }
  97. func (lh *LightHouse) Query(ip uint32, f 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 uint32, f 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", IntIp(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(lightHouse, 0, n, query, nb, out)
  128. }
  129. }
  130. func (lh *LightHouse) QueryCache(ip uint32) *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 uint32, 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 uint32) {
  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.", IntIp(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 uint32, toAddr *udpAddr) {
  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 uint32) *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 uint32, to *Ip4AndPort) bool {
  215. allow := lh.remoteAllowList.AllowIpV4(vpnIp, to.Ip)
  216. if lh.l.Level >= logrus.TraceLevel {
  217. lh.l.WithField("remoteIp", IntIp(to.Ip)).WithField("allow", allow).Trace("remoteAllowList.Allow")
  218. }
  219. if !allow || ipMaskContains(lh.myVpnIp, lh.myVpnZeros, 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 uint32, 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 uint32) bool {
  243. if _, ok := lh.lighthouses[vpnIP]; ok {
  244. return true
  245. }
  246. return false
  247. }
  248. func NewLhQueryByInt(VpnIp uint32) *NebulaMeta {
  249. return &NebulaMeta{
  250. Type: NebulaMeta_HostQuery,
  251. Details: &NebulaMetaDetails{
  252. VpnIp: VpnIp,
  253. },
  254. }
  255. }
  256. func NewIp4AndPort(ip net.IP, port uint32) *Ip4AndPort {
  257. ipp := Ip4AndPort{Port: port}
  258. ipp.Ip = ip2int(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) *udpAddr {
  269. ip := ipp.Ip
  270. return NewUDPAddr(
  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) *udpAddr {
  276. return NewUDPAddr(lhIp6ToIp(ipp), uint16(ipp.Port))
  277. }
  278. func (lh *LightHouse) LhUpdateWorker(ctx context.Context, f 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 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, ip2int(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: 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(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(NebulaMessageType(t), 0, i)
  351. }
  352. func (lh *LightHouse) metricTx(t NebulaMeta_MessageType, i int64) {
  353. lh.metrics.Tx(NebulaMessageType(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 *udpAddr, vpnIp uint32, p []byte, w EncWriter) {
  367. n := lhh.resetMeta()
  368. err := n.Unmarshal(p)
  369. if err != nil {
  370. lhh.l.WithError(err).WithField("vpnIp", IntIp(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", IntIp(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 uint32, addr *udpAddr, w 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(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", IntIp(vpnIp)).Error("Failed to marshal lighthouse host query reply")
  417. return
  418. }
  419. lhh.lh.metricTx(NebulaMeta_HostQueryReply, 1)
  420. w.SendMessageToVpnIp(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 = 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", IntIp(vpnIp)).Error("Failed to marshal lighthouse host was queried for")
  434. return
  435. }
  436. lhh.lh.metricTx(NebulaMeta_HostPunchNotification, 1)
  437. w.SendMessageToVpnIp(lightHouse, 0, 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 uint32) {
  458. if !lhh.lh.IsLighthouseIP(vpnIp) {
  459. return
  460. }
  461. lhh.lh.Lock()
  462. am := lhh.lh.unlockedGetRemoteList(n.Details.VpnIp)
  463. am.Lock()
  464. lhh.lh.Unlock()
  465. am.unlockedSetV4(vpnIp, n.Details.VpnIp, n.Details.Ip4AndPorts, lhh.lh.unlockedShouldAddV4)
  466. am.unlockedSetV6(vpnIp, n.Details.VpnIp, n.Details.Ip6AndPorts, lhh.lh.unlockedShouldAddV6)
  467. am.Unlock()
  468. // Non-blocking attempt to trigger, skip if it would block
  469. select {
  470. case lhh.lh.handshakeTrigger <- n.Details.VpnIp:
  471. default:
  472. }
  473. }
  474. func (lhh *LightHouseHandler) handleHostUpdateNotification(n *NebulaMeta, vpnIp uint32) {
  475. if !lhh.lh.amLighthouse {
  476. if lhh.l.Level >= logrus.DebugLevel {
  477. lhh.l.Debugln("I am not a lighthouse, do not take host updates: ", vpnIp)
  478. }
  479. return
  480. }
  481. //Simple check that the host sent this not someone else
  482. if n.Details.VpnIp != vpnIp {
  483. if lhh.l.Level >= logrus.DebugLevel {
  484. lhh.l.WithField("vpnIp", IntIp(vpnIp)).WithField("answer", IntIp(n.Details.VpnIp)).Debugln("Host sent invalid update")
  485. }
  486. return
  487. }
  488. lhh.lh.Lock()
  489. am := lhh.lh.unlockedGetRemoteList(vpnIp)
  490. am.Lock()
  491. lhh.lh.Unlock()
  492. am.unlockedSetV4(vpnIp, n.Details.VpnIp, n.Details.Ip4AndPorts, lhh.lh.unlockedShouldAddV4)
  493. am.unlockedSetV6(vpnIp, n.Details.VpnIp, n.Details.Ip6AndPorts, lhh.lh.unlockedShouldAddV6)
  494. am.Unlock()
  495. }
  496. func (lhh *LightHouseHandler) handleHostPunchNotification(n *NebulaMeta, vpnIp uint32, w EncWriter) {
  497. if !lhh.lh.IsLighthouseIP(vpnIp) {
  498. return
  499. }
  500. empty := []byte{0}
  501. punch := func(vpnPeer *udpAddr) {
  502. if vpnPeer == nil {
  503. return
  504. }
  505. go func() {
  506. time.Sleep(lhh.lh.punchDelay)
  507. lhh.lh.metricHolepunchTx.Inc(1)
  508. lhh.lh.punchConn.WriteTo(empty, vpnPeer)
  509. }()
  510. if lhh.l.Level >= logrus.DebugLevel {
  511. //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))
  512. lhh.l.Debugf("Punching on %d for %s", vpnPeer.Port, IntIp(n.Details.VpnIp))
  513. }
  514. }
  515. for _, a := range n.Details.Ip4AndPorts {
  516. punch(NewUDPAddrFromLH4(a))
  517. }
  518. for _, a := range n.Details.Ip6AndPorts {
  519. punch(NewUDPAddrFromLH6(a))
  520. }
  521. // This sends a nebula test packet to the host trying to contact us. In the case
  522. // of a double nat or other difficult scenario, this may help establish
  523. // a tunnel.
  524. if lhh.lh.punchBack {
  525. go func() {
  526. time.Sleep(time.Second * 5)
  527. if lhh.l.Level >= logrus.DebugLevel {
  528. lhh.l.Debugf("Sending a nebula test packet to vpn ip %s", IntIp(n.Details.VpnIp))
  529. }
  530. //NOTE: we have to allocate a new output buffer here since we are spawning a new goroutine
  531. // for each punchBack packet. We should move this into a timerwheel or a single goroutine
  532. // managed by a channel.
  533. w.SendMessageToVpnIp(test, testRequest, n.Details.VpnIp, []byte(""), make([]byte, 12, 12), make([]byte, mtu))
  534. }()
  535. }
  536. }
  537. // ipMaskContains checks if testIp is contained by ip after applying a cidr
  538. // zeros is 32 - bits from net.IPMask.Size()
  539. func ipMaskContains(ip uint32, zeros uint32, testIp uint32) bool {
  540. return (testIp^ip)>>zeros == 0
  541. }