webrelayserver.js 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344
  1. /**
  2. * @description Meshcentral web relay server
  3. * @author Ylian Saint-Hilaire
  4. * @copyright Intel Corporation 2018-2022
  5. * @license Apache-2.0
  6. * @version v0.0.1
  7. */
  8. /*jslint node: true */
  9. /*jshint node: true */
  10. /*jshint strict:false */
  11. /*jshint -W097 */
  12. /*jshint esversion: 6 */
  13. "use strict";
  14. // Construct a HTTP redirection web server object
  15. module.exports.CreateWebRelayServer = function (parent, db, args, certificates, func) {
  16. var obj = {};
  17. obj.parent = parent;
  18. obj.db = db;
  19. obj.express = require('express');
  20. obj.expressWs = null;
  21. obj.tlsServer = null;
  22. obj.net = require('net');
  23. obj.app = obj.express();
  24. obj.app.disable('x-powered-by');
  25. obj.webRelayServer = null;
  26. obj.port = 0;
  27. obj.cleanupTimer = null;
  28. var relaySessions = {} // RelayID --> Web Mutli-Tunnel
  29. const constants = (require('crypto').constants ? require('crypto').constants : require('constants')); // require('constants') is deprecated in Node 11.10, use require('crypto').constants instead.
  30. var tlsSessionStore = {}; // Store TLS session information for quick resume.
  31. var tlsSessionStoreCount = 0; // Number of cached TLS session information in store.
  32. function serverStart() {
  33. // Setup CrowdSec bouncer middleware if needed
  34. if (parent.crowdsecMiddleware != null) { obj.app.use(parent.crowdsecMiddleware); }
  35. if (args.trustedproxy) {
  36. // Reverse proxy should add the "X-Forwarded-*" headers
  37. try {
  38. obj.app.set('trust proxy', args.trustedproxy);
  39. } catch (ex) {
  40. // If there is an error, try to resolve the string
  41. if ((args.trustedproxy.length == 1) && (typeof args.trustedproxy[0] == 'string')) {
  42. require('dns').lookup(args.trustedproxy[0], function (err, address, family) { if (err == null) { obj.app.set('trust proxy', address); args.trustedproxy = [address]; } });
  43. }
  44. }
  45. }
  46. else if (typeof args.tlsoffload == 'object') {
  47. // Reverse proxy should add the "X-Forwarded-*" headers
  48. try {
  49. obj.app.set('trust proxy', args.tlsoffload);
  50. } catch (ex) {
  51. // If there is an error, try to resolve the string
  52. if ((Array.isArray(args.tlsoffload)) && (args.tlsoffload.length == 1) && (typeof args.tlsoffload[0] == 'string')) {
  53. require('dns').lookup(args.tlsoffload[0], function (err, address, family) { if (err == null) { obj.app.set('trust proxy', address); args.tlsoffload = [address]; } });
  54. }
  55. }
  56. }
  57. // Setup a keygrip instance with higher default security, default hash is SHA1, we want to bump that up with SHA384
  58. // If multiple instances of this server are behind a load-balancer, this secret must be the same for all instances
  59. // If args.sessionkey is a string, use it as a single key, but args.sessionkey can also be used as an array of keys.
  60. const keygrip = require('keygrip')((typeof args.sessionkey == 'string') ? [args.sessionkey] : args.sessionkey, 'sha384', 'base64');
  61. // Watch for device share removal
  62. parent.AddEventDispatch(['server-shareremove'], obj);
  63. obj.HandleEvent = function (source, event, ids, id) {
  64. if (event.action == 'removedDeviceShare') {
  65. for (var relaySessionId in relaySessions) {
  66. // A share was removed that matches an active session, close the session.
  67. if (relaySessions[relaySessionId].xpublicid === event.publicid) { relaySessions[relaySessionId].close(); }
  68. }
  69. }
  70. }
  71. // Setup cookie session
  72. const sessionOptions = {
  73. name: 'xid', // Recommended security practice to not use the default cookie name
  74. httpOnly: true,
  75. keys: keygrip,
  76. secure: (args.tlsoffload == null), // Use this cookie only over TLS (Check this: https://expressjs.com/en/guide/behind-proxies.html)
  77. sameSite: (args.sessionsamesite ? args.sessionsamesite : 'lax')
  78. }
  79. if (args.sessiontime != null) { sessionOptions.maxAge = (args.sessiontime * 60000); } // sessiontime is minutes
  80. obj.app.use(require('cookie-session')(sessionOptions));
  81. obj.app.use(function(request, response, next) { // Patch for passport 0.6.0 - https://github.com/jaredhanson/passport/issues/904
  82. if (request.session && !request.session.regenerate) {
  83. request.session.regenerate = function (cb) {
  84. cb()
  85. }
  86. }
  87. if (request.session && !request.session.save) {
  88. request.session.save = function (cb) {
  89. cb()
  90. }
  91. }
  92. next()
  93. });
  94. // Add HTTP security headers to all responses
  95. obj.app.use(function (req, res, next) {
  96. parent.debug('webrelay', req.url);
  97. res.removeHeader('X-Powered-By');
  98. res.set({
  99. 'strict-transport-security': 'max-age=60000; includeSubDomains',
  100. 'Referrer-Policy': 'no-referrer',
  101. 'x-frame-options': 'SAMEORIGIN',
  102. 'X-XSS-Protection': '1; mode=block',
  103. 'X-Content-Type-Options': 'nosniff',
  104. 'Content-Security-Policy': "default-src 'self'; style-src 'self' 'unsafe-inline';"
  105. });
  106. // Set the real IP address of the request
  107. // If a trusted reverse-proxy is sending us the remote IP address, use it.
  108. var ipex = '0.0.0.0', xforwardedhost = req.headers.host;
  109. if (typeof req.connection.remoteAddress == 'string') { ipex = (req.connection.remoteAddress.startsWith('::ffff:')) ? req.connection.remoteAddress.substring(7) : req.connection.remoteAddress; }
  110. if (
  111. (args.trustedproxy === true) || (args.tlsoffload === true) ||
  112. ((typeof args.trustedproxy == 'object') && (isIPMatch(ipex, args.trustedproxy))) ||
  113. ((typeof args.tlsoffload == 'object') && (isIPMatch(ipex, args.tlsoffload)))
  114. ) {
  115. // Get client IP
  116. if (req.headers['cf-connecting-ip']) { // Use CloudFlare IP address if present
  117. req.clientIp = req.headers['cf-connecting-ip'].split(',')[0].trim();
  118. } else if (req.headers['x-forwarded-for']) {
  119. req.clientIp = req.headers['x-forwarded-for'].split(',')[0].trim();
  120. } else if (req.headers['x-real-ip']) {
  121. req.clientIp = req.headers['x-real-ip'].split(',')[0].trim();
  122. } else {
  123. req.clientIp = ipex;
  124. }
  125. // If there is a port number, remove it. This will only work for IPv4, but nice for people that have a bad reverse proxy config.
  126. const clientIpSplit = req.clientIp.split(':');
  127. if (clientIpSplit.length == 2) { req.clientIp = clientIpSplit[0]; }
  128. // Get server host
  129. if (req.headers['x-forwarded-host']) { xforwardedhost = req.headers['x-forwarded-host'].split(',')[0]; } // If multiple hosts are specified with a comma, take the first one.
  130. } else {
  131. req.clientIp = ipex;
  132. }
  133. // If this is a session start or a websocket, have the application handle this
  134. if ((req.headers.upgrade == 'websocket') || (req.url.startsWith('/control-redirect.ashx?n='))) {
  135. return next();
  136. } else {
  137. // If this is a normal request (GET, POST, etc) handle it here
  138. var webSessionId = null;
  139. if ((req.session.userid != null) && (req.session.x != null)) { webSessionId = req.session.userid + '/' + req.session.x; }
  140. else if (req.session.z != null) { webSessionId = req.session.z; }
  141. if ((webSessionId != null) && (parent.webserver.destroyedSessions[webSessionId] == null)) {
  142. var relaySession = relaySessions[webSessionId];
  143. if (relaySession != null) {
  144. // The web relay session is valid, use it
  145. relaySession.handleRequest(req, res);
  146. } else {
  147. // No web relay ession with this relay identifier, close the HTTP request.
  148. res.end();
  149. }
  150. } else {
  151. // The user is not logged in or does not have a relay identifier, close the HTTP request.
  152. res.end();
  153. }
  154. }
  155. });
  156. // Start the server, only after users and meshes are loaded from the database.
  157. if (args.tlsoffload) {
  158. // Setup the HTTP server without TLS
  159. obj.expressWs = require('express-ws')(obj.app, null, { wsOptions: { perMessageDeflate: (args.wscompression === true) } });
  160. } else {
  161. // Setup the HTTP server with TLS, use only TLS 1.2 and higher with perfect forward secrecy (PFS).
  162. const tlsOptions = { cert: certificates.web.cert, key: certificates.web.key, ca: certificates.web.ca, rejectUnauthorized: true, ciphers: "HIGH:TLS_AES_256_GCM_SHA384:TLS_AES_128_GCM_SHA256:TLS_AES_128_CCM_8_SHA256:TLS_AES_128_CCM_SHA256:TLS_CHACHA20_POLY1305_SHA256", secureOptions: constants.SSL_OP_NO_SSLv2 | constants.SSL_OP_NO_SSLv3 | constants.SSL_OP_NO_COMPRESSION | constants.SSL_OP_CIPHER_SERVER_PREFERENCE | constants.SSL_OP_NO_TLSv1 | constants.SSL_OP_NO_TLSv1_1 };
  163. obj.tlsServer = require('https').createServer(tlsOptions, obj.app);
  164. obj.tlsServer.on('secureConnection', function () { /*console.log('tlsServer secureConnection');*/ });
  165. obj.tlsServer.on('error', function (err) { console.log('tlsServer error', err); });
  166. obj.tlsServer.on('newSession', function (id, data, cb) { if (tlsSessionStoreCount > 1000) { tlsSessionStoreCount = 0; tlsSessionStore = {}; } tlsSessionStore[id.toString('hex')] = data; tlsSessionStoreCount++; cb(); });
  167. obj.tlsServer.on('resumeSession', function (id, cb) { cb(null, tlsSessionStore[id.toString('hex')] || null); });
  168. obj.expressWs = require('express-ws')(obj.app, obj.tlsServer, { wsOptions: { perMessageDeflate: (args.wscompression === true) } });
  169. }
  170. // Handle incoming web socket calls
  171. obj.app.ws('/*', function (ws, req) {
  172. var webSessionId = null;
  173. if ((req.session.userid != null) && (req.session.x != null)) { webSessionId = req.session.userid + '/' + req.session.x; }
  174. else if (req.session.z != null) { webSessionId = req.session.z; }
  175. if ((webSessionId != null) && (parent.webserver.destroyedSessions[webSessionId] == null)) {
  176. var relaySession = relaySessions[webSessionId];
  177. if (relaySession != null) {
  178. // The multi-tunnel session is valid, use it
  179. relaySession.handleWebSocket(ws, req);
  180. } else {
  181. // No multi-tunnel session with this relay identifier, close the websocket.
  182. ws.close();
  183. }
  184. } else {
  185. // The user is not logged in or does not have a relay identifier, close the websocket.
  186. ws.close();
  187. }
  188. });
  189. // This is the magic URL that will setup the relay session
  190. obj.app.get('/control-redirect.ashx', function (req, res) {
  191. res.set({ 'Cache-Control': 'no-store' });
  192. parent.debug('webrelay', 'webRelaySetup');
  193. // Decode the relay cookie
  194. if (req.query.c == null) { res.sendStatus(404); return; }
  195. // Decode and check if this relay cookie is valid
  196. var userid, domainid, domain, nodeid, addr, port, appid, webSessionId, expire, publicid;
  197. const urlCookie = obj.parent.decodeCookie(req.query.c, parent.loginCookieEncryptionKey, 32); // Allow cookies up to 32 minutes old. The web page will renew this cookie every 30 minutes.
  198. if (urlCookie == null) { res.sendStatus(404); return; }
  199. // Decode the incoming cookie
  200. if ((urlCookie.ruserid != null) && (urlCookie.x != null)) {
  201. if (parent.webserver.destroyedSessions[urlCookie.ruserid + '/' + urlCookie.x] != null) { res.sendStatus(404); return; }
  202. // This is a standard user, figure out what our web relay will be.
  203. if (req.session.x != urlCookie.x) { req.session.x = urlCookie.x; } // Set the sessionid if missing
  204. if (req.session.userid != urlCookie.ruserid) { req.session.userid = urlCookie.ruserid; } // Set the session userid if missing
  205. if (req.session.z) { delete req.session.z; } // Clear the web relay guest session
  206. userid = req.session.userid;
  207. domainid = userid.split('/')[1];
  208. domain = parent.config.domains[domainid];
  209. nodeid = ((req.query.relayid != null) ? req.query.relayid : req.query.n);
  210. addr = (req.query.addr != null) ? req.query.addr : '127.0.0.1';
  211. port = parseInt(req.query.p);
  212. appid = parseInt(req.query.appid);
  213. webSessionId = req.session.userid + '/' + req.session.x;
  214. // Check that all the required arguments are present
  215. if ((req.session.userid == null) || (req.session.x == null) || (req.query.n == null) || (req.query.p == null) || (parent.webserver.destroyedSessions[webSessionId] != null) || ((req.query.appid != 1) && (req.query.appid != 2))) { res.redirect('/'); return; }
  216. } else if (urlCookie.r == 8) {
  217. // This is a guest user, figure out what our web relay will be.
  218. userid = urlCookie.userid;
  219. domainid = userid.split('/')[1];
  220. domain = parent.config.domains[domainid];
  221. nodeid = urlCookie.nid;
  222. addr = (urlCookie.addr != null) ? urlCookie.addr : '127.0.0.1';
  223. port = urlCookie.port;
  224. appid = (urlCookie.p == 16) ? 2 : 1; // appid: 1 = HTTP, 2 = HTTPS
  225. webSessionId = userid + '/' + urlCookie.pid;
  226. publicid = urlCookie.pid;
  227. if (req.session.x) { delete req.session.x; } // Clear the web relay sessionid
  228. if (req.session.userid) { delete req.session.userid; } // Clear the web relay userid
  229. if (req.session.z != webSessionId) { req.session.z = webSessionId; } // Set the web relay guest session
  230. expire = urlCookie.expire;
  231. if ((expire != null) && (expire <= Date.now())) { parent.debug('webrelay', 'expired link'); res.sendStatus(404); return; }
  232. }
  233. // No session identifier was setup, exit now
  234. if (webSessionId == null) { res.sendStatus(404); return; }
  235. // Check to see if we already have a multi-relay session that matches exactly this device and port for this user
  236. const xrelaySession = relaySessions[webSessionId];
  237. if ((xrelaySession != null) && (xrelaySession.domain.id == domain.id) && (xrelaySession.userid == userid) && (xrelaySession.nodeid == nodeid) && (xrelaySession.addr == addr) && (xrelaySession.port == port) && (xrelaySession.appid == appid)) {
  238. // We found an exact match, we are all setup already, redirect to root
  239. res.redirect('/');
  240. return;
  241. }
  242. // Check that the user has rights to access this device
  243. parent.webserver.GetNodeWithRights(domain, userid, nodeid, function (node, rights, visible) {
  244. // If there is no remote control or relay rights, reject this web relay
  245. if ((rights & 0x00200008) == 0) { res.sendStatus(404); return; } // MESHRIGHT_REMOTECONTROL or MESHRIGHT_RELAY
  246. // There is a relay session, but it's not correct, close it.
  247. if (xrelaySession != null) { xrelaySession.close(); delete relaySessions[webSessionId]; }
  248. // Create a web relay session
  249. const relaySession = require('./apprelays.js').CreateWebRelaySession(obj, db, req, args, domain, userid, nodeid, addr, port, appid, webSessionId, expire, node.mtype);
  250. relaySession.xpublicid = publicid;
  251. relaySession.onclose = function (sessionId) {
  252. // Remove the relay session
  253. delete relaySessions[sessionId];
  254. // If there are not more relay sessions, clear the cleanup timer
  255. if ((Object.keys(relaySessions).length == 0) && (obj.cleanupTimer != null)) { clearInterval(obj.cleanupTimer); obj.cleanupTimer = null; }
  256. }
  257. // Set the multi-tunnel session
  258. relaySessions[webSessionId] = relaySession;
  259. // Setup the cleanup timer if needed
  260. if (obj.cleanupTimer == null) { obj.cleanupTimer = setInterval(checkTimeout, 10000); }
  261. // Redirect to root
  262. res.redirect('/');
  263. });
  264. });
  265. }
  266. // Check that everything is cleaned up
  267. function checkTimeout() {
  268. for (var i in relaySessions) { relaySessions[i].checkTimeout(); }
  269. }
  270. // Find a free port starting with the specified one and going up.
  271. function CheckListenPort(port, addr, func) {
  272. var s = obj.net.createServer(function (socket) { });
  273. obj.webRelayServer = s.listen(port, addr, function () { s.close(function () { if (func) { func(port, addr); } }); }).on("error", function (err) {
  274. if (args.exactports) { console.error("ERROR: MeshCentral HTTP relay server port " + port + " not available."); process.exit(); }
  275. else { if (port < 65535) { CheckListenPort(port + 1, addr, func); } else { if (func) { func(0); } } }
  276. });
  277. }
  278. // Start the ExpressJS web server, if the port is busy try the next one.
  279. function StartWebRelayServer(port, addr) {
  280. if (port == 0 || port == 65535) { return; }
  281. if (obj.tlsServer != null) {
  282. if (args.lanonly == true) {
  283. obj.tcpServer = obj.tlsServer.listen(port, addr, function () { console.log('MeshCentral HTTPS relay server running on port ' + port + ((typeof args.relayaliasport == 'number') ? (', alias port ' + args.relayaliasport) : '') + '.'); });
  284. } else {
  285. obj.tcpServer = obj.tlsServer.listen(port, addr, function () { console.log('MeshCentral HTTPS relay server running on ' + certificates.CommonName + ':' + port + ((typeof args.relayaliasport == 'number') ? (', alias port ' + args.relayaliasport) : '') + '.'); });
  286. obj.parent.updateServerState('servername', certificates.CommonName);
  287. }
  288. if (obj.parent.authlog) { obj.parent.authLog('https', 'Web relay server listening on ' + ((addr != null) ? addr : '0.0.0.0') + ' port ' + port + '.'); }
  289. obj.parent.updateServerState('https-relay-port', port);
  290. if (typeof args.relayaliasport == 'number') { obj.parent.updateServerState('https-relay-aliasport', args.relayaliasport); }
  291. } else {
  292. obj.tcpServer = obj.app.listen(port, addr, function () { console.log('MeshCentral HTTP relay server running on port ' + port + ((typeof args.relayaliasport == 'number') ? (', alias port ' + args.relayaliasport) : '') + '.'); });
  293. obj.parent.updateServerState('http-relay-port', port);
  294. if (typeof args.relayaliasport == 'number') { obj.parent.updateServerState('http-relay-aliasport', args.relayaliasport); }
  295. }
  296. obj.port = port;
  297. }
  298. function getRandomPassword() { return Buffer.from(require('crypto').randomBytes(9), 'binary').toString('base64').split('/').join('@'); }
  299. // Perform a IP match against a list
  300. function isIPMatch(ip, matchList) {
  301. const ipcheck = require('ipcheck');
  302. for (var i in matchList) { if (ipcheck.match(ip, matchList[i]) == true) return true; }
  303. return false;
  304. }
  305. // Start up the web relay server
  306. serverStart();
  307. CheckListenPort(args.relayport, args.relayportbind, StartWebRelayServer);
  308. return obj;
  309. };