Completed desktop multiplexor.

Ylian Saint-Hilaire committed Apr 28, 2020 at 12:42 UTC ccab8a43e972ef1dac14787f397c9e5ec4f3c95c
3 files changed +80 -18
meshdesktopmultiplex.js
+68 -16
@@ -57,9 +57,9 @@ MNG_ERROR = 65,
57 MNG_ENCAPSULATE_AGENT_COMMAND = 70
58 */
59
60 -function CreateDesktopMultiplexor(parent, domain, id, func) {
60 +function CreateDesktopMultiplexor(parent, domain, nodeid, func) {
61 var obj = {};
62 - obj.id = id;
62 + obj.nodeid = nodeid;
63 obj.parent = parent;
64 obj.agent = null; // Reference to the connection object that is the agent.
65 obj.viewers = []; // Array of references to all viewers.
@@ -75,6 +75,7 @@ function CreateDesktopMultiplexor(parent, domain, id, func) {
75 obj.images = {}; // Main table of indexes --> image data object.
76 obj.lastScreenSizeCmd = null; // Pointer to the last screen size command from the agent.
77 obj.lastScreenSizeCounter = 0; // Index into the image table of the screen size command, this is generally also the first command.
78 + obj.lastConsoleMessage = null; // Last agent console message.
79 obj.firstData = null; // Index in the image table of the first image in the table, generally this points to the display resolution command.
80 obj.lastData = null; // Index in the images table of the last image in the table.
81 obj.lastDisplayInfoData = null; // Pointer to the last display information command from the agent (Number of displays).
@@ -86,11 +87,12 @@ function CreateDesktopMultiplexor(parent, domain, id, func) {
87 obj.viewerConnected = false; // Set to true if one viewer attempted to connect to the agent.
88 obj.recordingFile = null; // Present if we are recording to file.
89 obj.recordingFileWriting = false; // Set to true is we are in the process if writing to the recording file.
90 + obj.startTime = null; // Starting time of the multiplex session.
91
92 // Add an agent or viewer
93 obj.addPeer = function (peer) {
94 if (peer.req.query.browser) {
93 - //console.log('addPeer-viewer', obj.id);
95 + //console.log('addPeer-viewer', obj.nodeid);
96
97 // Setup the viewer
98 if (obj.viewers.indexOf(peer) >= 0) return true;
@@ -107,8 +109,18 @@ function CreateDesktopMultiplexor(parent, domain, id, func) {
109
110 // Indicated we are connected
111 obj.sendToViewer(peer, obj.recordingFile ? 'cr' : 'c');
112 +
113 + // If the agent sent display information or console message, send it to the viewer
114 + if (obj.lastDisplayInfoData != null) { obj.sendToViewer(peer, obj.lastDisplayInfoData); }
115 + if (obj.lastConsoleMessage != null) { obj.sendToViewer(peer, obj.lastConsoleMessage); }
116 +
117 + // Log joining the multiplex session
118 + if (obj.startTime != null) {
119 + var event = { etype: 'relay', action: 'relaylog', domain: domain.id, nodeid: obj.nodeid, userid: peer.user._id, username: peer.user.name, msg: "Joined desktop multiplex session", protocol: 2 };
120 + parent.parent.DispatchEvent(['*', obj.nodeid, peer.user._id], obj, event); // TODO: Add Node MeshID to targets
121 + }
122 } else {
111 - //console.log('addPeer-agent', obj.id);
123 + //console.log('addPeer-agent', obj.nodeid);
124 if (obj.agent != null) return false;
125
126 // Setup the agent
@@ -124,6 +136,13 @@ function CreateDesktopMultiplexor(parent, domain, id, func) {
136 obj.sendToAgent('2'); // Send remote desktop connect
137 }
138 }
139 +
140 + // Log multiplex session start
141 + if ((obj.agent != null) && (obj.viewers.length > 0) && (obj.startTime == null)) {
142 + var event = { etype: 'relay', action: 'relaylog', domain: domain.id, nodeid: obj.nodeid, userid: obj.viewers[0].user._id, username: obj.viewers[0].user.name, msg: "Started desktop multiplex session", protocol: 2 };
143 + parent.parent.DispatchEvent(['*', obj.nodeid, obj.viewers[0].user._id], obj, event); // TODO: Add Node MeshID to targets
144 + obj.startTime = Date.now();
145 + }
146 return true;
147 }
148
@@ -131,7 +150,7 @@ function CreateDesktopMultiplexor(parent, domain, id, func) {
150 // Return true if this multiplexor is no longer needed.
151 obj.removePeer = function (peer) {
152 if (peer == obj.agent) {
134 - //console.log('removePeer-agent', obj.id);
153 + //console.log('removePeer-agent', obj.nodeid);
154 // Clean up the agent
155 obj.agent = null;
156
@@ -140,7 +159,7 @@ function CreateDesktopMultiplexor(parent, domain, id, func) {
159 dispose();
160 return true;
161 } else {
143 - //console.log('removePeer-viewer', obj.id);
162 + //console.log('removePeer-viewer', obj.nodeid);
163 // Remove a viewer
164 var i = obj.viewers.indexOf(peer);
165 if (i == -1) return false;
@@ -163,6 +182,12 @@ function CreateDesktopMultiplexor(parent, domain, id, func) {
182 if ((obj.viewersSendingCount < obj.viewers.length) && (obj.recordingFileWriting == false) && obj.agent && (obj.agent.paused == true)) { obj.agent.paused = false; obj.agent.ws._socket.resume(); }
183 }
184
185 + // Log leaving the multiplex session
186 + if (obj.startTime != null) {
187 + var event = { etype: 'relay', action: 'relaylog', domain: domain.id, nodeid: obj.nodeid, userid: peer.user._id, username: peer.user.name, msg: "Left the desktop multiplex session", protocol: 2 };
188 + parent.parent.DispatchEvent(['*', obj.nodeid, peer.user._id], obj, event); // TODO: Add Node MeshID to targets
189 + }
190 +
191 // If this is the last viewer, disconnect the agent
192 if ((obj.viewers.length == 0) && (obj.agent != null)) { obj.agent.close(); dispose(); return true; }
193 }
@@ -171,7 +196,7 @@ function CreateDesktopMultiplexor(parent, domain, id, func) {
196
197 // Clean up ourselves
198 function dispose() {
174 - //console.log('dispose', obj.id);
199 + //console.log('dispose', obj.nodeid);
200 delete obj.viewers;
201 delete obj.imagesCounters;
202 delete obj.images;
@@ -186,6 +211,13 @@ function CreateDesktopMultiplexor(parent, domain, id, func) {
211 if (domain.sessionrecording.index !== false) { parent.parent.certificateOperations.acceleratorPerformOperation('indexMcRec', filename); }
212 }, rf.filename);
213 }
214 +
215 + // Log end of multiplex session
216 + if (obj.startTime != null) {
217 + var event = { etype: 'relay', action: 'relaylog', domain: domain.id, nodeid: obj.nodeid, msg: "Closed desktop multiplex session" + ', ' + Math.floor((Date.now() - obj.startTime) / 1000) + ' second(s)', protocol: 2 };
218 + parent.parent.DispatchEvent(['*', obj.nodeid], obj, event); // TODO: Add Node MeshID to targets
219 + obj.startTime = null;
220 + }
221 }
222
223 // Send data to the agent or queue it up for sending
@@ -382,6 +414,9 @@ function CreateDesktopMultiplexor(parent, domain, id, func) {
414 case 10:// CTRL-ALT-DEL, forward to agent
415 obj.sendToAgent(data);
416 break;
417 + case 12:// SET DISPLAY, forward to agent
418 + obj.sendToAgent(data);
419 + break;
420 case 14:// Touch setup
421 break;
422 default:
@@ -392,7 +427,20 @@ function CreateDesktopMultiplexor(parent, domain, id, func) {
427
428 // Process incoming agent data
429 obj.processAgentData = function (data) {
395 - if ((typeof data != 'object') || (data.length < 4)) return; // Ignore all control traffic for now (WebRTC)
430 + if ((typeof data != 'object') || (data.length < 4)) {
431 + if (typeof data == 'string') {
432 + var json = null;
433 + try { json = JSON.parse(data); } catch (ex) { }
434 + if (json == null) return;
435 + if (json.type == 'console') {
436 + // This is a console message, store it and forward this to all viewers
437 + if (json.msg != null) { obj.lastConsoleMessage = data; } else { obj.lastConsoleMessage = null; }
438 + obj.sendToAllViewers(data);
439 + }
440 + // All other control messages (notably WebRTC), are ignored for now.
441 + }
442 + return; // Ignore all other traffic
443 + }
444 const jumboData = data;
445 var command = data.readUInt16BE(0);
446 var cmdsize = data.readUInt16BE(2);
@@ -532,7 +580,7 @@ function CreateDesktopMultiplexor(parent, domain, id, func) {
580 // Setup session recording
581 if ((domain.sessionrecording == true || ((typeof domain.sessionrecording == 'object') && ((domain.sessionrecording.protocols == null) || (domain.sessionrecording.protocols.indexOf(2) >= 0))))) {
582 var now = new Date(Date.now());
535 - var recFilename = 'desktopSession' + ((domain.id == '') ? '' : '-') + domain.id + '-' + now.getUTCFullYear() + '-' + parent.common.zeroPad(now.getUTCMonth(), 2) + '-' + parent.common.zeroPad(now.getUTCDate(), 2) + '-' + parent.common.zeroPad(now.getUTCHours(), 2) + '-' + parent.common.zeroPad(now.getUTCMinutes(), 2) + '-' + parent.common.zeroPad(now.getUTCSeconds(), 2) + '-' + obj.id + '.mcrec'
583 + var recFilename = 'desktopSession' + ((domain.id == '') ? '' : '-') + domain.id + '-' + now.getUTCFullYear() + '-' + parent.common.zeroPad(now.getUTCMonth(), 2) + '-' + parent.common.zeroPad(now.getUTCDate(), 2) + '-' + parent.common.zeroPad(now.getUTCHours(), 2) + '-' + parent.common.zeroPad(now.getUTCMinutes(), 2) + '-' + parent.common.zeroPad(now.getUTCSeconds(), 2) + '-' + obj.nodeid.split('/')[2] + '.mcrec'
584 var recFullFilename = null;
585 if (domain.sessionrecording.filepath) {
586 try { parent.parent.fs.mkdirSync(domain.sessionrecording.filepath); } catch (e) { }
@@ -544,7 +592,7 @@ function CreateDesktopMultiplexor(parent, domain, id, func) {
592 parent.parent.fs.open(recFullFilename, 'w', function (err, fd) {
593 if (err != null) { func(false); return; }
594 // Write the recording file header
547 - var metadata = { magic: 'MeshCentralRelaySession', ver: 1, sessionid: obj.id, time: new Date().toLocaleString(), protocol: 2 };
595 + var metadata = { magic: 'MeshCentralRelaySession', ver: 1, nodeid: obj.nodeid, time: new Date().toLocaleString(), protocol: 2 };
596 var firstBlock = JSON.stringify(metadata);
597 recordingEntry(fd, 1, 0, firstBlock, function () {
598 obj.recordingFile = { fd: fd, filename: recFullFilename };
@@ -599,10 +647,12 @@ function CreateDesktopMultiplexor(parent, domain, id, func) {
647 }
648
649 module.exports.CreateMeshRelay = function (parent, ws, req, domain, user, cookie) {
650 + if ((req.query.nodeid == null) || (req.query.p != '2') || (req.query.id == null) || (domain == null)) { try { ws.close(); } catch (e) { } return; } // Not is not a valid remote desktop connection.
651 var obj = {};
652 obj.ws = ws;
653 obj.ws.me = obj;
654 obj.id = req.query.id;
655 + obj.nodeid = req.query.nodeid;
656 obj.user = user;
657 obj.ruserid = null;
658 obj.req = req; // Used in multi-server.js
@@ -611,6 +661,7 @@ module.exports.CreateMeshRelay = function (parent, ws, req, domain, user, cookie
661 if ((user == null) && (obj.req.query != null) && (obj.req.query.rauth != null)) {
662 const rcookie = parent.parent.decodeCookie(obj.req.query.rauth, parent.parent.loginCookieEncryptionKey, 240); // Cookie with 4 hour timeout
663 if (rcookie.ruserid != null) { obj.ruserid = rcookie.ruserid; }
664 + if (rcookie.nodeid != null) { obj.nodeid = rcookie.nodeid; }
665 }
666
667 // If there is no authentication, drop this connection
@@ -650,13 +701,14 @@ module.exports.CreateMeshRelay = function (parent, ws, req, domain, user, cookie
701 if ((arg == 1) || (arg == null)) { try { ws.close(); parent.parent.debug('relay', 'Relay: Soft disconnect (' + cleanRemoteAddr(obj.req.ip) + ')'); } catch (e) { console.log(e); } } // Soft close, close the websocket
702 if (arg == 2) { try { ws._socket._parent.end(); parent.parent.debug('relay', 'Relay: Hard disconnect (' + cleanRemoteAddr(obj.req.ip) + ')'); } catch (e) { console.log(e); } } // Hard close, close the TCP socket
703 if (obj.relaySessionCounted) { parent.relaySessionCount--; delete obj.relaySessionCounted; }
653 - if (obj.deskDecoder != null) { if (obj.deskDecoder.removePeer(obj) == true) { delete parent.desktoprelays[obj.id]; } }
704 + if (obj.deskDecoder != null) { if (obj.deskDecoder.removePeer(obj) == true) { delete parent.desktoprelays[obj.nodeid]; } }
705
706 // Aggressive cleanup
707 delete obj.id;
708 delete obj.ws;
709 delete obj.req;
710 delete obj.user;
711 + delete obj.nodeid;
712 delete obj.ruserid;
713 delete obj.deskDecoder;
714
@@ -744,11 +796,11 @@ module.exports.CreateMeshRelay = function (parent, ws, req, domain, user, cookie
796 else if ((typeof parent.parent.args.agentpong == 'number') && (obj.pongtimer == null)) { obj.pongtimer = setInterval(sendPong, parent.parent.args.agentpong * 1000); }
797
798 // Create if needed and add this peer to the desktop multiplexor
747 - obj.deskDecoder = parent.desktoprelays[obj.id];
799 + obj.deskDecoder = parent.desktoprelays[obj.nodeid];
800 if (obj.deskDecoder == null) {
749 - CreateDesktopMultiplexor(parent, domain, obj.id, function (deskDecoder) {
801 + CreateDesktopMultiplexor(parent, domain, obj.nodeid, function (deskDecoder) {
802 obj.deskDecoder = deskDecoder;
751 - parent.desktoprelays[obj.id] = obj.deskDecoder;
803 + parent.desktoprelays[obj.nodeid] = obj.deskDecoder;
804 obj.deskDecoder.addPeer(obj);
805 ws._socket.resume(); // Release the traffic
806 });
@@ -793,7 +845,7 @@ module.exports.CreateMeshRelay = function (parent, ws, req, domain, user, cookie
845 if ((parent.GetNodeRights(user, node.meshid, node._id) & MESHRIGHT_REMOTECONTROL) == 0) { console.log('ERR: Access denied (1)'); try { obj.close(); } catch (e) { } return; }
846
847 // Send connection request to agent
796 - const rcookie = parent.parent.encodeCookie({ ruserid: user._id }, parent.parent.loginCookieEncryptionKey);
848 + const rcookie = parent.parent.encodeCookie({ ruserid: user._id, nodeid: node._id }, parent.parent.loginCookieEncryptionKey);
849 if (obj.id == undefined) { obj.id = ('' + Math.random()).substring(2); } // If there is no connection id, generate one.
850 const command = { nodeid: cookie.nodeid, action: 'msg', type: 'tunnel', value: '*/meshrelay.ashx?id=' + obj.id + '&rauth=' + rcookie, tcpport: cookie.tcpport, tcpaddr: cookie.tcpaddr };
851 parent.parent.debug('relay', 'Relay: Sending agent tunnel command: ' + JSON.stringify(command));
@@ -812,7 +864,7 @@ module.exports.CreateMeshRelay = function (parent, ws, req, domain, user, cookie
864
865 // Send connection request to agent
866 if (obj.id == null) { obj.id = ('' + Math.random()).substring(2); } // If there is no connection id, generate one.
815 - const rcookie = parent.parent.encodeCookie({ ruserid: user._id }, parent.parent.loginCookieEncryptionKey);
867 + const rcookie = parent.parent.encodeCookie({ ruserid: user._id, nodeid: node._id }, parent.parent.loginCookieEncryptionKey);
868
869 if (obj.req.query.tcpport != null) {
870 const command = { nodeid: obj.req.query.nodeid, action: 'msg', type: 'tunnel', value: '*/meshrelay.ashx?id=' + obj.id + '&rauth=' + rcookie, tcpport: obj.req.query.tcpport, tcpaddr: ((obj.req.query.tcpaddr == null) ? '127.0.0.1' : obj.req.query.tcpaddr) };
meshuser.js
+10
@@ -1110,6 +1110,16 @@ module.exports.CreateMeshUser = function (parent, db, ws, req, args, domain, use
1110 }
1111 case 'msg':
1112 {
1113 + // Before routing this command, let's do some security checking.
1114 + // If this is a tunnel request, we need to make sure the NodeID in the URL matches the NodeID in the command.
1115 + if (command.type == 'tunnel') {
1116 + if ((typeof command.value != 'string') || (typeof command.nodeid != 'string')) break;
1117 + var url = null;
1118 + try { url = require('url').parse(command.value, true); } catch (ex) { }
1119 + if (url == null) break; // Bad URL
1120 + if (url.query && url.query.nodeid && (url.query.nodeid != command.nodeid)) break; // Bad NodeID in URL query string
1121 + }
1122 +
1123 // Route this command to a target node
1124 routeCommandToNode(command);
1125 break;
webserver.js
+2 -2
@@ -1843,7 +1843,7 @@ module.exports.CreateWebServer = function (parent, db, args, certificates) {
1843 if (obj.args.nousers == true) { features += 0x00000004; } // Single user mode
1844 if (domain.userQuota == -1) { features += 0x00000008; } // No server files mode
1845 if (obj.args.mpstlsoffload) { features += 0x00000010; } // No mutual-auth CIRA
1846 - if ((parent.config.settings.allowframing == true) || (typeof parent.config.settings.allowframing == 'string')) { features += 0x00000020; } // Allow site within iframe
1846 + if ((parent.config.settings.allowframing != null) || (domain.allowframing != null)) { features += 0x00000020; } // Allow site within iframe
1847 if ((obj.parent.mailserver != null) && (obj.parent.certificates.CommonName != null) && (obj.parent.certificates.CommonName.indexOf('.') != -1) && (obj.args.lanonly != true)) { features += 0x00000040; } // Email invites
1848 if (obj.args.webrtc == true) { features += 0x00000080; } // Enable WebRTC (Default false for now)
1849 if (obj.args.clickonce !== false) { features += 0x00000100; } // Enable ClickOnce (Default true)
@@ -3892,7 +3892,7 @@ module.exports.CreateWebServer = function (parent, db, args, certificates) {
3892 obj.app.ws(url + 'amtactivate', handleAmtActivateWebSocket);
3893 obj.app.ws(url + 'meshrelay.ashx', function (ws, req) {
3894 PerformWSSessionAuth(ws, req, true, function (ws1, req1, domain, user, cookie) {
3895 - if ((parent.config.settings.desktopmultiplex === true) && (req.query.p == 2)) {
3895 + if (((parent.config.settings.desktopmultiplex === true) || (domain.desktopmultiplex === true)) && (req.query.p == 2)) {
3896 obj.meshDesktopMultiplexHandler.CreateMeshRelay(obj, ws1, req1, domain, user, cookie); // Desktop multiplexor 1-to-n
3897 } else {
3898 obj.meshRelayHandler.CreateMeshRelay(obj, ws1, req1, domain, user, cookie); // Normal relay 1-to-1