UNPKG

meshcentral

Version:

Web based remote computer management server

904 lines (811 loc) • 137 kB
/** * @description MeshCentral MSTSC & SSH relay * @author Ylian Saint-Hilaire & Bryan Roe * @copyright Intel Corporation 2018-2022 * @license Apache-2.0 * @version v0.0.1 */ /*jslint node: true */ /*jshint node: true */ /*jshint strict:false */ /*jshint -W097 */ /*jshint esversion: 6 */ "use strict"; /* Protocol numbers 10 = RDP 11 = SSH-TERM 12 = VNC 13 = SSH-FILES 14 = Web-TCP */ // Protocol Numbers const PROTOCOL_TERMINAL = 1; const PROTOCOL_DESKTOP = 2; const PROTOCOL_FILES = 5; const PROTOCOL_AMTWSMAN = 100; const PROTOCOL_AMTREDIR = 101; const PROTOCOL_MESSENGER = 200; const PROTOCOL_WEBRDP = 201; const PROTOCOL_WEBSSH = 202; const PROTOCOL_WEBSFTP = 203; const PROTOCOL_WEBVNC = 204; // Mesh Rights const MESHRIGHT_EDITMESH = 0x00000001; // 1 const MESHRIGHT_MANAGEUSERS = 0x00000002; // 2 const MESHRIGHT_MANAGECOMPUTERS = 0x00000004; // 4 const MESHRIGHT_REMOTECONTROL = 0x00000008; // 8 const MESHRIGHT_AGENTCONSOLE = 0x00000010; // 16 const MESHRIGHT_SERVERFILES = 0x00000020; // 32 const MESHRIGHT_WAKEDEVICE = 0x00000040; // 64 const MESHRIGHT_SETNOTES = 0x00000080; // 128 const MESHRIGHT_REMOTEVIEWONLY = 0x00000100; // 256 const MESHRIGHT_NOTERMINAL = 0x00000200; // 512 const MESHRIGHT_NOFILES = 0x00000400; // 1024 const MESHRIGHT_NOAMT = 0x00000800; // 2048 const MESHRIGHT_DESKLIMITEDINPUT = 0x00001000; // 4096 const MESHRIGHT_LIMITEVENTS = 0x00002000; // 8192 const MESHRIGHT_CHATNOTIFY = 0x00004000; // 16384 const MESHRIGHT_UNINSTALL = 0x00008000; // 32768 const MESHRIGHT_NODESKTOP = 0x00010000; // 65536 const MESHRIGHT_REMOTECOMMAND = 0x00020000; // 131072 const MESHRIGHT_RESETOFF = 0x00040000; // 262144 const MESHRIGHT_GUESTSHARING = 0x00080000; // 524288 const MESHRIGHT_DEVICEDETAILS = 0x00100000; // 1048576 const MESHRIGHT_RELAY = 0x00200000; // 2097152 const MESHRIGHT_ADMIN = 0xFFFFFFFF; // SerialTunnel object is used to embed TLS within another connection. function SerialTunnel(options) { var obj = new require('stream').Duplex(options); obj.forwardwrite = null; obj.updateBuffer = function (chunk) { this.push(chunk); }; obj._write = function (chunk, encoding, callback) { if (obj.forwardwrite != null) { obj.forwardwrite(chunk); } else { console.err("Failed to fwd _write."); } if (callback) callback(); }; // Pass data written to forward obj._read = function (size) { }; // Push nothing, anything to read should be pushed from updateBuffer() return obj; } // Construct a Web relay object module.exports.CreateWebRelaySession = function (parent, db, req, args, domain, userid, nodeid, addr, port, appid, sessionid, expire, mtype) { const obj = {}; obj.parent = parent; obj.lastOperation = Date.now(); obj.domain = domain; obj.userid = userid; obj.nodeid = nodeid; obj.addr = addr; obj.port = port; obj.appid = appid; obj.sessionid = sessionid; obj.expireTimer = null; obj.mtype = mtype; var pendingRequests = []; var nextTunnelId = 1; var tunnels = {}; var errorCount = 0; // If we keep closing tunnels without processing requests, fail the requests parent.parent.debug('webrelay', 'CreateWebRelaySession, userid:' + userid + ', addr:' + addr + ', port:' + port); // Any HTTP cookie set by the device is going to be shared between all tunnels to that device. obj.webCookies = {}; // Setup an expire time if needed if (expire != null) { var timeout = (expire - Date.now()); if (timeout < 10) { timeout = 10; } parent.parent.debug('webrelay', 'timeout set to ' + Math.floor(timeout / 1000) + ' second(s).'); obj.expireTimer = setTimeout(function () { parent.parent.debug('webrelay', 'timeout'); close(); }, timeout); } // Events obj.closed = false; obj.onclose = null; // Check if any tunnels need to be cleaned up obj.checkTimeout = function () { const limit = Date.now() - (1 * 60 * 1000); // This is is 5 minutes before current time // Close any old non-websocket tunnels const tunnelToRemove = []; for (var i in tunnels) { if ((tunnels[i].lastOperation < limit) && (tunnels[i].isWebSocket !== true)) { tunnelToRemove.push(tunnels[i]); } } for (var i in tunnelToRemove) { tunnelToRemove[i].close(); } // Close this session if no longer used if (obj.lastOperation < limit) { var count = 0; for (var i in tunnels) { count++; } if (count == 0) { close(); } // Time limit reached and no tunnels, clean up. } } // Handle new HTTP request obj.handleRequest = function (req, res) { parent.parent.debug('webrelay', 'handleRequest, url:' + req.url); pendingRequests.push([req, res, false]); handleNextRequest(); } // Handle new websocket request obj.handleWebSocket = function (ws, req) { parent.parent.debug('webrelay', 'handleWebSocket, url:' + req.url); pendingRequests.push([req, ws, true]); handleNextRequest(); } // Handle request function handleNextRequest() { if (obj.closed == true) return; // if there are not pending requests, do nothing if (pendingRequests.length == 0) return; // If the errorCount is high, something is really wrong, we are opening lots of tunnels and not processing any requests. if (errorCount > 5) { close(); return; } // Check to see if any of the tunnels are free var count = 0; for (var i in tunnels) { count += ((tunnels[i].isWebSocket || tunnels[i].isStreaming) ? 0 : 1); if ((tunnels[i].relayActive == true) && (tunnels[i].res == null) && (tunnels[i].isWebSocket == false) && (tunnels[i].isStreaming == false)) { // Found a free tunnel, use it const x = pendingRequests.shift(); if (x[2] == true) { tunnels[i].processWebSocket(x[0], x[1]); } else { tunnels[i].processRequest(x[0], x[1]); } return; } } if (count > 0) return; launchNewTunnel(); } function launchNewTunnel() { // Launch a new tunnel if (obj.closed == true) return; parent.parent.debug('webrelay', 'launchNewTunnel'); const tunnel = module.exports.CreateWebRelay(obj, db, args, domain, obj.mtype); tunnel.onclose = function (tunnelId, processedCount) { if (tunnels == null) return; parent.parent.debug('webrelay', 'tunnel-onclose'); if (processedCount == 0) { errorCount++; } // If this tunnel closed without processing any requests, mark this as an error delete tunnels[tunnelId]; handleNextRequest(); } tunnel.onconnect = function (tunnelId) { if (tunnels == null) return; parent.parent.debug('webrelay', 'tunnel-onconnect'); if (pendingRequests.length > 0) { const x = pendingRequests.shift(); if (x[2] == true) { tunnels[tunnelId].processWebSocket(x[0], x[1]); } else { tunnels[tunnelId].processRequest(x[0], x[1]); } } } tunnel.oncompleted = function (tunnelId, closed) { if (tunnels == null) return; if (closed === true) { parent.parent.debug('webrelay', 'tunnel-oncompleted and closed'); } else { parent.parent.debug('webrelay', 'tunnel-oncompleted'); } if (closed !== true) { errorCount = 0; // Something got completed, clear any error count if (pendingRequests.length > 0) { const x = pendingRequests.shift(); if (x[2] == true) { tunnels[tunnelId].processWebSocket(x[0], x[1]); } else { tunnels[tunnelId].processRequest(x[0], x[1]); } } } } tunnel.onNextRequest = function () { if (tunnels == null) return; parent.parent.debug('webrelay', 'tunnel-onNextRequest'); handleNextRequest(); } tunnel.connect(userid, nodeid, addr, port, appid); tunnel.tunnelId = nextTunnelId++; tunnels[tunnel.tunnelId] = tunnel; } // Close all tunnels obj.close = function () { close(); } // Close all tunnels function close() { // Set the session as closed if (obj.closed == true) return; parent.parent.debug('webrelay', 'tunnel-close'); obj.closed = true; // Clear the time if present if (obj.expireTimer != null) { clearTimeout(obj.expireTimer); delete obj.expireTimer; } // Close all tunnels for (var i in tunnels) { tunnels[i].close(); } tunnels = null; // Close any pending requests for (var i in pendingRequests) { if (pendingRequests[i][2] == true) { pendingRequests[i][1].close(); } else { pendingRequests[i][1].end(); } } // Notify of session closure if (obj.onclose) { obj.onclose(obj.sessionid); } // Cleanup delete obj.userid; delete obj.lastOperation; } return obj; } // Construct a Web relay object module.exports.CreateWebRelay = function (parent, db, args, domain, mtype) { //const Net = require('net'); const WebSocket = require('ws') const obj = {}; obj.lastOperation = Date.now(); obj.relayActive = false; obj.closed = false; obj.isWebSocket = false; // If true, this request will not close and so, it can't be allowed to hold up other requests obj.isStreaming = false; // If true, this request will not close and so, it can't be allowed to hold up other requests obj.processedRequestCount = 0; obj.mtype = mtype; const constants = (require('crypto').constants ? require('crypto').constants : require('constants')); // require('constants') is deprecated in Node 11.10, use require('crypto').constants instead. // Events obj.onclose = null; obj.oncompleted = null; obj.onconnect = null; obj.onNextRequest = null; // Called when we need to close the tunnel because the response stream has closed function handleResponseClosure() { obj.close(); } // Return cookie name and values function parseRequestCookies(cookiesString) { var r = {}; if (typeof cookiesString != 'string') return r; var cookieString = cookiesString.split('; '); for (var i in cookieString) { var j = cookieString[i].indexOf('='); if (j > 0) { r[cookieString[i].substring(0, j)] = cookieString[i].substring(j + 1); } } return r; } // Process a HTTP request obj.processRequest = function (req, res) { if (obj.relayActive == false) { console.log("ERROR: Attempt to use an unconnected tunnel"); return false; } parent.lastOperation = obj.lastOperation = Date.now(); // Check if this is a websocket if (req.headers['upgrade'] == 'websocket') { console.log('Attempt to process a websocket in HTTP tunnel method.'); res.end(); return false; } // If the response stream is closed, close this tunnel right away res.socket.on('end', handleResponseClosure); // Construct the HTTP request var request = req.method + ' ' + req.url + ' HTTP/' + req.httpVersion + '\r\n'; const blockedHeaders = ['cookie', 'upgrade-insecure-requests', 'sec-ch-ua', 'sec-ch-ua-mobile', 'dnt', 'sec-fetch-user', 'sec-ch-ua-platform', 'sec-fetch-site', 'sec-fetch-mode', 'sec-fetch-dest']; // These are headers we do not forward for (var i in req.headers) { if (blockedHeaders.indexOf(i) == -1) { request += i + ': ' + req.headers[i] + '\r\n'; } } var cookieStr = ''; for (var i in parent.webCookies) { if (cookieStr != '') { cookieStr += '; ' } cookieStr += (i + '=' + parent.webCookies[i].value); } var reqCookies = parseRequestCookies(req.headers.cookie); for (var i in reqCookies) { if ((i != 'xid') && (i != 'xid.sig')) { if (cookieStr != '') { cookieStr += '; ' } cookieStr += (i + '=' + reqCookies[i]); } } if (cookieStr.length > 0) { request += 'cookie: ' + cookieStr + '\r\n' } // If we have session cookies, set them in the header here request += '\r\n'; if (req.headers['content-length'] != null) { // Stream the HTTP request and body, this is a content-length HTTP request, just forward the body data send(Buffer.from(request)); req.on('data', function (data) { send(data); }); // TODO: Flow control (Not sure how to do this in ExpressJS) req.on('end', function () { }); } else if (req.headers['transfer-encoding'] != null) { // Stream the HTTP request and body, this is a chunked encoded HTTP request // TODO: Flow control (Not sure how to do this in ExpressJS) send(Buffer.from(request)); req.on('data', function (data) { send(Buffer.concat([Buffer.from(data.length.toString(16) + '\r\n', 'binary'), data, send(Buffer.from('\r\n', 'binary'))])); }); req.on('end', function () { send(Buffer.from('0\r\n\r\n', 'binary')); }); } else { // Request has no body, send it now send(Buffer.from(request)); } obj.res = res; } // Process a websocket request obj.processWebSocket = function (req, ws) { if (obj.relayActive == false) { console.log("ERROR: Attempt to use an unconnected tunnel"); return false; } parent.lastOperation = obj.lastOperation = Date.now(); // Mark this tunnel as being a web socket tunnel obj.isWebSocket = true; obj.ws = ws; // Pause the websocket until we get a tunnel connected obj.ws._socket.pause(); // If the response stream is closed, close this tunnel right away obj.ws._socket.on('end', function () { obj.close(); }); // Remove the trailing '/.websocket' if needed var baseurl = req.url, i = req.url.indexOf('?'); if (i > 0) { baseurl = req.url.substring(0, i); } if (baseurl.endsWith('/.websocket')) { req.url = baseurl.substring(0, baseurl.length - 11) + ((i < 1) ? '' : req.url.substring(i)); } // Construct the HTTP request var request = req.method + ' ' + req.url + ' HTTP/' + req.httpVersion + '\r\n'; const blockedHeaders = ['cookie', 'sec-websocket-extensions']; // These are headers we do not forward for (var i in req.headers) { if (blockedHeaders.indexOf(i) == -1) { request += i + ': ' + req.headers[i] + '\r\n'; } } var cookieStr = ''; for (var i in parent.webCookies) { if (cookieStr != '') { cookieStr += '; ' } cookieStr += (i + '=' + parent.webCookies[i].value); } if (cookieStr.length > 0) { request += 'cookie: ' + cookieStr + '\r\n' } // If we have session cookies, set them in the header here request += '\r\n'; send(Buffer.from(request)); // Hook up the websocket events obj.ws.on('message', function (data) { // Setup opcode and payload var op = 2, payload = data; if (typeof data == 'string') { op = 1; payload = Buffer.from(data, 'binary'); } // Text frame sendWebSocketFrameToDevice(op, payload); }); obj.ws.on('ping', function (data) { sendWebSocketFrameToDevice(9, data); }); // Forward ping frame obj.ws.on('pong', function (data) { sendWebSocketFrameToDevice(10, data); }); // Forward pong frame obj.ws.on('close', function () { obj.close(); }); obj.ws.on('error', function (err) { obj.close(); }); } function sendWebSocketFrameToDevice(op, payload) { // Select a random mask const mask = parent.parent.parent.crypto.randomBytes(4) // Setup header and mask var header = null; if (payload.length < 126) { header = Buffer.alloc(6); // Header (2) + Mask (4) header[0] = 0x80 + op; // FIN + OP header[1] = 0x80 + payload.length; // Mask + Length mask.copy(header, 2, 0, 4); // Copy the mask } else if (payload.length <= 0xFFFF) { header = Buffer.alloc(8); // Header (2) + Length (2) + Mask (4) header[0] = 0x80 + op; // FIN + OP header[1] = 0x80 + 126; // Mask + 126 header.writeInt16BE(payload.length, 2); // Payload size mask.copy(header, 4, 0, 4); // Copy the mask } else { header = Buffer.alloc(14); // Header (2) + Length (8) + Mask (4) header[0] = 0x80 + op; // FIN + OP header[1] = 0x80 + 127; // Mask + 127 header.writeInt32BE(payload.length, 6); // Payload size mask.copy(header, 10, 0, 4); // Copy the mask } // Mask the payload for (var i = 0; i < payload.length; i++) { payload[i] = (payload[i] ^ mask[i % 4]); } // Send the frame //console.log(obj.tunnelId, '-->', op, payload.length); send(Buffer.concat([header, payload])); } // Disconnect obj.close = function (arg) { if (obj.closed == true) return; obj.closed = true; // If we are processing a http response that terminates when it closes, do this now. if ((obj.socketParseState == 1) && (obj.socketXHeader['connection'] != null) && (obj.socketXHeader['connection'].toLowerCase() == 'close')) { processHttpResponse(null, obj.socketAccumulator, true, true); // Indicate this tunnel is done and also closed, do not put a new request on this tunnel. obj.socketAccumulator = ''; obj.socketParseState = 0; } if (obj.tls) { try { obj.tls.end(); } catch (ex) { console.log(ex); } delete obj.tls; } /* // Event the session ending if ((obj.startTime) && (obj.meshid != null)) { // Collect how many raw bytes where received and sent. // We sum both the websocket and TCP client in this case. var inTraffc = obj.ws._socket.bytesRead, outTraffc = obj.ws._socket.bytesWritten; if (obj.wsClient != null) { inTraffc += obj.wsClient._socket.bytesRead; outTraffc += obj.wsClient._socket.bytesWritten; } const sessionSeconds = Math.round((Date.now() - obj.startTime) / 1000); const user = parent.users[obj.cookie.userid]; const username = (user != null) ? user.name : null; const event = { etype: 'relay', action: 'relaylog', domain: domain.id, nodeid: obj.nodeid, userid: obj.cookie.userid, username: username, sessionid: obj.sessionid, msgid: 123, msgArgs: [sessionSeconds, obj.sessionid], msg: "Left Web-SSH session \"" + obj.sessionid + "\" after " + sessionSeconds + " second(s).", protocol: PROTOCOL_WEBSSH, bytesin: inTraffc, bytesout: outTraffc }; parent.DispatchEvent(['*', obj.nodeid, obj.cookie.userid, obj.meshid], obj, event); delete obj.startTime; delete obj.sessionid; } */ if (obj.wsClient) { obj.wsClient.removeAllListeners('open'); obj.wsClient.removeAllListeners('message'); obj.wsClient.removeAllListeners('close'); try { obj.wsClient.close(); } catch (ex) { console.log(ex); } delete obj.wsClient; } // Close any pending request if (obj.res) { obj.res.socket.removeListener('end', handleResponseClosure); obj.res.end(); delete obj.res; } if (obj.ws) { obj.ws.close(); delete obj.ws; } // Event disconnection if (obj.onclose) { obj.onclose(obj.tunnelId, obj.processedRequestCount); } obj.relayActive = false; }; // Start the loopback server obj.connect = function (userid, nodeid, addr, port, appid) { if (obj.relayActive || obj.closed) return; obj.addr = addr; obj.port = port; obj.appid = appid; // Encode a cookie for the mesh relay const cookieContent = { userid: userid, domainid: domain.id, nodeid: nodeid, tcpport: port }; if (addr != null) { cookieContent.tcpaddr = addr; } const cookie = parent.parent.parent.encodeCookie(cookieContent, parent.parent.parent.loginCookieEncryptionKey); try { // Setup the correct URL with domain and use TLS only if needed. const options = { rejectUnauthorized: false }; const protocol = (args.tlsoffload) ? 'ws' : 'wss'; var domainadd = ''; if ((domain.dns == null) && (domain.id != '')) { domainadd = domain.id + '/' } var url = protocol + '://localhost:' + args.port + '/' + domainadd + (((obj.mtype == 3) && (obj.relaynodeid == null)) ? 'local' : 'mesh') + 'relay.ashx?p=14&auth=' + cookie; // Protocol 14 is Web-TCP if (domain.id != '') { url += '&domainid=' + domain.id; } // Since we are using "localhost", we are going to signal what domain we are on using a URL argument. parent.parent.parent.debug('relay', 'TCP: Connection websocket to ' + url); obj.wsClient = new WebSocket(url, options); obj.wsClient.on('open', function () { parent.parent.parent.debug('relay', 'TCP: Relay websocket open'); }); obj.wsClient.on('message', function (data) { // Make sure to handle flow control. if (obj.tls) { // WS --> TLS processRawHttpData(data); } else if (obj.relayActive == false) { if ((data == 'c') || (data == 'cr')) { if (appid == 2) { // TLS needs to be setup obj.ser = new SerialTunnel(); obj.ser.forwardwrite = function (data) { if (data.length > 0) { try { obj.wsClient.send(data); } catch (ex) { } } }; // TLS ---> WS // TLSSocket to encapsulate TLS communication, which then tunneled via SerialTunnel const tlsoptions = { socket: obj.ser, rejectUnauthorized: false }; obj.tls = require('tls').connect(tlsoptions, function () { parent.parent.parent.debug('relay', "Web Relay Secure TLS Connection"); obj.relayActive = true; parent.lastOperation = obj.lastOperation = Date.now(); // Update time of last opertion performed if (obj.onconnect) { obj.onconnect(obj.tunnelId); } // Event connection }); obj.tls.setEncoding('binary'); obj.tls.on('error', function (err) { parent.parent.parent.debug('relay', "Web Relay TLS Connection Error", err); obj.close(); }); // Decrypted tunnel from TLS communcation to be forwarded to the browser obj.tls.on('data', function (data) { processHttpData(data); }); // TLS ---> Browser } else { // No TLS needed, tunnel is now active obj.relayActive = true; parent.lastOperation = obj.lastOperation = Date.now(); // Update time of last opertion performed if (obj.onconnect) { obj.onconnect(obj.tunnelId); } // Event connection } } } else { processRawHttpData(data); } }); obj.wsClient.on('close', function () { parent.parent.parent.debug('relay', 'TCP: Relay websocket closed'); obj.close(); }); obj.wsClient.on('error', function (err) { parent.parent.parent.debug('relay', 'TCP: Relay websocket error: ' + err); obj.close(); }); } catch (ex) { console.log(ex); } } function processRawHttpData(data) { if (typeof data == 'string') { // Forward any ping/pong commands to the browser var cmd = null; try { cmd = JSON.parse(data); } catch (ex) { } if ((cmd != null) && (cmd.ctrlChannel == '102938') && (cmd.type == 'ping')) { cmd.type = 'pong'; obj.wsClient.send(JSON.stringify(cmd)); } return; } if (obj.tls) { // If TLS is in use, WS --> TLS if (data.length > 0) { try { obj.ser.updateBuffer(data); } catch (ex) { console.log(ex); } } } else { // Relay WS --> TCP, event data coming in processHttpData(data.toString('binary')); } } // Process incoming HTTP data obj.socketAccumulator = ''; obj.socketParseState = 0; obj.socketContentLengthRemaining = 0; function processHttpData(data) { //console.log('processHttpData', data.length); obj.socketAccumulator += data; while (true) { //console.log('ACC(' + obj.socketAccumulator + '): ' + obj.socketAccumulator); if (obj.socketParseState == 0) { var headersize = obj.socketAccumulator.indexOf('\r\n\r\n'); if (headersize < 0) return; //obj.Debug("Header: "+obj.socketAccumulator.substring(0, headersize)); // Display received HTTP header obj.socketHeader = obj.socketAccumulator.substring(0, headersize).split('\r\n'); obj.socketAccumulator = obj.socketAccumulator.substring(headersize + 4); obj.socketXHeader = { Directive: obj.socketHeader[0].split(' ') }; for (var i in obj.socketHeader) { if (i != 0) { var x2 = obj.socketHeader[i].indexOf(':'); const n = obj.socketHeader[i].substring(0, x2).toLowerCase(); const v = obj.socketHeader[i].substring(x2 + 2); if (n == 'set-cookie') { // Since "set-cookie" can be present many times in the header, handle it as an array of values if (obj.socketXHeader[n] == null) { obj.socketXHeader[n] = [v]; } else { obj.socketXHeader[n].push(v); } } else { obj.socketXHeader[n] = v; } } } // Check if this is a streaming response if ((obj.socketXHeader['content-type'] != null) && (obj.socketXHeader['content-type'].toLowerCase().indexOf('text/event-stream') >= 0)) { obj.isStreaming = true; // This tunnel is now a streaming tunnel and will not close anytime soon. if (obj.onNextRequest != null) obj.onNextRequest(); // Call this so that any HTTP requests that are waitting for this one to finish get handled by a new tunnel. } // Check if this HTTP request has a body if (obj.socketXHeader['content-length'] != null) { obj.socketParseState = 1; } if ((obj.socketXHeader['connection'] != null) && (obj.socketXHeader['connection'].toLowerCase() == 'close')) { obj.socketParseState = 1; } if ((obj.socketXHeader['transfer-encoding'] != null) && (obj.socketXHeader['transfer-encoding'].toLowerCase() == 'chunked')) { obj.socketParseState = 1; } if (obj.isWebSocket) { if ((obj.socketXHeader['connection'] != null) && (obj.socketXHeader['connection'].toLowerCase() == 'upgrade')) { obj.processedRequestCount++; obj.socketParseState = 2; // Switch to decoding websocket frames obj.ws._socket.resume(); // Resume the browser's websocket } else { obj.close(); // Failed to upgrade to websocket } } // Forward the HTTP request into the tunnel, if no body is present, close the request. processHttpResponse(obj.socketXHeader, null, (obj.socketParseState == 0)); } if (obj.socketParseState == 1) { var csize = -1; if (obj.socketXHeader['content-length'] != null) { // The body length is specified by the content-length if (obj.socketContentLengthRemaining == 0) { obj.socketContentLengthRemaining = parseInt(obj.socketXHeader['content-length']); } // Set the remaining content-length if not set var data = obj.socketAccumulator.substring(0, obj.socketContentLengthRemaining); // Grab the available data, not passed the expected content-length obj.socketAccumulator = obj.socketAccumulator.substring(data.length); // Remove the data from the accumulator obj.socketContentLengthRemaining -= data.length; // Substract the obtained data from the expected size if (obj.socketContentLengthRemaining > 0) { // Send any data we have, if we are done, signal the end of the response processHttpResponse(null, data, false); return; // More data is needed, return now so we exit the while() loop. } else { // We are done with this request const closing = (obj.socketXHeader['connection'] != null) && (obj.socketXHeader['connection'].toLowerCase() == 'close'); if (closing) { // We need to close this tunnel. processHttpResponse(null, data, false); obj.close(); } else { // Proceed with the next request. processHttpResponse(null, data, true); } } csize = 0; // We are done } else if ((obj.socketXHeader['connection'] != null) && (obj.socketXHeader['connection'].toLowerCase() == 'close')) { // The body ends with a close, in this case, we will only process the header processHttpResponse(null, obj.socketAccumulator, false); obj.socketAccumulator = ''; return; } else if ((obj.socketXHeader['transfer-encoding'] != null) && (obj.socketXHeader['transfer-encoding'].toLowerCase() == 'chunked')) { // The body is chunked var clen = obj.socketAccumulator.indexOf('\r\n'); if (clen < 0) { return; } // Chunk length not found, exit now and get more data. // Chunk length if found, lets see if we can get the data. csize = parseInt(obj.socketAccumulator.substring(0, clen), 16); if (obj.socketAccumulator.length < clen + 2 + csize + 2) return; // We got a chunk with all of the data, handle the chunck now. var data = obj.socketAccumulator.substring(clen + 2, clen + 2 + csize); obj.socketAccumulator = obj.socketAccumulator.substring(clen + 2 + csize + 2); processHttpResponse(null, data, (csize == 0)); } if (csize == 0) { //obj.Debug("xxOnSocketData DONE: (" + obj.socketData.length + "): " + obj.socketData); obj.socketParseState = 0; obj.socketHeader = null; } } if (obj.socketParseState == 2) { // We are in websocket pass-thru mode, decode the websocket frame if (obj.socketAccumulator.length < 2) return; // Need at least 2 bytes to decode a websocket header //console.log('WebSocket frame', obj.socketAccumulator.length, Buffer.from(obj.socketAccumulator, 'binary')); // Decode the websocket frame const buf = Buffer.from(obj.socketAccumulator, 'binary'); const fin = ((buf[0] & 0x80) != 0); const rsv = ((buf[0] & 0x70) != 0); const op = buf[0] & 0x0F; const mask = ((buf[1] & 0x80) != 0); var len = buf[1] & 0x7F; //console.log(obj.tunnelId, 'fin: ' + fin + ', rsv: ' + rsv + ', op: ' + op + ', len: ' + len); // Calculate the total length var payload = null; if (len < 126) { // 1 byte length if (buf.length < (2 + len)) return; // Insuffisent data payload = buf.slice(2, 2 + len); obj.socketAccumulator = obj.socketAccumulator.substring(2 + len); // Remove data from accumulator } else if (len == 126) { // 2 byte length if (buf.length < 4) return; len = buf.readUInt16BE(2); if (buf.length < (4 + len)) return; // Insuffisent data payload = buf.slice(4, 4 + len); obj.socketAccumulator = obj.socketAccumulator.substring(4 + len); // Remove data from accumulator } if (len == 127) { // 8 byte length if (buf.length < 10) return; len = buf.readUInt32BE(2); if (len > 0) { obj.close(); return; } // This frame is larger than 4 gigabyte, close the connection. len = buf.readUInt32BE(6); if (buf.length < (10 + len)) return; // Insuffisent data payload = buf.slice(10, 10 + len); obj.socketAccumulator = obj.socketAccumulator.substring(10 + len); // Remove data from accumulator } if (buf.length < len) return; // If the mask or reserved bit are true, we are not decoding this right, close the connection. if ((mask == true) || (rsv == true)) { obj.close(); return; } // TODO: If FIN is not set, we need to add support for continue frames //console.log(obj.tunnelId, '<--', op, payload ? payload.length : 0); // Perform operation switch (op) { case 0: { break; } // Continue frame (TODO) case 1: { try { obj.ws.send(payload.toString('binary')); } catch (ex) { } break; } // Text frame case 2: { try { obj.ws.send(payload); } catch (ex) { } break; } // Binary frame case 8: { obj.close(); return; } // Connection close case 9: { try { obj.ws.ping(payload); } catch (ex) { } break; } // Ping frame case 10: { try { obj.ws.pong(payload); } catch (ex) { } break; } // Pong frame } } } } // This is a fully parsed HTTP response from the remote device function processHttpResponse(header, data, done, closed) { //console.log('processHttpResponse', header, data ? data.length : 0, done, closed); if (obj.isWebSocket == false) { if (obj.res == null) return; parent.lastOperation = obj.lastOperation = Date.now(); // Update time of last opertion performed // If there is a header, send it if (header != null) { const statusCode = parseInt(header.Directive[1]); if ((!isNaN(statusCode)) && (statusCode > 0) && (statusCode <= 999)) { obj.res.status(statusCode); } // Set the status const blockHeaders = ['Directive', 'sec-websocket-extensions', 'connection', 'transfer-encoding', 'last-modified', 'content-security-policy', 'cache-control']; // We do not forward these headers for (var i in header) { if (i == 'set-cookie') { for (var ii in header[i]) { // Decode the new cookie //console.log('set-cookie', header[i][ii]); const cookieSplit = header[i][ii].split(';'); var newCookieName = null, newCookie = {}; for (var j in cookieSplit) { var l = cookieSplit[j].indexOf('='), k = null, v = null; if (l == -1) { k = cookieSplit[j].trim(); } else { k = cookieSplit[j].substring(0, l).trim(); v = cookieSplit[j].substring(l + 1).trim(); } if (j == 0) { newCookieName = k; newCookie.value = v; } else { newCookie[k.toLowerCase()] = (v == null) ? true : v; } } if (newCookieName != null) { if ((typeof newCookie['max-age'] == 'string') && (parseInt(newCookie['max-age']) <= 0)) { delete parent.webCookies[newCookieName]; // Remove a expired cookie //console.log('clear-cookie', newCookieName); } else if (((newCookie.secure != true) || (obj.tls != null))) { parent.webCookies[newCookieName] = newCookie; // Keep this cookie in the session if (newCookie.httponly != true) { obj.res.set(i, header[i]); } // if the cookie is not HTTP-only, forward it to the browser. We need to do this to allow JavaScript to read it. //console.log('new-cookie', newCookieName, newCookie); } } } } else if (blockHeaders.indexOf(i) == -1) { obj.res.set(i.trim(), header[i]); } // Set the headers if not blocked } // Dont set any Content-Security-Policy at all because some applications like Node-Red, access external websites from there javascript which would be forbidden by the below CSP //obj.res.set('Content-Security-Policy', "default-src 'self' 'unsafe-inline' 'unsafe-eval' data: blob:;"); // Set an "allow all" policy, see if the can restrict this in the future //obj.res.set('Content-Security-Policy', "default-src * 'unsafe-inline' 'unsafe-eval'; script-src * 'unsafe-inline' 'unsafe-eval'; connect-src * 'unsafe-inline'; img-src * data: blob: 'unsafe-inline'; frame-src *; style-src * 'unsafe-inline';"); // Set an "allow all" policy, see if the can restrict this in the future obj.res.set('Cache-Control', 'no-store'); // Tell the browser not to cache the responses since since the relay port can be used for many relays } // If there is data, send it if (data != null) { try { obj.res.write(data, 'binary'); } catch (ex) { } } // If we are done, close the response if (done == true) { // Close the response obj.res.socket.removeListener('end', handleResponseClosure); obj.res.end(); delete obj.res; // Event completion obj.processedRequestCount++; if (obj.oncompleted) { obj.oncompleted(obj.tunnelId, closed); } } } else { // Tunnel is now in web socket pass-thru mode if (header != null) { if ((typeof header.connection == 'string') && (header.connection.toLowerCase() == 'upgrade')) { // Websocket upgrade succesful obj.socketParseState = 2; } else { // Unable to upgrade to web socket obj.close(); } } } } // Send data thru the relay tunnel. Written to use TLS if needed. function send(data) { try { if (obj.tls) { obj.tls.write(data); } else { obj.wsClient.send(data); } } catch (ex) { } } parent.parent.parent.debug('relay', 'TCP: Request for web relay'); return obj; }; // Construct a MSTSC Relay object, called upon connection // This implementation does not have TLS support // This is a bit of a hack as we are going to run the RDP connection thru a loopback connection. // If the "node-rdpjs-2" module supported passing a socket, we would do something different. module.exports.CreateMstscRelay = function (parent, db, ws, req, args, domain) { const Net = require('net'); const WebSocket = require('ws'); const obj = {}; obj.ws = ws; obj.tcpServerPort = 0; obj.relayActive = false; var rdpClient = null; parent.parent.debug('relay', 'RDP: Request for RDP relay (' + req.clientIp + ')'); // Disconnect obj.close = function (arg) { if (obj.ws == null) return; // Event the session ending if ((obj.startTime) && (obj.meshid != null)) { // Collect how many raw bytes where received and sent. // We sum both the websocket and TCP client in this case. var inTraffc = obj.ws._socket.bytesRead, outTraffc = obj.ws._socket.bytesWritten; if (obj.wsClient != null) { inTraffc += obj.wsClient._socket.bytesRead; outTraffc += obj.wsClient._socket.bytesWritten; } const sessionSeconds = Math.round((Date.now() - obj.startTime) / 1000); const user = parent.users[obj.userid]; const username = (user != null) ? user.name : null; const event = { etype: 'relay', action: 'relaylog', domain: domain.id, nodeid: obj.nodeid, userid: obj.userid, username: username, sessionid: obj.sessionid, msgid: 125, msgArgs: [sessionSeconds, obj.sessionid], msg: "Left Web-RDP session \"" + obj.sessionid + "\" after " + sessionSeconds + " second(s).", protocol: PROTOCOL_WEBRDP, bytesin: inTraffc, bytesout: outTraffc }; parent.parent.DispatchEvent(['*', obj.nodeid, obj.userid, obj.meshid], obj, event); delete obj.startTime; delete obj.sessionid; } if (obj.wsClient) { obj.wsClient.close(); delete obj.wsClient; } if (obj.tcpServer) { obj.tcpServer.close(); delete obj.tcpServer; } if (rdpClient) { rdpClient.close(); rdpClient = null; } if ((arg == 1) || (arg == null)) { try { ws.close(); } catch (ex) { console.log(ex); } } // Soft close, close the websocket if (arg == 2) { try { ws._socket._parent.end(); } catch (ex) { console.log(ex); } } // Hard close, close the TCP socket obj.ws.removeAllListeners(); obj.relayActive = false; delete obj.ws; delete obj.nodeid; delete obj.meshid; delete obj.userid; }; // Start the looppback server function startTcpServer() { obj.tcpServer = new Net.Server(); obj.tcpServer.listen(0, 'localhost', function () { obj.tcpServerPort = obj.tcpServer.address().port; startRdp(obj.tcpServerPort); }); obj.tcpServer.on('connection', function (socket) { if (obj.relaySocket != null) { socket.close(); } else { obj.relaySocket = socket; obj.relaySocket.pause(); obj.relaySocket.on('data', function (chunk) { // Make sure to handle flow control. if (obj.relayActive == true) { obj.relaySocket.pause(); if (obj.wsClient != null) { obj.wsClient.send(chunk, function () { obj.relaySocket.resume(); }); } } }); obj.relaySocket.on('end', function () { obj.close(); }); obj.relaySocket.on('error', function (err) { obj.close(); }); // Setup the correct URL with domain and use TLS only if needed. const options = { rejectUnauthorized: false }; const protocol = (args.tlsoffload) ? 'ws' : 'wss'; var domainadd = ''; if ((domain.dns == null) && (domain.id != '')) { domainadd = domain.id + '/' } var url = protocol + '://localhost:' + args.port + '/' + domainadd + (((obj.mtype == 3) && (obj.relaynodeid == null)) ? 'local' : 'mesh') + 'relay.ashx?p=10&auth=' + obj.infos.ip; // Protocol 10 is Web-RDP if (domain.id != '') { url += '&domainid=' + domain.id; } // Since we are using "localhost", we are going to signal what domain we are on using a URL argument. parent.parent.debug('relay', 'RDP: Connection websocket to ' + url); obj.wsClient = new WebSocket(url, options); obj.wsClient.on('open', function () { parent.parent.debug('relay', 'RDP: Relay websocket open'); }); obj.wsClient.on('message', function (data) { // Make sure to handle flow control. if (obj.relayActive == false) { if ((data == 'c') || (data == 'cr')) { obj.relayActive = true; obj.relaySocket.resume(); } } else { try { // Forward any ping/pong commands to the browser var cmd = JSON.parse(data); if ((cmd != null) && (cmd.ctrlChannel == '102938')) { if (cmd.type == 'ping') { send(['ping']); } else if (cmd.type == 'pong') { send(['pong']); } } return; } catch (ex) { // You are not JSON data so just send over relaySocket obj.wsClient._socket.pause(); try { obj.relaySocket.write(data, function () { if (obj.wsClient && obj.wsClient._socket) { try { obj.wsClient._socket.resume(); } catch (ex) { console.log(ex); } } }); } catch (ex) { console.log(ex); obj.close(); } } } }); obj.wsClient.on('close', function () { parent.parent.debug('relay', 'RDP: Relay websocket closed'); obj.close(); }); obj.wsClient.on('error', function (err) { parent.parent.debug('relay', 'RDP: Relay websocket error: ' + err); obj.close(); }); obj.tcpServer.close(); obj.tcpServer = null; } }); } // Start the RDP client function startRdp(port) { parent.parent.debug('relay', 'RDP: Starting RDP client on loopback port ' + port); try { const args = { logLevel: 'NONE', // 'ERROR', domain: obj.infos.domain, userName: obj.infos.username, password: obj.infos.password, enablePerf: true, autoLogin: true, screen: obj.infos.screen, locale: obj.infos.locale, }; if (obj.infos.options) { if (obj.infos.options.flags != null) { args.perfFlags = obj.infos.options.flags; delete obj.infos.options.flags; } if ((obj.infos.options.workingDir != null) && (obj.infos.options.workingDir != '')) { args.workingDir = obj.infos.options.workingDir; } if ((obj.infos.options.alternateShell != null) && (obj.infos.options.alternateShell != '')) { args.alternateShell = obj.infos.options.alternateShell; } } rdpClient = require('./rdp').createClient(args).on('connect', function () { send(['rdp-connect']); if ((typeof obj.infos.options == 'object') && (obj.infos.options.savepass == true)) { saveRdpCredentials(); } // Save the credentials if needed obj.sessionid = Buffer.from(parent.crypto.randomBytes(9), 'binary').toString('base64').replace(/\+/g, '@').replace(/\//g, '$'); obj.startTime = Date.now(); // Event session start try { const user = parent.users[obj.userid]; const username = (user != null) ? user.name : null; const event = { etype: 'relay', action: 'relaylog', domain: domain.id, nodeid: obj.nodeid, userid: obj.userid, username: username, sessionid: obj.sessionid, msgid: 150, msgArgs: [obj.sessionid], msg: "Started Web-RDP session \"" + obj.sessionid + "\".", protocol: PROTOCOL_WEBRDP }; parent.parent.DispatchEvent(['*', obj.nodeid, obj.userid, obj.meshid], obj, event); } catch (ex) { console.log(ex); } }).on('bitmap', function (bitmap) { try { ws.send(bitma