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