lighthouse.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606
  1. package nebula
  2. import (
  3. "errors"
  4. "fmt"
  5. "net"
  6. "sync"
  7. "time"
  8. "github.com/golang/protobuf/proto"
  9. "github.com/rcrowley/go-metrics"
  10. "github.com/sirupsen/logrus"
  11. "github.com/slackhq/nebula/cert"
  12. )
  13. var ErrHostNotKnown = errors.New("host not known")
  14. type LightHouse struct {
  15. sync.RWMutex //Because we concurrently read and write to our maps
  16. amLighthouse bool
  17. myIp uint32
  18. punchConn *udpConn
  19. // Local cache of answers from light houses
  20. addrMap map[uint32][]*udpAddr
  21. // filters remote addresses allowed for each host
  22. // - When we are a lighthouse, this filters what addresses we store and
  23. // respond with.
  24. // - When we are not a lighthouse, this filters which addresses we accept
  25. // from lighthouses.
  26. remoteAllowList *AllowList
  27. // filters local addresses that we advertise to lighthouses
  28. localAllowList *AllowList
  29. // used to trigger the HandshakeManager when we receive HostQueryReply
  30. handshakeTrigger chan<- uint32
  31. // staticList exists to avoid having a bool in each addrMap entry
  32. // since static should be rare
  33. staticList map[uint32]struct{}
  34. lighthouses map[uint32]struct{}
  35. interval int
  36. nebulaPort uint32 // 32 bits because protobuf does not have a uint16
  37. punchBack bool
  38. punchDelay time.Duration
  39. metrics *MessageMetrics
  40. metricHolepunchTx metrics.Counter
  41. }
  42. type EncWriter interface {
  43. SendMessageToVpnIp(t NebulaMessageType, st NebulaMessageSubType, vpnIp uint32, p, nb, out []byte)
  44. SendMessageToAll(t NebulaMessageType, st NebulaMessageSubType, vpnIp uint32, p, nb, out []byte)
  45. }
  46. func NewLightHouse(amLighthouse bool, myIp uint32, ips []uint32, interval int, nebulaPort uint32, pc *udpConn, punchBack bool, punchDelay time.Duration, metricsEnabled bool) *LightHouse {
  47. h := LightHouse{
  48. amLighthouse: amLighthouse,
  49. myIp: myIp,
  50. addrMap: make(map[uint32][]*udpAddr),
  51. nebulaPort: nebulaPort,
  52. lighthouses: make(map[uint32]struct{}),
  53. staticList: make(map[uint32]struct{}),
  54. interval: interval,
  55. punchConn: pc,
  56. punchBack: punchBack,
  57. punchDelay: punchDelay,
  58. }
  59. if metricsEnabled {
  60. h.metrics = newLighthouseMetrics()
  61. h.metricHolepunchTx = metrics.GetOrRegisterCounter("messages.tx.holepunch", nil)
  62. } else {
  63. h.metricHolepunchTx = metrics.NilCounter{}
  64. }
  65. for _, ip := range ips {
  66. h.lighthouses[ip] = struct{}{}
  67. }
  68. return &h
  69. }
  70. func (lh *LightHouse) SetRemoteAllowList(allowList *AllowList) {
  71. lh.Lock()
  72. defer lh.Unlock()
  73. lh.remoteAllowList = allowList
  74. }
  75. func (lh *LightHouse) SetLocalAllowList(allowList *AllowList) {
  76. lh.Lock()
  77. defer lh.Unlock()
  78. lh.localAllowList = allowList
  79. }
  80. func (lh *LightHouse) ValidateLHStaticEntries() error {
  81. for lhIP, _ := range lh.lighthouses {
  82. if _, ok := lh.staticList[lhIP]; !ok {
  83. return fmt.Errorf("Lighthouse %s does not have a static_host_map entry", IntIp(lhIP))
  84. }
  85. }
  86. return nil
  87. }
  88. func (lh *LightHouse) Query(ip uint32, f EncWriter) ([]*udpAddr, error) {
  89. if !lh.IsLighthouseIP(ip) {
  90. lh.QueryServer(ip, f)
  91. }
  92. lh.RLock()
  93. if v, ok := lh.addrMap[ip]; ok {
  94. lh.RUnlock()
  95. return v, nil
  96. }
  97. lh.RUnlock()
  98. return nil, ErrHostNotKnown
  99. }
  100. // This is asynchronous so no reply should be expected
  101. func (lh *LightHouse) QueryServer(ip uint32, f EncWriter) {
  102. if !lh.amLighthouse {
  103. // Send a query to the lighthouses and hope for the best next time
  104. query, err := proto.Marshal(NewLhQueryByInt(ip))
  105. if err != nil {
  106. l.WithError(err).WithField("vpnIp", IntIp(ip)).Error("Failed to marshal lighthouse query payload")
  107. return
  108. }
  109. lh.metricTx(NebulaMeta_HostQuery, int64(len(lh.lighthouses)))
  110. nb := make([]byte, 12, 12)
  111. out := make([]byte, mtu)
  112. for n := range lh.lighthouses {
  113. f.SendMessageToVpnIp(lightHouse, 0, n, query, nb, out)
  114. }
  115. }
  116. }
  117. // Query our local lighthouse cached results
  118. func (lh *LightHouse) QueryCache(ip uint32) []*udpAddr {
  119. lh.RLock()
  120. if v, ok := lh.addrMap[ip]; ok {
  121. lh.RUnlock()
  122. return v
  123. }
  124. lh.RUnlock()
  125. return nil
  126. }
  127. func (lh *LightHouse) DeleteVpnIP(vpnIP uint32) {
  128. // First we check the static mapping
  129. // and do nothing if it is there
  130. if _, ok := lh.staticList[vpnIP]; ok {
  131. return
  132. }
  133. lh.Lock()
  134. //l.Debugln(lh.addrMap)
  135. delete(lh.addrMap, vpnIP)
  136. l.Debugf("deleting %s from lighthouse.", IntIp(vpnIP))
  137. lh.Unlock()
  138. }
  139. func (lh *LightHouse) AddRemote(vpnIP uint32, toIp *udpAddr, static bool) {
  140. // First we check if the sender thinks this is a static entry
  141. // and do nothing if it is not, but should be considered static
  142. if static == false {
  143. if _, ok := lh.staticList[vpnIP]; ok {
  144. return
  145. }
  146. }
  147. lh.Lock()
  148. defer lh.Unlock()
  149. for _, v := range lh.addrMap[vpnIP] {
  150. if v.Equals(toIp) {
  151. return
  152. }
  153. }
  154. allow := lh.remoteAllowList.Allow(toIp.IP)
  155. l.WithField("remoteIp", toIp).WithField("allow", allow).Debug("remoteAllowList.Allow")
  156. if !allow {
  157. return
  158. }
  159. //l.Debugf("Adding reply of %s as %s\n", IntIp(vpnIP), toIp)
  160. if static {
  161. lh.staticList[vpnIP] = struct{}{}
  162. }
  163. lh.addrMap[vpnIP] = append(lh.addrMap[vpnIP], toIp.Copy())
  164. }
  165. func (lh *LightHouse) AddRemoteAndReset(vpnIP uint32, toIp *udpAddr) {
  166. if lh.amLighthouse {
  167. lh.DeleteVpnIP(vpnIP)
  168. lh.AddRemote(vpnIP, toIp, false)
  169. }
  170. }
  171. func (lh *LightHouse) IsLighthouseIP(vpnIP uint32) bool {
  172. if _, ok := lh.lighthouses[vpnIP]; ok {
  173. return true
  174. }
  175. return false
  176. }
  177. func NewLhQueryByInt(VpnIp uint32) *NebulaMeta {
  178. return &NebulaMeta{
  179. Type: NebulaMeta_HostQuery,
  180. Details: &NebulaMetaDetails{
  181. VpnIp: VpnIp,
  182. },
  183. }
  184. }
  185. type ip4Or6 struct {
  186. v4 IpAndPort
  187. v6 Ip6AndPort
  188. }
  189. func NewIpAndPort(ip net.IP, port uint32) ip4Or6 {
  190. ipp := ip4Or6{}
  191. if ipv4 := ip.To4(); ipv4 != nil {
  192. ipp.v4 = IpAndPort{Port: port}
  193. ipp.v4.Ip = ip2int(ip)
  194. } else {
  195. ipp.v6 = Ip6AndPort{Port: port}
  196. ipp.v6.Ip = make([]byte, len(ip))
  197. copy(ipp.v6.Ip, ip)
  198. }
  199. return ipp
  200. }
  201. func NewIpAndPortFromUDPAddr(addr *udpAddr) ip4Or6 {
  202. return NewIpAndPort(addr.IP, uint32(addr.Port))
  203. }
  204. func NewUDPAddrFromLH4(ipp *IpAndPort) *udpAddr {
  205. ip := ipp.Ip
  206. return NewUDPAddr(
  207. net.IPv4(byte(ip&0xff000000>>24), byte(ip&0x00ff0000>>16), byte(ip&0x0000ff00>>8), byte(ip&0x000000ff)),
  208. uint16(ipp.Port),
  209. )
  210. }
  211. func NewUDPAddrFromLH6(ipp *Ip6AndPort) *udpAddr {
  212. return NewUDPAddr(ipp.Ip, uint16(ipp.Port))
  213. }
  214. func (lh *LightHouse) LhUpdateWorker(f EncWriter) {
  215. if lh.amLighthouse || lh.interval == 0 {
  216. return
  217. }
  218. for {
  219. lh.SendUpdate(f)
  220. time.Sleep(time.Second * time.Duration(lh.interval))
  221. }
  222. }
  223. func (lh *LightHouse) SendUpdate(f EncWriter) {
  224. var v4 []*IpAndPort
  225. var v6 []*Ip6AndPort
  226. for _, e := range *localIps(lh.localAllowList) {
  227. // Only add IPs that aren't my VPN/tun IP
  228. if ip2int(e) != lh.myIp {
  229. ipp := NewIpAndPort(e, lh.nebulaPort)
  230. if len(ipp.v6.Ip) > 0 {
  231. v6 = append(v6, &ipp.v6)
  232. } else {
  233. v4 = append(v4, &ipp.v4)
  234. }
  235. }
  236. }
  237. m := &NebulaMeta{
  238. Type: NebulaMeta_HostUpdateNotification,
  239. Details: &NebulaMetaDetails{
  240. VpnIp: lh.myIp,
  241. IpAndPorts: v4,
  242. Ip6AndPorts: v6,
  243. },
  244. }
  245. lh.metricTx(NebulaMeta_HostUpdateNotification, int64(len(lh.lighthouses)))
  246. nb := make([]byte, 12, 12)
  247. out := make([]byte, mtu)
  248. for vpnIp := range lh.lighthouses {
  249. mm, err := proto.Marshal(m)
  250. if err != nil {
  251. l.Debugf("Invalid marshal to update")
  252. }
  253. //l.Error("LIGHTHOUSE PACKET SEND", mm)
  254. f.SendMessageToVpnIp(lightHouse, 0, vpnIp, mm, nb, out)
  255. }
  256. }
  257. type LightHouseHandler struct {
  258. lh *LightHouse
  259. nb []byte
  260. out []byte
  261. meta *NebulaMeta
  262. iap []ip4Or6
  263. iapp []*ip4Or6
  264. }
  265. func (lh *LightHouse) NewRequestHandler() *LightHouseHandler {
  266. lhh := &LightHouseHandler{
  267. lh: lh,
  268. nb: make([]byte, 12, 12),
  269. out: make([]byte, mtu),
  270. meta: &NebulaMeta{
  271. Details: &NebulaMetaDetails{},
  272. },
  273. }
  274. lhh.resizeIpAndPorts(10)
  275. return lhh
  276. }
  277. // This method is similar to Reset(), but it re-uses the pointer structs
  278. // so that we don't have to re-allocate them
  279. func (lhh *LightHouseHandler) resetMeta() *NebulaMeta {
  280. details := lhh.meta.Details
  281. details.Reset()
  282. lhh.meta.Reset()
  283. lhh.meta.Details = details
  284. return lhh.meta
  285. }
  286. func (lhh *LightHouseHandler) resizeIpAndPorts(n int) {
  287. if cap(lhh.iap) < n {
  288. lhh.iap = make([]ip4Or6, n)
  289. lhh.iapp = make([]*ip4Or6, n)
  290. for i := range lhh.iap {
  291. lhh.iapp[i] = &lhh.iap[i]
  292. }
  293. }
  294. lhh.iap = lhh.iap[:n]
  295. lhh.iapp = lhh.iapp[:n]
  296. }
  297. func (lhh *LightHouseHandler) setIpAndPortsFromNetIps(ips []*udpAddr) []*ip4Or6 {
  298. lhh.resizeIpAndPorts(len(ips))
  299. for i, e := range ips {
  300. lhh.iap[i] = NewIpAndPortFromUDPAddr(e)
  301. }
  302. return lhh.iapp
  303. }
  304. func (lhh *LightHouseHandler) HandleRequest(rAddr *udpAddr, vpnIp uint32, p []byte, c *cert.NebulaCertificate, f EncWriter) {
  305. lh := lhh.lh
  306. n := lhh.resetMeta()
  307. err := proto.UnmarshalMerge(p, n)
  308. if err != nil {
  309. l.WithError(err).WithField("vpnIp", IntIp(vpnIp)).WithField("udpAddr", rAddr).
  310. Error("Failed to unmarshal lighthouse packet")
  311. //TODO: send recv_error?
  312. return
  313. }
  314. if n.Details == nil {
  315. l.WithField("vpnIp", IntIp(vpnIp)).WithField("udpAddr", rAddr).
  316. Error("Invalid lighthouse update")
  317. //TODO: send recv_error?
  318. return
  319. }
  320. lh.metricRx(n.Type, 1)
  321. switch n.Type {
  322. case NebulaMeta_HostQuery:
  323. // Exit if we don't answer queries
  324. if !lh.amLighthouse {
  325. l.Debugln("I don't answer queries, but received from: ", rAddr)
  326. return
  327. }
  328. //l.Debugln("Got Query")
  329. ips, err := lh.Query(n.Details.VpnIp, f)
  330. if err != nil {
  331. //l.Debugf("Can't answer query %s from %s because error: %s", IntIp(n.Details.VpnIp), rAddr, err)
  332. return
  333. } else {
  334. reqVpnIP := n.Details.VpnIp
  335. n = lhh.resetMeta()
  336. n.Type = NebulaMeta_HostQueryReply
  337. n.Details.VpnIp = reqVpnIP
  338. v4s := make([]*IpAndPort, 0)
  339. v6s := make([]*Ip6AndPort, 0)
  340. for _, v := range lhh.setIpAndPortsFromNetIps(ips) {
  341. if len(v.v6.Ip) > 0 {
  342. v6s = append(v6s, &v.v6)
  343. } else {
  344. v4s = append(v4s, &v.v4)
  345. }
  346. }
  347. if len(v4s) > 0 {
  348. n.Details.IpAndPorts = v4s
  349. }
  350. if len(v6s) > 0 {
  351. n.Details.Ip6AndPorts = v6s
  352. }
  353. reply, err := proto.Marshal(n)
  354. if err != nil {
  355. l.WithError(err).WithField("vpnIp", IntIp(vpnIp)).Error("Failed to marshal lighthouse host query reply")
  356. return
  357. }
  358. lh.metricTx(NebulaMeta_HostQueryReply, 1)
  359. f.SendMessageToVpnIp(lightHouse, 0, vpnIp, reply, lhh.nb, lhh.out[:0])
  360. // This signals the other side to punch some zero byte udp packets
  361. ips, err = lh.Query(vpnIp, f)
  362. if err != nil {
  363. l.WithField("vpnIp", IntIp(vpnIp)).Debugln("Can't notify host to punch")
  364. return
  365. } else {
  366. //l.Debugln("Notify host to punch", iap)
  367. n = lhh.resetMeta()
  368. n.Type = NebulaMeta_HostPunchNotification
  369. n.Details.VpnIp = vpnIp
  370. v4s := make([]*IpAndPort, 0)
  371. v6s := make([]*Ip6AndPort, 0)
  372. for _, v := range lhh.setIpAndPortsFromNetIps(ips) {
  373. if len(v.v6.Ip) > 0 {
  374. v6s = append(v6s, &v.v6)
  375. } else {
  376. v4s = append(v4s, &v.v4)
  377. }
  378. }
  379. if len(v4s) > 0 {
  380. n.Details.IpAndPorts = v4s
  381. }
  382. if len(v6s) > 0 {
  383. n.Details.Ip6AndPorts = v6s
  384. }
  385. reply, _ := proto.Marshal(n)
  386. lh.metricTx(NebulaMeta_HostPunchNotification, 1)
  387. f.SendMessageToVpnIp(lightHouse, 0, reqVpnIP, reply, lhh.nb, lhh.out[:0])
  388. }
  389. //fmt.Println(reply, remoteaddr)
  390. }
  391. case NebulaMeta_HostQueryReply:
  392. if !lh.IsLighthouseIP(vpnIp) {
  393. return
  394. }
  395. for _, a := range n.Details.IpAndPorts {
  396. ans := NewUDPAddrFromLH4(a)
  397. if ans != nil {
  398. lh.AddRemote(n.Details.VpnIp, ans, false)
  399. }
  400. }
  401. for _, a := range n.Details.Ip6AndPorts {
  402. ans := NewUDPAddrFromLH6(a)
  403. if ans != nil {
  404. lh.AddRemote(n.Details.VpnIp, ans, false)
  405. }
  406. }
  407. // Non-blocking attempt to trigger, skip if it would block
  408. select {
  409. case lh.handshakeTrigger <- n.Details.VpnIp:
  410. default:
  411. }
  412. case NebulaMeta_HostUpdateNotification:
  413. //Simple check that the host sent this not someone else
  414. if n.Details.VpnIp != vpnIp {
  415. l.WithField("vpnIp", IntIp(vpnIp)).WithField("answer", IntIp(n.Details.VpnIp)).Debugln("Host sent invalid update")
  416. return
  417. }
  418. for _, a := range n.Details.IpAndPorts {
  419. ans := NewUDPAddrFromLH4(a)
  420. if ans != nil {
  421. lh.AddRemote(n.Details.VpnIp, ans, false)
  422. }
  423. }
  424. for _, a := range n.Details.Ip6AndPorts {
  425. ans := NewUDPAddrFromLH6(a)
  426. if ans != nil {
  427. lh.AddRemote(n.Details.VpnIp, ans, false)
  428. }
  429. }
  430. case NebulaMeta_HostMovedNotification:
  431. case NebulaMeta_HostPunchNotification:
  432. if !lh.IsLighthouseIP(vpnIp) {
  433. return
  434. }
  435. empty := []byte{0}
  436. for _, a := range n.Details.IpAndPorts {
  437. vpnPeer := NewUDPAddrFromLH4(a)
  438. if vpnPeer == nil {
  439. continue
  440. }
  441. go func() {
  442. time.Sleep(lh.punchDelay)
  443. lh.metricHolepunchTx.Inc(1)
  444. lh.punchConn.WriteTo(empty, vpnPeer)
  445. }()
  446. if l.Level >= logrus.DebugLevel {
  447. //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))
  448. l.Debugf("Punching on %d for %s", a.Port, IntIp(n.Details.VpnIp))
  449. }
  450. }
  451. for _, a := range n.Details.Ip6AndPorts {
  452. vpnPeer := NewUDPAddrFromLH6(a)
  453. if vpnPeer == nil {
  454. continue
  455. }
  456. go func() {
  457. time.Sleep(lh.punchDelay)
  458. lh.metricHolepunchTx.Inc(1)
  459. lh.punchConn.WriteTo(empty, vpnPeer)
  460. }()
  461. if l.Level >= logrus.DebugLevel {
  462. //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))
  463. l.Debugf("Punching on %d for %s", a.Port, IntIp(n.Details.VpnIp))
  464. }
  465. }
  466. // This sends a nebula test packet to the host trying to contact us. In the case
  467. // of a double nat or other difficult scenario, this may help establish
  468. // a tunnel.
  469. if lh.punchBack {
  470. go func() {
  471. time.Sleep(time.Second * 5)
  472. l.Debugf("Sending a nebula test packet to vpn ip %s", IntIp(n.Details.VpnIp))
  473. // TODO we have to allocate a new output buffer here since we are spawning a new goroutine
  474. // for each punchBack packet. We should move this into a timerwheel or a single goroutine
  475. // managed by a channel.
  476. f.SendMessageToVpnIp(test, testRequest, n.Details.VpnIp, []byte(""), make([]byte, 12, 12), make([]byte, mtu))
  477. }()
  478. }
  479. }
  480. }
  481. func (lh *LightHouse) metricRx(t NebulaMeta_MessageType, i int64) {
  482. lh.metrics.Rx(NebulaMessageType(t), 0, i)
  483. }
  484. func (lh *LightHouse) metricTx(t NebulaMeta_MessageType, i int64) {
  485. lh.metrics.Tx(NebulaMessageType(t), 0, i)
  486. }
  487. /*
  488. func (f *Interface) sendPathCheck(ci *ConnectionState, endpoint *net.UDPAddr, counter int) {
  489. c := ci.messageCounter
  490. b := HeaderEncode(nil, Version, uint8(path_check), 0, ci.remoteIndex, c)
  491. ci.messageCounter++
  492. if ci.eKey != nil {
  493. msg := ci.eKey.EncryptDanger(b, nil, []byte(strconv.Itoa(counter)), c)
  494. //msg := ci.eKey.EncryptDanger(b, nil, []byte(fmt.Sprintf("%d", counter)), c)
  495. f.outside.WriteTo(msg, endpoint)
  496. l.Debugf("path_check sent, remote index: %d, pathCounter %d", ci.remoteIndex, counter)
  497. }
  498. }
  499. func (f *Interface) sendPathCheckReply(ci *ConnectionState, endpoint *net.UDPAddr, counter []byte) {
  500. c := ci.messageCounter
  501. b := HeaderEncode(nil, Version, uint8(path_check_reply), 0, ci.remoteIndex, c)
  502. ci.messageCounter++
  503. if ci.eKey != nil {
  504. msg := ci.eKey.EncryptDanger(b, nil, counter, c)
  505. f.outside.WriteTo(msg, endpoint)
  506. l.Debugln("path_check sent, remote index: ", ci.remoteIndex)
  507. }
  508. }
  509. */