Made improvements to server traffic relay.

Ylian Saint-Hilaire committed Apr 28, 2019 at 20:31 UTC 1527e28df885966c64be116931c598ea200cc9a3
3 files changed +82 -52
meshrelay.js
+66 -50
@@ -16,16 +16,11 @@
16 module.exports.CreateMeshRelay = function (parent, ws, req, domain, user, cookie) {
17 var obj = {};
18 obj.ws = ws;
19 - obj.req = req;
20 - obj.peer = null;
21 - obj.user = user;
22 - obj.cookie = cookie;
23 - obj.parent = parent;
19 obj.id = req.query.id;
25 - obj.remoteaddr = obj.ws._socket.remoteAddress;
26 - obj.domain = domain;
27 - if (obj.remoteaddr.startsWith('::ffff:')) { obj.remoteaddr = obj.remoteaddr.substring(7); }
28 - obj.parent.relaySessionCount++;
20 +
21 + // Relay session count (we may remove this in the future)
22 + obj.relaySessionCounted = true;
23 + parent.relaySessionCount++;
24
25 // Mesh Rights
26 const MESHRIGHT_EDITMESH = 1;
@@ -46,23 +41,31 @@ module.exports.CreateMeshRelay = function (parent, ws, req, domain, user, cookie
41 const SITERIGHT_SERVERUPDATE = 16;
42 const SITERIGHT_LOCKED = 32;
43
44 + // Clean a IPv6 address that encodes a IPv4 address
45 + function cleanRemoteAddr(addr) { if (addr.startsWith('::ffff:')) { return addr.substring(7); } else { return addr; } }
46 +
47 // Disconnect this agent
48 obj.close = function (arg) {
51 - if ((arg == 1) || (arg == null)) { try { obj.ws.close(); obj.parent.parent.debug(1, 'Relay: Soft disconnect (' + obj.remoteaddr + ')'); } catch (e) { console.log(e); } } // Soft close, close the websocket
52 - if (arg == 2) { try { obj.ws._socket._parent.end(); obj.parent.parent.debug(1, 'Relay: Hard disconnect (' + obj.remoteaddr + ')'); } catch (e) { console.log(e); } } // Hard close, close the TCP socket
49 + if ((arg == 1) || (arg == null)) { try { ws.close(); parent.parent.debug(1, 'Relay: Soft disconnect (' + cleanRemoteAddr(ws._socket.remoteAddress) + ')'); } catch (e) { console.log(e); } } // Soft close, close the websocket
50 + if (arg == 2) { try { ws._socket._parent.end(); parent.parent.debug(1, 'Relay: Hard disconnect (' + cleanRemoteAddr(ws._socket.remoteAddress) + ')'); } catch (e) { console.log(e); } } // Hard close, close the TCP socket
51 +
52 + // Aggressive cleanup
53 + delete obj.id;
54 + delete obj.ws;
55 + delete obj.peer;
56 };
57
58 obj.sendAgentMessage = function (command, userid, domainid) {
59 var rights, mesh;
60 if (command.nodeid == null) return false;
58 - var user = obj.parent.users[userid];
61 + var user = parent.users[userid];
62 if (user == null) return false;
63 var splitnodeid = command.nodeid.split('/');
64 // Check that we are in the same domain and the user has rights over this node.
65 if ((splitnodeid[0] == 'node') && (splitnodeid[1] == domainid)) {
66 // Get the user object
67 // See if the node is connected
65 - var agent = obj.parent.wsagents[command.nodeid];
68 + var agent = parent.wsagents[command.nodeid];
69 if (agent != null) {
70 // Check if we have permission to send a message to that node
71 rights = user.links[agent.dbMeshKey];
@@ -79,7 +82,7 @@ module.exports.CreateMeshRelay = function (parent, ws, req, domain, user, cookie
82 }
83 } else {
84 // Check if a peer server is connected to this agent
82 - var routing = obj.parent.parent.GetRoutingServerId(command.nodeid, 1); // 1 = MeshAgent routing type
85 + var routing = parent.parent.GetRoutingServerId(command.nodeid, 1); // 1 = MeshAgent routing type
86 if (routing != null) {
87 // Check if we have permission to send a message to that node
88 rights = user.links[routing.meshid];
@@ -90,7 +93,7 @@ module.exports.CreateMeshRelay = function (parent, ws, req, domain, user, cookie
93 command.consent = mesh.consent; // Add user consent
94 if (typeof domain.userconsentflags == 'number') { command.consent |= domain.userconsentflags; } // Add server required consent flags
95 command.username = user.name; // Add user name
93 - obj.parent.parent.multiServer.DispatchMessageSingleServer(command, routing.serverid);
96 + parent.parent.multiServer.DispatchMessageSingleServer(command, routing.serverid);
97 return true;
98 }
99 }
@@ -105,12 +108,12 @@ module.exports.CreateMeshRelay = function (parent, ws, req, domain, user, cookie
108
109 // If this is a MeshMessenger session, the ID is the two userid's and authentication must match one of them.
110 if (obj.id.startsWith('meshmessenger/')) {
108 - if ((obj.id.startsWith('meshmessenger/user/') == true) && (obj.user == null)) { try { obj.close(); } catch (e) { } return null; } // If user-to-user, both sides need to be authenticated.
111 + 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.
112 var x = obj.id.split('/'), user1 = x[1] + '/' + x[2] + '/' + x[3], user2 = x[4] + '/' + x[5] + '/' + x[6];
113 if ((x[1] != 'user') && (x[4] != 'user')) { try { obj.close(); } catch (e) { } return null; } // MeshMessenger session must have at least one authenticated user
114 if ((x[1] == 'user') && (x[4] == 'user')) {
115 // If this is a user-to-user session, you must be authenticated to join.
113 - if ((obj.user._id != user1) && (obj.user._id != user2)) { try { obj.close(); } catch (e) { } return null; }
116 + if ((user._id != user1) && (user._id != user2)) { try { obj.close(); } catch (e) { } return null; }
117 } else {
118 // If only one side of the session is a user
119 // !!!!! TODO: Need to make sure that one of the two sides is the correct user. !!!!!
@@ -123,9 +126,9 @@ module.exports.CreateMeshRelay = function (parent, ws, req, domain, user, cookie
126 if (!parent.args.notls) {
127 // Check the identifier, if running without TLS, skip this.
128 var ids = obj.id.split(':');
126 - if (ids.length != 3) { obj.ws.close(); obj.id = null; return null; } // Invalid ID, drop this.
127 - if (parent.crypto.createHmac('SHA384', parent.relayRandom).update(ids[0] + ':' + ids[1]).digest('hex') != ids[2]) { obj.ws.close(); obj.id = null; return null; } // Invalid HMAC, drop this.
128 - if ((Date.now() - parseInt(ids[1])) > 120000) { obj.ws.close(); obj.id = null; return null; } // Expired time, drop this.
129 + if (ids.length != 3) { ws.close(); delete obj.id; return null; } // Invalid ID, drop this.
130 + 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.
131 + if ((Date.now() - parseInt(ids[1])) > 120000) { ws.close(); delete obj.id; return null; } // Expired time, drop this.
132 obj.id = ids[0];
133 }
134 */
@@ -137,9 +140,11 @@ module.exports.CreateMeshRelay = function (parent, ws, req, domain, user, cookie
140 if (relayinfo.state == 1) {
141 // Check that at least one connection is authenticated
142 if ((obj.authenticated != true) && (relayinfo.peer1.authenticated != true)) {
140 - obj.id = null;
141 - obj.ws.close();
142 - obj.parent.parent.debug(1, 'Relay without-auth: ' + obj.id + ' (' + obj.remoteaddr + ')');
143 + ws.close();
144 + parent.parent.debug(1, 'Relay without-auth: ' + obj.id + ' (' + cleanRemoteAddr(ws._socket.remoteAddress) + ')');
145 + delete obj.id;
146 + delete obj.ws;
147 + delete obj.peer;
148 return null;
149 }
150
@@ -148,7 +153,7 @@ module.exports.CreateMeshRelay = function (parent, ws, req, domain, user, cookie
153 obj.peer.peer = obj;
154 relayinfo.peer2 = obj;
155 relayinfo.state = 2;
151 - obj.ws.send('c'); // Send connect to both peers
156 + ws.send('c'); // Send connect to both peers
157 relayinfo.peer1.ws.send('c');
158 relayinfo.peer1.ws._socket.resume(); // Release the traffic
159 relayinfo.peer2.ws._socket.resume(); // Release the traffic
@@ -156,24 +161,26 @@ module.exports.CreateMeshRelay = function (parent, ws, req, domain, user, cookie
161 relayinfo.peer1.ws.peer = relayinfo.peer2.ws;
162 relayinfo.peer2.ws.peer = relayinfo.peer1.ws;
163
159 - obj.parent.parent.debug(1, 'Relay connected: ' + obj.id + ' (' + obj.remoteaddr + ' --> ' + obj.peer.remoteaddr + ')');
164 + parent.parent.debug(1, 'Relay connected: ' + obj.id + ' (' + cleanRemoteAddr(ws._socket.remoteAddress) + ' --> ' + cleanRemoteAddr(obj.peer.ws._socket.remoteAddress) + ')');
165 } else {
166 // Connected already, drop (TODO: maybe we should re-connect?)
162 - obj.id = null;
163 - obj.ws.close();
164 - obj.parent.parent.debug(1, 'Relay duplicate: ' + obj.id + ' (' + obj.remoteaddr + ')');
167 + ws.close();
168 + parent.parent.debug(1, 'Relay duplicate: ' + obj.id + ' (' + cleanRemoteAddr(ws._socket.remoteAddress) + ')');
169 + delete obj.id;
170 + delete obj.ws;
171 + delete obj.peer;
172 return null;
173 }
174 } else {
175 // Wait for other relay connection
176 ws._socket.pause(); // Hold traffic until the other connection
177 parent.wsrelays[obj.id] = { peer1: obj, state: 1 };
171 - obj.parent.parent.debug(1, 'Relay holding: ' + obj.id + ' (' + obj.remoteaddr + ') ' + (obj.authenticated ? 'Authenticated' : ''));
178 + parent.parent.debug(1, 'Relay holding: ' + obj.id + ' (' + cleanRemoteAddr(ws._socket.remoteAddress) + ') ' + (obj.authenticated ? 'Authenticated' : ''));
179
180 // Check if a peer server has this connection
181 if (parent.parent.multiServer != null) {
175 - var rsession = obj.parent.wsPeerRelays[obj.id];
176 - if ((rsession != null) && (rsession.serverId > obj.parent.parent.serverId)) {
182 + var rsession = parent.wsPeerRelays[obj.id];
183 + if ((rsession != null) && (rsession.serverId > parent.parent.serverId)) {
184 // We must initiate the connection to the peer
185 parent.parent.multiServer.createPeerRelay(ws, req, rsession.serverId, req.session.userid);
186 delete parent.wsrelays[obj.id];
@@ -202,14 +209,15 @@ module.exports.CreateMeshRelay = function (parent, ws, req, domain, user, cookie
209
210 // If error, close both sides of the relay.
211 ws.on('error', function (err) {
205 - obj.parent.relaySessionErrorCount++;
206 - console.log('Relay error from ' + obj.remoteaddr + ', ' + err.toString().split('\r')[0] + '.');
212 + parent.relaySessionErrorCount++;
213 + if (obj.relaySessionCounted) { parent.relaySessionCount--; delete obj.relaySessionCounted; }
214 + console.log('Relay error from ' + cleanRemoteAddr(ws._socket.remoteAddress) + ', ' + err.toString().split('\r')[0] + '.');
215 closeBothSides();
216 });
217
218 // If the relay web socket is closed, close both sides.
219 ws.on('close', function (req) {
212 - obj.parent.relaySessionCount--;
220 + if (obj.relaySessionCounted) { parent.relaySessionCount--; delete obj.relaySessionCounted; }
221 closeBothSides();
222 });
223
@@ -221,58 +229,66 @@ module.exports.CreateMeshRelay = function (parent, ws, req, domain, user, cookie
229 if (relayinfo.state == 2) {
230 // Disconnect the peer
231 var peer = (relayinfo.peer1 == obj) ? relayinfo.peer2 : relayinfo.peer1;
224 - obj.parent.parent.debug(1, 'Relay disconnect: ' + obj.id + ' (' + obj.remoteaddr + ' --> ' + peer.remoteaddr + ')');
225 - peer.id = null;
232 + try { if (peer.relaySessionCounted) { parent.relaySessionCount--; delete peer.relaySessionCounted; } } catch (ex) { console.log(ex); }
233 + parent.parent.debug(1, 'Relay disconnect: ' + obj.id + ' (' + cleanRemoteAddr(ws._socket.remoteAddress) + ' --> ' + cleanRemoteAddr(peer.ws._socket.remoteAddress) + ')');
234 try { peer.ws.close(); } catch (e) { } // Soft disconnect
235 try { peer.ws._socket._parent.end(); } catch (e) { } // Hard disconnect
236 +
237 + // Aggressive peer cleanup
238 + delete peer.id;
239 + delete peer.ws;
240 + delete peer.peer;
241 } else {
229 - obj.parent.parent.debug(1, 'Relay disconnect: ' + obj.id + ' (' + obj.remoteaddr + ')');
242 + parent.parent.debug(1, 'Relay disconnect: ' + obj.id + ' (' + cleanRemoteAddr(ws._socket.remoteAddress) + ')');
243 }
244 delete parent.wsrelays[obj.id];
245 }
233 - obj.peer = null;
234 - obj.id = null;
246 }
247 +
248 + // Aggressive cleanup
249 + delete obj.id;
250 + delete obj.ws;
251 + delete obj.peer;
252 }
253
254 // Mark this relay session as authenticated if this is the user end.
239 - obj.authenticated = (obj.user != null);
255 + obj.authenticated = (user != null);
256 if (obj.authenticated) {
257 // Kick off the routing, if we have agent routing instructions, process them here.
258 // Routing instructions can only be given by a authenticated user
243 - if ((obj.cookie != null) && (obj.cookie.nodeid != null) && (obj.cookie.tcpport != null) && (obj.cookie.domainid != null)) {
259 + if ((cookie != null) && (cookie.nodeid != null) && (cookie.tcpport != null) && (cookie.domainid != null)) {
260 // We have routing instructions in the cookie, but first, check user access for this node.
245 - obj.parent.db.Get(obj.cookie.nodeid, function (err, docs) {
261 + parent.db.Get(cookie.nodeid, function (err, docs) {
262 if (docs.length == 0) { console.log('ERR: Node not found'); try { obj.close(); } catch (e) { } return; } // Disconnect websocket
263 var node = docs[0];
264
265 // Check if this user has permission to manage this computer
250 - var meshlinks = obj.user.links[node.meshid];
266 + var meshlinks = user.links[node.meshid];
267 if ((!meshlinks) || (!meshlinks.rights) || ((meshlinks.rights & MESHRIGHT_REMOTECONTROL) == 0)) { console.log('ERR: Access denied (2)'); try { obj.close(); } catch (e) { } return; }
268
269 // Send connection request to agent
270 if (obj.id == undefined) { obj.id = ('' + Math.random()).substring(2); } // If there is no connection id, generate one.
255 - var command = { nodeid: obj.cookie.nodeid, action: 'msg', type: 'tunnel', value: '*/meshrelay.ashx?id=' + obj.id, tcpport: obj.cookie.tcpport, tcpaddr: obj.cookie.tcpaddr };
256 - obj.parent.parent.debug(1, 'Relay: Sending agent tunnel command: ' + JSON.stringify(command));
257 - if (obj.sendAgentMessage(command, obj.user._id, obj.cookie.domainid) == false) { obj.id = null; obj.parent.parent.debug(1, 'Relay: Unable to contact this agent (' + obj.remoteaddr + ')'); }
271 + var command = { nodeid: cookie.nodeid, action: 'msg', type: 'tunnel', value: '*/meshrelay.ashx?id=' + obj.id, tcpport: cookie.tcpport, tcpaddr: cookie.tcpaddr };
272 + parent.parent.debug(1, 'Relay: Sending agent tunnel command: ' + JSON.stringify(command));
273 + if (obj.sendAgentMessage(command, user._id, cookie.domainid) == false) { delete obj.id; parent.parent.debug(1, 'Relay: Unable to contact this agent (' + cleanRemoteAddr(ws._socket.remoteAddress) + ')'); }
274 performRelay();
275 });
276 return obj;
277 } else if ((req.query.nodeid != null) && (req.query.tcpport != null)) {
278 // We have routing instructions in the URL arguments, but first, check user access for this node.
263 - obj.parent.db.Get(req.query.nodeid, function (err, docs) {
279 + parent.db.Get(req.query.nodeid, function (err, docs) {
280 if (docs.length == 0) { console.log('ERR: Node not found'); try { obj.close(); } catch (e) { } return; } // Disconnect websocket
281 var node = docs[0];
282
283 // Check if this user has permission to manage this computer
268 - var meshlinks = obj.user.links[node.meshid];
284 + var meshlinks = user.links[node.meshid];
285 if ((!meshlinks) || (!meshlinks.rights) || ((meshlinks.rights & MESHRIGHT_REMOTECONTROL) == 0)) { console.log('ERR: Access denied (2)'); try { obj.close(); } catch (e) { } return; }
286
287 // Send connection request to agent
288 if (obj.id == null) { obj.id = ('' + Math.random()).substring(2); } // If there is no connection id, generate one.
289 var command = { nodeid: req.query.nodeid, action: 'msg', type: 'tunnel', value: '*/meshrelay.ashx?id=' + obj.id, tcpport: req.query.tcpport, tcpaddr: ((req.query.tcpaddr == null) ? '127.0.0.1' : req.query.tcpaddr) };
274 - obj.parent.parent.debug(1, 'Relay: Sending agent tunnel command: ' + JSON.stringify(command));
275 - if (obj.sendAgentMessage(command, obj.user._id, obj.domain.id) == false) { obj.id = null; obj.parent.parent.debug(1, 'Relay: Unable to contact this agent (' + obj.remoteaddr + ')'); }
290 + parent.parent.debug(1, 'Relay: Sending agent tunnel command: ' + JSON.stringify(command));
291 + if (obj.sendAgentMessage(command, user._id, domain.id) == false) { delete obj.id; parent.parent.debug(1, 'Relay: Unable to contact this agent (' + cleanRemoteAddr(ws._socket.remoteAddress) + ')'); }
292 performRelay();
293 });
294 return obj;
meshuser.js
+15 -1
@@ -238,6 +238,7 @@ module.exports.CreateMeshUser = function (parent, db, ws, req, args, domain, use
238 "Connected Users": Object.keys(parent.wssessions).length,
239 "Users Sessions": Object.keys(parent.wssessions2).length,
240 "Relay Sessions": parent.relaySessionCount,
241 + "Relay Count": Object.keys(parent.wsrelays).length
242 };
243 if (parent.relaySessionErrorCount != 0) { serverStats['Relay Errors'] = parent.relaySessionErrorCount; }
244 if (parent.parent.mpsserver != null) { serverStats['Connected Intel® AMT'] = Object.keys(parent.parent.mpsserver.ciraConnections).length; }
@@ -519,7 +520,7 @@ module.exports.CreateMeshUser = function (parent, db, ws, req, args, domain, use
520 switch (cmd) {
521 case 'help': {
522 r = 'Available commands: help, info, versions, args, resetserver, showconfig, usersessions, tasklimiter, setmaxtasks, cores,\r\n'
522 - r += 'migrationagents, swarmstats, nodeconfig, heapdump.';
523 + r += 'migrationagents, swarmstats, nodeconfig, heapdump, relays.';
524 break;
525 }
526 case 'info': {
@@ -645,6 +646,16 @@ module.exports.CreateMeshUser = function (parent, db, ws, req, args, domain, use
646 }
647 break;
648 }
649 + case 'relays': {
650 + for (var i in parent.wsrelays) {
651 + r += 'id: ' + i + ', state: ' + parent.wsrelays[i].state;
652 + if (parent.wsrelays[i].peer1 != null) { r += ', peer1: ' + cleanRemoteAddr(parent.wsrelays[i].peer1.ws._socket.remoteAddress); }
653 + if (parent.wsrelays[i].peer2 != null) { r += ', peer2: ' + cleanRemoteAddr(parent.wsrelays[i].peer2.ws._socket.remoteAddress); }
654 + r += '<br />';
655 + }
656 + if (r == '') { r = 'No relays.'; }
657 + break;
658 + }
659 default: { // This is an unknown command, return an error message
660 r = 'Unknown command \"' + cmd + '\", type \"help\" for list of avaialble commands.';
661 break;
@@ -2469,5 +2480,8 @@ module.exports.CreateMeshUser = function (parent, db, ws, req, args, domain, use
2480 // Return true if at least one element of arr2 is in arr1
2481 function findOne(arr1, arr2) { if ((arr1 == null) || (arr2 == null)) return false; return arr2.some(function (v) { return arr1.indexOf(v) >= 0; }); };
2482
2483 + // Clean a IPv6 address that encodes a IPv4 address
2484 + function cleanRemoteAddr(addr) { if (addr.startsWith('::ffff:')) { return addr.substring(7); } else { return addr; } }
2485 +
2486 return obj;
2487 };
\ No newline at end of file
package.json
+1 -1
@@ -1,6 +1,6 @@
1 {
2 "name": "meshcentral",
3 - "version": "0.3.3-g",
3 + "version": "0.3.3-h",
4 "keywords": [
5 "Remote Management",
6 "Intel AMT",