meshrelay.js 91 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371
  1. /**
  2. * @description MeshCentral connection relay module
  3. * @author Ylian Saint-Hilaire
  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. // Mesh Rights
  15. const MESHRIGHT_EDITMESH = 0x00000001; // 1
  16. const MESHRIGHT_MANAGEUSERS = 0x00000002; // 2
  17. const MESHRIGHT_MANAGECOMPUTERS = 0x00000004; // 4
  18. const MESHRIGHT_REMOTECONTROL = 0x00000008; // 8
  19. const MESHRIGHT_AGENTCONSOLE = 0x00000010; // 16
  20. const MESHRIGHT_SERVERFILES = 0x00000020; // 32
  21. const MESHRIGHT_WAKEDEVICE = 0x00000040; // 64
  22. const MESHRIGHT_SETNOTES = 0x00000080; // 128
  23. const MESHRIGHT_REMOTEVIEWONLY = 0x00000100; // 256
  24. const MESHRIGHT_NOTERMINAL = 0x00000200; // 512
  25. const MESHRIGHT_NOFILES = 0x00000400; // 1024
  26. const MESHRIGHT_NOAMT = 0x00000800; // 2048
  27. const MESHRIGHT_DESKLIMITEDINPUT = 0x00001000; // 4096
  28. const MESHRIGHT_LIMITEVENTS = 0x00002000; // 8192
  29. const MESHRIGHT_CHATNOTIFY = 0x00004000; // 16384
  30. const MESHRIGHT_UNINSTALL = 0x00008000; // 32768
  31. const MESHRIGHT_NODESKTOP = 0x00010000; // 65536
  32. const MESHRIGHT_REMOTECOMMAND = 0x00020000; // 131072
  33. const MESHRIGHT_RESETOFF = 0x00040000; // 262144
  34. const MESHRIGHT_GUESTSHARING = 0x00080000; // 524288
  35. const MESHRIGHT_DEVICEDETAILS = 0x00100000; // 1048576
  36. const MESHRIGHT_RELAY = 0x00200000; // 2097152
  37. const MESHRIGHT_ADMIN = 0xFFFFFFFF;
  38. // Protocol:
  39. // 1 = Terminal
  40. // 2 = Desktop
  41. // 5 = Files
  42. // 6 = Admin PowerShell
  43. // 8 = User Shell
  44. // 9 = User PowerShell
  45. // 10 = Web-RDP
  46. // 11 = Web-SSH
  47. // 12 = Web-VNC
  48. // 13 = Web-SSH-Files
  49. // 14 = Web-TCP
  50. // 100 = Intel AMT WSMAN
  51. // 101 = Intel AMT Redirection
  52. // 200 = Messenger
  53. function checkDeviceSharePublicIdentifier(parent, domain, nodeid, pid, extraKey, func) {
  54. // Check the public id
  55. parent.db.GetAllTypeNodeFiltered([nodeid], domain.id, 'deviceshare', null, function (err, docs) {
  56. if ((err != null) || (docs.length == 0)) { func(false); return; }
  57. // Search for the device share public identifier
  58. var found = false;
  59. for (var i = 0; i < docs.length; i++) {
  60. for (var i = 0; i < docs.length; i++) { if ((docs[i].publicid == pid) && ((docs[i].extrakey == null) || (docs[i].extrakey === extraKey))) { found = true; } }
  61. }
  62. func(found);
  63. });
  64. }
  65. module.exports.CreateMeshRelay = function (parent, ws, req, domain, user, cookie) {
  66. if ((cookie != null) && (typeof cookie.nid == 'string') && (typeof cookie.pid == 'string')) {
  67. checkDeviceSharePublicIdentifier(parent, domain, cookie.nid, cookie.pid, cookie.k, function (result) {
  68. // If the identifier if not found, close the connection
  69. if (result == false) { try { ws.close(); } catch (e) { } return; }
  70. // Public device sharing identifier found, continue as normal.
  71. CreateMeshRelayEx(parent, ws, req, domain, user, cookie);
  72. });
  73. } else {
  74. CreateMeshRelayEx(parent, ws, req, domain, user, cookie);
  75. }
  76. }
  77. // Record a new entry in a recording log
  78. function recordingEntry (logfile, type, flags, data, func, tag) {
  79. try {
  80. if (logfile.text) {
  81. // Text recording format
  82. var out = '';
  83. const utcDate = new Date(Date.now());
  84. if (type == 1) {
  85. // End of start
  86. out = data + '\r\n' + utcDate.toUTCString() + ', ' + "<<<START>>>" + '\r\n';
  87. } else if (type == 3) {
  88. // End of log
  89. out = new Date(Date.now() - 5000).toUTCString() + ', ' + "<<<END>>>" + '\r\n';
  90. } else if (typeof data == 'string') {
  91. // Log message
  92. if (logfile.text == 1) {
  93. out = utcDate.toUTCString() + ', ' + data + '\r\n';
  94. } else if (logfile.text == 2) {
  95. try {
  96. var x = JSON.parse(data);
  97. if (typeof x.action == 'string') {
  98. if ((x.action == 'chat') && (typeof x.msg == 'string')) { out = utcDate.toUTCString() + ', ' + (((flags & 2) ? '--> ' : '<-- ') + x.msg + '\r\n'); }
  99. else if ((x.action == 'file') && (typeof x.name == 'string') && (typeof x.size == 'number')) { out = utcDate.toUTCString() + ', ' + (((flags & 2) ? '--> ' : '<-- ') + "File Transfer" + ', \"' + x.name + '\" (' + x.size + ' ' + "bytes" + ')\r\n'); }
  100. } else if (x.ctrlChannel == null) { out = utcDate.toUTCString() + ', ' + data + '\r\n'; }
  101. } catch (ex) {
  102. out = utcDate.toUTCString() + ', ' + data + '\r\n';
  103. }
  104. }
  105. }
  106. if (out != null) {
  107. // Log this event
  108. const block = Buffer.from(out);
  109. require('fs').write(logfile.fd, block, 0, block.length, function () { func(logfile, tag); });
  110. logfile.size += block.length;
  111. } else {
  112. // Skip logging this.
  113. func(logfile, tag);
  114. }
  115. } else {
  116. // Binary recording format
  117. if (typeof data == 'string') {
  118. // String write
  119. var blockData = Buffer.from(data), header = Buffer.alloc(16); // Header: Type (2) + Flags (2) + Size(4) + Time(8)
  120. header.writeInt16BE(type, 0); // Type (1 = Start, 2 = Network Data, 3 = End)
  121. header.writeInt16BE(flags, 2); // Flags (1 = Binary, 2 = User)
  122. header.writeInt32BE(blockData.length, 4); // Size
  123. header.writeIntBE((type == 3 ? new Date(Date.now() - 5000) : new Date()), 10, 6); // Time
  124. var block = Buffer.concat([header, blockData]);
  125. require('fs').write(logfile.fd, block, 0, block.length, function () { func(logfile, tag); });
  126. logfile.size += block.length;
  127. } else {
  128. // Binary write
  129. var header = Buffer.alloc(16); // Header: Type (2) + Flags (2) + Size(4) + Time(8)
  130. header.writeInt16BE(type, 0); // Type (1 = Start, 2 = Network Data)
  131. header.writeInt16BE(flags | 1, 2); // Flags (1 = Binary, 2 = User)
  132. header.writeInt32BE(data.length, 4); // Size
  133. header.writeIntBE((type == 3 ? new Date(Date.now() - 5000) : new Date()), 10, 6); // Time
  134. var block = Buffer.concat([header, data]);
  135. require('fs').write(logfile.fd, block, 0, block.length, function () { func(logfile, tag); });
  136. logfile.size += block.length;
  137. }
  138. }
  139. } catch (ex) { console.log(ex); func(logfile, tag); }
  140. }
  141. module.exports.recordingEntry = recordingEntry;
  142. function CreateMeshRelayEx(parent, ws, req, domain, user, cookie) {
  143. const currentTime = Date.now();
  144. if (cookie) {
  145. if ((typeof cookie.expire == 'number') && (cookie.expire <= currentTime)) { try { ws.close(); parent.parent.debug('relay', 'Relay: Expires cookie (' + req.clientIp + ')'); } catch (e) { console.log(e); } return; }
  146. if (typeof cookie.nid == 'string') { req.query.nodeid = cookie.nid; }
  147. }
  148. var obj = {};
  149. obj.ws = ws;
  150. obj.id = req.query.id;
  151. obj.user = user;
  152. obj.ruserid = null;
  153. obj.req = req; // Used in multi-server.js
  154. if ((cookie != null) && (cookie.nouser == 1)) { obj.nouser = true; } // This is a relay without user authentication
  155. // Setup subscription for desktop sharing public identifier
  156. // If the identifier is removed, drop the connection
  157. if ((cookie != null) && (typeof cookie.pid == 'string')) {
  158. obj.pid = cookie.pid;
  159. parent.parent.AddEventDispatch([cookie.nid], obj);
  160. obj.HandleEvent = function (source, event, ids, id) { if ((event.action == 'removedDeviceShare') && (obj.pid == event.publicid)) { closeBothSides(); } }
  161. }
  162. // Check relay authentication
  163. if ((user == null) && (obj.req.query != null) && (obj.req.query.rauth != null)) {
  164. const rcookie = parent.parent.decodeCookie(obj.req.query.rauth, parent.parent.loginCookieEncryptionKey, 240); // Cookie with 4 hour timeout
  165. if (rcookie.ruserid != null) { obj.ruserid = rcookie.ruserid; } else if (rcookie.nouser === 1) { obj.rnouser = true; }
  166. }
  167. // If there is no authentication, drop this connection
  168. if ((obj.id != null) && (obj.id.startsWith('meshmessenger/') == false) && (obj.user == null) && (obj.ruserid == null) && (obj.nouser !== true) && (obj.rnouser !== true)) { try { ws.close(); parent.parent.debug('relay', 'Relay: Connection with no authentication (' + obj.req.clientIp + ')'); } catch (e) { console.log(e); } return; }
  169. // Relay session count (we may remove this in the future)
  170. obj.relaySessionCounted = true;
  171. parent.relaySessionCount++;
  172. // Setup slow relay is requested. This will show down sending any data to this peer.
  173. if ((req.query.slowrelay != null)) {
  174. var sr = null;
  175. try { sr = parseInt(req.query.slowrelay); } catch (ex) { }
  176. if ((typeof sr == 'number') && (sr > 0) && (sr < 1000)) { obj.ws.slowRelay = sr; }
  177. }
  178. // Check if protocol is set in the cookie and if so replace req.query.p but only if its not already set or blank
  179. if ((cookie != null) && (typeof cookie.p == 'number') && (obj.req.query.p === undefined || obj.req.query.p === "")) { obj.req.query.p = cookie.p; }
  180. // Patch Messenger protocol to 200
  181. if ((obj.id != null) && (obj.id.startsWith('meshmessenger/') == true)) { obj.req.query.p = 200; }
  182. // Mesh Rights
  183. const MESHRIGHT_EDITMESH = 1;
  184. const MESHRIGHT_MANAGEUSERS = 2;
  185. const MESHRIGHT_MANAGECOMPUTERS = 4;
  186. const MESHRIGHT_REMOTECONTROL = 8;
  187. const MESHRIGHT_AGENTCONSOLE = 16;
  188. const MESHRIGHT_SERVERFILES = 32;
  189. const MESHRIGHT_WAKEDEVICE = 64;
  190. const MESHRIGHT_SETNOTES = 128;
  191. const MESHRIGHT_REMOTEVIEW = 256;
  192. // Site rights
  193. const SITERIGHT_SERVERBACKUP = 1;
  194. const SITERIGHT_MANAGEUSERS = 2;
  195. const SITERIGHT_SERVERRESTORE = 4;
  196. const SITERIGHT_FILEACCESS = 8;
  197. const SITERIGHT_SERVERUPDATE = 16;
  198. const SITERIGHT_LOCKED = 32;
  199. // Clean a IPv6 address that encodes a IPv4 address
  200. function cleanRemoteAddr(addr) { if (addr.startsWith('::ffff:')) { return addr.substring(7); } else { return addr; } }
  201. // Disconnect this agent
  202. obj.close = function (arg) {
  203. if ((arg == 1) || (arg == null)) { try { ws.close(); parent.parent.debug('relay', 'Relay: Soft disconnect (' + obj.req.clientIp + ')'); } catch (e) { console.log(e); } } // Soft close, close the websocket
  204. if ((arg == 2) || (req.query.hd == 1)) { try { ws._socket._parent.end(); parent.parent.debug('relay', 'Relay: Hard disconnect (' + obj.req.clientIp + ')'); } catch (e) { console.log(e); } } // Hard close, close the TCP socket
  205. // Aggressive cleanup
  206. delete obj.id;
  207. delete obj.ws;
  208. delete obj.peer;
  209. if (obj.expireTimer != null) { clearTimeout(obj.expireTimer); delete obj.expireTimer; }
  210. // Unsubscribe
  211. if (obj.pid != null) { parent.parent.RemoveAllEventDispatch(obj); }
  212. };
  213. obj.sendAgentMessage = function (command, userid, domainid) {
  214. var rights, mesh;
  215. if (command.nodeid == null) return false;
  216. var user = null;
  217. if (userid != null) { user = parent.users[userid]; if (user == null) return false; }
  218. var splitnodeid = command.nodeid.split('/');
  219. // Check that we are in the same domain and the user has rights over this node.
  220. if ((splitnodeid[0] == 'node') && (splitnodeid[1] == domainid)) {
  221. // Get the user object
  222. // See if the node is connected
  223. var agent = parent.wsagents[command.nodeid];
  224. if (agent != null) {
  225. // Check if we have permission to send a message to that node
  226. if (userid == null) { rights = MESHRIGHT_REMOTECONTROL; } else { rights = parent.GetNodeRights(user, agent.dbMeshKey, agent.dbNodeKey); }
  227. mesh = parent.meshes[agent.dbMeshKey];
  228. if ((rights != null) && (mesh != null) || ((rights & MESHRIGHT_REMOTECONTROL) != 0)) {
  229. if (ws.sessionId) { command.sessionid = ws.sessionId; } // Set the session id, required for responses.
  230. command.rights = rights; // Add user rights flags to the message
  231. if (typeof command.consent == 'number') { command.consent = command.consent | mesh.consent; } else { command.consent = mesh.consent; } // Add user consent
  232. if (typeof domain.userconsentflags == 'number') { command.consent |= domain.userconsentflags; } // Add server required consent flags
  233. if (user != null) {
  234. command.username = user.name; // Add user name
  235. command.realname = user.realname; // Add real name
  236. }
  237. if (typeof domain.desktopprivacybartext == 'string') { command.privacybartext = domain.desktopprivacybartext; } // Privacy bar text
  238. delete command.nodeid; // Remove the nodeid since it's implyed.
  239. agent.send(JSON.stringify(command));
  240. return true;
  241. }
  242. } else {
  243. // Check if a peer server is connected to this agent
  244. var routing = parent.parent.GetRoutingServerIdNotSelf(command.nodeid, 1); // 1 = MeshAgent routing type
  245. if (routing != null) {
  246. // Check if we have permission to send a message to that node
  247. if (userid == null) { rights = MESHRIGHT_REMOTECONTROL; } else { rights = parent.GetNodeRights(user, routing.meshid, command.nodeid); }
  248. mesh = parent.meshes[routing.meshid];
  249. if (rights != null || ((rights & MESHRIGHT_REMOTECONTROL) != 0)) {
  250. if (ws.sessionId) { command.fromSessionid = ws.sessionId; } // Set the session id, required for responses.
  251. command.rights = rights; // Add user rights flags to the message
  252. if (typeof command.consent == 'number') { command.consent = command.consent | mesh.consent; } else { command.consent = mesh.consent; } // Add user consent
  253. if (typeof domain.userconsentflags == 'number') { command.consent |= domain.userconsentflags; } // Add server required consent flags
  254. if (user != null) {
  255. command.username = user.name; // Add user name
  256. command.realname = user.realname; // Add real name
  257. }
  258. if (typeof domain.desktopprivacybartext == 'string') { command.privacybartext = domain.desktopprivacybartext; } // Privacy bar text
  259. parent.parent.multiServer.DispatchMessageSingleServer(command, routing.serverid);
  260. return true;
  261. }
  262. }
  263. }
  264. }
  265. return false;
  266. }
  267. // Push any stored message to the peer
  268. obj.pushStoredMessages = function () {
  269. if ((obj.storedPushedMessages != null) && (obj.peer != null)) {
  270. for (var i in obj.storedPushedMessages) {
  271. try { obj.peer.ws.send(JSON.stringify({ action: 'chat', msg: obj.storedPushedMessages[i] })); } catch (ex) { console.log(ex); }
  272. }
  273. }
  274. }
  275. // Push any stored message to the peer
  276. obj.sendPeerImage = function () {
  277. if ((typeof obj.id == 'string') && obj.id.startsWith('meshmessenger/') && (obj.peer != null) && (obj.user != null) && (typeof obj.user.flags == 'number') && (obj.user.flags & 1)) {
  278. parent.db.Get('im' + obj.user._id, function (err, docs) {
  279. if ((err == null) && (docs != null) && (docs.length == 1) && (typeof docs[0].image == 'string')) {
  280. try { obj.peer.ws.send(JSON.stringify({ ctrlChannel: '102938', type: 'image', image: docs[0].image })); } catch (ex) { }
  281. }
  282. });
  283. }
  284. }
  285. // Send a PING/PONG message
  286. function sendPing() {
  287. try { obj.ws.send('{"ctrlChannel":"102938","type":"ping"}'); } catch (ex) { }
  288. try { if (obj.peer != null) { obj.peer.ws.send('{"ctrlChannel":"102938","type":"ping"}'); } } catch (ex) { }
  289. }
  290. function sendPong() {
  291. try { obj.ws.send('{"ctrlChannel":"102938","type":"pong"}'); } catch (ex) { }
  292. try { if (obj.peer != null) { obj.peer.ws.send('{"ctrlChannel":"102938","type":"pong"}'); } } catch (ex) { }
  293. }
  294. function performRelay() {
  295. if (obj.id == null) { try { obj.close(); } catch (e) { } return null; } // Attempt to connect without id, drop this.
  296. ws._socket.setKeepAlive(true, 240000); // Set TCP keep alive
  297. // If this is a MeshMessenger session, the ID is the two userid's and authentication must match one of them.
  298. if (obj.id.startsWith('meshmessenger/')) {
  299. if ((obj.id.startsWith('meshmessenger/user/') == true) && (user == null)) { try { obj.close(); } catch (e) { } return null; } // If user-to-user, both sides need to be authenticated.
  300. var x = obj.id.split('/'), user1 = x[1] + '/' + x[2] + '/' + x[3], user2 = x[4] + '/' + x[5] + '/' + x[6];
  301. if ((x[1] != 'user') && (x[4] != 'user')) { try { obj.close(); } catch (e) { } return null; } // MeshMessenger session must have at least one authenticated user
  302. if ((x[1] == 'user') && (x[4] == 'user')) {
  303. // If this is a user-to-user session, you must be authenticated to join.
  304. if ((user._id != user1) && (user._id != user2)) { try { obj.close(); } catch (e) { } return null; }
  305. } else {
  306. // If only one side of the session is a user
  307. // !!!!! TODO: Need to make sure that one of the two sides is the correct user. !!!!!
  308. }
  309. }
  310. // Validate that the id is valid, we only need to do this on non-authenticated sessions.
  311. // TODO: Figure out when this needs to be done.
  312. /*
  313. if (!parent.args.notls) {
  314. // Check the identifier, if running without TLS, skip this.
  315. var ids = obj.id.split(':');
  316. if (ids.length != 3) { ws.close(); delete obj.id; return null; } // Invalid ID, drop this.
  317. if (parent.crypto.createHmac('SHA384', parent.relayRandom).update(ids[0] + ':' + ids[1]).digest('hex') != ids[2]) { ws.close(); delete obj.id; return null; } // Invalid HMAC, drop this.
  318. if ((Date.now() - parseInt(ids[1])) > 120000) { ws.close(); delete obj.id; return null; } // Expired time, drop this.
  319. obj.id = ids[0];
  320. }
  321. */
  322. // Check the peer connection status
  323. {
  324. var relayinfo = parent.wsrelays[obj.id];
  325. if (relayinfo) {
  326. if (relayinfo.state == 1) {
  327. // Check that at least one connection is authenticated
  328. if ((obj.authenticated != true) && (relayinfo.peer1.authenticated != true)) {
  329. ws.close();
  330. parent.parent.debug('relay', 'Relay without-auth: ' + obj.id + ' (' + obj.req.clientIp + ')');
  331. delete obj.id;
  332. delete obj.ws;
  333. delete obj.peer;
  334. return null;
  335. }
  336. // Check that both connection are for the same user
  337. if (!obj.id.startsWith('meshmessenger/')) {
  338. var u1 = obj.user ? obj.user._id : obj.ruserid;
  339. var u2 = relayinfo.peer1.user ? relayinfo.peer1.user._id : relayinfo.peer1.ruserid;
  340. if (parent.args.user != null) { // If the server is setup with a default user, correct the userid now.
  341. if (u1 != null) { u1 = 'user/' + domain.id + '/' + parent.args.user.toLowerCase(); }
  342. if (u2 != null) { u2 = 'user/' + domain.id + '/' + parent.args.user.toLowerCase(); }
  343. }
  344. if ((u1 != u2) && (obj.nouser !== true) && (relayinfo.peer1.nouser !== true)) {
  345. ws.close();
  346. parent.parent.debug('relay', 'Relay auth mismatch (' + u1 + ' != ' + u2 + '): ' + obj.id + ' (' + obj.req.clientIp + ')');
  347. delete obj.id;
  348. delete obj.ws;
  349. delete obj.peer;
  350. return null;
  351. }
  352. }
  353. // Check that both sides have websocket connections, this should never happen.
  354. if ((obj.ws == null) || (relayinfo.peer1.ws == null)) { relayinfo.peer1.close(); obj.close(); return null; }
  355. // Connect to peer
  356. obj.peer = relayinfo.peer1;
  357. obj.peer.peer = obj;
  358. relayinfo.peer2 = obj;
  359. relayinfo.state = 2;
  360. relayinfo.peer1.ws._socket.resume(); // Release the traffic
  361. relayinfo.peer2.ws._socket.resume(); // Release the traffic
  362. ws.time = relayinfo.peer1.ws.time = Date.now();
  363. relayinfo.peer1.ws.peer = relayinfo.peer2.ws;
  364. relayinfo.peer2.ws.peer = relayinfo.peer1.ws;
  365. // Remove the timeout
  366. if (relayinfo.timeout) { clearTimeout(relayinfo.timeout); delete relayinfo.timeout; }
  367. // Check the protocol in use
  368. req.query.p = parseInt(req.query.p);
  369. if (typeof req.query.p != 'number') { req.query.p = parseInt(obj.peer.req.query.p); if (typeof req.query.p != 'number') { req.query.p = 0; } }
  370. obj.peer.req.query.p = req.query.p;
  371. // Setup traffic accounting
  372. obj.ws._socket.bytesReadEx = 0;
  373. obj.ws._socket.bytesWrittenEx = 0;
  374. obj.ws._socket.p = req.query.p;
  375. obj.peer.ws._socket.bytesReadEx = 0;
  376. obj.peer.ws._socket.bytesWrittenEx = 0;
  377. obj.peer.ws._socket.p = req.query.p;
  378. if (parent.trafficStats.relayIn[req.query.p] == null) { parent.trafficStats.relayIn[req.query.p] = 0; }
  379. if (parent.trafficStats.relayOut[req.query.p] == null) { parent.trafficStats.relayOut[req.query.p] = 0; }
  380. if (parent.trafficStats.relayCount[req.query.p] == null) { parent.trafficStats.relayCount[req.query.p] = 1; } else { parent.trafficStats.relayCount[req.query.p]++; }
  381. // Setup the agent PING/PONG timers unless requested not to
  382. if ((obj.req.query.noping != 1) && (obj.peer.req != null) && (obj.peer.req.query != null) && (obj.peer.req.query.noping != 1)) {
  383. if ((typeof parent.parent.args.agentping == 'number') && (obj.pingtimer == null)) { obj.pingtimer = setInterval(sendPing, parent.parent.args.agentping * 1000); }
  384. else if ((typeof parent.parent.args.agentpong == 'number') && (obj.pongtimer == null)) { obj.pongtimer = setInterval(sendPong, parent.parent.args.agentpong * 1000); }
  385. }
  386. // Setup session recording
  387. var sessionUser = obj.user;
  388. if (sessionUser == null) { sessionUser = obj.peer.user; }
  389. // If this is a MeshMessenger session, set the protocol to 200.
  390. var xtextSession = 0;
  391. var recordSession = false;
  392. if ((obj.id.startsWith('meshmessenger/node/') == true) && (sessionUser != null) && (domain.sessionrecording == true || ((typeof domain.sessionrecording == 'object') && ((domain.sessionrecording.protocols == null) || (domain.sessionrecording.protocols.indexOf(parseInt(200)) >= 0))))) {
  393. var split = obj.id.split('/');
  394. obj.req.query.nodeid = split[1] + '/' + split[2] + '/' + split[3];
  395. recordSession = true;
  396. xtextSession = 2; // 1 = Raw recording of all strings, 2 = Record chat session messages only.
  397. }
  398. // See if any other recording may occur
  399. if ((obj.req.query.p != null) && (obj.req.query.nodeid != null) && (sessionUser != null) && (domain.sessionrecording == true || ((typeof domain.sessionrecording == 'object') && ((domain.sessionrecording.protocols == null) || (domain.sessionrecording.protocols.indexOf(parseInt(obj.req.query.p)) >= 0))))) { recordSession = true; }
  400. if (recordSession) {
  401. // Get the computer name
  402. parent.db.Get(obj.req.query.nodeid, function (err, nodes) {
  403. var xusername = '', xdevicename = '', xdevicename2 = null, node = null, record = true;
  404. if ((nodes != null) && (nodes.length == 1)) { node = nodes[0]; xdevicename2 = node.name; xdevicename = '-' + parent.common.makeFilename(node.name); }
  405. // Check again if we need to do session recording
  406. if ((typeof domain.sessionrecording == 'object') && ((domain.sessionrecording.onlyselectedusers === true) || (domain.sessionrecording.onlyselectedusergroups === true) || (domain.sessionrecording.onlyselecteddevicegroups === true))) {
  407. record = false;
  408. // Check if this user needs to be recorded
  409. if ((sessionUser != null) && (domain.sessionrecording.onlyselectedusers === true)) {
  410. if ((sessionUser.flags != null) && ((sessionUser.flags & 2) != 0)) { record = true; }
  411. }
  412. // Check if this device group needs to be recorded
  413. if ((record == false) && (node != null) && (domain.sessionrecording.onlyselecteddevicegroups === true)) {
  414. var mesh = parent.meshes[node.meshid];
  415. if ((mesh != null) && (mesh.flags != null) && ((mesh.flags & 4) != 0)) { record = true; }
  416. }
  417. // Check if any user groups need to be recorded
  418. if ((record == false) && (domain.sessionrecording.onlyselectedusergroups === true)) {
  419. // Check if there is a usergroup that requires recording of the session
  420. if ((sessionUser != null) && (sessionUser.links != null) && (sessionUser.links[node.meshid] == null) && (sessionUser.links[node._id] == null)) {
  421. // This user does not have a direct link to the device group or device. Find all user groups the would cause the link.
  422. for (var i in sessionUser.links) {
  423. var ugrp = parent.userGroups[i];
  424. if ((ugrp != null) && (typeof ugrp.flags == 'number') && ((ugrp.flags & 2) != 0) && (ugrp.links != null) && ((ugrp.links[node.meshid] != null) || (ugrp.links[node._id] != null))) { record = true; }
  425. }
  426. }
  427. }
  428. }
  429. // Do not record the session, just send session start
  430. if (record == false) {
  431. try { ws.send('c'); } catch (ex) { } // Send connect to both peers
  432. try { relayinfo.peer1.ws.send('c'); } catch (ex) { }
  433. // Send any stored push messages
  434. obj.pushStoredMessages();
  435. relayinfo.peer1.pushStoredMessages();
  436. // Send other peer's image
  437. obj.sendPeerImage();
  438. relayinfo.peer1.sendPeerImage();
  439. return;
  440. }
  441. // Get the username and make it acceptable as a filename
  442. if (sessionUser._id) { xusername = '-' + parent.common.makeFilename(sessionUser._id.split('/')[2]); }
  443. var now = new Date(Date.now());
  444. var xsessionid = obj.id;
  445. if ((typeof xsessionid == 'string') && (xsessionid.startsWith('meshmessenger/node/') == true)) { xsessionid = 'Messenger' }
  446. var recFilename = 'relaysession' + ((domain.id == '') ? '' : '-') + domain.id + '-' + now.getUTCFullYear() + '-' + parent.common.zeroPad(now.getUTCMonth() + 1, 2) + '-' + parent.common.zeroPad(now.getUTCDate(), 2) + '-' + parent.common.zeroPad(now.getUTCHours(), 2) + '-' + parent.common.zeroPad(now.getUTCMinutes(), 2) + '-' + parent.common.zeroPad(now.getUTCSeconds(), 2) + xusername + xdevicename + '-' + xsessionid + (xtextSession ? '.txt' : '.mcrec');
  447. var recFullFilename = null;
  448. if (domain.sessionrecording.filepath) {
  449. try { parent.parent.fs.mkdirSync(domain.sessionrecording.filepath); } catch (e) { }
  450. recFullFilename = parent.parent.path.join(domain.sessionrecording.filepath, recFilename);
  451. } else {
  452. try { parent.parent.fs.mkdirSync(parent.parent.recordpath); } catch (e) { }
  453. recFullFilename = parent.parent.path.join(parent.parent.recordpath, recFilename);
  454. }
  455. parent.parent.fs.open(recFullFilename, 'w', function (err, fd) {
  456. if (err != null) {
  457. // Unable to record
  458. parent.parent.debug('relay', 'Relay: Unable to record to file: ' + recFullFilename);
  459. try { ws.send('c'); } catch (ex) { } // Send connect to both peers
  460. try { relayinfo.peer1.ws.send('c'); } catch (ex) { }
  461. // Send any stored push messages
  462. obj.pushStoredMessages();
  463. relayinfo.peer1.pushStoredMessages();
  464. // Send other peer's image
  465. obj.sendPeerImage();
  466. relayinfo.peer1.sendPeerImage();
  467. } else {
  468. // Write the recording file header
  469. parent.parent.debug('relay', 'Relay: Started recording to file: ' + recFullFilename);
  470. var metadata = {
  471. magic: 'MeshCentralRelaySession',
  472. ver: 1,
  473. userid: sessionUser._id,
  474. username: sessionUser.name,
  475. sessionid: obj.id,
  476. ipaddr1: ((obj.peer == null) || (obj.peer.req == null)) ? null : obj.peer.req.clientIp,
  477. ipaddr2: (obj.req == null) ? null : obj.req.clientIp,
  478. time: new Date().toLocaleString(),
  479. protocol: (((obj.req == null) || (obj.req.query == null)) ? null : obj.req.query.p),
  480. nodeid: (((obj.req == null) || (obj.req.query == null)) ? null : obj.req.query.nodeid)
  481. };
  482. if (xdevicename2 != null) { metadata.devicename = xdevicename2; }
  483. var firstBlock = JSON.stringify(metadata);
  484. var logfile = { fd: fd, lock: false, filename: recFullFilename, startTime: Date.now(), size: 0, text: xtextSession };
  485. if (node != null) { logfile.nodeid = node._id; logfile.meshid = node.meshid; logfile.name = node.name; logfile.icon = node.icon; }
  486. recordingEntry(logfile, 1, 0, firstBlock, function () {
  487. try { relayinfo.peer1.ws.logfile = ws.logfile = logfile; } catch (ex) {
  488. try { ws.send('c'); } catch (ex) { } // Send connect to both peers, 'cr' indicates the session is being recorded.
  489. try { relayinfo.peer1.ws.send('c'); } catch (ex) { }
  490. // Send any stored push messages
  491. obj.pushStoredMessages();
  492. relayinfo.peer1.pushStoredMessages();
  493. // Send other peer's image
  494. obj.sendPeerImage();
  495. relayinfo.peer1.sendPeerImage();
  496. return;
  497. }
  498. try { ws.send('cr'); } catch (ex) { } // Send connect to both peers, 'cr' indicates the session is being recorded.
  499. try { relayinfo.peer1.ws.send('cr'); } catch (ex) { }
  500. // Send any stored push messages
  501. obj.pushStoredMessages();
  502. relayinfo.peer1.pushStoredMessages();
  503. // Send other peer's image
  504. obj.sendPeerImage();
  505. relayinfo.peer1.sendPeerImage();
  506. });
  507. }
  508. });
  509. });
  510. } else {
  511. // Send session start
  512. try { ws.send('c'); } catch (ex) { } // Send connect to both peers
  513. try { relayinfo.peer1.ws.send('c'); } catch (ex) { }
  514. // Send any stored push messages
  515. obj.pushStoredMessages();
  516. relayinfo.peer1.pushStoredMessages();
  517. // Send other peer's image
  518. obj.sendPeerImage();
  519. relayinfo.peer1.sendPeerImage();
  520. }
  521. parent.parent.debug('relay', 'Relay connected: ' + obj.id + ' (' + obj.req.clientIp + ' --> ' + obj.peer.req.clientIp + ')');
  522. // Log the connection
  523. if (sessionUser != null) {
  524. var msg = 'Started relay session', msgid = 13;
  525. if ([1,6,8,9].indexOf(obj.req.query.p) >= 0) { msg = 'Started terminal session'; msgid = 14; } // admin shell, admin powershell, user shell, user powershell
  526. else if (obj.req.query.p == 2) { msg = 'Started desktop session'; msgid = 15; }
  527. else if (obj.req.query.p == 5) { msg = 'Started file management session'; msgid = 16; }
  528. else if (obj.req.query.p == 200) { msg = 'Started messenger session'; msgid = 162; }
  529. var event = { etype: 'relay', action: 'relaylog', domain: domain.id, userid: sessionUser._id, username: sessionUser.name, msgid: msgid, msgArgs: [obj.id, obj.peer.req.clientIp, req.clientIp], msg: msg + ' \"' + obj.id + '\" from ' + obj.peer.req.clientIp + ' to ' + req.clientIp, protocol: req.query.p, nodeid: req.query.nodeid };
  530. if (obj.guestname) { event.guestname = obj.guestname; } else if (relayinfo.peer1.guestname) { event.guestname = relayinfo.peer1.guestname; } // If this is a sharing session, set the guest name here.
  531. parent.parent.DispatchEvent(['*', sessionUser._id], obj, event);
  532. // Update user last access time
  533. if ((obj.user != null) && (obj.guestname == null)) {
  534. const timeNow = Math.floor(Date.now() / 1000);
  535. if (obj.user.access < (timeNow - 300)) { // Only update user access time if longer than 5 minutes
  536. obj.user.access = timeNow;
  537. parent.db.SetUser(obj.user);
  538. // Event the change
  539. var message = { etype: 'user', userid: obj.user._id, username: obj.user.name, account: parent.CloneSafeUser(obj.user), action: 'accountchange', domain: domain.id, nolog: 1 };
  540. if (parent.db.changeStream) { message.noact = 1; } // If DB change stream is active, don't use this event to change the user. Another event will come.
  541. var targets = ['*', 'server-users', obj.user._id];
  542. if (obj.user.groups) { for (var i in obj.user.groups) { targets.push('server-users:' + i); } }
  543. parent.parent.DispatchEvent(targets, obj, message);
  544. }
  545. }
  546. }
  547. } else {
  548. // Connected already, drop (TODO: maybe we should re-connect?)
  549. ws.close();
  550. parent.parent.debug('relay', 'Relay duplicate: ' + obj.id + ' (' + obj.req.clientIp + ')');
  551. delete obj.id;
  552. delete obj.ws;
  553. delete obj.peer;
  554. return null;
  555. }
  556. } else {
  557. // Set authenticated side as browser side for messenger sessions
  558. if ((obj.id.startsWith('meshmessenger/node/') == true) && obj.authenticated) { obj.req.query.browser = 1; }
  559. // Wait for other relay connection
  560. if ((obj.id.startsWith('meshmessenger/node/') == true) && obj.authenticated && (parent.parent.firebase != null)) {
  561. // This is an authenticated messenger session, push messaging may be allowed. Don't hold traffic.
  562. ws._socket.resume(); // Don't hold traffic, process push messages
  563. parent.parent.debug('relay', 'Relay messenger waiting: ' + obj.id + ' (' + obj.req.clientIp + ') ' + (obj.authenticated ? 'Authenticated' : ''));
  564. // Fetch the Push Messaging Token
  565. const idsplit = obj.id.split('/');
  566. const nodeid = idsplit[1] + '/' + idsplit[2] + '/' + idsplit[3];
  567. parent.db.Get(nodeid, function (err, nodes) {
  568. if ((err == null) && (nodes != null) && (nodes.length == 1) && (typeof nodes[0].pmt == 'string')) {
  569. if ((parent.GetNodeRights(obj.user, nodes[0].meshid, nodes[0]._id) & MESHRIGHT_CHATNOTIFY) != 0) {
  570. obj.node = nodes[0];
  571. // Create the peer connection URL, we will include that in push messages
  572. obj.msgurl = req.headers.origin + (req.url.split('/.websocket')[0].split('/meshrelay.ashx').join('/messenger')) + '?id=' + req.query.id
  573. }
  574. }
  575. });
  576. parent.wsrelays[obj.id] = { peer1: obj, state: 1 }; // No timeout on connections with push notification.
  577. } else {
  578. ws._socket.pause(); // Hold traffic until the other connection
  579. parent.parent.debug('relay', 'Relay holding: ' + obj.id + ' (' + obj.req.clientIp + ') ' + (obj.authenticated ? 'Authenticated' : ''));
  580. parent.wsrelays[obj.id] = { peer1: obj, state: 1, timeout: setTimeout(closeBothSides, 15000) };
  581. }
  582. // Check if a peer server has this connection
  583. if (parent.parent.multiServer != null) {
  584. var rsession = parent.wsPeerRelays[obj.id];
  585. if ((rsession != null) && (rsession.serverId > parent.parent.serverId)) {
  586. // We must initiate the connection to the peer
  587. parent.parent.multiServer.createPeerRelay(ws, req, rsession.serverId, obj.req.session.userid);
  588. delete parent.wsrelays[obj.id];
  589. } else {
  590. // Send message to other peers that we have this connection
  591. parent.parent.multiServer.DispatchMessage(JSON.stringify({ action: 'relay', id: obj.id }));
  592. }
  593. }
  594. }
  595. }
  596. }
  597. ws.flushSink = function () { try { ws._socket.resume(); } catch (ex) { console.log(ex); } };
  598. // When data is received from the mesh relay web socket
  599. ws.on('message', function (data) {
  600. // Perform traffic accounting
  601. parent.trafficStats.relayIn[this._socket.p] += (this._socket.bytesRead - this._socket.bytesReadEx);
  602. parent.trafficStats.relayOut[this._socket.p] += (this._socket.bytesWritten - this._socket.bytesWrittenEx);
  603. if (this.peer != null) {
  604. //if (typeof data == 'string') { console.log('Relay: ' + data); } else { console.log('Relay:' + data.length + ' byte(s)'); }
  605. if (this.peer.slowRelay == null) {
  606. try {
  607. this._socket.pause();
  608. if (this.logfile != null) {
  609. // Write data to log file then perform relay
  610. var xthis = this;
  611. recordingEntry(this.logfile, 2, ((obj.req.query.browser) ? 2 : 0), data, function () { xthis.peer.send(data, ws.flushSink); });
  612. } else {
  613. // Perform relay
  614. this.peer.send(data, ws.flushSink);
  615. }
  616. } catch (ex) { console.log(ex); }
  617. } else {
  618. try {
  619. this._socket.pause();
  620. if (this.logfile != null) {
  621. // Write data to log file then perform slow relay
  622. var xthis = this;
  623. recordingEntry(this.logfile, 2, ((obj.req.query.browser) ? 2 : 0), data, function () {
  624. setTimeout(function () { xthis.peer.send(data, ws.flushSink); }, xthis.peer.slowRelay);
  625. });
  626. } else {
  627. // Perform slow relay
  628. var xthis = this;
  629. setTimeout(function () { xthis.peer.send(data, ws.flushSink); }, xthis.peer.slowRelay);
  630. }
  631. } catch (ex) { console.log(ex); }
  632. }
  633. } else {
  634. if ((typeof data == 'string') && (obj.node != null) && (obj.node.pmt != null)) {
  635. var command = null;
  636. try { command = JSON.parse(data); } catch (ex) { return; }
  637. if ((typeof command != 'object') || (command.action != 'chat') || (typeof command.msg != 'string') || (command.msg == '')) return;
  638. // Store pushed messages
  639. if (obj.storedPushedMessages == null) { obj.storedPushedMessages = []; }
  640. obj.storedPushedMessages.push(command.msg);
  641. while (obj.storedPushedMessages.length > 50) { obj.storedPushedMessages.shift(); } // Only keep last 50 notifications
  642. // Send out a push message to the device
  643. command.title = (domain.title ? domain.title : 'MeshCentral');
  644. var payload = { notification: { title: command.title, body: command.msg }, data: { url: obj.msgurl } };
  645. var options = { priority: 'High', timeToLive: 5 * 60 }; // TTL: 5 minutes, priority 'Normal' or 'High'
  646. parent.parent.firebase.sendToDevice(obj.node, payload, options, function (id, err, errdesc) {
  647. if (err == null) {
  648. parent.parent.debug('email', 'Successfully send push message to device ' + obj.node.name + ', title: ' + command.title + ', msg: ' + command.msg);
  649. try { ws.send(JSON.stringify({ action: 'ctrl', value: 1 })); } catch (ex) { } // Push notification success
  650. } else {
  651. parent.parent.debug('email', 'Failed to send push message to device ' + obj.node.name + ', title: ' + command.title + ', msg: ' + command.msg + ', error: ' + errdesc);
  652. try { ws.send(JSON.stringify({ action: 'ctrl', value: 2 })); } catch (ex) { } // Push notification failed
  653. }
  654. });
  655. }
  656. }
  657. });
  658. // If error, close both sides of the relay.
  659. ws.on('error', function (err) {
  660. parent.relaySessionErrorCount++;
  661. if (obj.relaySessionCounted) { parent.relaySessionCount--; delete obj.relaySessionCounted; }
  662. console.log('Relay error from ' + obj.req.clientIp + ', ' + err.toString().split('\r')[0] + '.');
  663. closeBothSides();
  664. });
  665. // If the relay web socket is closed, close both sides.
  666. ws.on('close', function (req) {
  667. // Perform traffic accounting
  668. parent.trafficStats.relayIn[this._socket.p] += (this._socket.bytesRead - this._socket.bytesReadEx);
  669. parent.trafficStats.relayOut[this._socket.p] += (this._socket.bytesWritten - this._socket.bytesWrittenEx);
  670. if (obj.relaySessionCounted) { parent.relaySessionCount--; delete obj.relaySessionCounted; }
  671. closeBothSides();
  672. });
  673. // Set the session expire timer
  674. function setExpireTimer() {
  675. if (obj.expireTimer != null) { clearTimeout(obj.expireTimer); delete obj.expireTimer; }
  676. if (cookie && (typeof cookie.expire == 'number')) {
  677. const timeToExpire = (cookie.expire - Date.now());
  678. if (timeToExpire < 1) {
  679. closeBothSides();
  680. } else if (timeToExpire >= 0x7FFFFFFF) {
  681. obj.expireTimer = setTimeout(setExpireTimer, 0x7FFFFFFF); // Since expire timer can't be larger than 0x7FFFFFFF, reset timer after that time.
  682. } else {
  683. obj.expireTimer = setTimeout(closeBothSides, timeToExpire);
  684. }
  685. }
  686. }
  687. // Close both our side and the peer side.
  688. function closeBothSides() {
  689. if (obj.id != null) {
  690. var relayinfo = parent.wsrelays[obj.id];
  691. if (relayinfo != null) {
  692. if (relayinfo.state == 2) {
  693. var peer = (relayinfo.peer1 == obj) ? relayinfo.peer2 : relayinfo.peer1;
  694. // Compute traffic
  695. var inTraffc, outTraffc;
  696. try { inTraffc = ws._socket.bytesRead + peer.ws._socket.bytesRead; } catch (ex) { }
  697. try { outTraffc = ws._socket.bytesWritten + peer.ws._socket.bytesWritten; } catch (ex) { }
  698. // Disconnect the peer
  699. try { if (peer.relaySessionCounted) { parent.relaySessionCount--; delete peer.relaySessionCounted; } } catch (ex) { console.log(ex); }
  700. parent.parent.debug('relay', 'Relay disconnect: ' + obj.id + ' (' + obj.req.clientIp + ' --> ' + peer.req.clientIp + ')');
  701. try { peer.ws.close(); } catch (e) { } // Soft disconnect
  702. try { peer.ws._socket._parent.end(); } catch (e) { } // Hard disconnect
  703. // Log the disconnection
  704. if (ws.time) {
  705. var msg = 'Ended relay session', msgid = 9;
  706. if ([1,6,8,9].indexOf(obj.req.query.p) >= 0) { msg = 'Ended terminal session', msgid = 10; } // admin shell, admin powershell, user shell, user powershell
  707. else if (obj.req.query.p == 2) { msg = 'Ended desktop session', msgid = 11; }
  708. else if (obj.req.query.p == 5) { msg = 'Ended file management session', msgid = 12; }
  709. else if (obj.req.query.p == 200) { msg = 'Ended messenger session', msgid = 112; }
  710. // Get the nodeid and meshid of this device
  711. var nodeid = (obj.nodeid == null) ? peer.nodeid : obj.nodeid;
  712. var meshid = (obj.meshid == null) ? peer.meshid : obj.meshid;
  713. if (user) {
  714. var event = { etype: 'relay', action: 'relaylog', domain: domain.id, userid: user._id, username: user.name, msgid: msgid, msgArgs: [obj.id, obj.req.clientIp, obj.peer.req.clientIp, Math.floor((Date.now() - ws.time) / 1000)], msg: msg + ' \"' + obj.id + '\" from ' + obj.req.clientIp + ' to ' + obj.peer.req.clientIp + ', ' + Math.floor((Date.now() - ws.time) / 1000) + ' second(s)', protocol: obj.req.query.p, nodeid: obj.req.query.nodeid, bytesin: inTraffc, bytesout: outTraffc };
  715. if (obj.guestname) { event.guestname = obj.guestname; } else if (peer.guestname) { event.guestname = peer.guestname; } // If this is a sharing session, set the guest name here.
  716. parent.parent.DispatchEvent(['*', user._id, nodeid, meshid], obj, event);
  717. } else if (peer.user) {
  718. var event = { etype: 'relay', action: 'relaylog', domain: domain.id, userid: peer.user._id, username: peer.user.name, msgid: msgid, msgArgs: [obj.id, obj.req.clientIp, obj.peer.req.clientIp, Math.floor((Date.now() - ws.time) / 1000)], msg: msg + ' \"' + obj.id + '\" from ' + obj.req.clientIp + ' to ' + obj.peer.req.clientIp + ', ' + Math.floor((Date.now() - ws.time) / 1000) + ' second(s)', protocol: obj.req.query.p, nodeid: obj.req.query.nodeid, bytesin: inTraffc, bytesout: outTraffc };
  719. if (obj.guestname) { event.guestname = obj.guestname; } else if (peer.guestname) { event.guestname = peer.guestname; } // If this is a sharing session, set the guest name here.
  720. parent.parent.DispatchEvent(['*', peer.user._id, nodeid, meshid], obj, event);
  721. }
  722. }
  723. // Aggressive peer cleanup
  724. delete peer.id;
  725. delete peer.ws;
  726. delete peer.peer;
  727. delete peer.nodeid;
  728. delete peer.meshid;
  729. if (peer.pingtimer != null) { clearInterval(peer.pingtimer); delete peer.pingtimer; }
  730. if (peer.pongtimer != null) { clearInterval(peer.pongtimer); delete peer.pongtimer; }
  731. } else {
  732. parent.parent.debug('relay', 'Relay disconnect: ' + obj.id + ' (' + obj.req.clientIp + ')');
  733. }
  734. // Close the recording file if needed
  735. if (ws.logfile != null) {
  736. var logfile = ws.logfile;
  737. delete ws.logfile;
  738. if (peer.ws) { delete peer.ws.logfile; }
  739. setTimeout(function(){ // wait 5 seconds before finishing file for some reason?
  740. recordingEntry(logfile, 3, 0, 'MeshCentralMCREC', function (logfile, tag) {
  741. parent.parent.fs.closeSync(logfile.fd);
  742. parent.parent.debug('relay', 'Relay: Finished recording to file: ' + tag.logfile.filename);
  743. // Now that the recording file is closed, check if we need to index this file.
  744. if (domain.sessionrecording.index && domain.sessionrecording.index !== false) { parent.parent.certificateOperations.acceleratorPerformOperation('indexMcRec', tag.logfile.filename); }
  745. // Compute session length
  746. var sessionLength = null;
  747. if (tag.logfile.startTime != null) { sessionLength = Math.round((Date.now() - tag.logfile.startTime) / 1000) - 5; }
  748. // Add a event entry about this recording
  749. var basefile = parent.parent.path.basename(tag.logfile.filename);
  750. var event = { etype: 'relay', action: 'recording', domain: domain.id, nodeid: tag.logfile.nodeid, msg: "Finished recording session" + (sessionLength ? (', ' + sessionLength + ' second(s)') : ''), filename: basefile, size: tag.logfile.size };
  751. if (user) { event.userids = [user._id]; } else if (peer.user) { event.userids = [peer.user._id]; }
  752. var xprotocol = (((obj.req == null) || (obj.req.query == null)) ? null : obj.req.query.p);
  753. if ((xprotocol == null) && (logfile.text == 2)) { xprotocol = 200; }
  754. if (xprotocol != null) { event.protocol = parseInt(xprotocol); }
  755. var mesh = parent.meshes[tag.logfile.meshid];
  756. if (mesh != null) { event.meshname = mesh.name; event.meshid = mesh._id; }
  757. if (tag.logfile.startTime) { event.startTime = tag.logfile.startTime; event.lengthTime = sessionLength; }
  758. if (tag.logfile.name) { event.name = tag.logfile.name; }
  759. if (tag.logfile.icon) { event.icon = tag.logfile.icon; }
  760. parent.parent.DispatchEvent(['*', 'recording', tag.logfile.nodeid, tag.logfile.meshid], obj, event);
  761. cleanUpRecordings();
  762. }, { ws: ws, pws: peer.ws, logfile: logfile });
  763. },5000);
  764. }
  765. try { ws.close(); } catch (ex) { }
  766. delete parent.wsrelays[obj.id];
  767. }
  768. }
  769. // Aggressive cleanup
  770. delete obj.id;
  771. delete obj.ws;
  772. delete obj.peer;
  773. delete obj.nodeid;
  774. delete obj.meshid;
  775. if (obj.pingtimer != null) { clearInterval(obj.pingtimer); delete obj.pingtimer; }
  776. if (obj.pongtimer != null) { clearInterval(obj.pongtimer); delete obj.pongtimer; }
  777. // Unsubscribe
  778. if (obj.pid != null) { parent.parent.RemoveAllEventDispatch(obj); }
  779. }
  780. // If this session has a expire time, setup the expire timer now.
  781. setExpireTimer();
  782. // Mark this relay session as authenticated if this is the user end.
  783. obj.authenticated = ((user != null) || (obj.nouser === true));
  784. if (obj.authenticated) {
  785. // To build the connection URL, if we are using a sub-domain or one with a DNS, we need to craft the URL correctly.
  786. var xdomain = (domain.dns == null) ? domain.id : '';
  787. if (xdomain != '') xdomain += '/';
  788. // Kick off the routing, if we have agent routing instructions, process them here.
  789. // Routing instructions can only be given by a authenticated user
  790. if ((cookie != null) && (cookie.nodeid != null) && (cookie.tcpport != null) && (cookie.domainid != null)) {
  791. // We have routing instructions in the cookie, but first, check user access for this node.
  792. parent.db.Get(cookie.nodeid, function (err, docs) {
  793. if (docs.length == 0) { console.log('ERR: Node not found'); try { obj.close(); } catch (e) { } return; } // Disconnect websocket
  794. const node = docs[0];
  795. // Check if this user has permission to relay thru this computer (MESHRIGHT_REMOTECONTROL or MESHRIGHT_RELAY rights)
  796. if ((obj.nouser !== true) && ((parent.GetNodeRights(obj.user, node.meshid, node._id) & 0x00200008) == 0)) { console.log('ERR: Access denied (1)'); try { obj.close(); } catch (ex) { } return; }
  797. // Set nodeid and meshid
  798. obj.nodeid = node._id;
  799. obj.meshid = node.meshid;
  800. // Send connection request to agent
  801. const rcookieData = {};
  802. if (user != null) { rcookieData.ruserid = user._id; } else if (obj.nouser === true) { rcookieData.nouser = 1; }
  803. const rcookie = parent.parent.encodeCookie(rcookieData, parent.parent.loginCookieEncryptionKey);
  804. if (obj.id == null) { obj.id = parent.crypto.randomBytes(9).toString('base64').replace(/\+/g, '@').replace(/\//g, '$'); } // If there is no connection id, generate one.
  805. const command = { nodeid: cookie.nodeid, action: 'msg', type: 'tunnel', value: '*/' + xdomain + 'meshrelay.ashx?' + (obj.req.query.p != null ? ('p=' + obj.req.query.p + '&') : '') + 'id=' + obj.id + '&rauth=' + rcookie, tcpport: cookie.tcpport, tcpaddr: cookie.tcpaddr, soptions: {} };
  806. if (user) { command.userid = user._id; }
  807. if (typeof domain.consentmessages == 'object') {
  808. if (typeof domain.consentmessages.title == 'string') { command.soptions.consentTitle = domain.consentmessages.title; }
  809. if (typeof domain.consentmessages.desktop == 'string') { command.soptions.consentMsgDesktop = domain.consentmessages.desktop; }
  810. if (typeof domain.consentmessages.terminal == 'string') { command.soptions.consentMsgTerminal = domain.consentmessages.terminal; }
  811. if (typeof domain.consentmessages.files == 'string') { command.soptions.consentMsgFiles = domain.consentmessages.files; }
  812. if ((typeof domain.consentmessages.consenttimeout == 'number') && (domain.consentmessages.consenttimeout > 0)) { command.soptions.consentTimeout = domain.consentmessages.consenttimeout; }
  813. if (domain.consentmessages.autoacceptontimeout === true) { command.soptions.consentAutoAccept = true; }
  814. if (domain.consentmessages.autoacceptifnouser === true) { command.soptions.consentAutoAcceptIfNoUser = true; }
  815. if (domain.consentmessages.autoacceptifdesktopnouser === true) { command.soptions.consentAutoAcceptIfDesktopNoUser = true; }
  816. if (domain.consentmessages.autoacceptifterminalnouser === true) { command.soptions.consentAutoAcceptIfTerminalNoUser = true; }
  817. if (domain.consentmessages.autoacceptiffilenouser === true) { command.soptions.consentAautoAcceptIfFileNoUser = true; }
  818. if (domain.consentmessages.autoacceptiflocked === true) { command.soptions.consentAutoAcceptIfLocked = true; }
  819. if (domain.consentmessages.autoacceptifdesktoplocked === true) { command.soptions.consentAutoAcceptIfDesktopLocked = true; }
  820. if (domain.consentmessages.autoacceptifterminallocked === true) { command.soptions.consentAutoAcceptIfTerminalLocked = true; }
  821. if (domain.consentmessages.autoacceptiffilelocked === true) { command.soptions.consentAutoAcceptIfFileLocked = true; }
  822. if (domain.consentmessages.oldstyle === true) { command.soptions.oldStyle = true; }
  823. }
  824. if (typeof domain.notificationmessages == 'object') {
  825. if (typeof domain.notificationmessages.title == 'string') { command.soptions.notifyTitle = domain.notificationmessages.title; }
  826. if (typeof domain.notificationmessages.desktop == 'string') { command.soptions.notifyMsgDesktop = domain.notificationmessages.desktop; }
  827. if (typeof domain.notificationmessages.terminal == 'string') { command.soptions.notifyMsgTerminal = domain.notificationmessages.terminal; }
  828. if (typeof domain.notificationmessages.files == 'string') { command.soptions.notifyMsgFiles = domain.notificationmessages.files; }
  829. }
  830. parent.parent.debug('relay', 'Relay: Sending agent tunnel command: ' + JSON.stringify(command));
  831. if (obj.sendAgentMessage(command, user?user._id:null, cookie.domainid) == false) { delete obj.id; parent.parent.debug('relay', 'Relay: Unable to contact this agent (' + obj.req.clientIp + ')'); }
  832. performRelay();
  833. });
  834. return obj;
  835. } else if ((obj.req.query.nodeid != null) && ((obj.req.query.tcpport != null) || (obj.req.query.udpport != null))) {
  836. // We have routing instructions in the URL arguments, but first, check user access for this node.
  837. parent.db.Get(obj.req.query.nodeid, function (err, docs) {
  838. if (docs.length == 0) { console.log('ERR: Node not found'); try { obj.close(); } catch (e) { } return; } // Disconnect websocket
  839. const node = docs[0];
  840. // Check if this user has permission to relay thru this computer (MESHRIGHT_REMOTECONTROL or MESHRIGHT_RELAY rights)
  841. if ((parent.GetNodeRights(obj.user, node.meshid, node._id) & 0x00200008) == 0) { console.log('ERR: Access denied (2)'); try { obj.close(); } catch (ex) { } return; }
  842. // Set nodeid and meshid
  843. obj.nodeid = node._id;
  844. obj.meshid = node.meshid;
  845. // Send connection request to agent
  846. if (obj.id == null) { obj.id = parent.crypto.randomBytes(9).toString('base64').replace(/\+/g, '@').replace(/\//g, '$'); } // If there is no connection id, generate one.
  847. const rcookie = parent.parent.encodeCookie({ ruserid: user._id }, parent.parent.loginCookieEncryptionKey);
  848. if (obj.req.query.tcpport != null) {
  849. const command = { nodeid: obj.req.query.nodeid, action: 'msg', type: 'tunnel', userid: user._id, value: '*/' + xdomain + 'meshrelay.ashx?' + (obj.req.query.p != null ? ('p=' + obj.req.query.p + '&') : '') + 'id=' + obj.id + '&rauth=' + rcookie, tcpport: obj.req.query.tcpport, tcpaddr: ((obj.req.query.tcpaddr == null) ? '127.0.0.1' : obj.req.query.tcpaddr), soptions: {} };
  850. if (typeof domain.consentmessages == 'object') {
  851. if (typeof domain.consentmessages.title == 'string') { command.soptions.consentTitle = domain.consentmessages.title; }
  852. if (typeof domain.consentmessages.desktop == 'string') { command.soptions.consentMsgDesktop = domain.consentmessages.desktop; }
  853. if (typeof domain.consentmessages.terminal == 'string') { command.soptions.consentMsgTerminal = domain.consentmessages.terminal; }
  854. if (typeof domain.consentmessages.files == 'string') { command.soptions.consentMsgFiles = domain.consentmessages.files; }
  855. if ((typeof domain.consentmessages.consenttimeout == 'number') && (domain.consentmessages.consenttimeout > 0)) { command.soptions.consentTimeout = domain.consentmessages.consenttimeout; }
  856. if (domain.consentmessages.autoacceptontimeout === true) { command.soptions.consentAutoAccept = true; }
  857. if (domain.consentmessages.autoacceptifnouser === true) { command.soptions.consentAutoAcceptIfNoUser = true; }
  858. if (domain.consentmessages.autoacceptifdesktopnouser === true) { command.soptions.consentAutoAcceptIfDesktopNoUser = true; }
  859. if (domain.consentmessages.autoacceptifterminalnouser === true) { command.soptions.consentAutoAcceptIfTerminalNoUser = true; }
  860. if (domain.consentmessages.autoacceptiffilenouser === true) { command.soptions.consentAautoAcceptIfFileNoUser = true; }
  861. if (domain.consentmessages.autoacceptiflocked === true) { command.soptions.consentAutoAcceptIfLocked = true; }
  862. if (domain.consentmessages.autoacceptifdesktoplocked === true) { command.soptions.consentAutoAcceptIfDesktopLocked = true; }
  863. if (domain.consentmessages.autoacceptifterminallocked === true) { command.soptions.consentAutoAcceptIfTerminalLocked = true; }
  864. if (domain.consentmessages.autoacceptiffilelocked === true) { command.soptions.consentAutoAcceptIfFileLocked = true; }
  865. if (domain.consentmessages.oldstyle === true) { command.soptions.oldStyle = true; }
  866. }
  867. if (typeof domain.notificationmessages == 'object') {
  868. if (typeof domain.notificationmessages.title == 'string') { command.soptions.notifyTitle = domain.notificationmessages.title; }
  869. if (typeof domain.notificationmessages.desktop == 'string') { command.soptions.notifyMsgDesktop = domain.notificationmessages.desktop; }
  870. if (typeof domain.notificationmessages.terminal == 'string') { command.soptions.notifyMsgTerminal = domain.notificationmessages.terminal; }
  871. if (typeof domain.notificationmessages.files == 'string') { command.soptions.notifyMsgFiles = domain.notificationmessages.files; }
  872. }
  873. parent.parent.debug('relay', 'Relay: Sending agent TCP tunnel command: ' + JSON.stringify(command));
  874. if (obj.sendAgentMessage(command, user._id, domain.id) == false) { delete obj.id; parent.parent.debug('relay', 'Relay: Unable to contact this agent (' + obj.req.clientIp + ')'); }
  875. } else if (obj.req.query.udpport != null) {
  876. const command = { nodeid: obj.req.query.nodeid, action: 'msg', type: 'tunnel', userid: user._id, value: '*/' + xdomain + 'meshrelay.ashx?' + (obj.req.query.p != null ? ('p=' + obj.req.query.p + '&') : '') + 'id=' + obj.id + '&rauth=' + rcookie, udpport: obj.req.query.udpport, udpaddr: ((obj.req.query.udpaddr == null) ? '127.0.0.1' : obj.req.query.udpaddr), soptions: {} }; if (typeof domain.consentmessages == 'object') {
  877. if (typeof domain.consentmessages.title == 'string') { command.soptions.consentTitle = domain.consentmessages.title; }
  878. if (typeof domain.consentmessages.desktop == 'string') { command.soptions.consentMsgDesktop = domain.consentmessages.desktop; }
  879. if (typeof domain.consentmessages.terminal == 'string') { command.soptions.consentMsgTerminal = domain.consentmessages.terminal; }
  880. if (typeof domain.consentmessages.files == 'string') { command.soptions.consentMsgFiles = domain.consentmessages.files; }
  881. if ((typeof domain.consentmessages.consenttimeout == 'number') && (domain.consentmessages.consenttimeout > 0)) { command.soptions.consentTimeout = domain.consentmessages.consenttimeout; }
  882. if (domain.consentmessages.autoacceptontimeout === true) { command.soptions.consentAutoAccept = true; }
  883. if (domain.consentmessages.autoacceptifnouser === true) { command.soptions.consentAutoAcceptIfNoUser = true; }
  884. if (domain.consentmessages.autoacceptifdesktopnouser === true) { command.soptions.consentAutoAcceptIfDesktopNoUser = true; }
  885. if (domain.consentmessages.autoacceptifterminalnouser === true) { command.soptions.consentAutoAcceptIfTerminalNoUser = true; }
  886. if (domain.consentmessages.autoacceptiffilenouser === true) { command.soptions.consentAautoAcceptIfFileNoUser = true; }
  887. if (domain.consentmessages.autoacceptiflocked === true) { command.soptions.consentAutoAcceptIfLocked = true; }
  888. if (domain.consentmessages.autoacceptifdesktoplocked === true) { command.soptions.consentAutoAcceptIfDesktopLocked = true; }
  889. if (domain.consentmessages.autoacceptifterminallocked === true) { command.soptions.consentAutoAcceptIfTerminalLocked = true; }
  890. if (domain.consentmessages.autoacceptiffilelocked === true) { command.soptions.consentAutoAcceptIfFileLocked = true; }
  891. if (domain.consentmessages.oldstyle === true) { command.soptions.oldStyle = true; }
  892. }
  893. if (typeof domain.notificationmessages == 'object') {
  894. if (typeof domain.notificationmessages.title == 'string') { command.soptions.notifyTitle = domain.notificationmessages.title; }
  895. if (typeof domain.notificationmessages.desktop == 'string') { command.soptions.notifyMsgDesktop = domain.notificationmessages.desktop; }
  896. if (typeof domain.notificationmessages.terminal == 'string') { command.soptions.notifyMsgTerminal = domain.notificationmessages.terminal; }
  897. if (typeof domain.notificationmessages.files == 'string') { command.soptions.notifyMsgFiles = domain.notificationmessages.files; }
  898. }
  899. parent.parent.debug('relay', 'Relay: Sending agent UDP tunnel command: ' + JSON.stringify(command));
  900. if (obj.sendAgentMessage(command, user._id, domain.id) == false) { delete obj.id; parent.parent.debug('relay', 'Relay: Unable to contact this agent (' + obj.req.clientIp + ')'); }
  901. }
  902. performRelay();
  903. });
  904. return obj;
  905. } else if ((cookie != null) && (cookie.nid != null) && (typeof cookie.r == 'number') && (typeof cookie.p == 'number') && (typeof cookie.cf == 'number') && (typeof cookie.gn == 'string')) {
  906. // We have routing instructions in the cookie, but first, check user access for this node.
  907. parent.db.Get(cookie.nid, function (err, docs) {
  908. if (docs.length == 0) { console.log('ERR: Node not found'); try { obj.close(); } catch (e) { } return; } // Disconnect websocket
  909. const node = docs[0];
  910. // Check if this user has permission to relay thru this computer (MESHRIGHT_REMOTECONTROL or MESHRIGHT_RELAY rights)
  911. if ((obj.nouser !== true) && ((parent.GetNodeRights(obj.user, node.meshid, node._id) & 0x00200008) == 0)) { console.log('ERR: Access denied (2)'); try { obj.close(); } catch (ex) { } return; }
  912. // Set nodeid and meshid
  913. obj.nodeid = node._id;
  914. obj.meshid = node.meshid;
  915. // Send connection request to agent
  916. if (obj.id == null) { obj.id = parent.crypto.randomBytes(9).toString('base64').replace(/\+/g, '@').replace(/\//g, '$'); } // If there is no connection id, generate one.
  917. const rcookieData = { nodeid: node._id };
  918. if (user != null) { rcookieData.ruserid = user._id; } else if (obj.nouser === true) { rcookieData.nouser = 1; }
  919. const rcookie = parent.parent.encodeCookie(rcookieData, parent.parent.loginCookieEncryptionKey);
  920. const command = { nodeid: node._id, action: 'msg', type: 'tunnel', value: '*/' + xdomain + 'meshrelay.ashx?p=' + obj.req.query.p + '&id=' + obj.id + '&rauth=' + rcookie + '&nodeid=' + node._id, soptions: {}, rights: cookie.r, guestuserid: user._id, guestname: cookie.gn, consent: cookie.cf, remoteaddr: cleanRemoteAddr(obj.req.clientIp) };
  921. obj.guestname = cookie.gn;
  922. // Limit what this relay connection can do
  923. if (typeof cookie.p == 'number') {
  924. var usages = [];
  925. if (cookie.p & 1) { usages.push(1); usages.push(6); usages.push(8); usages.push(9); } // Terminal
  926. if (cookie.p & 2) { usages.push(2); } // Desktop
  927. if (cookie.p & 4) { usages.push(5); usages.push(10); } // Files
  928. command.soptions.usages = usages;
  929. }
  930. if (usages.indexOf(parseInt(obj.req.query.p)) < 0) { console.log('ERR: Invalid protocol usage'); try { obj.close(); } catch (e) { } return; }
  931. if (typeof domain.consentmessages == 'object') {
  932. if (typeof domain.consentmessages.title == 'string') { command.soptions.consentTitle = domain.consentmessages.title; }
  933. if (typeof domain.consentmessages.desktop == 'string') { command.soptions.consentMsgDesktop = domain.consentmessages.desktop; }
  934. if (typeof domain.consentmessages.terminal == 'string') { command.soptions.consentMsgTerminal = domain.consentmessages.terminal; }
  935. if (typeof domain.consentmessages.files == 'string') { command.soptions.consentMsgFiles = domain.consentmessages.files; }
  936. if ((typeof domain.consentmessages.consenttimeout == 'number') && (domain.consentmessages.consenttimeout > 0)) { command.soptions.consentTimeout = domain.consentmessages.consenttimeout; }
  937. if (domain.consentmessages.autoacceptontimeout === true) { command.soptions.consentAutoAccept = true; }
  938. if (domain.consentmessages.autoacceptifnouser === true) { command.soptions.consentAutoAcceptIfNoUser = true; }
  939. if (domain.consentmessages.autoacceptifdesktopnouser === true) { command.soptions.consentAutoAcceptIfDesktopNoUser = true; }
  940. if (domain.consentmessages.autoacceptifterminalnouser === true) { command.soptions.consentAutoAcceptIfTerminalNoUser = true; }
  941. if (domain.consentmessages.autoacceptiffilenouser === true) { command.soptions.consentAautoAcceptIfFileNoUser = true; }
  942. if (domain.consentmessages.autoacceptiflocked === true) { command.soptions.consentAutoAcceptIfLocked = true; }
  943. if (domain.consentmessages.autoacceptifdesktoplocked === true) { command.soptions.consentAutoAcceptIfDesktopLocked = true; }
  944. if (domain.consentmessages.autoacceptifterminallocked === true) { command.soptions.consentAutoAcceptIfTerminalLocked = true; }
  945. if (domain.consentmessages.autoacceptiffilelocked === true) { command.soptions.consentAutoAcceptIfFileLocked = true; }
  946. if (domain.consentmessages.oldstyle === true) { command.soptions.oldStyle = true; }
  947. }
  948. if (typeof domain.notificationmessages == 'object') {
  949. if (typeof domain.notificationmessages.title == 'string') { command.soptions.notifyTitle = domain.notificationmessages.title; }
  950. if (typeof domain.notificationmessages.desktop == 'string') { command.soptions.notifyMsgDesktop = domain.notificationmessages.desktop; }
  951. if (typeof domain.notificationmessages.terminal == 'string') { command.soptions.notifyMsgTerminal = domain.notificationmessages.terminal; }
  952. if (typeof domain.notificationmessages.files == 'string') { command.soptions.notifyMsgFiles = domain.notificationmessages.files; }
  953. }
  954. parent.parent.debug('relay', 'Relay: Sending agent tunnel command: ' + JSON.stringify(command));
  955. if (obj.sendAgentMessage(command, user?user._id:null, domain.id) == false) { delete obj.id; parent.parent.debug('relay', 'Relay: Unable to contact this agent (' + obj.req.clientIp + ')'); }
  956. performRelay(0);
  957. });
  958. return obj;
  959. } else {
  960. // No routing needed. Just check permissions and fill in the device nodeid and meshid.
  961. if ((obj.req.query.nodeid != null) && (obj.req.query.nodeid.startsWith('node/'))) {
  962. var nodeSplit = obj.req.query.nodeid.split('/');
  963. if ((nodeSplit.length != 3) || (nodeSplit[1] != domain.id)) { console.log('ERR: Invalid NodeID'); try { obj.close(); } catch (e) { } return; }
  964. parent.db.Get(obj.req.query.nodeid, function (err, docs) {
  965. if (docs.length == 0) { console.log('ERR: Node not found'); try { obj.close(); } catch (e) { } return; } // Disconnect websocket
  966. const node = docs[0];
  967. // Check if this user has permission to relay thru this computer (MESHRIGHT_REMOTECONTROL or MESHRIGHT_RELAY rights)
  968. if ((parent.GetNodeRights(obj.user, node.meshid, node._id) & 0x00200008) == 0) { console.log('ERR: Access denied (2)'); try { obj.close(); } catch (ex) { } return; }
  969. // Set nodeid and meshid
  970. obj.nodeid = node._id;
  971. obj.meshid = node.meshid;
  972. });
  973. }
  974. }
  975. }
  976. // If there is a recording quota, remove any old recordings if needed
  977. function cleanUpRecordings() {
  978. if ((parent.cleanUpRecordingsActive !== true) && domain.sessionrecording && ((typeof domain.sessionrecording.maxrecordings == 'number') || (typeof domain.sessionrecording.maxrecordingsizemegabytes == 'number') || (typeof domain.sessionrecording.maxrecordingdays == 'number'))) {
  979. parent.cleanUpRecordingsActive = true;
  980. setTimeout(function () {
  981. var recPath = null, fs = require('fs'), now = Date.now();
  982. if (domain.sessionrecording.filepath) { recPath = domain.sessionrecording.filepath; } else { recPath = parent.parent.recordpath; }
  983. fs.readdir(recPath, function (err, files) {
  984. if ((err != null) || (files == null)) { delete parent.cleanUpRecordingsActive; return; }
  985. var recfiles = [];
  986. for (var i in files) {
  987. if (files[i].endsWith('.mcrec')) {
  988. var j = files[i].indexOf('-');
  989. if (j > 0) {
  990. var stats = null;
  991. try { stats = fs.statSync(parent.parent.path.join(recPath, files[i])); } catch (ex) { }
  992. if (stats != null) { recfiles.push({ n: files[i], r: files[i].substring(j + 1), s: stats.size, t: stats.mtimeMs }); }
  993. }
  994. }
  995. }
  996. recfiles.sort(function (a, b) { if (a.r < b.r) return 1; if (a.r > b.r) return -1; return 0; });
  997. var totalFiles = 0, totalSize = 0;
  998. for (var i in recfiles) {
  999. var overQuota = false;
  1000. if ((typeof domain.sessionrecording.maxrecordings == 'number') && (domain.sessionrecording.maxrecordings > 0) && (totalFiles >= domain.sessionrecording.maxrecordings)) { overQuota = true; }
  1001. else if ((typeof domain.sessionrecording.maxrecordingsizemegabytes == 'number') && (domain.sessionrecording.maxrecordingsizemegabytes > 0) && (totalSize >= (domain.sessionrecording.maxrecordingsizemegabytes * 1048576))) { overQuota = true; }
  1002. else if ((typeof domain.sessionrecording.maxrecordingdays == 'number') && (domain.sessionrecording.maxrecordingdays > 0) && (((now - recfiles[i].t) / 1000 / 60 / 60 / 24) >= domain.sessionrecording.maxrecordingdays)) { overQuota = true; }
  1003. if (overQuota) { fs.unlinkSync(parent.parent.path.join(recPath, recfiles[i].n)); }
  1004. totalFiles++;
  1005. totalSize += recfiles[i].s;
  1006. }
  1007. delete parent.cleanUpRecordingsActive;
  1008. });
  1009. }, 500);
  1010. }
  1011. }
  1012. // If this is not an authenticated session, or the session does not have routing instructions, just go ahead an connect to existing session.
  1013. performRelay();
  1014. return obj;
  1015. };
  1016. /*
  1017. Relay session recording required that "SessionRecording":true be set in the domain section of the config.json.
  1018. Once done, a folder "meshcentral-recordings" will be created next to "meshcentral-data" that will contain all
  1019. of the recording files with the .mcrec extension.
  1020. The recording files are binary and contain a set of:
  1021. <HEADER><DATABLOCK><HEADER><DATABLOCK><HEADER><DATABLOCK><HEADER><DATABLOCK>...
  1022. The header is always 16 bytes long and is encoded like this:
  1023. TYPE 2 bytes, 1 = Header, 2 = Network Data, 3 = EndBlock
  1024. FLAGS 2 bytes, 0x0001 = Binary, 0x0002 = User
  1025. SIZE 4 bytes, Size of the data following this header.
  1026. TIME 8 bytes, Time this record was written, number of milliseconds since 1 January, 1970 UTC.
  1027. All values are BigEndian encoded. The first data block is of TYPE 1 and contains a JSON string with information
  1028. about this recording. It looks something like this:
  1029. {
  1030. magic: 'MeshCentralRelaySession',
  1031. ver: 1,
  1032. userid: "user\domain\userid",
  1033. username: "username",
  1034. sessionid: "RandomValue",
  1035. ipaddr1: 1.2.3.4,
  1036. ipaddr2: 1.2.3.5,
  1037. time: new Date().toLocaleString()
  1038. }
  1039. The rest of the data blocks are all network traffic that was relayed thru the server. They are of TYPE 2 and have
  1040. a given size and timestamp. When looking at network traffic the flags are important:
  1041. - If traffic has the first (0x0001) flag set, the data is binary otherwise it's a string.
  1042. - If the traffic has the second (0x0002) flag set, traffic is coming from the user's browser, if not, it's coming from the MeshAgent.
  1043. */
  1044. module.exports.CreateLocalRelay = function (parent, ws, req, domain, user, cookie) {
  1045. CreateLocalRelayEx(parent, ws, req, domain, user, cookie);
  1046. }
  1047. function CreateLocalRelayEx(parent, ws, req, domain, user, cookie) {
  1048. const net = require('net');
  1049. var obj = {};
  1050. obj.id = parent.crypto.randomBytes(9).toString('base64').replace(/\+/g, '@').replace(/\//g, '$');
  1051. obj.req = req;
  1052. obj.ws = ws;
  1053. obj.user = user;
  1054. // Check the protocol in use
  1055. var protocolInUse = parseInt(req.query.p);
  1056. if (typeof protocolInUse != 'number') { protocolInUse = 0; }
  1057. // If there is no authentication, drop this connection
  1058. if (obj.user == null) { try { ws.close(); parent.parent.debug('relay', 'LocalRelay: Connection with no authentication'); } catch (e) { console.log(e); } return; }
  1059. // Use cookie values when present
  1060. if (cookie != null) {
  1061. if (cookie.nodeid) { req.query.nodeid = cookie.nodeid; }
  1062. if (cookie.tcpport) { req.query.tcpport = cookie.tcpport; }
  1063. }
  1064. // Check for nodeid and tcpport
  1065. if ((req.query == null) || (req.query.nodeid == null) || (req.query.tcpport == null)) { try { ws.close(); parent.parent.debug('relay', 'LocalRelay: Connection with invalid arguments'); } catch (e) { console.log(e); } return; }
  1066. const tcpport = parseInt(req.query.tcpport);
  1067. if ((typeof tcpport != 'number') || (tcpport < 1) || (tcpport > 65535)) { try { ws.close(); parent.parent.debug('relay', 'LocalRelay: Connection with invalid arguments'); } catch (e) { console.log(e); } return; }
  1068. var nodeidsplit = req.query.nodeid.split('/');
  1069. if ((nodeidsplit.length != 3) || (nodeidsplit[0] != 'node') || (nodeidsplit[1] != domain.id) || (nodeidsplit[2].length < 10)) { try { ws.close(); parent.parent.debug('relay', 'LocalRelay: Connection with invalid arguments'); } catch (e) { console.log(e); } return; }
  1070. obj.nodeid = req.query.nodeid;
  1071. obj.tcpport = tcpport;
  1072. // Relay session count (we may remove this in the future)
  1073. obj.relaySessionCounted = true;
  1074. parent.relaySessionCount++;
  1075. // Setup slow relay is requested. This will show down sending any data to this peer.
  1076. if ((req.query.slowrelay != null)) {
  1077. var sr = null;
  1078. try { sr = parseInt(req.query.slowrelay); } catch (ex) { }
  1079. if ((typeof sr == 'number') && (sr > 0) && (sr < 1000)) { obj.ws.slowRelay = sr; }
  1080. }
  1081. // Hold traffic until we connect to the target
  1082. ws._socket.pause();
  1083. ws._socket.bytesReadEx = 0;
  1084. ws._socket.bytesWrittenEx = 0;
  1085. // Mesh Rights
  1086. const MESHRIGHT_EDITMESH = 1;
  1087. const MESHRIGHT_MANAGEUSERS = 2;
  1088. const MESHRIGHT_MANAGECOMPUTERS = 4;
  1089. const MESHRIGHT_REMOTECONTROL = 8;
  1090. const MESHRIGHT_AGENTCONSOLE = 16;
  1091. const MESHRIGHT_SERVERFILES = 32;
  1092. const MESHRIGHT_WAKEDEVICE = 64;
  1093. const MESHRIGHT_SETNOTES = 128;
  1094. const MESHRIGHT_REMOTEVIEW = 256;
  1095. // Site rights
  1096. const SITERIGHT_SERVERBACKUP = 1;
  1097. const SITERIGHT_MANAGEUSERS = 2;
  1098. const SITERIGHT_SERVERRESTORE = 4;
  1099. const SITERIGHT_FILEACCESS = 8;
  1100. const SITERIGHT_SERVERUPDATE = 16;
  1101. const SITERIGHT_LOCKED = 32;
  1102. // Clean a IPv6 address that encodes a IPv4 address
  1103. function cleanRemoteAddr(addr) { if (addr.startsWith('::ffff:')) { return addr.substring(7); } else { return addr; } }
  1104. // Perform data accounting
  1105. function dataAccounting() {
  1106. const datain = ((obj.client.bytesRead - obj.client.bytesReadEx) + (ws._socket.bytesRead - ws._socket.bytesReadEx));
  1107. const dataout = ((obj.client.bytesWritten - obj.client.bytesWrittenEx) + (ws._socket.bytesWritten - ws._socket.bytesWrittenEx));
  1108. obj.client.bytesReadEx = obj.client.bytesRead;
  1109. obj.client.bytesWrittenEx = obj.client.bytesWritten;
  1110. ws._socket.bytesReadEx = ws._socket.bytesRead;
  1111. ws._socket.bytesWrittenEx = ws._socket.bytesWritten;
  1112. // Add to counters
  1113. if (parent.trafficStats.localRelayIn[protocolInUse]) { parent.trafficStats.localRelayIn[protocolInUse] += datain; } else { parent.trafficStats.localRelayIn[protocolInUse] = datain; }
  1114. if (parent.trafficStats.localRelayOut[protocolInUse]) { parent.trafficStats.localRelayOut[protocolInUse] += dataout; } else { parent.trafficStats.localRelayOut[protocolInUse] = dataout; }
  1115. }
  1116. // Disconnect
  1117. obj.close = function (arg) {
  1118. // If the web socket is already closed, stop here.
  1119. if (obj.ws == null) return;
  1120. // Perform data accounting
  1121. dataAccounting();
  1122. // Collect how many raw bytes where received and sent.
  1123. // We sum both the websocket and TCP client in this case.
  1124. var inTraffc = obj.ws._socket.bytesRead, outTraffc = obj.ws._socket.bytesWritten;
  1125. if (obj.client != null) { inTraffc += obj.client.bytesRead; outTraffc += obj.client.bytesWritten; }
  1126. // Close the web socket
  1127. if ((arg == 1) || (arg == null)) { try { obj.ws.close(); parent.parent.debug('relay', 'LocalRelay: Soft disconnect'); } catch (e) { console.log(e); } } // Soft close, close the websocket
  1128. if (arg == 2) { try { obj.ws._socket._parent.end(); parent.parent.debug('relay', 'LocalRelay: Hard disconnect'); } catch (e) { console.log(e); } } // Hard close, close the TCP socket
  1129. // Update the relay session count
  1130. if (obj.relaySessionCounted) { parent.relaySessionCount--; delete obj.relaySessionCounted; }
  1131. // Log the disconnection, traffic will be credited to the authenticated user
  1132. if (obj.time) {
  1133. var protocolStr = req.query.p;
  1134. if (req.query.p == 10) { protocolStr = 'RDP'; }
  1135. else if (req.query.p == 11) { protocolStr = 'SSH-TERM'; }
  1136. else if (req.query.p == 12) { protocolStr = 'VNC'; }
  1137. else if (req.query.p == 13) { protocolStr = 'SSH-FILES'; }
  1138. else if (req.query.p == 14) { protocolStr = 'Web-TCP'; }
  1139. var event = { etype: 'relay', action: 'relaylog', domain: domain.id, userid: obj.user._id, username: obj.user.name, msgid: 121, msgArgs: [obj.id, protocolStr, obj.host, Math.floor((Date.now() - obj.time) / 1000)], msg: 'Ended local relay session \"' + obj.id + '\", protocol ' + protocolStr + ' to ' + obj.host + ', ' + Math.floor((Date.now() - obj.time) / 1000) + ' second(s)', nodeid: obj.req.query.nodeid, protocol: req.query.p, in: inTraffc, out: outTraffc };
  1140. if (obj.guestname) { event.guestname = obj.guestname; } // If this is a sharing session, set the guest name here.
  1141. parent.parent.DispatchEvent(['*', user._id], obj, event);
  1142. }
  1143. // Aggressive cleanup
  1144. delete obj.ws;
  1145. delete obj.req;
  1146. delete obj.time;
  1147. delete obj.nodeid;
  1148. delete obj.meshid;
  1149. delete obj.tcpport;
  1150. if (obj.expireTimer != null) { clearTimeout(obj.expireTimer); delete obj.expireTimer; }
  1151. if (obj.client != null) { obj.client.destroy(); delete obj.client; } // Close the client socket
  1152. if (obj.pingtimer != null) { clearInterval(obj.pingtimer); delete obj.pingtimer; }
  1153. if (obj.pongtimer != null) { clearInterval(obj.pongtimer); delete obj.pongtimer; }
  1154. // Unsubscribe
  1155. if (obj.pid != null) { parent.parent.RemoveAllEventDispatch(obj); }
  1156. };
  1157. // Send a PING/PONG message
  1158. function sendPing() { try { obj.ws.send('{"ctrlChannel":"102938","type":"ping"}'); } catch (ex) { } }
  1159. function sendPong() { try { obj.ws.send('{"ctrlChannel":"102938","type":"pong"}'); } catch (ex) { } }
  1160. function performRelay() {
  1161. ws._socket.setKeepAlive(true, 240000); // Set TCP keep alive
  1162. // Setup the agent PING/PONG timers unless requested not to
  1163. if (obj.req.query.noping != 1) {
  1164. if ((typeof parent.parent.args.agentping == 'number') && (obj.pingtimer == null)) { obj.pingtimer = setInterval(sendPing, parent.parent.args.agentping * 1000); }
  1165. else if ((typeof parent.parent.args.agentpong == 'number') && (obj.pongtimer == null)) { obj.pongtimer = setInterval(sendPong, parent.parent.args.agentpong * 1000); }
  1166. }
  1167. parent.db.Get(obj.nodeid, function (err, docs) {
  1168. if ((err != null) || (docs == null) || (docs.length != 1)) { try { obj.close(); } catch (e) { } return; } // Disconnect websocket
  1169. const node = docs[0];
  1170. obj.host = node.host;
  1171. obj.meshid = node.meshid;
  1172. // Check if this user has permission to relay thru this computer (MESHRIGHT_REMOTECONTROL or MESHRIGHT_RELAY rights)
  1173. if ((parent.GetNodeRights(obj.user, node.meshid, node._id) & 0x00200008) == 0) { console.log('ERR: Access denied (2)'); try { obj.close(); } catch (ex) { } return; }
  1174. // Setup TCP client
  1175. obj.client = new net.Socket();
  1176. obj.client.bytesReadEx = 0;
  1177. obj.client.bytesWrittenEx = 0;
  1178. obj.client.connect(obj.tcpport, node.host, function () {
  1179. // Log the start of the connection
  1180. var protocolStr = req.query.p;
  1181. if (req.query.p == 10) { protocolStr = 'RDP'; }
  1182. else if (req.query.p == 11) { protocolStr = 'SSH-TERM'; }
  1183. else if (req.query.p == 12) { protocolStr = 'VNC'; }
  1184. else if (req.query.p == 13) { protocolStr = 'SSH-FILES'; }
  1185. else if (req.query.p == 14) { protocolStr = 'Web-TCP'; }
  1186. obj.time = Date.now();
  1187. var event = { etype: 'relay', action: 'relaylog', domain: domain.id, userid: obj.user._id, username: obj.user.name, msgid: 120, msgArgs: [obj.id, protocolStr, obj.host], msg: 'Started local relay session \"' + obj.id + '\", protocol ' + protocolStr + ' to ' + obj.host, nodeid: req.query.nodeid, protocol: req.query.p };
  1188. if (obj.guestname) { event.guestname = obj.guestname; } // If this is a sharing session, set the guest name here.
  1189. parent.parent.DispatchEvent(['*', obj.user._id, obj.meshid, obj.nodeid], obj, event);
  1190. // Count the session
  1191. if (parent.trafficStats.localRelayCount[protocolInUse]) { parent.trafficStats.localRelayCount[protocolInUse] += 1; } else { parent.trafficStats.localRelayCount[protocolInUse] = 1; }
  1192. // Start the session
  1193. ws.send('c');
  1194. ws._socket.resume();
  1195. });
  1196. obj.client.on('data', function (data) {
  1197. // Perform data accounting
  1198. dataAccounting();
  1199. // Perform relay
  1200. try { this.pause(); ws.send(data, this.clientResume); } catch (ex) { console.log(ex); }
  1201. });
  1202. obj.client.on('close', function () { obj.close(); });
  1203. obj.client.on('error', function (err) { obj.close(); });
  1204. obj.client.clientResume = function () { try { obj.client.resume(); } catch (ex) { console.log(ex); } };
  1205. });
  1206. }
  1207. ws.flushSink = function () { try { ws._socket.resume(); } catch (ex) { console.log(ex); } };
  1208. // When data is received from the mesh relay web socket
  1209. ws.on('message', function (data) { if (typeof data != 'string') { try { ws._socket.pause(); obj.client.write(data, ws.flushSink); } catch (ex) { } } }); // Perform relay
  1210. // If error, close both sides of the relay.
  1211. ws.on('error', function (err) { parent.relaySessionErrorCount++; obj.close(); });
  1212. // Relay web socket is closed
  1213. ws.on('close', function (req) { obj.close(); });
  1214. // If this is not an authenticated session, or the session does not have routing instructions, just go ahead an connect to existing session.
  1215. performRelay();
  1216. return obj;
  1217. };