lighthouse.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484
  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. for _, v := range lh.addrMap[vpnIP] {
  148. if v.Equals(toIp) {
  149. lh.Unlock()
  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. lh.Unlock()
  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. func NewIpAndPort(ip net.IP, port uint32) IpAndPort {
  186. return IpAndPort{Ip: ip2int(ip), Port: port}
  187. }
  188. func NewIpAndPortFromUDPAddr(addr udpAddr) IpAndPort {
  189. return IpAndPort{Ip: udp2ipInt(&addr), Port: uint32(addr.Port)}
  190. }
  191. func (lh *LightHouse) LhUpdateWorker(f EncWriter) {
  192. if lh.amLighthouse || lh.interval == 0 {
  193. return
  194. }
  195. for {
  196. lh.SendUpdate(f)
  197. time.Sleep(time.Second * time.Duration(lh.interval))
  198. }
  199. }
  200. func (lh *LightHouse) SendUpdate(f EncWriter) {
  201. var ipps []*IpAndPort
  202. for _, e := range *localIps(lh.localAllowList) {
  203. // Only add IPs that aren't my VPN/tun IP
  204. if ip2int(e) != lh.myIp {
  205. ipp := NewIpAndPort(e, lh.nebulaPort)
  206. ipps = append(ipps, &ipp)
  207. }
  208. }
  209. m := &NebulaMeta{
  210. Type: NebulaMeta_HostUpdateNotification,
  211. Details: &NebulaMetaDetails{
  212. VpnIp: lh.myIp,
  213. IpAndPorts: ipps,
  214. },
  215. }
  216. lh.metricTx(NebulaMeta_HostUpdateNotification, int64(len(lh.lighthouses)))
  217. nb := make([]byte, 12, 12)
  218. out := make([]byte, mtu)
  219. for vpnIp := range lh.lighthouses {
  220. mm, err := proto.Marshal(m)
  221. if err != nil {
  222. l.Debugf("Invalid marshal to update")
  223. }
  224. //l.Error("LIGHTHOUSE PACKET SEND", mm)
  225. f.SendMessageToVpnIp(lightHouse, 0, vpnIp, mm, nb, out)
  226. }
  227. }
  228. type LightHouseHandler struct {
  229. lh *LightHouse
  230. nb []byte
  231. out []byte
  232. meta *NebulaMeta
  233. iap []IpAndPort
  234. iapp []*IpAndPort
  235. }
  236. func (lh *LightHouse) NewRequestHandler() *LightHouseHandler {
  237. lhh := &LightHouseHandler{
  238. lh: lh,
  239. nb: make([]byte, 12, 12),
  240. out: make([]byte, mtu),
  241. meta: &NebulaMeta{
  242. Details: &NebulaMetaDetails{},
  243. },
  244. }
  245. lhh.resizeIpAndPorts(10)
  246. return lhh
  247. }
  248. // This method is similar to Reset(), but it re-uses the pointer structs
  249. // so that we don't have to re-allocate them
  250. func (lhh *LightHouseHandler) resetMeta() *NebulaMeta {
  251. details := lhh.meta.Details
  252. details.Reset()
  253. lhh.meta.Reset()
  254. lhh.meta.Details = details
  255. return lhh.meta
  256. }
  257. func (lhh *LightHouseHandler) resizeIpAndPorts(n int) {
  258. if cap(lhh.iap) < n {
  259. lhh.iap = make([]IpAndPort, n)
  260. lhh.iapp = make([]*IpAndPort, n)
  261. for i := range lhh.iap {
  262. lhh.iapp[i] = &lhh.iap[i]
  263. }
  264. }
  265. lhh.iap = lhh.iap[:n]
  266. lhh.iapp = lhh.iapp[:n]
  267. }
  268. func (lhh *LightHouseHandler) setIpAndPortsFromNetIps(ips []udpAddr) []*IpAndPort {
  269. lhh.resizeIpAndPorts(len(ips))
  270. for i, e := range ips {
  271. lhh.iap[i] = NewIpAndPortFromUDPAddr(e)
  272. }
  273. return lhh.iapp
  274. }
  275. func (lhh *LightHouseHandler) HandleRequest(rAddr *udpAddr, vpnIp uint32, p []byte, c *cert.NebulaCertificate, f EncWriter) {
  276. lh := lhh.lh
  277. n := lhh.resetMeta()
  278. err := proto.UnmarshalMerge(p, n)
  279. if err != nil {
  280. l.WithError(err).WithField("vpnIp", IntIp(vpnIp)).WithField("udpAddr", rAddr).
  281. Error("Failed to unmarshal lighthouse packet")
  282. //TODO: send recv_error?
  283. return
  284. }
  285. if n.Details == nil {
  286. l.WithField("vpnIp", IntIp(vpnIp)).WithField("udpAddr", rAddr).
  287. Error("Invalid lighthouse update")
  288. //TODO: send recv_error?
  289. return
  290. }
  291. lh.metricRx(n.Type, 1)
  292. switch n.Type {
  293. case NebulaMeta_HostQuery:
  294. // Exit if we don't answer queries
  295. if !lh.amLighthouse {
  296. l.Debugln("I don't answer queries, but received from: ", rAddr)
  297. return
  298. }
  299. //l.Debugln("Got Query")
  300. ips, err := lh.Query(n.Details.VpnIp, f)
  301. if err != nil {
  302. //l.Debugf("Can't answer query %s from %s because error: %s", IntIp(n.Details.VpnIp), rAddr, err)
  303. return
  304. } else {
  305. reqVpnIP := n.Details.VpnIp
  306. n = lhh.resetMeta()
  307. n.Type = NebulaMeta_HostQueryReply
  308. n.Details.VpnIp = reqVpnIP
  309. n.Details.IpAndPorts = lhh.setIpAndPortsFromNetIps(ips)
  310. reply, err := proto.Marshal(n)
  311. if err != nil {
  312. l.WithError(err).WithField("vpnIp", IntIp(vpnIp)).Error("Failed to marshal lighthouse host query reply")
  313. return
  314. }
  315. lh.metricTx(NebulaMeta_HostQueryReply, 1)
  316. f.SendMessageToVpnIp(lightHouse, 0, vpnIp, reply, lhh.nb, lhh.out[:0])
  317. // This signals the other side to punch some zero byte udp packets
  318. ips, err = lh.Query(vpnIp, f)
  319. if err != nil {
  320. l.WithField("vpnIp", IntIp(vpnIp)).Debugln("Can't notify host to punch")
  321. return
  322. } else {
  323. //l.Debugln("Notify host to punch", iap)
  324. n = lhh.resetMeta()
  325. n.Type = NebulaMeta_HostPunchNotification
  326. n.Details.VpnIp = vpnIp
  327. n.Details.IpAndPorts = lhh.setIpAndPortsFromNetIps(ips)
  328. reply, _ := proto.Marshal(n)
  329. lh.metricTx(NebulaMeta_HostPunchNotification, 1)
  330. f.SendMessageToVpnIp(lightHouse, 0, reqVpnIP, reply, lhh.nb, lhh.out[:0])
  331. }
  332. //fmt.Println(reply, remoteaddr)
  333. }
  334. case NebulaMeta_HostQueryReply:
  335. if !lh.IsLighthouseIP(vpnIp) {
  336. return
  337. }
  338. for _, a := range n.Details.IpAndPorts {
  339. //first := n.Details.IpAndPorts[0]
  340. ans := NewUDPAddr(a.Ip, uint16(a.Port))
  341. lh.AddRemote(n.Details.VpnIp, ans, false)
  342. }
  343. // Non-blocking attempt to trigger, skip if it would block
  344. select {
  345. case lh.handshakeTrigger <- n.Details.VpnIp:
  346. default:
  347. }
  348. case NebulaMeta_HostUpdateNotification:
  349. //Simple check that the host sent this not someone else
  350. if n.Details.VpnIp != vpnIp {
  351. l.WithField("vpnIp", IntIp(vpnIp)).WithField("answer", IntIp(n.Details.VpnIp)).Debugln("Host sent invalid update")
  352. return
  353. }
  354. for _, a := range n.Details.IpAndPorts {
  355. ans := NewUDPAddr(a.Ip, uint16(a.Port))
  356. lh.AddRemote(n.Details.VpnIp, ans, false)
  357. }
  358. case NebulaMeta_HostMovedNotification:
  359. case NebulaMeta_HostPunchNotification:
  360. if !lh.IsLighthouseIP(vpnIp) {
  361. return
  362. }
  363. empty := []byte{0}
  364. for _, a := range n.Details.IpAndPorts {
  365. vpnPeer := NewUDPAddr(a.Ip, uint16(a.Port))
  366. go func() {
  367. time.Sleep(lh.punchDelay)
  368. lh.metricHolepunchTx.Inc(1)
  369. lh.punchConn.WriteTo(empty, vpnPeer)
  370. }()
  371. l.Debugf("Punching %s on %d for %s", IntIp(a.Ip), a.Port, IntIp(n.Details.VpnIp))
  372. }
  373. // This sends a nebula test packet to the host trying to contact us. In the case
  374. // of a double nat or other difficult scenario, this may help establish
  375. // a tunnel.
  376. if lh.punchBack {
  377. go func() {
  378. time.Sleep(time.Second * 5)
  379. l.Debugf("Sending a nebula test packet to vpn ip %s", IntIp(n.Details.VpnIp))
  380. // TODO we have to allocate a new output buffer here since we are spawning a new goroutine
  381. // for each punchBack packet. We should move this into a timerwheel or a single goroutine
  382. // managed by a channel.
  383. f.SendMessageToVpnIp(test, testRequest, n.Details.VpnIp, []byte(""), make([]byte, 12, 12), make([]byte, mtu))
  384. }()
  385. }
  386. }
  387. }
  388. func (lh *LightHouse) metricRx(t NebulaMeta_MessageType, i int64) {
  389. lh.metrics.Rx(NebulaMessageType(t), 0, i)
  390. }
  391. func (lh *LightHouse) metricTx(t NebulaMeta_MessageType, i int64) {
  392. lh.metrics.Tx(NebulaMessageType(t), 0, i)
  393. }
  394. /*
  395. func (f *Interface) sendPathCheck(ci *ConnectionState, endpoint *net.UDPAddr, counter int) {
  396. c := ci.messageCounter
  397. b := HeaderEncode(nil, Version, uint8(path_check), 0, ci.remoteIndex, c)
  398. ci.messageCounter++
  399. if ci.eKey != nil {
  400. msg := ci.eKey.EncryptDanger(b, nil, []byte(strconv.Itoa(counter)), c)
  401. //msg := ci.eKey.EncryptDanger(b, nil, []byte(fmt.Sprintf("%d", counter)), c)
  402. f.outside.WriteTo(msg, endpoint)
  403. l.Debugf("path_check sent, remote index: %d, pathCounter %d", ci.remoteIndex, counter)
  404. }
  405. }
  406. func (f *Interface) sendPathCheckReply(ci *ConnectionState, endpoint *net.UDPAddr, counter []byte) {
  407. c := ci.messageCounter
  408. b := HeaderEncode(nil, Version, uint8(path_check_reply), 0, ci.remoteIndex, c)
  409. ci.messageCounter++
  410. if ci.eKey != nil {
  411. msg := ci.eKey.EncryptDanger(b, nil, counter, c)
  412. f.outside.WriteTo(msg, endpoint)
  413. l.Debugln("path_check sent, remote index: ", ci.remoteIndex)
  414. }
  415. }
  416. */