meshrelay.js 85 KB

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