meshdevicefile.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312
  1. /**
  2. * @description MeshCentral device file download 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. module.exports.CreateMeshDeviceFile = function (parent, ws, res, req, domain, user, meshid, nodeid) {
  15. var obj = {};
  16. obj.ws = ws;
  17. obj.res = res;
  18. obj.user = user;
  19. obj.ruserid = null;
  20. obj.req = req; // Used in multi-server.js
  21. obj.id = req.query.id;
  22. obj.file = req.query.f;
  23. // Check relay authentication
  24. if ((user == null) && (obj.req.query != null) && (obj.req.query.rauth != null)) {
  25. const rcookie = parent.parent.decodeCookie(obj.req.query.rauth, parent.parent.loginCookieEncryptionKey, 240); // Cookie with 4 hour timeout
  26. if (rcookie.ruserid != null) { obj.ruserid = rcookie.ruserid; }
  27. }
  28. // Relay session count (we may remove this in the future)
  29. obj.relaySessionCounted = true;
  30. parent.relaySessionCount++;
  31. // Mesh Rights
  32. const MESHRIGHT_EDITMESH = 1;
  33. const MESHRIGHT_MANAGEUSERS = 2;
  34. const MESHRIGHT_MANAGECOMPUTERS = 4;
  35. const MESHRIGHT_REMOTECONTROL = 8;
  36. const MESHRIGHT_AGENTCONSOLE = 16;
  37. const MESHRIGHT_SERVERFILES = 32;
  38. const MESHRIGHT_WAKEDEVICE = 64;
  39. const MESHRIGHT_SETNOTES = 128;
  40. const MESHRIGHT_REMOTEVIEW = 256;
  41. // Site rights
  42. const SITERIGHT_SERVERBACKUP = 1;
  43. const SITERIGHT_MANAGEUSERS = 2;
  44. const SITERIGHT_SERVERRESTORE = 4;
  45. const SITERIGHT_FILEACCESS = 8;
  46. const SITERIGHT_SERVERUPDATE = 16;
  47. const SITERIGHT_LOCKED = 32;
  48. // Clean a IPv6 address that encodes a IPv4 address
  49. function cleanRemoteAddr(addr) { if (addr.startsWith('::ffff:')) { return addr.substring(7); } else { return addr; } }
  50. // Disconnect
  51. obj.close = function (arg) {
  52. if (obj.ws != null) {
  53. if ((arg == 1) || (arg == null)) { try { obj.ws.close(); parent.parent.debug('relay', 'FileRelay: Soft disconnect (' + obj.req.clientIp + ')'); } catch (ex) { console.log(e); } } // Soft close, close the websocket
  54. if (arg == 2) { try { obj.ws._socket._parent.end(); parent.parent.debug('relay', 'FileRelay: Hard disconnect (' + obj.req.clientIp + ')'); } catch (ex) { console.log(e); } } // Hard close, close the TCP socket
  55. } else if (obj.res != null) {
  56. try { res.sendStatus(404); } catch (ex) { }
  57. }
  58. // Aggressive cleanup
  59. delete obj.ws;
  60. delete obj.res;
  61. delete obj.peer;
  62. };
  63. // If there is no authentication, drop this connection
  64. if ((obj.id == null) || ((obj.user == null) && (obj.ruserid == null))) { try { obj.close(); parent.parent.debug('relay', 'FileRelay: Connection with no authentication (' + obj.req.clientIp + ')'); } catch (e) { console.log(e); } return; }
  65. obj.sendAgentMessage = function (command, user, domainid) {
  66. var rights, mesh;
  67. if (command.nodeid == null) return false;
  68. var splitnodeid = command.nodeid.split('/');
  69. // Check that we are in the same domain and the user has rights over this node.
  70. if ((splitnodeid[0] == 'node') && (splitnodeid[1] == domainid)) {
  71. // Get the user object
  72. // See if the node is connected
  73. var agent = parent.wsagents[command.nodeid];
  74. if (agent != null) {
  75. // Check if we have permission to send a message to that node
  76. rights = parent.GetNodeRights(user, agent.dbMeshKey, agent.dbNodeKey);
  77. mesh = parent.meshes[agent.dbMeshKey];
  78. if ((rights != null) && (mesh != null) || ((rights & MESHRIGHT_REMOTECONTROL) != 0)) { // 8 is device remote control
  79. command.rights = rights; // Add user rights flags to the message
  80. if (typeof command.consent == 'number') { command.consent = command.consent | mesh.consent; } else { command.consent = mesh.consent; } // Add user consent
  81. if (typeof domain.userconsentflags == 'number') { command.consent |= domain.userconsentflags; } // Add server required consent flags
  82. command.username = user.name; // Add user name
  83. command.realname = user.realname; // Add real name
  84. if (typeof domain.desktopprivacybartext == 'string') { command.privacybartext = domain.desktopprivacybartext; } // Privacy bar text
  85. delete command.nodeid; // Remove the nodeid since it's implyed.
  86. agent.send(JSON.stringify(command));
  87. return true;
  88. }
  89. } else {
  90. // Check if a peer server is connected to this agent
  91. var routing = parent.parent.GetRoutingServerIdNotSelf(command.nodeid, 1); // 1 = MeshAgent routing type
  92. if (routing != null) {
  93. // Check if we have permission to send a message to that node
  94. rights = parent.GetNodeRights(user, routing.meshid, command.nodeid);
  95. mesh = parent.meshes[routing.meshid];
  96. if (rights != null || ((rights & MESHRIGHT_REMOTECONTROL) != 0)) { // 8 is device remote control
  97. command.rights = rights; // Add user rights flags to the message
  98. if (typeof command.consent == 'number') { command.consent = command.consent | mesh.consent; } else { command.consent = mesh.consent; } // Add user consent
  99. if (typeof domain.userconsentflags == 'number') { command.consent |= domain.userconsentflags; } // Add server required consent flags
  100. command.username = user.name; // Add user name
  101. command.realname = user.realname; // Add real name
  102. if (typeof domain.desktopprivacybartext == 'string') { command.privacybartext = domain.desktopprivacybartext; } // Privacy bar text
  103. parent.parent.multiServer.DispatchMessageSingleServer(command, routing.serverid);
  104. return true;
  105. }
  106. }
  107. }
  108. }
  109. return false;
  110. };
  111. function performRelay() {
  112. if (obj.id == null) { try { obj.close(); } catch (e) { } return; } // Attempt to connect without id, drop this.
  113. if (obj.ws != null) { obj.ws._socket.setKeepAlive(true, 240000); } // Set TCP keep alive
  114. // Check the peer connection status
  115. {
  116. var relayinfo = parent.wsrelays[obj.id];
  117. if (relayinfo) {
  118. if (relayinfo.state == 1) {
  119. // Check that at least one connection is authenticated
  120. if ((obj.authenticated != true) && (relayinfo.peer1.authenticated != true)) {
  121. if (ws) { ws.close(); }
  122. parent.parent.debug('relay', 'FileRelay without-auth: ' + obj.id + ' (' + obj.req.clientIp + ')');
  123. delete obj.id;
  124. delete obj.ws;
  125. delete obj.peer;
  126. return;
  127. }
  128. // Connect to peer
  129. obj.peer = relayinfo.peer1;
  130. obj.peer.peer = obj;
  131. relayinfo.peer2 = obj;
  132. relayinfo.state = 2;
  133. // Remove the timeout
  134. if (relayinfo.timeout) { clearTimeout(relayinfo.timeout); delete relayinfo.timeout; }
  135. var agentws = null, file = null;
  136. if (relayinfo.peer1.ws) { relayinfo.peer1.ws.res = relayinfo.peer2.res; relayinfo.peer1.ws.res = relayinfo.peer2.res; relayinfo.peer1.ws.file = relayinfo.peer2.file; agentws = relayinfo.peer1.ws; file = relayinfo.peer2.file; }
  137. if (relayinfo.peer2.ws) { relayinfo.peer2.ws.res = relayinfo.peer1.res; relayinfo.peer2.ws.res = relayinfo.peer1.res; relayinfo.peer2.ws.file = relayinfo.peer1.file; agentws = relayinfo.peer2.ws; file = relayinfo.peer1.file; }
  138. agentws._socket.resume(); // Release the traffic
  139. try { agentws.send('c'); } catch (ex) { } // Send connect to agent
  140. try { agentws.send(JSON.stringify({ type: 'options', file: file })); } catch (ex) { } // Send options to agent
  141. try { agentws.send('10'); } catch (ex) { } // Send file transfer protocol to agent
  142. parent.parent.debug('relay', 'FileRelay connected: ' + obj.id + ' (' + obj.req.clientIp + ' --> ' + obj.peer.req.clientIp + ')');
  143. // Log the connection
  144. if (obj.user != null) {
  145. var event = { etype: 'relay', action: 'relaylog', domain: domain.id, userid: obj.user._id, username: obj.user.name, msg: "Started file transfer session" + ' \"' + obj.id + '\" from ' + obj.peer.req.clientIp + ' to ' + req.clientIp, protocol: req.query.p, nodeid: req.query.nodeid };
  146. parent.parent.DispatchEvent(['*', obj.user._id], obj, event);
  147. }
  148. } else {
  149. // Connected already, drop this connection.
  150. if (obj.ws) { obj.ws.close(); }
  151. parent.parent.debug('relay', 'FileRelay duplicate: ' + obj.id + ' (' + obj.req.clientIp + ')');
  152. delete obj.id;
  153. delete obj.ws;
  154. delete obj.peer;
  155. return;
  156. }
  157. } else {
  158. // Wait for other relay connection
  159. parent.wsrelays[obj.id] = { peer1: obj, state: 1, timeout: setTimeout(closeBothSides, 30000) };
  160. parent.parent.debug('relay', 'FileRelay holding: ' + obj.id + ' (' + obj.req.clientIp + ') ' + (obj.authenticated ? 'Authenticated' : ''));
  161. if (obj.ws != null) {
  162. // Websocket connection
  163. obj.ws._socket.pause();
  164. // Check if a peer server has this connection
  165. if (parent.parent.multiServer != null) {
  166. var rsession = parent.wsPeerRelays[obj.id];
  167. if ((rsession != null) && (rsession.serverId > parent.parent.serverId)) {
  168. // We must initiate the connection to the peer
  169. parent.parent.multiServer.createPeerRelay(ws, req, rsession.serverId, obj.req.session.userid);
  170. delete parent.wsrelays[obj.id];
  171. return;
  172. } else {
  173. // Unexpected connection, drop it
  174. if (obj.ws) { obj.ws.close(); }
  175. parent.parent.debug('relay', 'FileRelay unexpected connection: ' + obj.id + ' (' + obj.req.clientIp + ')');
  176. delete obj.id;
  177. delete obj.ws;
  178. delete obj.peer;
  179. return;
  180. }
  181. }
  182. } else {
  183. // HTTP connection, Send message to other peers that we have this connection
  184. if (parent.parent.multiServer != null) { parent.parent.multiServer.DispatchMessage(JSON.stringify({ action: 'relay', id: obj.id })); }
  185. return;
  186. }
  187. }
  188. }
  189. // Websocket handling
  190. if (obj.ws != null) {
  191. // When data is received from the mesh relay web socket
  192. obj.ws.on('message', function (data) {
  193. if (this.res == null) { return; } // File download websocket does not have an HTTP peer, should not happen.
  194. if (typeof data == 'string') {
  195. var cmd = null;
  196. try { cmd = JSON.parse(data); } catch (ex) { }
  197. if ((cmd == null) || (typeof cmd.op == 'string')) {
  198. if (cmd.op == 'ok') {
  199. setContentDispositionHeader(this.res, 'application/octet-stream', this.file, cmd.size, 'file.bin');
  200. } else {
  201. try { this.res.sendStatus(401); } catch (ex) { }
  202. }
  203. }
  204. } else {
  205. var unpause = function unpauseFunc(err) { try { unpauseFunc.s.resume(); } catch (ex) { } }
  206. unpause.s = this._socket;
  207. this._socket.pause();
  208. try { this.res.write(data, unpause); } catch (ex) { }
  209. }
  210. });
  211. // If error, close both sides of the relay.
  212. obj.ws.on('error', function (err) {
  213. parent.relaySessionErrorCount++;
  214. //console.log('FileRelay error from ' + obj.req.clientIp + ', ' + err.toString().split('\r')[0] + '.');
  215. closeBothSides();
  216. });
  217. // If the relay web socket is closed, close both sides.
  218. obj.ws.on('close', function (req) { closeBothSides(); });
  219. }
  220. }
  221. // Close both our side and the peer side.
  222. function closeBothSides() {
  223. if (obj.relaySessionCounted) { parent.relaySessionCount--; delete obj.relaySessionCounted; }
  224. if (obj.id != null) {
  225. var relayinfo = parent.wsrelays[obj.id];
  226. if (relayinfo != null) {
  227. if (relayinfo.state == 2) {
  228. var peer = (relayinfo.peer1 == obj) ? relayinfo.peer2 : relayinfo.peer1;
  229. // Disconnect the peer
  230. try { if (peer.relaySessionCounted) { parent.relaySessionCount--; delete peer.relaySessionCounted; } } catch (ex) { console.log(ex); }
  231. parent.parent.debug('relay', 'FileRelay disconnect: ' + obj.id + ' (' + obj.req.clientIp + ' --> ' + peer.req.clientIp + ')');
  232. if (peer.ws) { try { peer.ws.close(); } catch (e) { } try { peer.ws._socket._parent.end(); } catch (e) { } }
  233. if (peer.res) { try { peer.res.end(); } catch (ex) { } }
  234. // Aggressive peer cleanup
  235. delete peer.id;
  236. delete peer.ws;
  237. delete peer.res;
  238. delete peer.peer;
  239. } else {
  240. parent.parent.debug('relay', 'FileRelay disconnect: ' + obj.id + ' (' + obj.req.clientIp + ')');
  241. }
  242. if (obj.ws) { try { obj.ws.close(); } catch (ex) { } }
  243. if (obj.res) { try { obj.res.end(); } catch (ex) { } }
  244. delete parent.wsrelays[obj.id];
  245. }
  246. }
  247. // Aggressive cleanup
  248. delete obj.id;
  249. delete obj.ws;
  250. delete obj.res;
  251. delete obj.peer;
  252. }
  253. // Mark this relay session as authenticated if this is the user end.
  254. obj.authenticated = (user != null);
  255. if (obj.authenticated) {
  256. // Send connection request to agent
  257. const rcookie = parent.parent.encodeCookie({ ruserid: user._id }, parent.parent.loginCookieEncryptionKey);
  258. const command = { nodeid: nodeid, action: 'msg', type: 'tunnel', userid: user._id, value: '*/devicefile.ashx?id=' + obj.id + '&rauth=' + rcookie, soptions: {} };
  259. parent.parent.debug('relay', 'FileRelay: Sending agent tunnel command: ' + JSON.stringify(command));
  260. if (obj.sendAgentMessage(command, user, domain.id) == false) { delete obj.id; parent.parent.debug('relay', 'FileRelay: Unable to contact this agent (' + obj.req.clientIp + ')'); }
  261. }
  262. // Set the content disposition header for a HTTP response.
  263. // Because the filename can't have any special characters in it, we need to be extra careful.
  264. function setContentDispositionHeader(res, type, name, size, altname) {
  265. if (name != null) { name = require('path').basename(name).split('\\').join('').split('/').join('').split(':').join('').split('*').join('').split('?').join('').split('"').join('').split('<').join('').split('>').join('').split('|').join('').split('\'').join(''); } else { name = altname; }
  266. try {
  267. var x = { 'Cache-Control': 'no-store', 'Content-Type': type, 'Content-Disposition': 'attachment; filename="' + encodeURIComponent(name) + '"' };
  268. if (typeof size == 'number') { x['Content-Length'] = size; }
  269. res.set(x);
  270. } catch (ex) {
  271. var x = { 'Cache-Control': 'no-store', 'Content-Type': type, 'Content-Disposition': 'attachment; filename="' + altname + '"' };
  272. if (typeof size == 'number') { x['Content-Length'] = size; }
  273. try { res.set(x); } catch (ex) { }
  274. }
  275. }
  276. // If this is not an authenticated session, or the session does not have routing instructions, just go ahead an connect to existing session.
  277. performRelay();
  278. return obj;
  279. };