EverydayTech Platform - Developer Reference
Complete Source Code Documentation - All Applications
Loading...
Searching...
No Matches
apprelays.js
Go to the documentation of this file.
1/**
2* @description MeshCentral MSTSC & SSH relay
3* @author Ylian Saint-Hilaire & Bryan Roe
4* @copyright Intel Corporation 2018-2022
5* @license Apache-2.0
6* @version v0.0.1
7*/
8
9/*jslint node: true */
10/*jshint node: true */
11/*jshint strict:false */
12/*jshint -W097 */
13/*jshint esversion: 6 */
14"use strict";
15
16/*
17Protocol numbers
1810 = RDP
1911 = SSH-TERM
2012 = VNC
2113 = SSH-FILES
2214 = Web-TCP
23*/
24
25// Protocol Numbers
26const PROTOCOL_TERMINAL = 1;
27const PROTOCOL_DESKTOP = 2;
28const PROTOCOL_FILES = 5;
29const PROTOCOL_AMTWSMAN = 100;
30const PROTOCOL_AMTREDIR = 101;
31const PROTOCOL_MESSENGER = 200;
32const PROTOCOL_WEBRDP = 201;
33const PROTOCOL_WEBSSH = 202;
34const PROTOCOL_WEBSFTP = 203;
35const PROTOCOL_WEBVNC = 204;
36
37// Mesh Rights
38const MESHRIGHT_EDITMESH = 0x00000001; // 1
39const MESHRIGHT_MANAGEUSERS = 0x00000002; // 2
40const MESHRIGHT_MANAGECOMPUTERS = 0x00000004; // 4
41const MESHRIGHT_REMOTECONTROL = 0x00000008; // 8
42const MESHRIGHT_AGENTCONSOLE = 0x00000010; // 16
43const MESHRIGHT_SERVERFILES = 0x00000020; // 32
44const MESHRIGHT_WAKEDEVICE = 0x00000040; // 64
45const MESHRIGHT_SETNOTES = 0x00000080; // 128
46const MESHRIGHT_REMOTEVIEWONLY = 0x00000100; // 256
47const MESHRIGHT_NOTERMINAL = 0x00000200; // 512
48const MESHRIGHT_NOFILES = 0x00000400; // 1024
49const MESHRIGHT_NOAMT = 0x00000800; // 2048
50const MESHRIGHT_DESKLIMITEDINPUT = 0x00001000; // 4096
51const MESHRIGHT_LIMITEVENTS = 0x00002000; // 8192
52const MESHRIGHT_CHATNOTIFY = 0x00004000; // 16384
53const MESHRIGHT_UNINSTALL = 0x00008000; // 32768
54const MESHRIGHT_NODESKTOP = 0x00010000; // 65536
55const MESHRIGHT_REMOTECOMMAND = 0x00020000; // 131072
56const MESHRIGHT_RESETOFF = 0x00040000; // 262144
57const MESHRIGHT_GUESTSHARING = 0x00080000; // 524288
58const MESHRIGHT_DEVICEDETAILS = 0x00100000; // 1048576
59const MESHRIGHT_RELAY = 0x00200000; // 2097152
60const MESHRIGHT_ADMIN = 0xFFFFFFFF;
61
62// SerialTunnel object is used to embed TLS within another connection.
63function SerialTunnel(options) {
64 var obj = new require('stream').Duplex(options);
65 obj.forwardwrite = null;
66 obj.updateBuffer = function (chunk) { this.push(chunk); };
67 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
68 obj._read = function (size) { }; // Push nothing, anything to read should be pushed from updateBuffer()
69 return obj;
70}
71
72// Construct a Web relay object
73module.exports.CreateWebRelaySession = function (parent, db, req, args, domain, userid, nodeid, addr, port, appid, sessionid, expire, mtype) {
74 const obj = {};
75 obj.parent = parent;
76 obj.lastOperation = Date.now();
77 obj.domain = domain;
78 obj.userid = userid;
79 obj.nodeid = nodeid;
80 obj.addr = addr;
81 obj.port = port;
82 obj.appid = appid;
83 obj.sessionid = sessionid;
84 obj.expireTimer = null;
85 obj.mtype = mtype;
86 var pendingRequests = [];
87 var nextTunnelId = 1;
88 var tunnels = {};
89 var errorCount = 0; // If we keep closing tunnels without processing requests, fail the requests
90
91 parent.parent.debug('webrelay', 'CreateWebRelaySession, userid:' + userid + ', addr:' + addr + ', port:' + port);
92
93 // Any HTTP cookie set by the device is going to be shared between all tunnels to that device.
94 obj.webCookies = {};
95
96 // Setup an expire time if needed
97 if (expire != null) {
98 var timeout = (expire - Date.now());
99 if (timeout < 10) { timeout = 10; }
100 parent.parent.debug('webrelay', 'timeout set to ' + Math.floor(timeout / 1000) + ' second(s).');
101 obj.expireTimer = setTimeout(function () { parent.parent.debug('webrelay', 'timeout'); close(); }, timeout);
102 }
103
104 // Events
105 obj.closed = false;
106 obj.onclose = null;
107
108 // Check if any tunnels need to be cleaned up
109 obj.checkTimeout = function () {
110 const limit = Date.now() - (5 * 60 * 1000); // This is 5 minutes before current time
111
112 // Close any old non-websocket tunnels
113 const tunnelToRemove = [];
114 for (var i in tunnels) { if ((tunnels[i].lastOperation < limit) && (tunnels[i].isWebSocket !== true)) { tunnelToRemove.push(tunnels[i]); } }
115 for (var i in tunnelToRemove) { tunnelToRemove[i].close(); }
116
117 // Close this session if no longer used
118 if (obj.lastOperation < limit) {
119 var count = 0;
120 for (var i in tunnels) { count++; }
121 if (count == 0) { close(); } // Time limit reached and no tunnels, clean up.
122 }
123 }
124
125 // Handle new HTTP request
126 obj.handleRequest = function (req, res) {
127 parent.parent.debug('webrelay', 'handleRequest, url:' + req.url);
128 pendingRequests.push([req, res, false]);
129 handleNextRequest();
130 }
131
132 // Handle new websocket request
133 obj.handleWebSocket = function (ws, req) {
134 parent.parent.debug('webrelay', 'handleWebSocket, url:' + req.url);
135 pendingRequests.push([req, ws, true]);
136 handleNextRequest();
137 }
138
139 // Handle request
140 function handleNextRequest() {
141 if (obj.closed == true) return;
142
143 // if there are not pending requests, do nothing
144 if (pendingRequests.length == 0) return;
145
146 // If the errorCount is high, something is really wrong, we are opening lots of tunnels and not processing any requests.
147 if (errorCount > 5) { close(); return; }
148
149 // Check to see if any of the tunnels are free
150 var count = 0;
151 for (var i in tunnels) {
152 count += ((tunnels[i].isWebSocket || tunnels[i].isStreaming || (tunnels[i].res != null)) ? 0 : 1);
153 if ((tunnels[i].relayActive == true) && (tunnels[i].res == null) && (tunnels[i].isWebSocket == false) && (tunnels[i].isStreaming == false)) {
154 // Found a free tunnel, use it
155 const x = pendingRequests.shift();
156 if (x[2] == true) { tunnels[i].processWebSocket(x[0], x[1]); } else { tunnels[i].processRequest(x[0], x[1]); }
157 return;
158 }
159 }
160
161 if (count > 0) return;
162 launchNewTunnel();
163 }
164
165 function launchNewTunnel() {
166 // Launch a new tunnel
167 if (obj.closed == true) return;
168 parent.parent.debug('webrelay', 'launchNewTunnel');
169 const tunnel = module.exports.CreateWebRelay(obj, db, args, domain, obj.mtype);
170 tunnel.onclose = function (tunnelId, processedCount) {
171 if (tunnels == null) return;
172 parent.parent.debug('webrelay', 'tunnel-onclose');
173 if (processedCount == 0) { errorCount++; } // If this tunnel closed without processing any requests, mark this as an error
174 delete tunnels[tunnelId];
175 handleNextRequest();
176 }
177 tunnel.onconnect = function (tunnelId) {
178 if (tunnels == null) return;
179 parent.parent.debug('webrelay', 'tunnel-onconnect');
180 if (pendingRequests.length > 0) {
181 const x = pendingRequests.shift();
182 if (x[2] == true) { tunnels[tunnelId].processWebSocket(x[0], x[1]); } else { tunnels[tunnelId].processRequest(x[0], x[1]); }
183 }
184 }
185 tunnel.oncompleted = function (tunnelId, closed) {
186 if (tunnels == null) return;
187 if (closed === true) {
188 parent.parent.debug('webrelay', 'tunnel-oncompleted and closed');
189 } else {
190 parent.parent.debug('webrelay', 'tunnel-oncompleted');
191 }
192 if (closed !== true) {
193 errorCount = 0; // Something got completed, clear any error count
194 if (pendingRequests.length > 0) {
195 const x = pendingRequests.shift();
196 if (x[2] == true) { tunnels[tunnelId].processWebSocket(x[0], x[1]); } else { tunnels[tunnelId].processRequest(x[0], x[1]); }
197 }
198 }
199 }
200 tunnel.onNextRequest = function () {
201 if (tunnels == null) return;
202 parent.parent.debug('webrelay', 'tunnel-onNextRequest');
203 handleNextRequest();
204 }
205 tunnel.connect(userid, nodeid, addr, port, appid);
206 tunnel.tunnelId = nextTunnelId++;
207 tunnels[tunnel.tunnelId] = tunnel;
208 }
209
210 // Close all tunnels
211 obj.close = function () { close(); }
212
213 // Close all tunnels
214 function close() {
215 // Set the session as closed
216 if (obj.closed == true) return;
217 parent.parent.debug('webrelay', 'tunnel-close');
218 obj.closed = true;
219
220 // Clear the time if present
221 if (obj.expireTimer != null) { clearTimeout(obj.expireTimer); delete obj.expireTimer; }
222
223 // Close all tunnels
224 for (var i in tunnels) { tunnels[i].close(); }
225 tunnels = null;
226
227 // Close any pending requests
228 for (var i in pendingRequests) { if (pendingRequests[i][2] == true) { pendingRequests[i][1].close(); } else { pendingRequests[i][1].end(); } }
229
230 // Notify of session closure
231 if (obj.onclose) { obj.onclose(obj.sessionid); }
232
233 // Cleanup
234 delete obj.userid;
235 delete obj.lastOperation;
236 }
237
238 return obj;
239}
240
241
242// Construct a Web relay object
243module.exports.CreateWebRelay = function (parent, db, args, domain, mtype) {
244 //const Net = require('net');
245 const WebSocket = require('ws')
246
247 const obj = {};
248 obj.lastOperation = Date.now();
249 obj.relayActive = false;
250 obj.closed = false;
251 obj.isWebSocket = false; // If true, this request will not close and so, it can't be allowed to hold up other requests
252 obj.isStreaming = false; // If true, this request will not close and so, it can't be allowed to hold up other requests
253 obj.processedRequestCount = 0;
254 obj.mtype = mtype;
255 const constants = (require('crypto').constants ? require('crypto').constants : require('constants')); // require('constants') is deprecated in Node 11.10, use require('crypto').constants instead.
256
257 // Events
258 obj.onclose = null;
259 obj.oncompleted = null;
260 obj.onconnect = null;
261 obj.onNextRequest = null;
262
263 // Called when we need to close the tunnel because the response stream has closed
264 function handleResponseClosure() { obj.close(); }
265
266 // Return cookie name and values
267 function parseRequestCookies(cookiesString) {
268 var r = {};
269 if (typeof cookiesString != 'string') return r;
270 var cookieString = cookiesString.split('; ');
271 for (var i in cookieString) { var j = cookieString[i].indexOf('='); if (j > 0) { r[cookieString[i].substring(0, j)] = cookieString[i].substring(j + 1); } }
272 return r;
273 }
274
275 // Process a HTTP request
276 obj.processRequest = function (req, res) {
277 if (obj.relayActive == false) { console.log("ERROR: Attempt to use an unconnected tunnel"); return false; }
278 parent.lastOperation = obj.lastOperation = Date.now();
279
280 // Check if this is a websocket
281 if (req.headers['upgrade'] == 'websocket') { console.log('Attempt to process a websocket in HTTP tunnel method.'); res.end(); return false; }
282
283 // If the response stream is closed, close this tunnel right away
284 res.socket.on('end', handleResponseClosure);
285
286 // Construct the HTTP request
287 var request = req.method + ' ' + req.url + ' HTTP/' + req.httpVersion + '\r\n';
288 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
289 for (var i in req.headers) { if (blockedHeaders.indexOf(i) == -1) { request += i + ': ' + req.headers[i] + '\r\n'; } }
290 var cookieStr = '';
291 for (var i in parent.webCookies) { if (cookieStr != '') { cookieStr += '; ' } cookieStr += (i + '=' + parent.webCookies[i].value); }
292 var reqCookies = parseRequestCookies(req.headers.cookie);
293 for (var i in reqCookies) { if ((i != 'xid') && (i != 'xid.sig')) { if (cookieStr != '') { cookieStr += '; ' } cookieStr += (i + '=' + reqCookies[i]); } }
294 if (cookieStr.length > 0) { request += 'cookie: ' + cookieStr + '\r\n' } // If we have session cookies, set them in the header here
295 request += '\r\n';
296
297 if (req.headers['content-length'] != null) {
298 // Stream the HTTP request and body, this is a content-length HTTP request, just forward the body data
299 send(Buffer.from(request));
300 req.on('data', function (data) { send(data); }); // TODO: Flow control (Not sure how to do this in ExpressJS)
301 req.on('end', function () { });
302 } else if (req.headers['transfer-encoding'] != null) {
303 // Stream the HTTP request and body, this is a chunked encoded HTTP request
304 // TODO: Flow control (Not sure how to do this in ExpressJS)
305 send(Buffer.from(request));
306 req.on('data', function (data) { send(Buffer.concat([Buffer.from(data.length.toString(16) + '\r\n', 'binary'), data, send(Buffer.from('\r\n', 'binary'))])); });
307 req.on('end', function () { send(Buffer.from('0\r\n\r\n', 'binary')); });
308 } else {
309 // Request has no body, send it now
310 send(Buffer.from(request));
311 }
312 obj.res = res;
313 }
314
315 // Process a websocket request
316 obj.processWebSocket = function (req, ws) {
317 if (obj.relayActive == false) { console.log("ERROR: Attempt to use an unconnected tunnel"); return false; }
318 parent.lastOperation = obj.lastOperation = Date.now();
319
320 // Mark this tunnel as being a web socket tunnel
321 obj.isWebSocket = true;
322 obj.ws = ws;
323
324 // Pause the websocket until we get a tunnel connected
325 obj.ws._socket.pause();
326
327 // If the response stream is closed, close this tunnel right away
328 obj.ws._socket.on('end', function () { obj.close(); });
329
330 // Remove the trailing '/.websocket' if needed
331 var baseurl = req.url, i = req.url.indexOf('?');
332 if (i > 0) { baseurl = req.url.substring(0, i); }
333 if (baseurl.endsWith('/.websocket')) { req.url = baseurl.substring(0, baseurl.length - 11) + ((i < 1) ? '' : req.url.substring(i)); }
334
335 // Construct the HTTP request
336 var request = req.method + ' ' + req.url + ' HTTP/' + req.httpVersion + '\r\n';
337 const blockedHeaders = ['cookie', 'sec-websocket-extensions']; // These are headers we do not forward
338 for (var i in req.headers) { if (blockedHeaders.indexOf(i) == -1) { request += i + ': ' + req.headers[i] + '\r\n'; } }
339 var cookieStr = '';
340 for (var i in parent.webCookies) { if (cookieStr != '') { cookieStr += '; ' } cookieStr += (i + '=' + parent.webCookies[i].value); }
341 if (cookieStr.length > 0) { request += 'cookie: ' + cookieStr + '\r\n' } // If we have session cookies, set them in the header here
342 var reqCookies = parseRequestCookies(req.headers.cookie);
343 for (var i in reqCookies) { if ((i != 'xid') && (i != 'xid.sig')) { if (cookieStr != '') { cookieStr += '; ' } cookieStr += (i + '=' + reqCookies[i]); } }
344 if (cookieStr.length > 0) { request += 'cookie: ' + cookieStr + '\r\n' } // If we have session cookies, set them in the header here
345 request += '\r\n';
346 send(Buffer.from(request));
347
348 // Hook up the websocket events
349 obj.ws.on('message', function (data) {
350 // Setup opcode and payload
351 var op = 2, payload = data;
352 if (typeof data == 'string') { op = 1; payload = Buffer.from(data, 'binary'); } // Text frame
353 sendWebSocketFrameToDevice(op, payload);
354 });
355
356 obj.ws.on('ping', function (data) { sendWebSocketFrameToDevice(9, data); }); // Forward ping frame
357 obj.ws.on('pong', function (data) { sendWebSocketFrameToDevice(10, data); }); // Forward pong frame
358 obj.ws.on('close', function () { obj.close(); });
359 obj.ws.on('error', function (err) { obj.close(); });
360 }
361
362 function sendWebSocketFrameToDevice(op, payload) {
363 // Select a random mask
364 const mask = parent.parent.parent.crypto.randomBytes(4)
365
366 // Setup header and mask
367 var header = null;
368 if (payload.length < 126) {
369 header = Buffer.alloc(6); // Header (2) + Mask (4)
370 header[0] = 0x80 + op; // FIN + OP
371 header[1] = 0x80 + payload.length; // Mask + Length
372 mask.copy(header, 2, 0, 4); // Copy the mask
373 } else if (payload.length <= 0xFFFF) {
374 header = Buffer.alloc(8); // Header (2) + Length (2) + Mask (4)
375 header[0] = 0x80 + op; // FIN + OP
376 header[1] = 0x80 + 126; // Mask + 126
377 header.writeInt16BE(payload.length, 2); // Payload size
378 mask.copy(header, 4, 0, 4); // Copy the mask
379 } else {
380 header = Buffer.alloc(14); // Header (2) + Length (8) + Mask (4)
381 header[0] = 0x80 + op; // FIN + OP
382 header[1] = 0x80 + 127; // Mask + 127
383 header.writeInt32BE(payload.length, 6); // Payload size
384 mask.copy(header, 10, 0, 4); // Copy the mask
385 }
386
387 // Mask the payload
388 for (var i = 0; i < payload.length; i++) { payload[i] = (payload[i] ^ mask[i % 4]); }
389
390 // Send the frame
391 //console.log(obj.tunnelId, '-->', op, payload.length);
392 send(Buffer.concat([header, payload]));
393 }
394
395 // Disconnect
396 obj.close = function (arg) {
397 if (obj.closed == true) return;
398 obj.closed = true;
399
400 // If we are processing a http response that terminates when it closes, do this now.
401 if ((obj.socketParseState == 1) && (obj.socketXHeader['connection'] != null) && (obj.socketXHeader['connection'].toLowerCase() == 'close')) {
402 processHttpResponse(null, obj.socketAccumulator, true, true); // Indicate this tunnel is done and also closed, do not put a new request on this tunnel.
403 obj.socketAccumulator = '';
404 obj.socketParseState = 0;
405 }
406
407 if (obj.tls) {
408 try { obj.tls.end(); } catch (ex) { console.log(ex); }
409 delete obj.tls;
410 }
411
412 /*
413 // Event the session ending
414 if ((obj.startTime) && (obj.meshid != null)) {
415 // Collect how many raw bytes where received and sent.
416 // We sum both the websocket and TCP client in this case.
417 var inTraffc = obj.ws._socket.bytesRead, outTraffc = obj.ws._socket.bytesWritten;
418 if (obj.wsClient != null) { inTraffc += obj.wsClient._socket.bytesRead; outTraffc += obj.wsClient._socket.bytesWritten; }
419 const sessionSeconds = Math.round((Date.now() - obj.startTime) / 1000);
420 const user = parent.users[obj.cookie.userid];
421 const username = (user != null) ? user.name : null;
422 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 };
423 parent.DispatchEvent(['*', obj.nodeid, obj.cookie.userid, obj.meshid], obj, event);
424 delete obj.startTime;
425 delete obj.sessionid;
426 }
427 */
428 if (obj.wsClient) {
429 obj.wsClient.removeAllListeners('open');
430 obj.wsClient.removeAllListeners('message');
431 obj.wsClient.removeAllListeners('close');
432 try { obj.wsClient.close(); } catch (ex) { console.log(ex); }
433 delete obj.wsClient;
434 }
435
436 // Close any pending request
437 if (obj.res) { obj.res.socket.removeListener('end', handleResponseClosure); obj.res.end(); delete obj.res; }
438 if (obj.ws) { obj.ws.close(); delete obj.ws; }
439
440 // Event disconnection
441 if (obj.onclose) { obj.onclose(obj.tunnelId, obj.processedRequestCount); }
442
443 obj.relayActive = false;
444 };
445
446 // Start the loopback server
447 obj.connect = function (userid, nodeid, addr, port, appid) {
448 if (obj.relayActive || obj.closed) return;
449 obj.addr = addr;
450 obj.port = port;
451 obj.appid = appid;
452
453 // Encode a cookie for the mesh relay
454 const cookieContent = { userid: userid, domainid: domain.id, nodeid: nodeid, tcpport: port };
455 if (addr != null) { cookieContent.tcpaddr = addr; }
456 const cookie = parent.parent.parent.encodeCookie(cookieContent, parent.parent.parent.loginCookieEncryptionKey);
457
458 try {
459 // Setup the correct URL with domain and use TLS only if needed.
460 const options = { rejectUnauthorized: false };
461 const protocol = (args.tlsoffload) ? 'ws' : 'wss';
462 var domainadd = '';
463 if ((domain.dns == null) && (domain.id != '')) { domainadd = domain.id + '/' }
464 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
465 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.
466 parent.parent.parent.debug('relay', 'TCP: Connection websocket to ' + url);
467 obj.wsClient = new WebSocket(url, options);
468 obj.wsClient.on('open', function () { parent.parent.parent.debug('relay', 'TCP: Relay websocket open'); });
469 obj.wsClient.on('message', function (data) { // Make sure to handle flow control.
470 if (obj.tls) {
471 // WS --> TLS
472 processRawHttpData(data);
473 } else if (obj.relayActive == false) {
474 if ((data == 'c') || (data == 'cr')) {
475 if (appid == 2) {
476 // TLS needs to be setup
477 obj.ser = new SerialTunnel();
478 obj.ser.forwardwrite = function (data) { if (data.length > 0) { try { obj.wsClient.send(data); } catch (ex) { } } }; // TLS ---> WS
479
480 // TLSSocket to encapsulate TLS communication, which then tunneled via SerialTunnel
481 const tlsoptions = { socket: obj.ser, rejectUnauthorized: false };
482 obj.tls = require('tls').connect(tlsoptions, function () {
483 parent.parent.parent.debug('relay', "Web Relay Secure TLS Connection");
484 obj.relayActive = true;
485 parent.lastOperation = obj.lastOperation = Date.now(); // Update time of last opertion performed
486 if (obj.onconnect) { obj.onconnect(obj.tunnelId); } // Event connection
487 });
488 obj.tls.setEncoding('binary');
489 obj.tls.on('error', function (err) { parent.parent.parent.debug('relay', "Web Relay TLS Connection Error", err); obj.close(); });
490
491 // Decrypted tunnel from TLS communcation to be forwarded to the browser
492 obj.tls.on('data', function (data) { processHttpData(data); }); // TLS ---> Browser
493 } else {
494 // No TLS needed, tunnel is now active
495 obj.relayActive = true;
496 parent.lastOperation = obj.lastOperation = Date.now(); // Update time of last opertion performed
497 if (obj.onconnect) { obj.onconnect(obj.tunnelId); } // Event connection
498 }
499 }
500 } else {
501 processRawHttpData(data);
502 }
503 });
504 obj.wsClient.on('close', function () { parent.parent.parent.debug('relay', 'TCP: Relay websocket closed'); obj.close(); });
505 obj.wsClient.on('error', function (err) { parent.parent.parent.debug('relay', 'TCP: Relay websocket error: ' + err); obj.close(); });
506 } catch (ex) {
507 console.log(ex);
508 }
509 }
510
511 function processRawHttpData(data) {
512 if (typeof data == 'string') {
513 // Forward any ping/pong commands to the browser
514 var cmd = null;
515 try { cmd = JSON.parse(data); } catch (ex) { }
516 if ((cmd != null) && (cmd.ctrlChannel == '102938') && (cmd.type == 'ping')) { cmd.type = 'pong'; obj.wsClient.send(JSON.stringify(cmd)); }
517 return;
518 }
519 if (obj.tls) {
520 // If TLS is in use, WS --> TLS
521 if (data.length > 0) { try { obj.ser.updateBuffer(data); } catch (ex) { console.log(ex); } }
522 } else {
523 // Relay WS --> TCP, event data coming in
524 processHttpData(data.toString('binary'));
525 }
526 }
527
528 // Process incoming HTTP data
529 obj.socketAccumulator = '';
530 obj.socketParseState = 0;
531 obj.socketContentLengthRemaining = 0;
532 function processHttpData(data) {
533 //console.log('processHttpData', data.length);
534 obj.socketAccumulator += data;
535 while (true) {
536 //console.log('ACC(' + obj.socketAccumulator + '): ' + obj.socketAccumulator);
537 if (obj.socketParseState == 0) {
538 var headersize = obj.socketAccumulator.indexOf('\r\n\r\n');
539 if (headersize < 0) return;
540 //obj.Debug("Header: "+obj.socketAccumulator.substring(0, headersize)); // Display received HTTP header
541 obj.socketHeader = obj.socketAccumulator.substring(0, headersize).split('\r\n');
542 obj.socketAccumulator = obj.socketAccumulator.substring(headersize + 4);
543 obj.socketXHeader = { Directive: obj.socketHeader[0].split(' ') };
544 for (var i in obj.socketHeader) {
545 if (i != 0) {
546 var x2 = obj.socketHeader[i].indexOf(':');
547 const n = obj.socketHeader[i].substring(0, x2).toLowerCase();
548 const v = obj.socketHeader[i].substring(x2 + 2);
549 if (n == 'set-cookie') { // Since "set-cookie" can be present many times in the header, handle it as an array of values
550 if (obj.socketXHeader[n] == null) { obj.socketXHeader[n] = [v]; } else { obj.socketXHeader[n].push(v); }
551 } else {
552 obj.socketXHeader[n] = v;
553 }
554 }
555 }
556
557 // Check if this is a streaming response
558 if ((obj.socketXHeader['content-type'] != null) && (obj.socketXHeader['content-type'].toLowerCase().indexOf('text/event-stream') >= 0)) {
559 obj.isStreaming = true; // This tunnel is now a streaming tunnel and will not close anytime soon.
560 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.
561 }
562
563 // Check if this HTTP request has a body
564 if (obj.socketXHeader['content-length'] != null) { obj.socketParseState = 1; }
565 if ((obj.socketXHeader['connection'] != null) && (obj.socketXHeader['connection'].toLowerCase() == 'close')) { obj.socketParseState = 1; }
566 if ((obj.socketXHeader['transfer-encoding'] != null) && (obj.socketXHeader['transfer-encoding'].toLowerCase() == 'chunked')) { obj.socketParseState = 1; }
567 if (obj.isWebSocket) {
568 if ((obj.socketXHeader['connection'] != null) && (obj.socketXHeader['connection'].toLowerCase() == 'upgrade')) {
569 obj.processedRequestCount++;
570 obj.socketParseState = 2; // Switch to decoding websocket frames
571 obj.ws._socket.resume(); // Resume the browser's websocket
572 } else {
573 obj.close(); // Failed to upgrade to websocket
574 }
575 }
576
577 // Forward the HTTP request into the tunnel, if no body is present, close the request.
578 processHttpResponse(obj.socketXHeader, null, (obj.socketParseState == 0));
579 }
580 if (obj.socketParseState == 1) {
581 var csize = -1;
582 if (obj.socketXHeader['content-length'] != null) {
583 // The body length is specified by the content-length
584 if (obj.socketContentLengthRemaining == 0) { obj.socketContentLengthRemaining = parseInt(obj.socketXHeader['content-length']); } // Set the remaining content-length if not set
585 var data = obj.socketAccumulator.substring(0, obj.socketContentLengthRemaining); // Grab the available data, not passed the expected content-length
586 obj.socketAccumulator = obj.socketAccumulator.substring(data.length); // Remove the data from the accumulator
587 obj.socketContentLengthRemaining -= data.length; // Substract the obtained data from the expected size
588 if (obj.socketContentLengthRemaining > 0) {
589 // Send any data we have, if we are done, signal the end of the response
590 processHttpResponse(null, data, false);
591 return; // More data is needed, return now so we exit the while() loop.
592 } else {
593 // We are done with this request
594 const closing = (obj.socketXHeader['connection'] != null) && (obj.socketXHeader['connection'].toLowerCase() == 'close');
595 if (closing) {
596 // We need to close this tunnel.
597 processHttpResponse(null, data, false);
598 obj.close();
599 } else {
600 // Proceed with the next request.
601 processHttpResponse(null, data, true);
602 }
603 }
604 csize = 0; // We are done
605 } else if ((obj.socketXHeader['connection'] != null) && (obj.socketXHeader['connection'].toLowerCase() == 'close')) {
606 // The body ends with a close, in this case, we will only process the header
607 processHttpResponse(null, obj.socketAccumulator, false);
608 obj.socketAccumulator = '';
609 return;
610 } else if ((obj.socketXHeader['transfer-encoding'] != null) && (obj.socketXHeader['transfer-encoding'].toLowerCase() == 'chunked')) {
611 // The body is chunked
612 var clen = obj.socketAccumulator.indexOf('\r\n');
613 if (clen < 0) { return; } // Chunk length not found, exit now and get more data.
614 // Chunk length if found, lets see if we can get the data.
615 csize = parseInt(obj.socketAccumulator.substring(0, clen), 16);
616 if (obj.socketAccumulator.length < clen + 2 + csize + 2) return;
617 // We got a chunk with all of the data, handle the chunck now.
618 var data = obj.socketAccumulator.substring(clen + 2, clen + 2 + csize);
619 obj.socketAccumulator = obj.socketAccumulator.substring(clen + 2 + csize + 2);
620 processHttpResponse(null, data, (csize == 0));
621 }
622 if (csize == 0) {
623 //obj.Debug("xxOnSocketData DONE: (" + obj.socketData.length + "): " + obj.socketData);
624 obj.socketParseState = 0;
625 obj.socketHeader = null;
626 }
627 }
628 if (obj.socketParseState == 2) {
629 // We are in websocket pass-thru mode, decode the websocket frame
630 if (obj.socketAccumulator.length < 2) return; // Need at least 2 bytes to decode a websocket header
631 //console.log('WebSocket frame', obj.socketAccumulator.length, Buffer.from(obj.socketAccumulator, 'binary'));
632
633 // Decode the websocket frame
634 const buf = Buffer.from(obj.socketAccumulator, 'binary');
635 const fin = ((buf[0] & 0x80) != 0);
636 const rsv = ((buf[0] & 0x70) != 0);
637 const op = buf[0] & 0x0F;
638 const mask = ((buf[1] & 0x80) != 0);
639 var len = buf[1] & 0x7F;
640 //console.log(obj.tunnelId, 'fin: ' + fin + ', rsv: ' + rsv + ', op: ' + op + ', len: ' + len);
641
642 // Calculate the total length
643 var payload = null;
644 if (len < 126) {
645 // 1 byte length
646 if (buf.length < (2 + len)) return; // Insuffisent data
647 payload = buf.slice(2, 2 + len);
648 obj.socketAccumulator = obj.socketAccumulator.substring(2 + len); // Remove data from accumulator
649 } else if (len == 126) {
650 // 2 byte length
651 if (buf.length < 4) return;
652 len = buf.readUInt16BE(2);
653 if (buf.length < (4 + len)) return; // Insuffisent data
654 payload = buf.slice(4, 4 + len);
655 obj.socketAccumulator = obj.socketAccumulator.substring(4 + len); // Remove data from accumulator
656 } if (len == 127) {
657 // 8 byte length
658 if (buf.length < 10) return;
659 len = buf.readUInt32BE(2);
660 if (len > 0) { obj.close(); return; } // This frame is larger than 4 gigabyte, close the connection.
661 len = buf.readUInt32BE(6);
662 if (buf.length < (10 + len)) return; // Insuffisent data
663 payload = buf.slice(10, 10 + len);
664 obj.socketAccumulator = obj.socketAccumulator.substring(10 + len); // Remove data from accumulator
665 }
666 if (buf.length < len) return;
667
668 // If the mask or reserved bit are true, we are not decoding this right, close the connection.
669 if ((mask == true) || (rsv == true)) { obj.close(); return; }
670
671 // TODO: If FIN is not set, we need to add support for continue frames
672 //console.log(obj.tunnelId, '<--', op, payload ? payload.length : 0);
673
674 // Perform operation
675 switch (op) {
676 case 0: { break; } // Continue frame (TODO)
677 case 1: { try { obj.ws.send(payload.toString('binary')); } catch (ex) { } break; } // Text frame
678 case 2: { try { obj.ws.send(payload); } catch (ex) { } break; } // Binary frame
679 case 8: { obj.close(); return; } // Connection close
680 case 9: { try { obj.ws.ping(payload); } catch (ex) { } break; } // Ping frame
681 case 10: { try { obj.ws.pong(payload); } catch (ex) { } break; } // Pong frame
682 }
683 }
684 }
685 }
686
687 // This is a fully parsed HTTP response from the remote device
688 function processHttpResponse(header, data, done, closed) {
689 //console.log('processHttpResponse', header, data ? data.length : 0, done, closed);
690 if (obj.isWebSocket == false) {
691 if (obj.res == null) return;
692 parent.lastOperation = obj.lastOperation = Date.now(); // Update time of last opertion performed
693
694 // If there is a header, send it
695 if (header != null) {
696 const statusCode = parseInt(header.Directive[1]);
697 if ((!isNaN(statusCode)) && (statusCode > 0) && (statusCode <= 999)) { obj.res.status(statusCode); } // Set the status
698 const blockHeaders = ['Directive', 'sec-websocket-extensions', 'connection', 'transfer-encoding', 'last-modified', 'content-security-policy', 'cache-control']; // We do not forward these headers
699 for (var i in header) {
700 if (i == 'set-cookie') {
701 for (var ii in header[i]) {
702 // Decode the new cookie
703 //console.log('set-cookie', header[i][ii]);
704 const cookieSplit = header[i][ii].split(';');
705 var newCookieName = null, newCookie = {};
706 for (var j in cookieSplit) {
707 var l = cookieSplit[j].indexOf('='), k = null, v = null;
708 if (l == -1) { k = cookieSplit[j].trim(); } else { k = cookieSplit[j].substring(0, l).trim(); v = cookieSplit[j].substring(l + 1).trim(); }
709 if (j == 0) { newCookieName = k; newCookie.value = v; } else { newCookie[k.toLowerCase()] = (v == null) ? true : v; }
710 }
711 if (newCookieName != null) {
712 if ((typeof newCookie['max-age'] == 'string') && (parseInt(newCookie['max-age']) <= 0)) {
713 delete parent.webCookies[newCookieName]; // Remove a expired cookie
714 //console.log('clear-cookie', newCookieName);
715 } else if (((newCookie.secure != true) || (obj.tls != null))) {
716 parent.webCookies[newCookieName] = newCookie; // Keep this cookie in the session
717 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.
718 //console.log('new-cookie', newCookieName, newCookie);
719 }
720 }
721 }
722 }
723 else if (blockHeaders.indexOf(i) == -1) { obj.res.set(i.trim(), header[i]); } // Set the headers if not blocked
724 }
725 // 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
726 //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
727 //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
728 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
729 }
730
731 // If there is data, send it
732 if (data != null) { try { obj.res.write(data, 'binary'); } catch (ex) { } }
733
734 // If we are done, close the response
735 if (done == true) {
736 // Close the response
737 obj.res.socket.removeListener('end', handleResponseClosure);
738 obj.res.end();
739 delete obj.res;
740
741 // Event completion
742 obj.processedRequestCount++;
743 if (obj.oncompleted) { obj.oncompleted(obj.tunnelId, closed); }
744 }
745 } else {
746 // Tunnel is now in web socket pass-thru mode
747 if (header != null) {
748 if ((typeof header.connection == 'string') && (header.connection.toLowerCase() == 'upgrade')) {
749 // Websocket upgrade succesful
750 obj.socketParseState = 2;
751 } else {
752 // Unable to upgrade to web socket
753 obj.close();
754 }
755 }
756 }
757 }
758
759 // Send data thru the relay tunnel. Written to use TLS if needed.
760 function send(data) { try { if (obj.tls) { obj.tls.write(data); } else { obj.wsClient.send(data); } } catch (ex) { } }
761
762 parent.parent.parent.debug('relay', 'TCP: Request for web relay');
763 return obj;
764};
765
766
767// Construct a MSTSC Relay object, called upon connection
768// This implementation does not have TLS support
769// This is a bit of a hack as we are going to run the RDP connection thru a loopback connection.
770// If the "node-rdpjs-2" module supported passing a socket, we would do something different.
771module.exports.CreateMstscRelay = function (parent, db, ws, req, args, domain) {
772 const Net = require('net');
773 const WebSocket = require('ws');
774
775 const obj = {};
776 obj.ws = ws;
777 obj.tcpServerPort = 0;
778 obj.relayActive = false;
779 var rdpClient = null;
780
781 parent.parent.debug('relay', 'RDP: Request for RDP relay (' + req.clientIp + ')');
782
783 // Disconnect
784 obj.close = function (arg) {
785 if (obj.ws == null) return;
786
787 // Event the session ending
788 if ((obj.startTime) && (obj.meshid != null)) {
789 // Collect how many raw bytes where received and sent.
790 // We sum both the websocket and TCP client in this case.
791 var inTraffc = obj.ws._socket.bytesRead, outTraffc = obj.ws._socket.bytesWritten;
792 if (obj.wsClient != null) { inTraffc += obj.wsClient._socket.bytesRead; outTraffc += obj.wsClient._socket.bytesWritten; }
793 const sessionSeconds = Math.round((Date.now() - obj.startTime) / 1000);
794 const user = parent.users[obj.userid];
795 const username = (user != null) ? user.name : null;
796 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 };
797 parent.parent.DispatchEvent(['*', obj.nodeid, obj.userid, obj.meshid], obj, event);
798 delete obj.startTime;
799 delete obj.sessionid;
800 }
801
802 if (obj.wsClient) { obj.wsClient.close(); delete obj.wsClient; }
803 if (obj.tcpServer) { obj.tcpServer.close(); delete obj.tcpServer; }
804 if (rdpClient) { rdpClient.close(); rdpClient = null; }
805 if ((arg == 1) || (arg == null)) { try { ws.close(); } catch (ex) { console.log(ex); } } // Soft close, close the websocket
806 if (arg == 2) { try { ws._socket._parent.end(); } catch (ex) { console.log(ex); } } // Hard close, close the TCP socket
807 obj.ws.removeAllListeners();
808 obj.relayActive = false;
809
810 delete obj.ws;
811 delete obj.nodeid;
812 delete obj.meshid;
813 delete obj.userid;
814 };
815
816 // Start the looppback server
817 function startTcpServer() {
818 obj.tcpServer = new Net.Server();
819 obj.tcpServer.listen(0, 'localhost', function () { obj.tcpServerPort = obj.tcpServer.address().port; startRdp(obj.tcpServerPort); });
820 obj.tcpServer.on('connection', function (socket) {
821 if (obj.relaySocket != null) {
822 socket.close();
823 } else {
824 obj.relaySocket = socket;
825 obj.relaySocket.pause();
826 obj.relaySocket.on('data', function (chunk) { // Make sure to handle flow control.
827 if (obj.relayActive == true) { obj.relaySocket.pause(); if (obj.wsClient != null) { obj.wsClient.send(chunk, function () { obj.relaySocket.resume(); }); } }
828 });
829 obj.relaySocket.on('end', function () { obj.close(); });
830 obj.relaySocket.on('error', function (err) { obj.close(); });
831
832 // Setup the correct URL with domain and use TLS only if needed.
833 const options = { rejectUnauthorized: false };
834 const protocol = (args.tlsoffload) ? 'ws' : 'wss';
835 var domainadd = '';
836 if ((domain.dns == null) && (domain.id != '')) { domainadd = domain.id + '/' }
837 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
838 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.
839 parent.parent.debug('relay', 'RDP: Connection websocket to ' + url);
840 obj.wsClient = new WebSocket(url, options);
841 obj.wsClient.on('open', function () { parent.parent.debug('relay', 'RDP: Relay websocket open'); });
842 obj.wsClient.on('message', function (data) { // Make sure to handle flow control.
843 if (obj.relayActive == false) {
844 if ((data == 'c') || (data == 'cr')) {
845 obj.relayActive = true;
846 obj.relaySocket.resume();
847 }
848 } else {
849 try { // Forward any ping/pong commands to the browser
850 var cmd = JSON.parse(data);
851 if ((cmd != null) && (cmd.ctrlChannel == '102938')) {
852 if (cmd.type == 'ping') { send(['ping']); }
853 else if (cmd.type == 'pong') { send(['pong']); }
854 }
855 return;
856 } catch (ex) { // You are not JSON data so just send over relaySocket
857 obj.wsClient._socket.pause();
858 try {
859 obj.relaySocket.write(data, function () {
860 if (obj.wsClient && obj.wsClient._socket) { try { obj.wsClient._socket.resume(); } catch (ex) { console.log(ex); } }
861 });
862 } catch (ex) { console.log(ex); obj.close(); }
863 }
864 }
865 });
866 obj.wsClient.on('close', function () { parent.parent.debug('relay', 'RDP: Relay websocket closed'); obj.close(); });
867 obj.wsClient.on('error', function (err) { parent.parent.debug('relay', 'RDP: Relay websocket error: ' + err); obj.close(); });
868 obj.tcpServer.close();
869 obj.tcpServer = null;
870 }
871 });
872 }
873
874 // Start the RDP client
875 function startRdp(port) {
876 parent.parent.debug('relay', 'RDP: Starting RDP client on loopback port ' + port);
877 try {
878 const args = {
879 logLevel: 'NONE', // 'ERROR',
880 domain: obj.infos.domain,
881 userName: obj.infos.username,
882 password: obj.infos.password,
883 enablePerf: true,
884 autoLogin: true,
885 screen: obj.infos.screen,
886 locale: obj.infos.locale,
887 };
888 if (obj.infos.options) {
889 if (obj.infos.options.flags != null) { args.perfFlags = obj.infos.options.flags; delete obj.infos.options.flags; }
890 if ((obj.infos.options.workingDir != null) && (obj.infos.options.workingDir != '')) { args.workingDir = obj.infos.options.workingDir; }
891 if ((obj.infos.options.alternateShell != null) && (obj.infos.options.alternateShell != '')) { args.alternateShell = obj.infos.options.alternateShell; }
892 }
893 rdpClient = require('./rdp').createClient(args).on('connect', function () {
894 send(['rdp-connect']);
895 if ((typeof obj.infos.options == 'object') && (obj.infos.options.savepass == true)) { saveRdpCredentials(); } // Save the credentials if needed
896 obj.sessionid = Buffer.from(parent.crypto.randomBytes(9), 'binary').toString('base64').replace(/\+/g, '@').replace(/\//g, '$');
897 obj.startTime = Date.now();
898
899 // Event session start
900 try {
901 const user = parent.users[obj.userid];
902 const username = (user != null) ? user.name : null;
903 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 };
904 parent.parent.DispatchEvent(['*', obj.nodeid, obj.userid, obj.meshid], obj, event);
905 } catch (ex) { console.log(ex); }
906 }).on('bitmap', function (bitmap) {
907 try { ws.send(bitmap.data); } catch (ex) { } // Send the bitmap data as binary
908 delete bitmap.data;
909 send(['rdp-bitmap', bitmap]); // Send the bitmap metadata seperately, without bitmap data.
910 }).on('clipboard', function (content) {
911 send(['rdp-clipboard', content]); // The clipboard data has changed
912 }).on('pointer', function (cursorId, cursorStr) {
913 if (cursorStr == null) { cursorStr = 'default'; }
914 if (obj.lastCursorStrSent != cursorStr) {
915 obj.lastCursorStrSent = cursorStr;
916 //console.log('pointer', cursorStr);
917 send(['rdp-pointer', cursorStr]); // The mouse pointer has changed
918 }
919 }).on('close', function () {
920 send(['rdp-close']); // This RDP session has closed
921 }).on('error', function (err) {
922 if (typeof err == 'string') { send(['rdp-error', err]); }
923 if ((typeof err == 'object') && (err.err) && (err.code)) { send(['rdp-error', err.err, err.code]); }
924 }).connect('localhost', obj.tcpServerPort);
925 } catch (ex) {
926 console.log('startRdpException', ex);
927 obj.close();
928 }
929 }
930
931 // Save RDP credentials into database
932 function saveRdpCredentials() {
933 if (domain.allowsavingdevicecredentials == false) return;
934 parent.parent.db.Get(obj.nodeid, function (err, nodes) {
935 if ((err != null) || (nodes == null) || (nodes.length != 1)) return;
936 const node = nodes[0];
937 if (node.rdp == null) { node.rdp = {}; }
938
939 // Check if credentials are already set
940 if ((typeof node.rdp[obj.userid] == 'object') && (node.rdp[obj.userid].d == obj.infos.domain) && (node.rdp[obj.userid].u == obj.infos.username) && (node.rdp[obj.userid].p == obj.infos.password)) return;
941
942 // Clear up any existing credentials or credentials for users that don't exist anymore
943 for (var i in node.rdp) { if (!i.startsWith('user/') || (parent.users[i] == null)) { delete node.rdp[i]; } }
944
945 // Clear legacy credentials
946 delete node.rdp.d;
947 delete node.rdp.u;
948 delete node.rdp.p;
949
950 // Save the credentials
951 node.rdp[obj.userid] = { d: obj.infos.domain, u: obj.infos.username, p: obj.infos.password };
952 parent.parent.db.Set(node);
953
954 // Event the node change
955 const event = { etype: 'node', action: 'changenode', nodeid: obj.nodeid, domain: domain.id, userid: obj.userid, node: parent.CloneSafeNode(node), msg: "Changed RDP credentials" };
956 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.
957 parent.parent.DispatchEvent(parent.CreateMeshDispatchTargets(node.meshid, [obj.nodeid]), obj, event);
958 });
959 }
960
961 // When data is received from the web socket
962 // RDP default port is 3389
963 ws.on('message', function (data) {
964 try {
965 var msg = null;
966 try { msg = JSON.parse(data); } catch (ex) { }
967 if ((msg == null) || (typeof msg != 'object')) return;
968 switch (msg[0]) {
969 case 'infos': {
970 obj.infos = msg[1];
971
972 if (obj.infos.ip.startsWith('node/')) {
973 // Use the user session
974 obj.nodeid = obj.infos.ip;
975 obj.userid = req.session.userid;
976 } else {
977 // Decode the authentication cookie
978 obj.cookie = parent.parent.decodeCookie(obj.infos.ip, parent.parent.loginCookieEncryptionKey);
979 if ((obj.cookie == null) || (typeof obj.cookie.nodeid != 'string') || (typeof obj.cookie.userid != 'string')) { obj.close(); return; }
980 obj.nodeid = obj.cookie.nodeid;
981 obj.userid = obj.cookie.userid;
982 }
983
984 // Get node and rights
985 parent.GetNodeWithRights(domain, obj.userid, obj.nodeid, function (node, rights, visible) {
986 if (obj.ws == null) return; // obj has been cleaned up, just exit.
987 if ((node == null) || (visible == false) || ((rights & MESHRIGHT_REMOTECONTROL) == 0)) { obj.close(); return; }
988 if ((rights != MESHRIGHT_ADMIN) && ((rights & MESHRIGHT_REMOTEVIEWONLY) != 0)) { obj.viewonly = true; }
989 if ((rights != MESHRIGHT_ADMIN) && ((rights & MESHRIGHT_DESKLIMITEDINPUT) != 0)) { obj.limitedinput = true; }
990 node = parent.common.unEscapeLinksFieldName(node); // unEscape node data for rdp/ssh credentials
991 obj.mtype = node.mtype; // Store the device group type
992 obj.meshid = node.meshid; // Store the MeshID
993
994 // Check if we need to relay thru a different agent
995 const mesh = parent.meshes[obj.meshid];
996 if (mesh && mesh.relayid) {
997 obj.relaynodeid = mesh.relayid;
998 obj.tcpaddr = node.host;
999
1000 // Get the TCP port to use
1001 var tcpport = 3389;
1002 if ((obj.cookie != null) && (obj.cookie.tcpport != null)) { tcpport = obj.cookie.tcpport; } else { if (node.rdpport) { tcpport = node.rdpport } }
1003
1004 // Re-encode a cookie with a device relay
1005 const cookieContent = { userid: obj.userid, domainid: domain.id, nodeid: mesh.relayid, tcpaddr: node.host, tcpport: tcpport };
1006 obj.infos.ip = parent.parent.encodeCookie(cookieContent, parent.parent.loginCookieEncryptionKey);
1007 } else if (obj.infos.ip.startsWith('node/')) {
1008 // Encode a cookie with a device relay
1009 const cookieContent = { userid: obj.userid, domainid: domain.id, nodeid: obj.nodeid, tcpport: node.rdpport ? node.rdpport : 3389 };
1010 obj.infos.ip = parent.parent.encodeCookie(cookieContent, parent.parent.loginCookieEncryptionKey);
1011 }
1012
1013 // Check if we have rights to the relayid device, does nothing if a relay is not used
1014 checkRelayRights(parent, domain, obj.userid, obj.relaynodeid, function (allowed) {
1015 if (obj.ws == null) return; // obj has been cleaned up, just exit.
1016 if (allowed !== true) { parent.parent.debug('relay', 'RDP: Attempt to use un-authorized relay'); obj.close(); return; }
1017
1018 // Check if we need to load server stored credentials
1019 if ((typeof obj.infos.options == 'object') && (obj.infos.options.useServerCreds == true)) {
1020 // Check if RDP credentials exist
1021 if ((domain.allowsavingdevicecredentials !== false) && (typeof node.rdp == 'object') && (typeof node.rdp[obj.userid] == 'object') && (typeof node.rdp[obj.userid].d == 'string') && (typeof node.rdp[obj.userid].u == 'string') && (typeof node.rdp[obj.userid].p == 'string')) {
1022 obj.infos.domain = node.rdp[obj.userid].d;
1023 obj.infos.username = node.rdp[obj.userid].u;
1024 obj.infos.password = node.rdp[obj.userid].p;
1025 startTcpServer();
1026 } else {
1027 // No server credentials.
1028 obj.infos.domain = '';
1029 obj.infos.username = '';
1030 obj.infos.password = '';
1031 startTcpServer();
1032 }
1033 } else {
1034 startTcpServer();
1035 }
1036 });
1037 });
1038 break;
1039 }
1040 case 'mouse': { if (rdpClient && (obj.viewonly != true)) { rdpClient.sendPointerEvent(msg[1], msg[2], msg[3], msg[4]); } break; }
1041 case 'wheel': { if (rdpClient && (obj.viewonly != true)) { rdpClient.sendWheelEvent(msg[1], msg[2], msg[3], msg[4]); } break; }
1042 case 'clipboard': { rdpClient.setClipboardData(msg[1]); break; }
1043 case 'scancode': {
1044 if (obj.limitedinput == true) { // Limit keyboard input
1045 var ok = false, k = msg[1];
1046 if ((k >= 2) && (k <= 11)) { ok = true; } // Number keys 1 to 0
1047 if ((k >= 16) && (k <= 25)) { ok = true; } // First keyboard row
1048 if ((k >= 30) && (k <= 38)) { ok = true; } // Second keyboard row
1049 if ((k >= 44) && (k <= 50)) { ok = true; } // Third keyboard row
1050 if ((k == 14) || (k == 28)) { ok = true; } // Enter and backspace
1051 if (ok == false) return;
1052 }
1053 var extended = false;
1054 var extendedkeys = [57419,57421,57416,57424,57426,57427,57417,57425,57372,57397,57415,57423,57373,57400,57399];
1055 // left,right,up,down,insert,delete,pageup,pagedown,numpadenter,numpaddivide,home,end,controlright,altright,printscreen
1056 if (extendedkeys.includes(msg[1])) extended=true;
1057 if (rdpClient && (obj.viewonly != true)) { rdpClient.sendKeyEventScancode(msg[1], msg[2], extended); } break;
1058 }
1059 case 'unicode': { if (rdpClient && (obj.viewonly != true)) { rdpClient.sendKeyEventUnicode(msg[1], msg[2]); } break; }
1060 case 'utype': {
1061 if (!rdpClient) return;
1062 obj.utype = msg[1];
1063 if (obj.utypetimer == null) {
1064 obj.utypetimer = setInterval(function () {
1065 if ((obj.utype == null) || (obj.utype.length == 0)) { clearInterval(obj.utypetimer); obj.utypetimer = null; return; }
1066 var c = obj.utype.charCodeAt(0);
1067 obj.utype = obj.utype.substring(1);
1068 if (c == 13) return;
1069 if (c == 10) { rdpClient.sendKeyEventScancode(28, true); rdpClient.sendKeyEventScancode(28, false); }
1070 else { rdpClient.sendKeyEventUnicode(c, true); rdpClient.sendKeyEventUnicode(c, false); }
1071 }, 5);
1072 }
1073 break;
1074 }
1075 case 'ping': { try { obj.wsClient.send('{"ctrlChannel":102938,"type":"ping"}'); } catch (ex) { } break; }
1076 case 'pong': { try { obj.wsClient.send('{"ctrlChannel":102938,"type":"pong"}'); } catch (ex) { } break; }
1077 case 'disconnect': { obj.close(); break; }
1078 }
1079 } catch (ex) {
1080 console.log('RdpMessageException', msg, ex);
1081 obj.close();
1082 }
1083 });
1084
1085 // If error, do nothing
1086 ws.on('error', function (err) { parent.parent.debug('relay', 'RDP: Browser websocket error: ' + err); obj.close(); });
1087
1088 // If the web socket is closed
1089 ws.on('close', function (req) { parent.parent.debug('relay', 'RDP: Browser websocket closed'); obj.close(); });
1090
1091 // Send an object with flow control
1092 function send(obj) {
1093 try { rdpClient.bufferLayer.socket.pause(); } catch (ex) { }
1094 try { ws.send(JSON.stringify(obj), function () { try { rdpClient.bufferLayer.socket.resume(); } catch (ex) { } }); } catch (ex) { }
1095 }
1096
1097 // We are all set, start receiving data
1098 ws._socket.resume();
1099
1100 return obj;
1101};
1102
1103
1104// Construct a SSH Relay object, called upon connection
1105module.exports.CreateSshRelay = function (parent, db, ws, req, args, domain) {
1106 const Net = require('net');
1107 const WebSocket = require('ws');
1108
1109 // SerialTunnel object is used to embed SSH within another connection.
1110 function SerialTunnel(options) {
1111 const obj = new require('stream').Duplex(options);
1112 obj.forwardwrite = null;
1113 obj.updateBuffer = function (chunk) { this.push(chunk); };
1114 obj._write = function (chunk, encoding, callback) { if (obj.forwardwrite != null) { obj.forwardwrite(chunk); } if (callback) callback(); }; // Pass data written to forward
1115 obj._read = function (size) { }; // Push nothing, anything to read should be pushed from updateBuffer()
1116 obj.destroy = function () { delete obj.forwardwrite; }
1117 return obj;
1118 }
1119
1120 const obj = {};
1121 obj.ws = ws;
1122 obj.relayActive = false;
1123
1124 // Disconnect
1125 obj.close = function (arg) {
1126 if (obj.ws == null) return;
1127
1128 // Event the session ending
1129 if ((obj.startTime) && (obj.meshid != null)) {
1130 // Collect how many raw bytes where received and sent.
1131 // We sum both the websocket and TCP client in this case.
1132 var inTraffc = obj.ws._socket.bytesRead, outTraffc = obj.ws._socket.bytesWritten;
1133 if (obj.wsClient != null) { inTraffc += obj.wsClient._socket.bytesRead; outTraffc += obj.wsClient._socket.bytesWritten; }
1134 const sessionSeconds = Math.round((Date.now() - obj.startTime) / 1000);
1135 const user = parent.users[obj.cookie.userid];
1136 const username = (user != null) ? user.name : null;
1137 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 };
1138 parent.parent.DispatchEvent(['*', obj.nodeid, obj.cookie.userid, obj.meshid], obj, event);
1139 delete obj.startTime;
1140 delete obj.sessionid;
1141 }
1142
1143 if (obj.sshShell) {
1144 obj.sshShell.destroy();
1145 obj.sshShell.removeAllListeners('data');
1146 obj.sshShell.removeAllListeners('close');
1147 try { obj.sshShell.end(); } catch (ex) { console.log(ex); }
1148 delete obj.sshShell;
1149 }
1150 if (obj.sshClient) {
1151 obj.sshClient.destroy();
1152 obj.sshClient.removeAllListeners('ready');
1153 try { obj.sshClient.end(); } catch (ex) { console.log(ex); }
1154 delete obj.sshClient;
1155 }
1156 if (obj.wsClient) {
1157 obj.wsClient.removeAllListeners('open');
1158 obj.wsClient.removeAllListeners('message');
1159 obj.wsClient.removeAllListeners('close');
1160 try { obj.wsClient.close(); } catch (ex) { console.log(ex); }
1161 delete obj.wsClient;
1162 }
1163
1164 if ((arg == 1) || (arg == null)) { try { ws.close(); } catch (ex) { console.log(ex); } } // Soft close, close the websocket
1165 if (arg == 2) { try { ws._socket._parent.end(); } catch (ex) { console.log(ex); } } // Hard close, close the TCP socket
1166 obj.ws.removeAllListeners();
1167
1168 obj.relayActive = false;
1169 delete obj.termSize;
1170 delete obj.cookie;
1171 delete obj.nodeid;
1172 delete obj.meshid;
1173 delete obj.userid;
1174 delete obj.ws;
1175 };
1176
1177 // Save SSH credentials into database
1178 function saveSshCredentials(keep) {
1179 if (((keep != 1) && (keep != 2)) || (domain.allowsavingdevicecredentials == false)) return;
1180 parent.parent.db.Get(obj.nodeid, function (err, nodes) {
1181 if ((err != null) || (nodes == null) || (nodes.length != 1)) return;
1182 const node = nodes[0];
1183 if (node.ssh == null) { node.ssh = {}; }
1184
1185 // Check if credentials are the same
1186 //if ((typeof node.ssh[obj.userid] == 'object') && (node.ssh[obj.userid].u == obj.username) && (node.ssh[obj.userid].p == obj.password)) return; // TODO
1187
1188 // Clear up any existing credentials or credentials for users that don't exist anymore
1189 for (var i in node.ssh) { if (!i.startsWith('user/') || (parent.users[i] == null)) { delete node.ssh[i]; } }
1190
1191 // Clear legacy credentials
1192 delete node.ssh.u;
1193 delete node.ssh.p;
1194 delete node.ssh.k;
1195 delete node.ssh.kp;
1196
1197 // Save the credentials
1198 if (obj.password != null) {
1199 node.ssh[obj.userid] = { u: obj.username, p: obj.password };
1200 } else if (obj.privateKey != null) {
1201 node.ssh[obj.userid] = { u: obj.username, k: obj.privateKey };
1202 if (keep == 2) { node.ssh[obj.userid].kp = obj.privateKeyPass; }
1203 } else return;
1204 parent.parent.db.Set(node);
1205
1206 // Event the node change
1207 const event = { etype: 'node', action: 'changenode', nodeid: obj.nodeid, domain: domain.id, userid: obj.userid, node: parent.CloneSafeNode(node), msg: "Changed SSH credentials" };
1208 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.
1209 parent.parent.DispatchEvent(parent.CreateMeshDispatchTargets(node.meshid, [obj.nodeid]), obj, event);
1210 });
1211 }
1212
1213 // Start the looppback server
1214 function startRelayConnection() {
1215 try {
1216 // Setup the correct URL with domain and use TLS only if needed.
1217 const options = { rejectUnauthorized: false };
1218 const protocol = (args.tlsoffload) ? 'ws' : 'wss';
1219 var domainadd = '';
1220 if ((domain.dns == null) && (domain.id != '')) { domainadd = domain.id + '/' }
1221 var url = protocol + '://localhost:' + args.port + '/' + domainadd + (((obj.mtype == 3) && (obj.relaynodeid == null)) ? 'local' : 'mesh') + 'relay.ashx?p=11&auth=' + obj.xcookie; // Protocol 11 is Web-SSH
1222 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.
1223 parent.parent.debug('relay', 'SSH: Connection websocket to ' + url);
1224 obj.wsClient = new WebSocket(url, options);
1225 obj.wsClient.on('open', function () { parent.parent.debug('relay', 'SSH: Relay websocket open'); });
1226 obj.wsClient.on('message', function (data) { // Make sure to handle flow control.
1227 if (obj.relayActive == false) {
1228 if ((data == 'c') || (data == 'cr')) {
1229 obj.relayActive = true;
1230
1231 // Create a serial tunnel && SSH module
1232 obj.ser = new SerialTunnel();
1233 const Client = require('ssh2').Client;
1234 obj.sshClient = new Client();
1235 obj.sshClient.on('ready', function () { // Authentication was successful.
1236 // If requested, save the credentials
1237 saveSshCredentials(obj.keep);
1238 obj.sessionid = Buffer.from(parent.crypto.randomBytes(9), 'binary').toString('base64').replace(/\+/g, '@').replace(/\//g, '$');
1239 obj.startTime = Date.now();
1240
1241 // Event start of session
1242 try {
1243 const user = parent.users[obj.cookie.userid];
1244 const username = (user != null) ? user.name : null;
1245 const event = { etype: 'relay', action: 'relaylog', domain: domain.id, nodeid: obj.nodeid, userid: user._id, username: user.name, msgid: 148, msgArgs: [obj.sessionid], msg: "Started Web-SSH session \"" + obj.sessionid + "\".", protocol: PROTOCOL_WEBSSH };
1246 parent.parent.DispatchEvent(['*', obj.nodeid, user._id, obj.meshid], obj, event);
1247 } catch (ex) { console.log(ex); }
1248
1249 obj.sshClient.shell(function (err, stream) { // Start a remote shell
1250 if (err) { obj.close(); return; }
1251 obj.sshShell = stream;
1252 obj.sshShell.setWindow(obj.termSize.rows, obj.termSize.cols, obj.termSize.height, obj.termSize.width);
1253 obj.sshShell.on('close', function () { obj.close(); });
1254 obj.sshShell.on('data', function (data) { obj.ws.send('~' + data.toString()); });
1255 });
1256 obj.ws.send(JSON.stringify({ action: 'connected' }));
1257 });
1258 obj.sshClient.on('error', function (err) {
1259 if (err.level == 'client-authentication') { try { obj.ws.send(JSON.stringify({ action: 'autherror' })); } catch (ex) { } }
1260 if (err.level == 'client-timeout') { try { obj.ws.send(JSON.stringify({ action: 'sessiontimeout' })); } catch (ex) { } }
1261 obj.close();
1262 });
1263
1264 // Setup the serial tunnel, SSH ---> Relay WS
1265 obj.ser.forwardwrite = function (data) { if ((data.length > 0) && (obj.wsClient != null)) { try { obj.wsClient.send(data); } catch (ex) { } } };
1266
1267 // Connect the SSH module to the serial tunnel
1268 const connectionOptions = { sock: obj.ser }
1269 if (typeof obj.username == 'string') { connectionOptions.username = obj.username; }
1270 if (typeof obj.password == 'string') { connectionOptions.password = obj.password; }
1271 if (typeof obj.privateKey == 'string') { connectionOptions.privateKey = obj.privateKey; }
1272 if (typeof obj.privateKeyPass == 'string') { connectionOptions.passphrase = obj.privateKeyPass; }
1273 try {
1274 obj.sshClient.connect(connectionOptions);
1275 } catch (ex) {
1276 // Exception, this is generally because we did not provide proper credentials. Ask again.
1277 obj.relayActive = false;
1278 delete obj.sshClient;
1279 delete obj.ser.forwardwrite;
1280 obj.close();
1281 return;
1282 }
1283
1284 // We are all set, start receiving data
1285 ws._socket.resume();
1286 }
1287 } else {
1288 try { // Forward any ping/pong commands to the browser
1289 var cmd = null;
1290 cmd = JSON.parse(data);
1291 if ((cmd != null) && (cmd.ctrlChannel == '102938') && ((cmd.type == 'ping') || (cmd.type == 'pong'))) { obj.ws.send(data); }
1292 return;
1293 } catch(ex) { // Relay WS --> SSH instead
1294 if ((data.length > 0) && (obj.ser != null)) { try { obj.ser.updateBuffer(data); } catch (ex) { console.log(ex); } }
1295 }
1296 }
1297 });
1298 obj.wsClient.on('close', function () { parent.parent.debug('relay', 'SSH: Relay websocket closed'); obj.close(); });
1299 obj.wsClient.on('error', function (err) { parent.parent.debug('relay', 'SSH: Relay websocket error: ' + err); obj.close(); });
1300 } catch (ex) {
1301 console.log(ex);
1302 }
1303 }
1304
1305 // When data is received from the web socket
1306 // SSH default port is 22
1307 ws.on('message', function (data) {
1308 try {
1309 if (typeof data != 'string') return;
1310 if (data[0] == '{') {
1311 // Control data
1312 var msg = null;
1313 try { msg = JSON.parse(data); } catch (ex) { }
1314 if ((msg == null) || (typeof msg != 'object')) return;
1315 if ((msg.ctrlChannel == '102938') && ((msg.type == 'ping') || (msg.type == 'pong'))) { try { obj.wsClient.send(data); } catch (ex) { } return; }
1316 if (typeof msg.action != 'string') return;
1317 switch (msg.action) {
1318 case 'connect': {
1319 if (msg.useexisting) {
1320 // Check if we have SSH credentials for this device
1321 parent.parent.db.Get(obj.cookie.nodeid, function (err, nodes) {
1322 if ((err != null) || (nodes == null) || (nodes.length != 1)) return;
1323 const node = parent.common.unEscapeLinksFieldName(nodes[0]); // unEscape node data for rdp/ssh credentials
1324 if ((domain.allowsavingdevicecredentials === false) || (node.ssh == null) || (typeof node.ssh != 'object') || (node.ssh[obj.userid] == null) || (typeof node.ssh[obj.userid].u != 'string') || ((typeof node.ssh[obj.userid].p != 'string') && (typeof node.ssh[obj.userid].k != 'string'))) {
1325 // Send a request for SSH authentication
1326 try { ws.send(JSON.stringify({ action: 'sshauth' })) } catch (ex) { }
1327 } else if ((domain.allowsavingdevicecredentials !== false) && (node.ssh != null) && (typeof node.ssh[obj.userid].k == 'string') && (node.ssh[obj.userid].kp == null)) {
1328 // Send a request for SSH authentication with option for only the private key password
1329 obj.username = node.ssh[obj.userid].u;
1330 obj.privateKey = node.ssh[obj.userid].k;
1331 try { ws.send(JSON.stringify({ action: 'sshauth', askkeypass: true })) } catch (ex) { }
1332 } else {
1333 // Use our existing credentials
1334 obj.termSize = msg;
1335 delete obj.keep;
1336 obj.username = node.ssh[obj.userid].u;
1337 if (typeof node.ssh[obj.userid].p == 'string') {
1338 obj.password = node.ssh[obj.userid].p;
1339 } else if (typeof node.ssh[obj.userid].k == 'string') {
1340 obj.privateKey = node.ssh[obj.userid].k;
1341 obj.privateKeyPass = node.ssh[obj.userid].kp;
1342 }
1343 startRelayConnection();
1344 }
1345 });
1346 } else {
1347 // Verify inputs
1348 if ((typeof msg.username != 'string') || ((typeof msg.password != 'string') && (typeof msg.key != 'string'))) break;
1349 if ((typeof msg.rows != 'number') || (typeof msg.cols != 'number') || (typeof msg.height != 'number') || (typeof msg.width != 'number')) break;
1350
1351 obj.termSize = msg;
1352 if (msg.keep === true) { msg.keep = 1; } // If true, change to 1. For user/pass, 1 to store user/pass in db. For user/key/pass, 1 to store user/key in db, 2 to store everything in db.
1353 obj.keep = msg.keep; // If set, keep store credentials on the server if the SSH tunnel connected succesfully.
1354 obj.username = msg.username;
1355 obj.password = msg.password;
1356 obj.privateKey = msg.key;
1357 obj.privateKeyPass = msg.keypass;
1358 startRelayConnection();
1359 }
1360 break;
1361 }
1362 case 'connectKeyPass': {
1363 // Verify inputs
1364 if (typeof msg.keypass != 'string') break;
1365
1366 // Check if we have SSH credentials for this device
1367 obj.privateKeyPass = msg.keypass;
1368 obj.termSize = msg;
1369 parent.parent.db.Get(obj.cookie.nodeid, function (err, nodes) {
1370 if ((err != null) || (nodes == null) || (nodes.length != 1)) return;
1371 const node = parent.common.unEscapeLinksFieldName(nodes[0]); // unEscape node data for rdp/ssh credentials
1372 if (node.ssh != null) {
1373 obj.username = node.ssh.u;
1374 obj.privateKey = node.ssh.k;
1375 startRelayConnection();
1376 }
1377 });
1378 break;
1379 }
1380 case 'resize': {
1381 // Verify inputs
1382 if ((typeof msg.rows != 'number') || (typeof msg.cols != 'number') || (typeof msg.height != 'number') || (typeof msg.width != 'number')) break;
1383
1384 obj.termSize = msg;
1385 if (obj.sshShell != null) { obj.sshShell.setWindow(obj.termSize.rows, obj.termSize.cols, obj.termSize.height, obj.termSize.width); }
1386 break;
1387 }
1388 }
1389 } else if (data[0] == '~') {
1390 // Terminal data
1391 if (obj.sshShell != null) { obj.sshShell.write(data.substring(1)); }
1392 }
1393 } catch (ex) { obj.close(); }
1394 });
1395
1396 // If error, do nothing
1397 ws.on('error', function (err) { parent.parent.debug('relay', 'SSH: Browser websocket error: ' + err); obj.close(); });
1398
1399 // If the web socket is closed
1400 ws.on('close', function (req) { parent.parent.debug('relay', 'SSH: Browser websocket closed'); obj.close(); });
1401
1402 parent.parent.debug('relay', 'SSH: Request for SSH relay (' + req.clientIp + ')');
1403
1404 // Decode the authentication cookie
1405 obj.cookie = parent.parent.decodeCookie(req.query.auth, parent.parent.loginCookieEncryptionKey);
1406 if ((obj.cookie == null) || (obj.cookie.userid == null) || (parent.users[obj.cookie.userid] == null)) { obj.ws.send(JSON.stringify({ action: 'sessionerror' })); obj.close(); return; }
1407 obj.userid = obj.cookie.userid;
1408
1409 // Get the meshid for this device
1410 parent.parent.db.Get(obj.cookie.nodeid, function (err, nodes) {
1411 if (obj.cookie == null) return; // obj has been cleaned up, just exit.
1412 if ((err != null) || (nodes == null) || (nodes.length != 1)) { parent.parent.debug('relay', 'SSH: Invalid device'); obj.close(); }
1413 const node = parent.common.unEscapeLinksFieldName(nodes[0]); // unEscape node data for rdp/ssh credentials
1414 obj.nodeid = node._id; // Store the NodeID
1415 obj.meshid = node.meshid; // Store the MeshID
1416 obj.mtype = node.mtype; // Store the device group type
1417
1418 // Check if we need to relay thru a different agent
1419 const mesh = parent.meshes[obj.meshid];
1420 if (mesh && mesh.relayid) {
1421 obj.relaynodeid = mesh.relayid;
1422 obj.tcpaddr = node.host;
1423
1424 // Check if we have rights to the relayid device, does nothing if a relay is not used
1425 checkRelayRights(parent, domain, obj.cookie.userid, obj.relaynodeid, function (allowed) {
1426 if (obj.cookie == null) return; // obj has been cleaned up, just exit.
1427 if (allowed !== true) { parent.parent.debug('relay', 'SSH: Attempt to use un-authorized relay'); obj.close(); return; }
1428
1429 // Re-encode a cookie with a device relay
1430 const cookieContent = { userid: obj.cookie.userid, domainid: obj.cookie.domainid, nodeid: mesh.relayid, tcpaddr: node.host, tcpport: obj.cookie.tcpport };
1431 obj.xcookie = parent.parent.encodeCookie(cookieContent, parent.parent.loginCookieEncryptionKey);
1432 });
1433 } else {
1434 obj.xcookie = req.query.auth;
1435 }
1436 });
1437
1438 return obj;
1439};
1440
1441
1442// Construct a SSH Terminal Relay object, called upon connection
1443module.exports.CreateSshTerminalRelay = function (parent, db, ws, req, domain, user, cookie, args) {
1444 const Net = require('net');
1445 const WebSocket = require('ws');
1446
1447 // SerialTunnel object is used to embed SSH within another connection.
1448 function SerialTunnel(options) {
1449 const obj = new require('stream').Duplex(options);
1450 obj.forwardwrite = null;
1451 obj.updateBuffer = function (chunk) { this.push(chunk); };
1452 obj._write = function (chunk, encoding, callback) { if (obj.forwardwrite != null) { obj.forwardwrite(chunk); } if (callback) callback(); }; // Pass data written to forward
1453 obj._read = function (size) { }; // Push nothing, anything to read should be pushed from updateBuffer()
1454 obj.destroy = function () { delete obj.forwardwrite; }
1455 return obj;
1456 }
1457
1458 const obj = {};
1459 obj.ws = ws;
1460 obj.relayActive = false;
1461
1462 parent.parent.debug('relay', 'SSH: Request for SSH terminal relay (' + req.clientIp + ')');
1463
1464 // Disconnect
1465 obj.close = function (arg) {
1466 if (obj.ws == null) return;
1467
1468 // Event the session ending
1469 if (obj.startTime) {
1470 // Collect how many raw bytes where received and sent.
1471 // We sum both the websocket and TCP client in this case.
1472 var inTraffc = obj.ws._socket.bytesRead, outTraffc = obj.ws._socket.bytesWritten;
1473 if (obj.wsClient != null) { inTraffc += obj.wsClient._socket.bytesRead; outTraffc += obj.wsClient._socket.bytesWritten; }
1474 const sessionSeconds = Math.round((Date.now() - obj.startTime) / 1000);
1475 const event = { etype: 'relay', action: 'relaylog', domain: domain.id, nodeid: obj.nodeid, userid: user._id, username: user.name, msgid: 123, msgArgs: [sessionSeconds, obj.sessionid], msg: "Left Web-SSH session \"" + obj.sessionid + "\" after " + sessionSeconds + " second(s).", protocol: PROTOCOL_WEBSSH, bytesin: inTraffc, bytesout: outTraffc };
1476 parent.parent.DispatchEvent(['*', obj.nodeid, user._id, obj.meshid], obj, event);
1477 delete obj.startTime;
1478 delete obj.sessionid;
1479 }
1480
1481 if (obj.sshShell) {
1482 obj.sshShell.destroy();
1483 obj.sshShell.removeAllListeners('data');
1484 obj.sshShell.removeAllListeners('close');
1485 try { obj.sshShell.end(); } catch (ex) { console.log(ex); }
1486 delete obj.sshShell;
1487 }
1488 if (obj.sshClient) {
1489 obj.sshClient.destroy();
1490 obj.sshClient.removeAllListeners('ready');
1491 try { obj.sshClient.end(); } catch (ex) { console.log(ex); }
1492 delete obj.sshClient;
1493 }
1494 if (obj.wsClient) {
1495 obj.wsClient.removeAllListeners('open');
1496 obj.wsClient.removeAllListeners('message');
1497 obj.wsClient.removeAllListeners('close');
1498 try { obj.wsClient.close(); } catch (ex) { console.log(ex); }
1499 delete obj.wsClient;
1500 }
1501
1502 if ((arg == 1) || (arg == null)) { try { ws.close(); } catch (ex) { console.log(ex); } } // Soft close, close the websocket
1503 if (arg == 2) { try { ws._socket._parent.end(); } catch (ex) { console.log(ex); } } // Hard close, close the TCP socket
1504 obj.ws.removeAllListeners();
1505
1506 obj.relayActive = false;
1507 delete obj.termSize;
1508 delete obj.nodeid;
1509 delete obj.meshid;
1510 delete obj.ws;
1511 };
1512
1513 // Save SSH credentials into device
1514 function saveSshCredentials(keep) {
1515 if (((keep != 1) && (keep != 2)) || (domain.allowsavingdevicecredentials == false)) return;
1516 parent.parent.db.Get(obj.nodeid, function (err, nodes) {
1517 if ((err != null) || (nodes == null) || (nodes.length != 1)) return;
1518 const node = nodes[0];
1519 if (node.ssh == null) { node.ssh = {}; }
1520
1521 // Check if credentials are the same
1522 //if ((typeof node.ssh == 'object') && (node.ssh.u == obj.username) && (node.ssh.p == obj.password)) return; // TODO
1523
1524 // Clear up any existing credentials or credentials for users that don't exist anymore
1525 for (var i in node.ssh) { if (!i.startsWith('user/') || (parent.users[i] == null)) { delete node.ssh[i]; } }
1526
1527 // Clear legacy credentials
1528 delete node.ssh.u;
1529 delete node.ssh.p;
1530 delete node.ssh.k;
1531 delete node.ssh.kp;
1532
1533 // Save the credentials
1534 if (obj.password != null) {
1535 node.ssh[user._id] = { u: obj.username, p: obj.password };
1536 } else if (obj.privateKey != null) {
1537 node.ssh[user._id] = { u: obj.username, k: obj.privateKey };
1538 if (keep == 2) { node.ssh[user._id].kp = obj.privateKeyPass; }
1539 } else return;
1540 parent.parent.db.Set(node);
1541
1542 // Event the node change
1543 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" };
1544 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.
1545 parent.parent.DispatchEvent(parent.CreateMeshDispatchTargets(node.meshid, [obj.nodeid]), obj, event);
1546 });
1547 }
1548
1549
1550 // Start the looppback server
1551 function startRelayConnection(authCookie) {
1552 try {
1553 // Setup the correct URL with domain and use TLS only if needed.
1554 const options = { rejectUnauthorized: false };
1555 const protocol = (args.tlsoffload) ? 'ws' : 'wss';
1556 var domainadd = '';
1557 if ((domain.dns == null) && (domain.id != '')) { domainadd = domain.id + '/' }
1558 var url = protocol + '://localhost:' + args.port + '/' + domainadd + (((obj.mtype == 3) && (obj.relaynodeid == null)) ? 'local' : 'mesh') + 'relay.ashx?p=11&auth=' + authCookie // Protocol 11 is Web-SSH
1559 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.
1560 parent.parent.debug('relay', 'SSH: Connection websocket to ' + url);
1561 obj.wsClient = new WebSocket(url, options);
1562 obj.wsClient.on('open', function () { parent.parent.debug('relay', 'SSH: Relay websocket open'); });
1563 obj.wsClient.on('message', function (data) { // Make sure to handle flow control.
1564 if (obj.relayActive == false) {
1565 if ((data == 'c') || (data == 'cr')) {
1566 obj.relayActive = true;
1567
1568 // Create a serial tunnel && SSH module
1569 obj.ser = new SerialTunnel();
1570 const Client = require('ssh2').Client;
1571 obj.sshClient = new Client();
1572 obj.sshClient.on('ready', function () { // Authentication was successful.
1573 // If requested, save the credentials
1574 saveSshCredentials(obj.keep);
1575 obj.sessionid = Buffer.from(parent.crypto.randomBytes(9), 'binary').toString('base64').replace(/\+/g, '@').replace(/\//g, '$');
1576 obj.startTime = Date.now();
1577
1578 try {
1579 // Event start of session
1580 const event = { etype: 'relay', action: 'relaylog', domain: domain.id, nodeid: obj.nodeid, userid: user._id, username: user.name, msgid: 148, msgArgs: [obj.sessionid], msg: "Started Web-SSH session \"" + obj.sessionid + "\".", protocol: PROTOCOL_WEBSSH };
1581 parent.parent.DispatchEvent(['*', obj.nodeid, user._id, obj.meshid], obj, event);
1582 } catch (ex) {
1583 console.log(ex);
1584 }
1585
1586 obj.sshClient.shell(function (err, stream) { // Start a remote shell
1587 if (err) { obj.close(); return; }
1588 obj.sshShell = stream;
1589 obj.sshShell.setWindow(obj.termSize.rows, obj.termSize.cols, obj.termSize.height, obj.termSize.width);
1590 obj.sshShell.on('close', function () { obj.close(); });
1591 obj.sshShell.on('data', function (data) { obj.ws.send('~' + data.toString()); });
1592 });
1593
1594 obj.connected = true;
1595 obj.ws.send('c');
1596 });
1597 obj.sshClient.on('error', function (err) {
1598 if (err.level == 'client-authentication') { try { obj.ws.send(JSON.stringify({ action: 'autherror' })); } catch (ex) { } }
1599 if (err.level == 'client-timeout') { try { obj.ws.send(JSON.stringify({ action: 'sessiontimeout' })); } catch (ex) { } }
1600 obj.close();
1601 });
1602
1603 // Setup the serial tunnel, SSH ---> Relay WS
1604 obj.ser.forwardwrite = function (data) { if ((data.length > 0) && (obj.wsClient != null)) { try { obj.wsClient.send(data); } catch (ex) { } } };
1605
1606 // Connect the SSH module to the serial tunnel
1607 const connectionOptions = { sock: obj.ser }
1608 if (typeof obj.username == 'string') { connectionOptions.username = obj.username; }
1609 if (typeof obj.password == 'string') { connectionOptions.password = obj.password; }
1610 if (typeof obj.privateKey == 'string') { connectionOptions.privateKey = obj.privateKey; }
1611 if (typeof obj.privateKeyPass == 'string') { connectionOptions.passphrase = obj.privateKeyPass; }
1612 try {
1613 obj.sshClient.connect(connectionOptions);
1614 } catch (ex) {
1615 // Exception, this is generally because we did not provide proper credentials. Ask again.
1616 obj.relayActive = false;
1617 delete obj.sshClient;
1618 delete obj.ser.forwardwrite;
1619 try { ws.send(JSON.stringify({ action: 'sshauth', askkeypass: ((obj.username != null) && (obj.privateKey != null)) })) } catch (ex) { }
1620 }
1621
1622 // We are all set, start receiving data
1623 ws._socket.resume();
1624 }
1625 } else {
1626 try { // Forward any ping/pong commands to the browser
1627 var cmd = null;
1628 cmd = JSON.parse(data);
1629 if ((cmd != null) && (cmd.ctrlChannel == '102938') && ((cmd.type == 'ping') || (cmd.type == 'pong'))) { try { obj.ws.send(data); } catch (ex) { console.log(ex); } }
1630 return;
1631 } catch (ex) { // Relay WS --> SSH
1632 if ((data.length > 0) && (obj.ser != null)) { try { obj.ser.updateBuffer(data); } catch (ex) { console.log(ex); } }
1633 }
1634 }
1635 });
1636 obj.wsClient.on('close', function () {
1637 if (obj.connected !== true) { try { obj.ws.send(JSON.stringify({ action: 'connectionerror' })); } catch (ex) { } }
1638 parent.parent.debug('relay', 'SSH: Relay websocket closed'); obj.close();
1639 });
1640 obj.wsClient.on('error', function (err) { parent.parent.debug('relay', 'SSH: Relay websocket error: ' + err); obj.close(); });
1641 } catch (ex) {
1642 console.log(ex);
1643 }
1644 }
1645
1646 // When data is received from the web socket
1647 // SSH default port is 22
1648 ws.on('message', function (data) {
1649 try {
1650 if (typeof data != 'string') return;
1651 if (data[0] == '{') {
1652 // Control data
1653 var msg = null;
1654 try { msg = JSON.parse(data); } catch (ex) { }
1655 if ((msg == null) || (typeof msg != 'object')) return;
1656 if ((msg.ctrlChannel == '102938') && ((msg.type == 'ping') || (msg.type == 'pong'))) { try { obj.wsClient.send(data); } catch (ex) { } return; }
1657 switch (msg.action) {
1658 case 'sshauth': {
1659 // Verify inputs
1660 if ((typeof msg.username != 'string') || ((typeof msg.password != 'string') && (typeof msg.key != 'string'))) break;
1661 if ((typeof msg.rows != 'number') || (typeof msg.cols != 'number') || (typeof msg.height != 'number') || (typeof msg.width != 'number')) break;
1662
1663 if (msg.keep === true) { msg.keep = 1; } // If true, change to 1. For user/pass, 1 to store user/pass in db. For user/key/pass, 1 to store user/key in db, 2 to store everything in db.
1664 obj.keep = msg.keep; // If set, keep store credentials on the server if the SSH tunnel connected succesfully.
1665 obj.termSize = msg;
1666 obj.username = msg.username;
1667 obj.password = msg.password;
1668 obj.privateKey = msg.key;
1669 obj.privateKeyPass = msg.keypass;
1670
1671 // Create a mesh relay authentication cookie
1672 const cookieContent = { userid: user._id, domainid: user.domain, nodeid: obj.nodeid, tcpport: obj.tcpport };
1673 if (obj.relaynodeid) {
1674 cookieContent.nodeid = obj.relaynodeid;
1675 cookieContent.tcpaddr = obj.tcpaddr;
1676 } else {
1677 if (obj.mtype == 3) { cookieContent.lc = 1; } // This is a local device
1678 }
1679 startRelayConnection(parent.parent.encodeCookie(cookieContent, parent.parent.loginCookieEncryptionKey));
1680 break;
1681 }
1682 case 'sshkeyauth': {
1683 // Verify inputs
1684 if (typeof msg.keypass != 'string') break;
1685 if ((typeof msg.rows != 'number') || (typeof msg.cols != 'number') || (typeof msg.height != 'number') || (typeof msg.width != 'number')) break;
1686
1687 delete obj.keep;
1688 obj.termSize = msg;
1689 obj.privateKeyPass = msg.keypass;
1690
1691 // Create a mesh relay authentication cookie
1692 const cookieContent = { userid: user._id, domainid: user.domain, nodeid: obj.nodeid, tcpport: obj.tcpport };
1693 if (obj.relaynodeid) {
1694 cookieContent.nodeid = obj.relaynodeid;
1695 cookieContent.tcpaddr = obj.tcpaddr;
1696 } else {
1697 if (obj.mtype == 3) { cookieContent.lc = 1; } // This is a local device
1698 }
1699 startRelayConnection(parent.parent.encodeCookie(cookieContent, parent.parent.loginCookieEncryptionKey));
1700 break;
1701 }
1702 case 'sshautoauth': {
1703 // Verify inputs
1704 if ((typeof msg.rows != 'number') || (typeof msg.cols != 'number') || (typeof msg.height != 'number') || (typeof msg.width != 'number')) break;
1705 obj.termSize = msg;
1706
1707 if ((obj.username == null) || ((obj.password == null) && (obj.privateKey == null))) return;
1708
1709 // Create a mesh relay authentication cookie
1710 const cookieContent = { userid: user._id, domainid: user.domain, nodeid: obj.nodeid, tcpport: obj.tcpport };
1711 if (obj.relaynodeid) {
1712 cookieContent.nodeid = obj.relaynodeid;
1713 cookieContent.tcpaddr = obj.tcpaddr;
1714 } else {
1715 if (obj.mtype == 3) { cookieContent.lc = 1; } // This is a local device
1716 }
1717 startRelayConnection(parent.parent.encodeCookie(cookieContent, parent.parent.loginCookieEncryptionKey));
1718 break;
1719 }
1720 case 'resize': {
1721 // Verify inputs
1722 if ((typeof msg.rows != 'number') || (typeof msg.cols != 'number') || (typeof msg.height != 'number') || (typeof msg.width != 'number')) break;
1723
1724 obj.termSize = msg;
1725 if (obj.sshShell != null) { obj.sshShell.setWindow(obj.termSize.rows, obj.termSize.cols, obj.termSize.height, obj.termSize.width); }
1726 break;
1727 }
1728 }
1729 } else if (data[0] == '~') {
1730 // Terminal data
1731 if (obj.sshShell != null) { obj.sshShell.write(data.substring(1)); }
1732 }
1733 } catch (ex) { obj.close(); }
1734 });
1735
1736 // If error, do nothing
1737 ws.on('error', function (err) { parent.parent.debug('relay', 'SSH: Browser websocket error: ' + err); obj.close(); });
1738
1739 // If the web socket is closed
1740 ws.on('close', function (req) { parent.parent.debug('relay', 'SSH: Browser websocket closed'); obj.close(); });
1741
1742 // Check that we have a user and nodeid
1743 if ((user == null) || (req.query.nodeid == null)) { obj.close(); return; } // Invalid nodeid
1744 parent.GetNodeWithRights(domain, user, req.query.nodeid, function (node, rights, visible) {
1745 if (obj.ws == null) return; // obj has been cleaned up, just exit.
1746 node = parent.common.unEscapeLinksFieldName(node); // unEscape node data for rdp/ssh credentials
1747
1748 // Check permissions
1749 if ((rights & 8) == 0) { obj.close(); return; } // No MESHRIGHT_REMOTECONTROL rights
1750 if ((rights != 0xFFFFFFFF) && (rights & 0x00000200)) { obj.close(); return; } // MESHRIGHT_NOTERMINAL is set
1751 obj.mtype = node.mtype; // Store the device group type
1752 obj.nodeid = node._id; // Store the NodeID
1753 obj.meshid = node.meshid; // Store the MeshID
1754
1755 // Check the SSH port
1756 obj.tcpport = 22;
1757 if (typeof node.sshport == 'number') { obj.tcpport = node.sshport; }
1758
1759 // Check if we need to relay thru a different agent
1760 const mesh = parent.meshes[obj.meshid];
1761 if (mesh && mesh.relayid) { obj.relaynodeid = mesh.relayid; obj.tcpaddr = node.host; }
1762
1763 // Check if we have rights to the relayid device, does nothing if a relay is not used
1764 checkRelayRights(parent, domain, user, obj.relaynodeid, function (allowed) {
1765 if (obj.ws == null) return; // obj has been cleaned up, just exit.
1766 if (allowed !== true) { parent.parent.debug('relay', 'SSH: Attempt to use un-authorized relay'); obj.close(); return; }
1767
1768 // We are all set, start receiving data
1769 ws._socket.resume();
1770
1771 // Check if we have SSH credentials for this device
1772 if ((domain.allowsavingdevicecredentials === false) || (node.ssh == null) || (typeof node.ssh != 'object') || (node.ssh[user._id] == null) || (typeof node.ssh[user._id].u != 'string') || ((typeof node.ssh[user._id].p != 'string') && (typeof node.ssh[user._id].k != 'string'))) {
1773 // Send a request for SSH authentication
1774 try { ws.send(JSON.stringify({ action: 'sshauth' })) } catch (ex) { }
1775 } else if ((typeof node.ssh[user._id].k == 'string') && (typeof node.ssh[user._id].kp != 'string')) {
1776 // Send a request for SSH authentication with option for only the private key password
1777 obj.username = node.ssh[user._id].u;
1778 obj.privateKey = node.ssh[user._id].k;
1779 try { ws.send(JSON.stringify({ action: 'sshauth', askkeypass: true })) } catch (ex) { }
1780 } else {
1781 // Use our existing credentials
1782 obj.username = node.ssh[user._id].u;
1783 if (typeof node.ssh[user._id].p == 'string') {
1784 obj.password = node.ssh[user._id].p;
1785 } else if (typeof node.ssh[user._id].k == 'string') {
1786 obj.privateKey = node.ssh[user._id].k;
1787 obj.privateKeyPass = node.ssh[user._id].kp;
1788 }
1789 try { ws.send(JSON.stringify({ action: 'sshautoauth' })) } catch (ex) { }
1790 }
1791 });
1792
1793 });
1794
1795 return obj;
1796};
1797
1798
1799
1800// Construct a SSH Files Relay object, called upon connection
1801module.exports.CreateSshFilesRelay = function (parent, db, ws, req, domain, user, cookie, args) {
1802 const Net = require('net');
1803 const WebSocket = require('ws');
1804
1805 // SerialTunnel object is used to embed SSH within another connection.
1806 function SerialTunnel(options) {
1807 const obj = new require('stream').Duplex(options);
1808 obj.forwardwrite = null;
1809 obj.updateBuffer = function (chunk) { this.push(chunk); };
1810 obj._write = function (chunk, encoding, callback) { if (obj.forwardwrite != null) { obj.forwardwrite(chunk); } if (callback) callback(); }; // Pass data written to forward
1811 obj._read = function (size) { }; // Push nothing, anything to read should be pushed from updateBuffer()
1812 obj.destroy = function () { delete obj.forwardwrite; }
1813 return obj;
1814 }
1815
1816 const obj = {};
1817 obj.ws = ws;
1818 obj.path = require('path');
1819 obj.relayActive = false;
1820 obj.firstMessage = true;
1821
1822 parent.parent.debug('relay', 'SSH: Request for SSH files relay (' + req.clientIp + ')');
1823
1824 // Disconnect
1825 obj.close = function (arg) {
1826 if (obj.ws == null) return;
1827
1828 // Event the session ending
1829 if (obj.startTime) {
1830 // Collect how many raw bytes where received and sent.
1831 // We sum both the websocket and TCP client in this case.
1832 var inTraffc = obj.ws._socket.bytesRead, outTraffc = obj.ws._socket.bytesWritten;
1833 if (obj.wsClient != null) { inTraffc += obj.wsClient._socket.bytesRead; outTraffc += obj.wsClient._socket.bytesWritten; }
1834 const sessionSeconds = Math.round((Date.now() - obj.startTime) / 1000);
1835 const event = { etype: 'relay', action: 'relaylog', domain: domain.id, nodeid: obj.nodeid, userid: user._id, username: user.name, sessionid: obj.sessionid, msgid: 124, msgArgs: [sessionSeconds, obj.sessionid], msg: "Left Web-SFTP session \"" + obj.sessionid + "\" after " + sessionSeconds + " second(s).", protocol: PROTOCOL_WEBSFTP, bytesin: inTraffc, bytesout: outTraffc };
1836 parent.parent.DispatchEvent(['*', obj.nodeid, user._id, obj.meshid], obj, event);
1837 delete obj.startTime;
1838 delete obj.sessionid;
1839 }
1840
1841 if (obj.sshClient) {
1842 obj.sshClient.destroy();
1843 obj.sshClient.removeAllListeners('ready');
1844 try { obj.sshClient.end(); } catch (ex) { console.log(ex); }
1845 delete obj.sshClient;
1846 }
1847 if (obj.wsClient) {
1848 obj.wsClient.removeAllListeners('open');
1849 obj.wsClient.removeAllListeners('message');
1850 obj.wsClient.removeAllListeners('close');
1851 try { obj.wsClient.close(); } catch (ex) { console.log(ex); }
1852 delete obj.wsClient;
1853 }
1854
1855 if ((arg == 1) || (arg == null)) { try { ws.close(); } catch (ex) { console.log(ex); } } // Soft close, close the websocket
1856 if (arg == 2) { try { ws._socket._parent.end(); } catch (ex) { console.log(ex); } } // Hard close, close the TCP socket
1857 obj.ws.removeAllListeners();
1858
1859 obj.relayActive = false;
1860 delete obj.sftp;
1861 delete obj.nodeid;
1862 delete obj.meshid;
1863 delete obj.ws;
1864 };
1865
1866 // Save SSH credentials into device
1867 function saveSshCredentials(keep) {
1868 if (((keep != 1) && (keep != 2)) || (domain.allowsavingdevicecredentials == false)) return;
1869 parent.parent.db.Get(obj.nodeid, function (err, nodes) {
1870 if ((err != null) || (nodes == null) || (nodes.length != 1)) return;
1871 const node = nodes[0];
1872 if (node.ssh == null) { node.ssh = {}; }
1873
1874 // Check if credentials are the same
1875 //if ((typeof node.ssh[obj.userid] == 'object') && (node.ssh[obj.userid].u == obj.username) && (node.ssh[obj.userid].p == obj.password)) return; // TODO
1876
1877 // Clear up any existing credentials or credentials for users that don't exist anymore
1878 for (var i in node.ssh) { if (!i.startsWith('user/') || (parent.users[i] == null)) { delete node.ssh[i]; } }
1879
1880 // Clear legacy credentials
1881 delete node.ssh.u;
1882 delete node.ssh.p;
1883 delete node.ssh.k;
1884 delete node.ssh.kp;
1885
1886 // Save the credentials
1887 if (obj.password != null) {
1888 node.ssh[user._id] = { u: obj.username, p: obj.password };
1889 } else if (obj.privateKey != null) {
1890 node.ssh[user._id] = { u: obj.username, k: obj.privateKey };
1891 if (keep == 2) { node.ssh[user._id].kp = obj.privateKeyPass; }
1892 } else return;
1893 parent.parent.db.Set(node);
1894
1895 // Event the node change
1896 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" };
1897 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.
1898 parent.parent.DispatchEvent(parent.CreateMeshDispatchTargets(node.meshid, [obj.nodeid]), obj, event);
1899 });
1900 }
1901
1902
1903 // Start the looppback server
1904 function startRelayConnection(authCookie) {
1905 try {
1906 // Setup the correct URL with domain and use TLS only if needed.
1907 const options = { rejectUnauthorized: false };
1908 const protocol = (args.tlsoffload) ? 'ws' : 'wss';
1909 var domainadd = '';
1910 if ((domain.dns == null) && (domain.id != '')) { domainadd = domain.id + '/' }
1911 var url = protocol + '://localhost:' + args.port + '/' + domainadd + (((obj.mtype == 3) && (obj.relaynodeid == null)) ? 'local' : 'mesh') + 'relay.ashx?p=13&auth=' + authCookie // Protocol 13 is Web-SSH-Files
1912 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.
1913 parent.parent.debug('relay', 'SSH: Connection websocket to ' + url);
1914 obj.wsClient = new WebSocket(url, options);
1915 obj.wsClient.on('open', function () { parent.parent.debug('relay', 'SSH: Relay websocket open'); });
1916 obj.wsClient.on('message', function (data) { // Make sure to handle flow control.
1917 if (obj.relayActive == false) {
1918 if ((data == 'c') || (data == 'cr')) {
1919 obj.relayActive = true;
1920
1921 // Create a serial tunnel && SSH module
1922 obj.ser = new SerialTunnel();
1923 const Client = require('ssh2').Client;
1924 obj.sshClient = new Client();
1925 obj.sshClient.on('ready', function () { // Authentication was successful.
1926 // If requested, save the credentials
1927 saveSshCredentials(obj.keep);
1928 obj.sessionid = Buffer.from(parent.crypto.randomBytes(9), 'binary').toString('base64').replace(/\+/g, '@').replace(/\//g, '$');
1929 obj.startTime = Date.now();
1930
1931 // Event start of session
1932 try {
1933 const event = { etype: 'relay', action: 'relaylog', domain: domain.id, nodeid: obj.nodeid, userid: user._id, username: user.name, msgid: 149, msgArgs: [obj.sessionid], msg: "Started Web-SFTP session \"" + obj.sessionid + "\".", protocol: PROTOCOL_WEBSFTP };
1934 parent.parent.DispatchEvent(['*', obj.nodeid, user._id, obj.meshid], obj, event);
1935 } catch (ex) { console.log(ex); }
1936
1937 obj.sshClient.sftp(function (err, sftp) {
1938 if (err) { obj.close(); return; }
1939 obj.connected = true;
1940 obj.sftp = sftp;
1941 obj.ws.send('c');
1942 });
1943 });
1944 obj.sshClient.on('error', function (err) {
1945 if (err.level == 'client-authentication') { try { obj.ws.send(JSON.stringify({ action: 'autherror' })); } catch (ex) { } }
1946 if (err.level == 'client-timeout') { try { obj.ws.send(JSON.stringify({ action: 'sessiontimeout' })); } catch (ex) { } }
1947 obj.close();
1948 });
1949
1950 // Setup the serial tunnel, SSH ---> Relay WS
1951 obj.ser.forwardwrite = function (data) { if ((data.length > 0) && (obj.wsClient != null)) { try { obj.wsClient.send(data); } catch (ex) { } } };
1952
1953 // Connect the SSH module to the serial tunnel
1954 const connectionOptions = { sock: obj.ser }
1955 if (typeof obj.username == 'string') { connectionOptions.username = obj.username; }
1956 if (typeof obj.password == 'string') { connectionOptions.password = obj.password; }
1957 if (typeof obj.privateKey == 'string') { connectionOptions.privateKey = obj.privateKey; }
1958 if (typeof obj.privateKeyPass == 'string') { connectionOptions.passphrase = obj.privateKeyPass; }
1959 try {
1960 obj.sshClient.connect(connectionOptions);
1961 } catch (ex) {
1962 // Exception, this is generally because we did not provide proper credentials. Ask again.
1963 obj.relayActive = false;
1964 delete obj.sshClient;
1965 delete obj.ser.forwardwrite;
1966 try { ws.send(JSON.stringify({ action: 'sshauth', askkeypass: ((obj.username != null) && (obj.privateKey != null)) })) } catch (ex) { }
1967 }
1968
1969 // We are all set, start receiving data
1970 ws._socket.resume();
1971 }
1972 } else {
1973 try {
1974 // Forward any ping/pong commands to the browser
1975 var cmd = null;
1976 cmd = JSON.parse(data);
1977 if ((cmd != null) && (cmd.ctrlChannel == '102938') && ((cmd.type == 'ping') || (cmd.type == 'pong'))) { obj.ws.send(data); }
1978 return;
1979 } catch (ex) { // Relay WS --> SSH
1980 if ((data.length > 0) && (obj.ser != null)) { try { obj.ser.updateBuffer(data); } catch (ex) { console.log(ex); } }
1981 }
1982 }
1983 });
1984 obj.wsClient.on('close', function () {
1985 if (obj.connected !== true) { try { obj.ws.send(JSON.stringify({ action: 'connectionerror' })); } catch (ex) { } }
1986 parent.parent.debug('relay', 'SSH: Files relay websocket closed'); obj.close();
1987 });
1988 obj.wsClient.on('error', function (err) { parent.parent.debug('relay', 'SSH: Files relay websocket error: ' + err); obj.close(); });
1989 } catch (ex) {
1990 console.log(ex);
1991 }
1992 }
1993
1994 // When data is received from the web socket
1995 // SSH default port is 22
1996 ws.on('message', function (data) {
1997 //if ((obj.firstMessage === true) && (msg != 5)) { obj.close(); return; } else { delete obj.firstMessage; }
1998 try {
1999 if (typeof data != 'string') {
2000 if (data[0] == 123) {
2001 data = data.toString();
2002 } else if ((obj.sftp != null) && (obj.uploadHandle != null)) {
2003 const off = (data[0] == 0) ? 1 : 0;
2004 obj.sftp.write(obj.uploadHandle, data, off, data.length - off, obj.uploadPosition, function (err) {
2005 if (err != null) {
2006 obj.sftp.close(obj.uploadHandle, function () { });
2007 try { obj.ws.send(Buffer.from(JSON.stringify({ action: 'uploaddone', reqid: obj.uploadReqid }))) } catch (ex) { }
2008 delete obj.uploadHandle;
2009 delete obj.uploadFullpath;
2010 delete obj.uploadSize;
2011 delete obj.uploadReqid;
2012 delete obj.uploadPosition;
2013 } else {
2014 try { obj.ws.send(Buffer.from(JSON.stringify({ action: 'uploadack', reqid: obj.uploadReqid }))) } catch (ex) { }
2015 }
2016 });
2017 obj.uploadPosition += (data.length - off);
2018 return;
2019 }
2020 }
2021 if (data[0] == '{') {
2022 // Control data
2023 var msg = null;
2024 try { msg = JSON.parse(data); } catch (ex) { }
2025 if ((msg == null) || (typeof msg != 'object')) return;
2026 if ((msg.ctrlChannel == '102938') && ((msg.type == 'ping') || (msg.type == 'pong'))) { try { obj.wsClient.send(data); } catch (ex) { } return; }
2027 if (typeof msg.action != 'string') return;
2028 switch (msg.action) {
2029 case 'ls': {
2030 if (obj.sftp == null) return;
2031 var requestedPath = msg.path;
2032 if (requestedPath.startsWith('/') == false) { requestedPath = '/' + requestedPath; }
2033 obj.sftp.readdir(requestedPath, function(err, list) {
2034 if (err) { console.log(err); obj.close(); }
2035 const r = { path: requestedPath, reqid: msg.reqid, dir: [] };
2036 for (var i in list) {
2037 const file = list[i];
2038 if (file.longname[0] == 'd') { r.dir.push({ t: 2, n: file.filename, d: new Date(file.attrs.mtime * 1000).toISOString() }); }
2039 else { r.dir.push({ t: 3, n: file.filename, d: new Date(file.attrs.mtime * 1000).toISOString(), s: file.attrs.size }); }
2040 }
2041 try { obj.ws.send(Buffer.from(JSON.stringify(r))) } catch (ex) { }
2042 });
2043 break;
2044 }
2045 case 'mkdir': {
2046 if (obj.sftp == null) return;
2047 var requestedPath = msg.path;
2048 if (requestedPath.startsWith('/') == false) { requestedPath = '/' + requestedPath; }
2049 obj.sftp.mkdir(requestedPath, function (err) { });
2050
2051 // Event the file delete
2052 const targets = ['*', 'server-users'];
2053 if (user.groups) { for (var i in user.groups) { targets.push('server-users:' + i); } }
2054 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 });
2055 break;
2056 }
2057 case 'mkfile': {
2058 if (obj.sftp == null) return;
2059 var requestedPath = msg.path;
2060 if (requestedPath.startsWith('/') == false) { requestedPath = '/' + requestedPath; }
2061 obj.sftp.open(requestedPath, 'w', 0o666, function (err, handle) {
2062 if (err != null) {
2063 // To-do: Report error?
2064 } else {
2065 obj.uploadHandle = handle;
2066 if (obj.uploadHandle != null) {
2067 obj.sftp.close(obj.uploadHandle, function () {
2068 // Event the file create
2069 const targets = ['*', 'server-users'];
2070 if (user.groups) { for (var i in user.groups) { targets.push('server-users:' + i); } }
2071 parent.parent.DispatchEvent(targets, obj, { etype: 'node', action: 'agentlog', nodeid: obj.nodeid, userid: user._id, username: user.name, msgid: 164, msgArgs: [requestedPath], msg: 'Create file: \"' + requestedPath + '\"', domain: domain.id });
2072 });
2073 delete obj.uploadHandle;
2074 }
2075 }
2076 });
2077 break;
2078 }
2079 case 'rm': {
2080 if (obj.sftp == null) return;
2081 var requestedPath = msg.path;
2082 if (requestedPath.startsWith('/') == false) { requestedPath = '/' + requestedPath; }
2083 for (var i in msg.delfiles) {
2084 const ul = obj.path.join(requestedPath, msg.delfiles[i]).split('\\').join('/');
2085 obj.sftp.unlink(ul, function (err) { });
2086 if (msg.rec === true) { obj.sftp.rmdir(ul + '/', function (err) { }); }
2087
2088 // Event the file delete
2089 const targets = ['*', 'server-users'];
2090 if (user.groups) { for (var i in user.groups) { targets.push('server-users:' + i); } }
2091 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 });
2092 }
2093
2094 break;
2095 }
2096 case 'rename': {
2097 if (obj.sftp == null) return;
2098 var requestedPath = msg.path;
2099 if (requestedPath.startsWith('/') == false) { requestedPath = '/' + requestedPath; }
2100 const oldpath = obj.path.join(requestedPath, msg.oldname).split('\\').join('/');
2101 const newpath = obj.path.join(requestedPath, msg.newname).split('\\').join('/');
2102 obj.sftp.rename(oldpath, newpath, function (err) { });
2103
2104 // Event the file rename
2105 const targets = ['*', 'server-users'];
2106 if (user.groups) { for (var i in user.groups) { targets.push('server-users:' + i); } }
2107 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 });
2108 break;
2109 }
2110 case 'upload': {
2111 if (obj.sftp == null) return;
2112 var requestedPath = msg.path;
2113 if (requestedPath.startsWith('/') == false) { requestedPath = '/' + requestedPath; }
2114 obj.uploadFullpath = obj.path.join(requestedPath, msg.name).split('\\').join('/');
2115 obj.uploadSize = msg.size;
2116 obj.uploadReqid = msg.reqid;
2117 obj.uploadPosition = 0;
2118 obj.sftp.open(obj.uploadFullpath, 'w', 0o666, function (err, handle) {
2119 if (err != null) {
2120 try { obj.ws.send(Buffer.from(JSON.stringify({ action: 'uploaderror', reqid: obj.uploadReqid }))) } catch (ex) { }
2121 } else {
2122 obj.uploadHandle = handle;
2123 try { obj.ws.send(Buffer.from(JSON.stringify({ action: 'uploadstart', reqid: obj.uploadReqid }))) } catch (ex) { }
2124
2125 // Event the file upload
2126 const targets = ['*', 'server-users'];
2127 if (user.groups) { for (var i in user.groups) { targets.push('server-users:' + i); } }
2128 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 });
2129 }
2130 });
2131 break;
2132 }
2133 case 'uploaddone': {
2134 if (obj.sftp == null) return;
2135 if (obj.uploadHandle != null) {
2136 obj.sftp.close(obj.uploadHandle, function () { });
2137 try { obj.ws.send(Buffer.from(JSON.stringify({ action: 'uploaddone', reqid: obj.uploadReqid }))) } catch (ex) { }
2138 delete obj.uploadHandle;
2139 delete obj.uploadFullpath;
2140 delete obj.uploadSize;
2141 delete obj.uploadReqid;
2142 delete obj.uploadPosition;
2143 }
2144 break;
2145 }
2146 case 'uploadcancel': {
2147 if (obj.sftp == null) return;
2148 if (obj.uploadHandle != null) {
2149 obj.sftp.close(obj.uploadHandle, function () { });
2150 obj.sftp.unlink(obj.uploadFullpath, function (err) { });
2151 try { obj.ws.send(Buffer.from(JSON.stringify({ action: 'uploadcancel', reqid: obj.uploadReqid }))) } catch (ex) { }
2152 delete obj.uploadHandle;
2153 delete obj.uploadFullpath;
2154 delete obj.uploadSize;
2155 delete obj.uploadReqid;
2156 delete obj.uploadPosition;
2157 }
2158 break;
2159 }
2160 case 'download': {
2161 if (obj.sftp == null) return;
2162 switch (msg.sub) {
2163 case 'start': {
2164 var requestedPath = msg.path;
2165 if (requestedPath.startsWith('/') == false) { requestedPath = '/' + requestedPath; }
2166 obj.downloadFullpath = requestedPath;
2167 obj.downloadId = msg.id;
2168 obj.downloadPosition = 0;
2169 obj.downloadBuffer = Buffer.alloc(16384);
2170 obj.sftp.open(obj.downloadFullpath, 'r', function (err, handle) {
2171 if (err != null) {
2172 try { obj.ws.send(Buffer.from(JSON.stringify({ action: 'download', sub: 'cancel', id: obj.downloadId }))) } catch (ex) { }
2173 } else {
2174 obj.downloadHandle = handle;
2175 try { obj.ws.send(JSON.stringify({ action: 'download', sub: 'start', id: obj.downloadId })) } catch (ex) { }
2176
2177 // Event the file download
2178 const targets = ['*', 'server-users'];
2179 if (user.groups) { for (var i in user.groups) { targets.push('server-users:' + i); } }
2180 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 });
2181 }
2182 });
2183 break;
2184 }
2185 case 'startack': {
2186 if ((obj.downloadHandle == null) || (obj.downloadId != msg.id)) break;
2187 obj.downloadPendingBlockCount = (typeof msg.ack == 'number') ? msg.ack : 8;
2188 uploadNextBlock();
2189 break;
2190 }
2191 case 'ack': {
2192 if ((obj.downloadHandle == null) || (obj.downloadId != msg.id)) break;
2193 if (obj.downloadPendingBlockCount == 0) { obj.downloadPendingBlockCount = 1; uploadNextBlock(); }
2194 break;
2195 }
2196 case 'stop': {
2197 if ((obj.downloadHandle == null) || (obj.downloadId != msg.id)) break;
2198 if (obj.downloadHandle != null) { obj.sftp.close(obj.downloadHandle, function () { }); }
2199 delete obj.downloadId;
2200 delete obj.downloadBuffer;
2201 delete obj.downloadHandle;
2202 delete obj.downloadFullpath;
2203 delete obj.downloadPosition;
2204 delete obj.downloadPendingBlockCount;
2205 break;
2206 }
2207 }
2208 break;
2209 }
2210 case 'sshauth': {
2211 if (obj.sshClient != null) return;
2212
2213 // Verify inputs
2214 if ((typeof msg.username != 'string') || ((typeof msg.password != 'string') && (typeof msg.key != 'string'))) break;
2215
2216 if (msg.keep === true) { msg.keep = 1; } // If true, change to 1. For user/pass, 1 to store user/pass in db. For user/key/pass, 1 to store user/key in db, 2 to store everything in db.
2217 obj.keep = msg.keep; // If set, keep store credentials on the server if the SSH tunnel connected succesfully.
2218 obj.username = msg.username;
2219 obj.password = msg.password;
2220 obj.privateKey = msg.key;
2221 obj.privateKeyPass = msg.keypass;
2222
2223 // Create a mesh relay authentication cookie
2224 const cookieContent = { userid: user._id, domainid: user.domain, nodeid: obj.nodeid, tcpport: obj.tcpport };
2225 if (obj.relaynodeid) {
2226 cookieContent.nodeid = obj.relaynodeid;
2227 cookieContent.tcpaddr = obj.tcpaddr;
2228 } else {
2229 if (obj.mtype == 3) { cookieContent.lc = 1; } // This is a local device
2230 }
2231 startRelayConnection(parent.parent.encodeCookie(cookieContent, parent.parent.loginCookieEncryptionKey));
2232 break;
2233 }
2234 case 'sshkeyauth': {
2235 if (obj.sshClient != null) return;
2236
2237 // Verify inputs
2238 if (typeof msg.keypass != 'string') break;
2239
2240 delete obj.keep;
2241 obj.privateKeyPass = msg.keypass;
2242
2243 // Create a mesh relay authentication cookie
2244 const cookieContent = { userid: user._id, domainid: user.domain, nodeid: obj.nodeid, tcpport: obj.tcpport };
2245 if (obj.relaynodeid) {
2246 cookieContent.nodeid = obj.relaynodeid;
2247 cookieContent.tcpaddr = obj.tcpaddr;
2248 } else {
2249 if (obj.mtype == 3) { cookieContent.lc = 1; } // This is a local device
2250 }
2251 startRelayConnection(parent.parent.encodeCookie(cookieContent, parent.parent.loginCookieEncryptionKey));
2252 break;
2253 }
2254 }
2255 }
2256 } catch (ex) { obj.close(); }
2257 });
2258
2259 function uploadNextBlock() {
2260 if (obj.downloadBuffer == null) return;
2261 obj.sftp.read(obj.downloadHandle, obj.downloadBuffer, 4, obj.downloadBuffer.length - 4, obj.downloadPosition, function (err, len, buf) {
2262 obj.downloadPendingBlockCount--;
2263 if (obj.downloadBuffer == null) return;
2264 if (err != null) {
2265 try { obj.ws.send(Buffer.from(JSON.stringify({ action: 'download', sub: 'cancel', id: obj.downloadId }))) } catch (ex) { }
2266 } else {
2267 obj.downloadPosition += len;
2268 if (len < (obj.downloadBuffer.length - 4)) {
2269 obj.downloadBuffer.writeInt32BE(0x01000001, 0)
2270 if (len > 0) { try { obj.ws.send(obj.downloadBuffer.slice(0, len + 4)); } catch (ex) { console.log(ex); } }
2271 } else {
2272 obj.downloadBuffer.writeInt32BE(0x01000000, 0);
2273 try { obj.ws.send(obj.downloadBuffer.slice(0, len + 4)); } catch (ex) { console.log(ex); }
2274 if (obj.downloadPendingBlockCount > 0) { uploadNextBlock(); }
2275 return;
2276 }
2277 }
2278 if (obj.downloadHandle != null) { obj.sftp.close(obj.downloadHandle, function () { }); }
2279 delete obj.downloadId;
2280 delete obj.downloadBuffer;
2281 delete obj.downloadHandle;
2282 delete obj.downloadFullpath;
2283 delete obj.downloadPosition;
2284 delete obj.downloadPendingBlockCount;
2285 });
2286 }
2287
2288 // If error, do nothing
2289 ws.on('error', function (err) { parent.parent.debug('relay', 'SSH: Browser websocket error: ' + err); obj.close(); });
2290
2291 // If the web socket is closed
2292 ws.on('close', function (req) { parent.parent.debug('relay', 'SSH: Browser websocket closed'); obj.close(); });
2293
2294 // Check that we have a user and nodeid
2295 if ((user == null) || (req.query.nodeid == null)) { obj.close(); return; } // Invalid nodeid
2296 parent.GetNodeWithRights(domain, user, req.query.nodeid, function (node, rights, visible) {
2297 if (obj.ws == null) return; // obj has been cleaned up, just exit.
2298 node = parent.common.unEscapeLinksFieldName(node); // unEscape node data for rdp/ssh credentials
2299
2300 // Check permissions
2301 if ((rights & 8) == 0) { obj.close(); return; } // No MESHRIGHT_REMOTECONTROL rights
2302 if ((rights != 0xFFFFFFFF) && (rights & 0x00000200)) { obj.close(); return; } // MESHRIGHT_NOTERMINAL is set
2303 obj.mtype = node.mtype; // Store the device group type
2304 obj.nodeid = node._id; // Store the NodeID
2305 obj.meshid = node.meshid; // Store the MeshID
2306
2307 // Check the SSH port
2308 obj.tcpport = 22;
2309 if (typeof node.sshport == 'number') { obj.tcpport = node.sshport; }
2310
2311 // Check if we need to relay thru a different agent
2312 const mesh = parent.meshes[obj.meshid];
2313 if (mesh && mesh.relayid) { obj.relaynodeid = mesh.relayid; obj.tcpaddr = node.host; }
2314
2315 // Check if we have rights to the relayid device, does nothing if a relay is not used
2316 checkRelayRights(parent, domain, user, obj.relaynodeid, function (allowed) {
2317 if (obj.ws == null) return; // obj has been cleaned up, just exit.
2318 if (allowed !== true) { parent.parent.debug('relay', 'SSH: Attempt to use un-authorized relay'); obj.close(); return; }
2319
2320 // We are all set, start receiving data
2321 ws._socket.resume();
2322
2323 // Check if we have SSH credentials for this device
2324 if ((domain.allowsavingdevicecredentials === false) || (node.ssh == null) || (typeof node.ssh != 'object') || (node.ssh[user._id] == null) || (typeof node.ssh[user._id].u != 'string') || ((typeof node.ssh[user._id].p != 'string') && (typeof node.ssh[user._id].k != 'string'))) {
2325 // Send a request for SSH authentication
2326 try { ws.send(JSON.stringify({ action: 'sshauth' })) } catch (ex) { }
2327 } else if ((typeof node.ssh[user._id].k == 'string') && (typeof node.ssh[user._id].kp != 'string')) {
2328 // Send a request for SSH authentication with option for only the private key password
2329 obj.username = node.ssh[user._id].u;
2330 obj.privateKey = node.ssh[user._id].k;
2331 try { ws.send(JSON.stringify({ action: 'sshauth', askkeypass: true })) } catch (ex) { }
2332 } else {
2333 // Use our existing credentials
2334 obj.username = node.ssh[user._id].u;
2335 if (typeof node.ssh[user._id].p == 'string') {
2336 obj.password = node.ssh[user._id].p;
2337 } else if (typeof node.ssh[user._id].k == 'string') {
2338 obj.privateKey = node.ssh[user._id].k;
2339 obj.privateKeyPass = node.ssh[user._id].kp;
2340 }
2341
2342 // Create a mesh relay authentication cookie
2343 const cookieContent = { userid: user._id, domainid: user.domain, nodeid: obj.nodeid, tcpport: obj.tcpport };
2344 if (obj.relaynodeid) {
2345 cookieContent.nodeid = obj.relaynodeid;
2346 cookieContent.tcpaddr = obj.tcpaddr;
2347 } else {
2348 if (obj.mtype == 3) { cookieContent.lc = 1; } // This is a local device
2349 }
2350 startRelayConnection(parent.parent.encodeCookie(cookieContent, parent.parent.loginCookieEncryptionKey));
2351 }
2352 });
2353 });
2354
2355 return obj;
2356};
2357
2358
2359// Check that the user has full rights on a relay device before allowing it.
2360function checkRelayRights(parent, domain, user, relayNodeId, func) {
2361 if (relayNodeId == null) { func(true); return; } // No relay, do nothing.
2362 parent.GetNodeWithRights(domain, user, relayNodeId, function (node, rights, visible) {
2363 func((node != null) && ((rights & 0x00200008) != 0)); // MESHRIGHT_REMOTECONTROL or MESHRIGHT_RELAY rights
2364 });
2365}