lighthouse.go 13 KB

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