apprelays.js 132 KB

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