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