apprelays.js 134 KB

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