Many improvements to apprelay.js

Ylian Saint-Hilaire committed Apr 14, 2022 at 11:47 UTC af8a6ec2a1488d1de4810fbb3a158d4e03e5a390
3 files changed +108 -91
apprelays.js
+106 -91
@@ -42,7 +42,7 @@ module.exports.CreateMstscRelay = function (parent, db, ws, req, args, domain) {
42 const Net = require('net');
43 const WebSocket = require('ws');
44
45 - var obj = {};
45 + const obj = {};
46 obj.ws = ws;
47 obj.tcpServerPort = 0;
48 obj.relayActive = false;
@@ -86,7 +86,7 @@ module.exports.CreateMstscRelay = function (parent, db, ws, req, args, domain) {
86 // Start the looppback server
87 function startTcpServer() {
88 obj.tcpServer = new Net.Server();
89 - obj.tcpServer.listen(0, '127.0.0.1', function () { obj.tcpServerPort = obj.tcpServer.address().port; startRdp(obj.tcpServerPort); });
89 + obj.tcpServer.listen(0, 'localhost', function () { obj.tcpServerPort = obj.tcpServer.address().port; startRdp(obj.tcpServerPort); });
90 obj.tcpServer.on('connection', function (socket) {
91 if (obj.relaySocket != null) {
92 socket.close();
@@ -100,12 +100,11 @@ module.exports.CreateMstscRelay = function (parent, db, ws, req, args, domain) {
100 obj.relaySocket.on('error', function (err) { obj.close(); });
101
102 // Setup the correct URL with domain and use TLS only if needed.
103 - var options = { rejectUnauthorized: false };
104 - if (domain.dns != null) { options.servername = domain.dns; }
105 - var protocol = (args.tlsoffload) ? 'ws' : 'wss';
103 + const options = { rejectUnauthorized: false };
104 + const protocol = (args.tlsoffload) ? 'ws' : 'wss';
105 var domainadd = '';
106 if ((domain.dns == null) && (domain.id != '')) { domainadd = domain.id + '/' }
108 - var url = protocol + '://127.0.0.1:' + args.port + '/' + domainadd + (((obj.mtype == 3) && (obj.relaynodeid == null)) ? 'local' : 'mesh') + 'relay.ashx?noping=1&p=10&auth=' + obj.infos.ip; // Protocol 10 is Web-RDP
107 + const url = protocol + '://localhost:' + args.port + '/' + domainadd + (((obj.mtype == 3) && (obj.relaynodeid == null)) ? 'local' : 'mesh') + 'relay.ashx?noping=1&p=10&auth=' + obj.infos.ip; // Protocol 10 is Web-RDP
108 parent.parent.debug('relay', 'RDP: Connection websocket to ' + url);
109 obj.wsClient = new WebSocket(url, options);
110 obj.wsClient.on('open', function () { parent.parent.debug('relay', 'RDP: Relay websocket open'); });
@@ -159,7 +158,7 @@ module.exports.CreateMstscRelay = function (parent, db, ws, req, args, domain) {
158 send(['rdp-close']);
159 }).on('error', function (err) {
160 send(['rdp-error', err]);
162 - }).connect('127.0.0.1', obj.tcpServerPort);
161 + }).connect('localhost', obj.tcpServerPort);
162 } catch (ex) {
163 console.log('startRdpException', ex);
164 obj.close();
@@ -184,7 +183,7 @@ module.exports.CreateMstscRelay = function (parent, db, ws, req, args, domain) {
183 // Event node change if needed
184 if (changed) {
185 // Event the node change
187 - var event = { etype: 'node', action: 'changenode', nodeid: obj.nodeid, domain: domain.id, userid: obj.cookie.userid, node: parent.CloneSafeNode(node), msg: "Changed RDP credentials" };
186 + const event = { etype: 'node', action: 'changenode', nodeid: obj.nodeid, domain: domain.id, userid: obj.cookie.userid, node: parent.CloneSafeNode(node), msg: "Changed RDP credentials" };
187 if (parent.parent.db.changeStream) { event.noact = 1; } // If DB change stream is active, don't use this event to change the node. Another event will come.
188 parent.parent.DispatchEvent(parent.CreateMeshDispatchTargets(node.meshid, [obj.nodeid]), obj, event);
189 }
@@ -208,14 +207,14 @@ module.exports.CreateMstscRelay = function (parent, db, ws, req, args, domain) {
207
208 // Get node
209 parent.parent.db.Get(obj.nodeid, function (err, nodes) {
210 + if (obj.ws == null) return; // obj has been cleaned up, just exit.
211 if ((err != null) || (nodes == null) || (nodes.length != 1)) { obj.close(); return; }
212 const node = nodes[0];
213 obj.mtype = node.mtype; // Store the device group type
214 obj.meshid = node.meshid; // Store the MeshID
215
216 // Check if we need to relay thru a different agent
217 - // TODO: Check if we have rights to the relayid device
218 - var mesh = parent.meshes[obj.meshid];
217 + const mesh = parent.meshes[obj.meshid];
218 if (mesh && mesh.relayid) {
219 obj.relaynodeid = mesh.relayid;
220 obj.tcpaddr = node.host;
@@ -225,24 +224,30 @@ module.exports.CreateMstscRelay = function (parent, db, ws, req, args, domain) {
224 obj.infos.ip = parent.parent.encodeCookie(cookieContent, parent.parent.loginCookieEncryptionKey);
225 }
226
228 - // Check if we need to load server stored credentials
229 - if ((typeof obj.infos.options == 'object') && (obj.infos.options.useServerCreds == true)) {
230 - // Check if RDP credentials exist
231 - if ((domain.allowsavingdevicecredentials === false) && (typeof node.rdp == 'object') && (typeof node.rdp.d == 'string') && (typeof node.rdp.u == 'string') && (typeof node.rdp.p == 'string')) {
232 - obj.infos.domain = node.rdp.d;
233 - obj.infos.username = node.rdp.u;
234 - obj.infos.password = node.rdp.p;
235 - startTcpServer();
227 + // Check if we have rights to the relayid device, does nothing if a relay is not used
228 + checkRelayRights(parent, domain, obj.userid, obj.relaynodeid, function (allowed) {
229 + if (obj.ws == null) return; // obj has been cleaned up, just exit.
230 + if (allowed !== true) { parent.parent.debug('relay', 'RDP: Attempt to use un-authorized relay'); obj.close(); return; }
231 +
232 + // Check if we need to load server stored credentials
233 + if ((typeof obj.infos.options == 'object') && (obj.infos.options.useServerCreds == true)) {
234 + // Check if RDP credentials exist
235 + if ((domain.allowsavingdevicecredentials === false) && (typeof node.rdp == 'object') && (typeof node.rdp.d == 'string') && (typeof node.rdp.u == 'string') && (typeof node.rdp.p == 'string')) {
236 + obj.infos.domain = node.rdp.d;
237 + obj.infos.username = node.rdp.u;
238 + obj.infos.password = node.rdp.p;
239 + startTcpServer();
240 + } else {
241 + // No server credentials.
242 + obj.infos.domain = '';
243 + obj.infos.username = '';
244 + obj.infos.password = '';
245 + startTcpServer();
246 + }
247 } else {
237 - // No server credentials.
238 - obj.infos.domain = '';
239 - obj.infos.username = '';
240 - obj.infos.password = '';
248 startTcpServer();
249 }
243 - } else {
244 - startTcpServer();
245 - }
250 + });
251 });
252 break;
253 }
@@ -285,7 +290,7 @@ module.exports.CreateSshRelay = function (parent, db, ws, req, args, domain) {
290
291 // SerialTunnel object is used to embed SSH within another connection.
292 function SerialTunnel(options) {
288 - var obj = new require('stream').Duplex(options);
293 + const obj = new require('stream').Duplex(options);
294 obj.forwardwrite = null;
295 obj.updateBuffer = function (chunk) { this.push(chunk); };
296 obj._write = function (chunk, encoding, callback) { if (obj.forwardwrite != null) { obj.forwardwrite(chunk); } if (callback) callback(); }; // Pass data written to forward
@@ -298,8 +303,6 @@ module.exports.CreateSshRelay = function (parent, db, ws, req, args, domain) {
303 obj.ws = ws;
304 obj.relayActive = false;
305
301 - parent.parent.debug('relay', 'SSH: Request for SSH relay (' + req.clientIp + ')');
302 -
306 // Disconnect
307 obj.close = function (arg) {
308 if (obj.ws == null) return;
@@ -374,28 +377,22 @@ module.exports.CreateSshRelay = function (parent, db, ws, req, args, domain) {
377 // Event node change if needed
378 if (changed) {
379 // Event the node change
377 - var event = { etype: 'node', action: 'changenode', nodeid: obj.cookie.nodeid, domain: domain.id, userid: obj.cookie.userid, node: parent.CloneSafeNode(node), msg: "Changed SSH credentials" };
380 + const event = { etype: 'node', action: 'changenode', nodeid: obj.cookie.nodeid, domain: domain.id, userid: obj.cookie.userid, node: parent.CloneSafeNode(node), msg: "Changed SSH credentials" };
381 if (parent.parent.db.changeStream) { event.noact = 1; } // If DB change stream is active, don't use this event to change the node. Another event will come.
382 parent.parent.DispatchEvent(parent.CreateMeshDispatchTargets(node.meshid, [obj.cookie.nodeid]), obj, event);
383 }
384 });
385 }
386
384 - // Decode the authentication cookie
385 - obj.cookie = parent.parent.decodeCookie(req.query.auth, parent.parent.loginCookieEncryptionKey);
386 - if (obj.cookie == null) { obj.ws.send(JSON.stringify({ action: 'sessionerror' })); obj.close(); return; }
387 -
387 // Start the looppback server
388 function startRelayConnection() {
389 try {
390 // Setup the correct URL with domain and use TLS only if needed.
392 - var options = { rejectUnauthorized: false };
393 - if (domain.dns != null) { options.servername = domain.dns; }
394 - var protocol = 'wss';
395 - if (args.tlsoffload) { protocol = 'ws'; }
391 + const options = { rejectUnauthorized: false };
392 + const protocol = (args.tlsoffload) ? 'ws' : 'wss';
393 var domainadd = '';
394 if ((domain.dns == null) && (domain.id != '')) { domainadd = domain.id + '/' }
398 - var url = protocol + '://127.0.0.1:' + args.port + '/' + domainadd + (((obj.mtype == 3) && (obj.relaynodeid == null)) ? 'local' : 'mesh') + 'relay.ashx?noping=1&p=11&auth=' + obj.xcookie; // Protocol 11 is Web-SSH
395 + const url = protocol + '://localhost:' + args.port + '/' + domainadd + (((obj.mtype == 3) && (obj.relaynodeid == null)) ? 'local' : 'mesh') + 'relay.ashx?noping=1&p=11&auth=' + obj.xcookie; // Protocol 11 is Web-SSH
396 parent.parent.debug('relay', 'SSH: Connection websocket to ' + url);
397 obj.wsClient = new WebSocket(url, options);
398 obj.wsClient.on('open', function () { parent.parent.debug('relay', 'SSH: Relay websocket open'); });
@@ -440,7 +437,7 @@ module.exports.CreateSshRelay = function (parent, db, ws, req, args, domain) {
437 obj.ser.forwardwrite = function (data) { if ((data.length > 0) && (obj.wsClient != null)) { try { obj.wsClient.send(data); } catch (ex) { } } };
438
439 // Connect the SSH module to the serial tunnel
443 - var connectionOptions = { sock: obj.ser }
440 + const connectionOptions = { sock: obj.ser }
441 if (typeof obj.username == 'string') { connectionOptions.username = obj.username; }
442 if (typeof obj.password == 'string') { connectionOptions.password = obj.password; }
443 if (typeof obj.privateKey == 'string') { connectionOptions.privateKey = obj.privateKey; }
@@ -540,8 +537,15 @@ module.exports.CreateSshRelay = function (parent, db, ws, req, args, domain) {
537 // If the web socket is closed
538 ws.on('close', function (req) { parent.parent.debug('relay', 'SSH: Browser websocket closed'); obj.close(); });
539
540 + parent.parent.debug('relay', 'SSH: Request for SSH relay (' + req.clientIp + ')');
541 +
542 + // Decode the authentication cookie
543 + obj.cookie = parent.parent.decodeCookie(req.query.auth, parent.parent.loginCookieEncryptionKey);
544 + if (obj.cookie == null) { obj.ws.send(JSON.stringify({ action: 'sessionerror' })); obj.close(); return; }
545 +
546 // Get the meshid for this device
547 parent.parent.db.Get(obj.cookie.nodeid, function (err, nodes) {
548 + if (obj.cookie == null) return; // obj has been cleaned up, just exit.
549 if ((err != null) || (nodes == null) || (nodes.length != 1)) { parent.parent.debug('relay', 'SSH: Invalid device'); obj.close(); }
550 const node = nodes[0];
551 obj.nodeid = node._id; // Store the NodeID
@@ -549,15 +553,20 @@ module.exports.CreateSshRelay = function (parent, db, ws, req, args, domain) {
553 obj.mtype = node.mtype; // Store the device group type
554
555 // Check if we need to relay thru a different agent
552 - // TODO: Check if we have rights to the relayid device
553 - var mesh = parent.meshes[obj.meshid];
556 + const mesh = parent.meshes[obj.meshid];
557 if (mesh && mesh.relayid) {
558 obj.relaynodeid = mesh.relayid;
559 obj.tcpaddr = node.host;
560
558 - // Re-encode a cookie with a device relay
559 - const cookieContent = { userid: obj.cookie.userid, domainid: obj.cookie.domainid, nodeid: mesh.relayid, tcpaddr: node.host, tcpport: obj.cookie.tcpport };
560 - obj.xcookie = parent.parent.encodeCookie(cookieContent, parent.parent.loginCookieEncryptionKey);
561 + // Check if we have rights to the relayid device, does nothing if a relay is not used
562 + checkRelayRights(parent, domain, obj.cookie.userid, obj.relaynodeid, function (allowed) {
563 + if (obj.cookie == null) return; // obj has been cleaned up, just exit.
564 + if (allowed !== true) { parent.parent.debug('relay', 'SSH: Attempt to use un-authorized relay'); obj.close(); return; }
565 +
566 + // Re-encode a cookie with a device relay
567 + const cookieContent = { userid: obj.cookie.userid, domainid: obj.cookie.domainid, nodeid: mesh.relayid, tcpaddr: node.host, tcpport: obj.cookie.tcpport };
568 + obj.xcookie = parent.parent.encodeCookie(cookieContent, parent.parent.loginCookieEncryptionKey);
569 + });
570 } else {
571 obj.xcookie = req.query.auth;
572 }
@@ -574,7 +583,7 @@ module.exports.CreateSshTerminalRelay = function (parent, db, ws, req, domain, u
583
584 // SerialTunnel object is used to embed SSH within another connection.
585 function SerialTunnel(options) {
577 - var obj = new require('stream').Duplex(options);
586 + const obj = new require('stream').Duplex(options);
587 obj.forwardwrite = null;
588 obj.updateBuffer = function (chunk) { this.push(chunk); };
589 obj._write = function (chunk, encoding, callback) { if (obj.forwardwrite != null) { obj.forwardwrite(chunk); } if (callback) callback(); }; // Pass data written to forward
@@ -633,7 +642,6 @@ module.exports.CreateSshTerminalRelay = function (parent, db, ws, req, domain, u
642
643 obj.relayActive = false;
644 delete obj.termSize;
636 - delete obj.cookie;
645 delete obj.nodeid;
646 delete obj.meshid;
647 delete obj.ws;
@@ -661,7 +669,7 @@ module.exports.CreateSshTerminalRelay = function (parent, db, ws, req, domain, u
669 // Event node change if needed
670 if (changed) {
671 // Event the node change
664 - var event = { etype: 'node', action: 'changenode', nodeid: obj.nodeid, domain: domain.id, userid: user._id, username: user.name, node: parent.CloneSafeNode(node), msg: "Changed SSH credentials" };
672 + const event = { etype: 'node', action: 'changenode', nodeid: obj.nodeid, domain: domain.id, userid: user._id, username: user.name, node: parent.CloneSafeNode(node), msg: "Changed SSH credentials" };
673 if (parent.parent.db.changeStream) { event.noact = 1; } // If DB change stream is active, don't use this event to change the node. Another event will come.
674 parent.parent.DispatchEvent(parent.CreateMeshDispatchTargets(node.meshid, [obj.nodeid]), obj, event);
675 }
@@ -672,13 +680,11 @@ module.exports.CreateSshTerminalRelay = function (parent, db, ws, req, domain, u
680 function startRelayConnection(authCookie) {
681 try {
682 // Setup the correct URL with domain and use TLS only if needed.
675 - var options = { rejectUnauthorized: false };
676 - if (domain.dns != null) { options.servername = domain.dns; }
677 - var protocol = 'wss';
678 - if (args.tlsoffload) { protocol = 'ws'; }
683 + const options = { rejectUnauthorized: false };
684 + const protocol = (args.tlsoffload) ? 'ws' : 'wss';
685 var domainadd = '';
686 if ((domain.dns == null) && (domain.id != '')) { domainadd = domain.id + '/' }
681 - var url = protocol + '://127.0.0.1:' + args.port + '/' + domainadd + (((obj.mtype == 3) && (obj.relaynodeid == null)) ? 'local' : 'mesh') + 'relay.ashx?noping=1&p=11&auth=' + authCookie // Protocol 11 is Web-SSH
687 + const url = protocol + '://localhost:' + args.port + '/' + domainadd + (((obj.mtype == 3) && (obj.relaynodeid == null)) ? 'local' : 'mesh') + 'relay.ashx?noping=1&p=11&auth=' + authCookie // Protocol 11 is Web-SSH
688 parent.parent.debug('relay', 'SSH: Connection websocket to ' + url);
689 obj.wsClient = new WebSocket(url, options);
690 obj.wsClient.on('open', function () { parent.parent.debug('relay', 'SSH: Relay websocket open'); });
@@ -725,7 +731,7 @@ module.exports.CreateSshTerminalRelay = function (parent, db, ws, req, domain, u
731 obj.ser.forwardwrite = function (data) { if ((data.length > 0) && (obj.wsClient != null)) { try { obj.wsClient.send(data); } catch (ex) { } } };
732
733 // Connect the SSH module to the serial tunnel
728 - var connectionOptions = { sock: obj.ser }
734 + const connectionOptions = { sock: obj.ser }
735 if (typeof obj.username == 'string') { connectionOptions.username = obj.username; }
736 if (typeof obj.password == 'string') { connectionOptions.password = obj.password; }
737 if (typeof obj.privateKey == 'string') { connectionOptions.privateKey = obj.privateKey; }
@@ -780,7 +786,7 @@ module.exports.CreateSshTerminalRelay = function (parent, db, ws, req, domain, u
786 obj.privateKeyPass = msg.keypass;
787
788 // Create a mesh relay authentication cookie
783 - var cookieContent = { userid: user._id, domainid: user.domain, nodeid: obj.nodeid, tcpport: obj.tcpport };
789 + const cookieContent = { userid: user._id, domainid: user.domain, nodeid: obj.nodeid, tcpport: obj.tcpport };
790 if (obj.relaynodeid) {
791 cookieContent.nodeid = obj.relaynodeid;
792 cookieContent.tcpaddr = obj.tcpaddr;
@@ -798,7 +804,7 @@ module.exports.CreateSshTerminalRelay = function (parent, db, ws, req, domain, u
804 if ((obj.username == null) || ((obj.password == null) && (obj.privateKey == null))) return;
805
806 // Create a mesh relay authentication cookie
801 - var cookieContent = { userid: user._id, domainid: user.domain, nodeid: obj.nodeid, tcpport: obj.tcpport };
807 + const cookieContent = { userid: user._id, domainid: user.domain, nodeid: obj.nodeid, tcpport: obj.tcpport };
808 if (obj.relaynodeid) {
809 cookieContent.nodeid = obj.relaynodeid;
810 cookieContent.tcpaddr = obj.tcpaddr;
@@ -833,6 +839,8 @@ module.exports.CreateSshTerminalRelay = function (parent, db, ws, req, domain, u
839 // Check that we have a user and nodeid
840 if ((user == null) || (req.query.nodeid == null)) { obj.close(); return; } // Invalid nodeid
841 parent.GetNodeWithRights(domain, user, req.query.nodeid, function (node, rights, visible) {
842 + if (obj.ws == null) return; // obj has been cleaned up, just exit.
843 +
844 // Check permissions
845 if ((rights & 8) == 0) { obj.close(); return; } // No MESHRIGHT_REMOTECONTROL rights
846 if ((rights != 0xFFFFFFFF) && (rights & 0x00000200)) { obj.close(); return; } // MESHRIGHT_NOTERMINAL is set
@@ -845,18 +853,18 @@ module.exports.CreateSshTerminalRelay = function (parent, db, ws, req, domain, u
853 if (typeof node.sshport == 'number') { obj.tcpport = node.sshport; }
854
855 // Check if we need to relay thru a different agent
848 - // TODO: Check if we have rights to the relayid device
849 - var mesh = parent.meshes[obj.meshid];
856 + const mesh = parent.meshes[obj.meshid];
857 if (mesh && mesh.relayid) { obj.relaynodeid = mesh.relayid; obj.tcpaddr = node.host; }
858
852 - // We are all set, start receiving data
853 - ws._socket.resume();
859 + // Check if we have rights to the relayid device, does nothing if a relay is not used
860 + checkRelayRights(parent, domain, user, obj.relaynodeid, function (allowed) {
861 + if (obj.ws == null) return; // obj has been cleaned up, just exit.
862 + if (allowed !== true) { parent.parent.debug('relay', 'SSH: Attempt to use un-authorized relay'); obj.close(); return; }
863
855 - // Check if we have SSH credentials for this device
856 - parent.parent.db.Get(obj.nodeid, function (err, nodes) {
857 - if ((err != null) || (nodes == null) || (nodes.length != 1)) return;
858 - const node = nodes[0];
864 + // We are all set, start receiving data
865 + ws._socket.resume();
866
867 + // Check if we have SSH credentials for this device
868 if ((domain.allowsavingdevicecredentials === false) || (node.ssh == null) || (typeof node.ssh != 'object') || (typeof node.ssh.u != 'string') || ((typeof node.ssh.p != 'string') && (typeof node.ssh.k != 'string'))) {
869 // Send a request for SSH authentication
870 try { ws.send(JSON.stringify({ action: 'sshauth' })) } catch (ex) { }
@@ -887,7 +895,7 @@ module.exports.CreateSshFilesRelay = function (parent, db, ws, req, domain, user
895
896 // SerialTunnel object is used to embed SSH within another connection.
897 function SerialTunnel(options) {
890 - var obj = new require('stream').Duplex(options);
898 + const obj = new require('stream').Duplex(options);
899 obj.forwardwrite = null;
900 obj.updateBuffer = function (chunk) { this.push(chunk); };
901 obj._write = function (chunk, encoding, callback) { if (obj.forwardwrite != null) { obj.forwardwrite(chunk); } if (callback) callback(); }; // Pass data written to forward
@@ -940,7 +948,6 @@ module.exports.CreateSshFilesRelay = function (parent, db, ws, req, domain, user
948 obj.ws.removeAllListeners();
949
950 obj.relayActive = false;
943 - delete obj.cookie;
951 delete obj.sftp;
952 delete obj.nodeid;
953 delete obj.meshid;
@@ -969,7 +976,7 @@ module.exports.CreateSshFilesRelay = function (parent, db, ws, req, domain, user
976 // Event node change if needed
977 if (changed) {
978 // Event the node change
972 - var event = { etype: 'node', action: 'changenode', nodeid: obj.nodeid, domain: domain.id, userid: user._id, username: user.name, node: parent.CloneSafeNode(node), msg: "Changed SSH credentials" };
979 + const event = { etype: 'node', action: 'changenode', nodeid: obj.nodeid, domain: domain.id, userid: user._id, username: user.name, node: parent.CloneSafeNode(node), msg: "Changed SSH credentials" };
980 if (parent.parent.db.changeStream) { event.noact = 1; } // If DB change stream is active, don't use this event to change the node. Another event will come.
981 parent.parent.DispatchEvent(parent.CreateMeshDispatchTargets(node.meshid, [obj.nodeid]), obj, event);
982 }
@@ -980,13 +987,11 @@ module.exports.CreateSshFilesRelay = function (parent, db, ws, req, domain, user
987 function startRelayConnection(authCookie) {
988 try {
989 // Setup the correct URL with domain and use TLS only if needed.
983 - var options = { rejectUnauthorized: false };
984 - if (domain.dns != null) { options.servername = domain.dns; }
985 - var protocol = 'wss';
986 - if (args.tlsoffload) { protocol = 'ws'; }
990 + const options = { rejectUnauthorized: false };
991 + const protocol = (args.tlsoffload) ? 'ws' : 'wss';
992 var domainadd = '';
993 if ((domain.dns == null) && (domain.id != '')) { domainadd = domain.id + '/' }
989 - var url = protocol + '://127.0.0.1:' + args.port + '/' + domainadd + (((obj.mtype == 3) && (obj.relaynodeid == null)) ? 'local' : 'mesh') + 'relay.ashx?noping=1&p=13&auth=' + authCookie // Protocol 13 is Web-SSH-Files
994 + const url = protocol + '://localhost:' + args.port + '/' + domainadd + (((obj.mtype == 3) && (obj.relaynodeid == null)) ? 'local' : 'mesh') + 'relay.ashx?noping=1&p=13&auth=' + authCookie // Protocol 13 is Web-SSH-Files
995 parent.parent.debug('relay', 'SSH: Connection websocket to ' + url);
996 obj.wsClient = new WebSocket(url, options);
997 obj.wsClient.on('open', function () { parent.parent.debug('relay', 'SSH: Relay websocket open'); });
@@ -1027,7 +1032,7 @@ module.exports.CreateSshFilesRelay = function (parent, db, ws, req, domain, user
1032 obj.ser.forwardwrite = function (data) { if ((data.length > 0) && (obj.wsClient != null)) { try { obj.wsClient.send(data); } catch (ex) { } } };
1033
1034 // Connect the SSH module to the serial tunnel
1030 - var connectionOptions = { sock: obj.ser }
1035 + const connectionOptions = { sock: obj.ser }
1036 if (typeof obj.username == 'string') { connectionOptions.username = obj.username; }
1037 if (typeof obj.password == 'string') { connectionOptions.password = obj.password; }
1038 if (typeof obj.privateKey == 'string') { connectionOptions.privateKey = obj.privateKey; }
@@ -1068,7 +1073,7 @@ module.exports.CreateSshFilesRelay = function (parent, db, ws, req, domain, user
1073 if (msg[0] == 123) {
1074 msg = msg.toString();
1075 } else if ((obj.sftp != null) && (obj.uploadHandle != null)) {
1071 - var off = (msg[0] == 0) ? 1 : 0;
1076 + const off = (msg[0] == 0) ? 1 : 0;
1077 obj.sftp.write(obj.uploadHandle, msg, off, msg.length - off, obj.uploadPosition, function (err) {
1078 if (err != null) {
1079 obj.sftp.close(obj.uploadHandle, function () { });
@@ -1097,9 +1102,9 @@ module.exports.CreateSshFilesRelay = function (parent, db, ws, req, domain, user
1102 if (requestedPath.startsWith('/') == false) { requestedPath = '/' + requestedPath; }
1103 obj.sftp.readdir(requestedPath, function(err, list) {
1104 if (err) { console.log(err); obj.close(); }
1100 - var r = { path: requestedPath, reqid: msg.reqid, dir: [] };
1105 + const r = { path: requestedPath, reqid: msg.reqid, dir: [] };
1106 for (var i in list) {
1102 - var file = list[i];
1107 + const file = list[i];
1108 if (file.longname[0] == 'd') { r.dir.push({ t: 2, n: file.filename, d: new Date(file.attrs.mtime * 1000).toISOString() }); }
1109 else { r.dir.push({ t: 3, n: file.filename, d: new Date(file.attrs.mtime * 1000).toISOString(), s: file.attrs.size }); }
1110 }
@@ -1114,7 +1119,7 @@ module.exports.CreateSshFilesRelay = function (parent, db, ws, req, domain, user
1119 obj.sftp.mkdir(requestedPath, function (err) { });
1120
1121 // Event the file delete
1117 - var targets = ['*', 'server-users'];
1122 + const targets = ['*', 'server-users'];
1123 if (user.groups) { for (var i in user.groups) { targets.push('server-users:' + i); } }
1124 parent.parent.DispatchEvent(targets, obj, { etype: 'node', action: 'agentlog', nodeid: obj.nodeid, userid: user._id, username: user.name, msgid: 44, msgArgs: [requestedPath], msg: 'Create folder: \"' + requestedPath + '\"', domain: domain.id });
1125 break;
@@ -1129,7 +1134,7 @@ module.exports.CreateSshFilesRelay = function (parent, db, ws, req, domain, user
1134 if (msg.rec === true) { obj.sftp.rmdir(ul + '/', function (err) { }); }
1135
1136 // Event the file delete
1132 - var targets = ['*', 'server-users'];
1137 + const targets = ['*', 'server-users'];
1138 if (user.groups) { for (var i in user.groups) { targets.push('server-users:' + i); } }
1139 parent.parent.DispatchEvent(targets, obj, { etype: 'node', action: 'agentlog', nodeid: obj.nodeid, userid: user._id, username: user.name, msgid: 45, msgArgs: [ul], msg: 'Delete: \"' + ul + '\"', domain: domain.id });
1140 }
@@ -1145,7 +1150,7 @@ module.exports.CreateSshFilesRelay = function (parent, db, ws, req, domain, user
1150 obj.sftp.rename(oldpath, newpath, function (err) { });
1151
1152 // Event the file rename
1148 - var targets = ['*', 'server-users'];
1153 + const targets = ['*', 'server-users'];
1154 if (user.groups) { for (var i in user.groups) { targets.push('server-users:' + i); } }
1155 parent.parent.DispatchEvent(targets, obj, { etype: 'node', action: 'agentlog', nodeid: obj.nodeid, userid: user._id, username: user.name, msgid: 48, msgArgs: [oldpath, msg.newname], msg: 'Rename: \"' + oldpath + '\" to \"' + msg.newname + '\"', domain: domain.id });
1156 break;
@@ -1166,7 +1171,7 @@ module.exports.CreateSshFilesRelay = function (parent, db, ws, req, domain, user
1171 try { obj.ws.send(Buffer.from(JSON.stringify({ action: 'uploadstart', reqid: obj.uploadReqid }))) } catch (ex) { }
1172
1173 // Event the file upload
1169 - var targets = ['*', 'server-users'];
1174 + const targets = ['*', 'server-users'];
1175 if (user.groups) { for (var i in user.groups) { targets.push('server-users:' + i); } }
1176 parent.parent.DispatchEvent(targets, obj, { etype: 'node', action: 'agentlog', nodeid: obj.nodeid, userid: user._id, username: user.name, msgid: 105, msgArgs: [obj.uploadFullpath, obj.uploadSize], msg: 'Upload: ' + obj.uploadFullpath + ', Size: ' + obj.uploadSize, domain: domain.id });
1177 }
@@ -1218,7 +1223,7 @@ module.exports.CreateSshFilesRelay = function (parent, db, ws, req, domain, user
1223 try { obj.ws.send(JSON.stringify({ action: 'download', sub: 'start', id: obj.downloadId })) } catch (ex) { }
1224
1225 // Event the file download
1221 - var targets = ['*', 'server-users'];
1226 + const targets = ['*', 'server-users'];
1227 if (user.groups) { for (var i in user.groups) { targets.push('server-users:' + i); } }
1228 parent.parent.DispatchEvent(targets, obj, { etype: 'node', action: 'agentlog', nodeid: obj.nodeid, userid: user._id, username: user.name, msgid: 49, msgArgs: [obj.downloadFullpath], msg: 'Download: ' + obj.downloadFullpath, domain: domain.id });
1229 }
@@ -1263,7 +1268,7 @@ module.exports.CreateSshFilesRelay = function (parent, db, ws, req, domain, user
1268 obj.privateKeyPass = msg.keypass;
1269
1270 // Create a mesh relay authentication cookie
1266 - var cookieContent = { userid: user._id, domainid: user.domain, nodeid: obj.nodeid, tcpport: obj.tcpport };
1271 + const cookieContent = { userid: user._id, domainid: user.domain, nodeid: obj.nodeid, tcpport: obj.tcpport };
1272 if (obj.relaynodeid) {
1273 cookieContent.nodeid = obj.relaynodeid;
1274 cookieContent.tcpaddr = obj.tcpaddr;
@@ -1316,6 +1321,8 @@ module.exports.CreateSshFilesRelay = function (parent, db, ws, req, domain, user
1321 // Check that we have a user and nodeid
1322 if ((user == null) || (req.query.nodeid == null)) { obj.close(); return; } // Invalid nodeid
1323 parent.GetNodeWithRights(domain, user, req.query.nodeid, function (node, rights, visible) {
1324 + if (obj.ws == null) return; // obj has been cleaned up, just exit.
1325 +
1326 // Check permissions
1327 if ((rights & 8) == 0) { obj.close(); return; } // No MESHRIGHT_REMOTECONTROL rights
1328 if ((rights != 0xFFFFFFFF) && (rights & 0x00000200)) { obj.close(); return; } // MESHRIGHT_NOTERMINAL is set
@@ -1328,18 +1335,18 @@ module.exports.CreateSshFilesRelay = function (parent, db, ws, req, domain, user
1335 if (typeof node.sshport == 'number') { obj.tcpport = node.sshport; }
1336
1337 // Check if we need to relay thru a different agent
1331 - // TODO: Check if we have rights to the relayid device
1332 - var mesh = parent.meshes[obj.meshid];
1338 + const mesh = parent.meshes[obj.meshid];
1339 if (mesh && mesh.relayid) { obj.relaynodeid = mesh.relayid; obj.tcpaddr = node.host; }
1340
1335 - // We are all set, start receiving data
1336 - ws._socket.resume();
1341 + // Check if we have rights to the relayid device, does nothing if a relay is not used
1342 + checkRelayRights(parent, domain, user, obj.relaynodeid, function (allowed) {
1343 + if (obj.ws == null) return; // obj has been cleaned up, just exit.
1344 + if (allowed !== true) { parent.parent.debug('relay', 'SSH: Attempt to use un-authorized relay'); obj.close(); return; }
1345
1338 - // Check if we have SSH credentials for this device
1339 - parent.parent.db.Get(obj.nodeid, function (err, nodes) {
1340 - if ((err != null) || (nodes == null) || (nodes.length != 1)) return;
1341 - const node = nodes[0];
1346 + // We are all set, start receiving data
1347 + ws._socket.resume();
1348
1349 + // Check if we have SSH credentials for this device
1350 if ((domain.allowsavingdevicecredentials === false) || (node.ssh == null) || (typeof node.ssh != 'object') || (typeof node.ssh.u != 'string') || ((typeof node.ssh.p != 'string') && (typeof node.ssh.k != 'string'))) {
1351 // Send a request for SSH authentication
1352 try { ws.send(JSON.stringify({ action: 'sshauth' })) } catch (ex) { }
@@ -1354,7 +1361,7 @@ module.exports.CreateSshFilesRelay = function (parent, db, ws, req, domain, user
1361 }
1362
1363 // Create a mesh relay authentication cookie
1357 - var cookieContent = { userid: user._id, domainid: user.domain, nodeid: obj.nodeid, tcpport: obj.tcpport };
1364 + const cookieContent = { userid: user._id, domainid: user.domain, nodeid: obj.nodeid, tcpport: obj.tcpport };
1365 if (obj.relaynodeid) {
1366 cookieContent.nodeid = obj.relaynodeid;
1367 cookieContent.tcpaddr = obj.tcpaddr;
@@ -1364,8 +1371,16 @@ module.exports.CreateSshFilesRelay = function (parent, db, ws, req, domain, user
1371 startRelayConnection(parent.parent.encodeCookie(cookieContent, parent.parent.loginCookieEncryptionKey));
1372 }
1373 });
1367 -
1374 });
1375
1376 return obj;
1377 };
1378 +
1379 +
1380 +// Check that the user has full rights on a relay device before allowing it.
1381 +function checkRelayRights(parent, domain, user, relayNodeId, func) {
1382 + if (relayNodeId == null) { func(true); return; } // No relay, do nothing.
1383 + parent.GetNodeWithRights(domain, user, relayNodeId, function (node, rights, visible) {
1384 + func((node != null) && (rights == 0xFFFFFFFF));
1385 + });
1386 +}
\ No newline at end of file
meshcentral.js
+1
@@ -447,6 +447,7 @@ function CreateMeshCentralServer(config, args) {
447 // Launch MeshCentral as a child server and monitor it.
448 obj.launchChildServer = function (startArgs) {
449 var child_process = require('child_process');
450 + try { if (process.traceDeprecation === true) { startArgs.unshift('--trace-deprecation'); } } catch (ex) { }
451 childProcess = child_process.execFile(process.argv[0], startArgs, { maxBuffer: Infinity, cwd: obj.parentpath }, function (error, stdout, stderr) {
452 if (childProcess.xrestart == 1) {
453 setTimeout(function () { obj.launchChildServer(startArgs); }, 500); // This is an expected restart.
meshuser.js
+1
@@ -6677,6 +6677,7 @@ module.exports.CreateMeshUser = function (parent, db, ws, req, args, domain, use
6677 try { info.memoryUsage = process.memoryUsage(); } catch (ex) { }
6678 try { info.warnings = parent.parent.getServerWarnings(); } catch (ex) { }
6679 try { info.allDevGroupManagers = parent.parent.config.settings.managealldevicegroups; } catch (ex) { }
6680 + try { if (process.traceDeprecation == true) { info.traceDeprecation = true; } } catch (ex) { }
6681 cmdData.result = JSON.stringify(info, null, 4);
6682 }
6683