Added NGNX reverse-proxy support.

Ylian Saint-Hilaire committed Nov 1, 2018 at 15:01 UTC 1491431a526dda07c96e0aaa5c4bb756bb65ef5e
5 files changed +39 -42
certoperations.js
+4 -4
@@ -39,7 +39,7 @@ module.exports.CertificateOperations = function () {
39 } else { func(url, null, tag); }
40 };
41
42 - // Return the SHA386 hash of the certificate public key
42 + // Return the SHA384 hash of the certificate public key
43 obj.getPublicKeyHash = function (cert) {
44 var publickey = obj.pki.certificateFromPem(cert).publicKey;
45 return obj.pki.getPublicKeyFingerprint(publickey, { encoding: "hex", md: obj.forge.md.sha384.create() });
@@ -122,7 +122,7 @@ module.exports.CertificateOperations = function () {
122 rcount++;
123 }
124
125 - if (args.tlsoffload === true) {
125 + if (args.tlsoffload) {
126 // If the web certificate already exist, load it. Load just the certificate since we are in TLS offload situation
127 if (obj.fileExists(parent.getConfigFilePath("webserver-cert-public.crt"))) {
128 r.web = { cert: obj.fs.readFileSync(parent.getConfigFilePath("webserver-cert-public.crt"), "utf8") };
@@ -204,7 +204,7 @@ module.exports.CertificateOperations = function () {
204 for (i in config.domains) {
205 if ((i != "") && (config.domains[i] != null) && (config.domains[i].dns != null)) {
206 dnsname = config.domains[i].dns;
207 - if (args.tlsoffload === true) {
207 + if (args.tlsoffload) {
208 // If the web certificate already exist, load it. Load just the certificate since we are in TLS offload situation
209 if (obj.fileExists(parent.getConfigFilePath("webserver-" + i + "-cert-public.crt"))) {
210 r.dns[i] = { cert: obj.fs.readFileSync(parent.getConfigFilePath("webserver-" + i + "-cert-public.crt"), "utf8") };
@@ -370,7 +370,7 @@ module.exports.CertificateOperations = function () {
370 for (i in config.domains) {
371 if ((i != "") && (config.domains[i] != null) && (config.domains[i].dns != null)) {
372 dnsname = config.domains[i].dns;
373 - if (args.tlsoffload != true) {
373 + if (!args.tlsoffload) {
374 // If the web certificate does not exist, create it
375 if ((obj.fileExists(parent.getConfigFilePath("webserver-" + i + "-cert-public.crt")) === false) || (obj.fileExists(parent.getConfigFilePath("webserver-" + i + "-cert-private.key")) === false)) {
376 console.log("Generating HTTPS certificate for " + i + "...");
meshagent.js
+16 -16
@@ -38,10 +38,10 @@ module.exports.CreateMeshAgent = function (parent, db, ws, req, args, domain) {
38 obj.agentInfo = null;
39 obj.agentUpdate = null;
40 const agentUpdateBlockSize = 65520;
41 - obj.remoteaddr = obj.ws._socket.remoteAddress;
42 - obj.useSHA386 = false;
43 - obj.agentConnectCount = ++AgentConnectCount;
41 + obj.remoteaddr = req.ip;
42 if (obj.remoteaddr.startsWith('::ffff:')) { obj.remoteaddr = obj.remoteaddr.substring(7); }
43 + obj.remoteaddrport = obj.remoteaddr + ':' + obj.ws._socket.remotePort;
44 + obj.agentConnectCount = ++AgentConnectCount;
45 ws._socket.setKeepAlive(true, 240000); // Set TCP keep alive, 4 minutes
46
47 // Send a message to the mesh agent
@@ -49,8 +49,8 @@ module.exports.CreateMeshAgent = function (parent, db, ws, req, args, domain) {
49
50 // Disconnect this agent
51 obj.close = function (arg) {
52 - if ((arg == 1) || (arg == null)) { try { obj.ws.close(); if (obj.nodeid != null) { obj.parent.parent.debug(1, 'Soft disconnect ' + obj.nodeid + ' (' + obj.remoteaddr + ')'); } } catch (e) { console.log(e); } } // Soft close, close the websocket
53 - if (arg == 2) { try { obj.ws._socket._parent.end(); if (obj.nodeid != null) { obj.parent.parent.debug(1, 'Hard disconnect ' + obj.nodeid + ' (' + obj.remoteaddr + ')'); } } catch (e) { console.log(e); } } // Hard close, close the TCP socket
52 + if ((arg == 1) || (arg == null)) { try { obj.ws.close(); if (obj.nodeid != null) { obj.parent.parent.debug(1, 'Soft disconnect ' + obj.nodeid + ' (' + obj.remoteaddrport + ')'); } } catch (e) { console.log(e); } } // Soft close, close the websocket
53 + if (arg == 2) { try { obj.ws._socket._parent.end(); if (obj.nodeid != null) { obj.parent.parent.debug(1, 'Hard disconnect ' + obj.nodeid + ' (' + obj.remoteaddrport + ')'); } } catch (e) { console.log(e); } } // Hard close, close the TCP socket
54 if (arg == 3) { obj.authenticated = -1; } // Don't communicate with this agent anymore, but don't disconnect (Duplicate agent).
55 if (obj.parent.wsagents[obj.dbNodeKey] == obj) {
56 delete obj.parent.wsagents[obj.dbNodeKey];
@@ -197,8 +197,8 @@ module.exports.CreateMeshAgent = function (parent, db, ws, req, args, domain) {
197 if ((msg.length != 98) || ((obj.receivedCommands & 1) != 0)) return;
198 obj.receivedCommands += 1; // Agent can't send the same command twice on the same connection ever. Block DOS attack path.
199
200 - // Check that the server hash matches our own web certificate hash (SHA386)
201 - if (getWebCertHash(obj.domain) != msg.substring(2, 50)) { console.log('Agent connected with bad web certificate hash (' + (new Buffer(getWebCertHash(obj.domain), 'binary').toString('hex').substring(0, 10)) + ' != ' + (new Buffer(msg.substring(2, 50), 'binary').toString('hex').substring(0, 10)) + '), holding connection (' + obj.remoteaddr + ').'); return; }
200 + // Check that the server hash matches our own web certificate hash (SHA384)
201 + if (getWebCertHash(obj.domain) != msg.substring(2, 50)) { console.log('Agent connected with bad web certificate hash (' + (new Buffer(getWebCertHash(obj.domain), 'binary').toString('hex').substring(0, 10)) + ' != ' + (new Buffer(msg.substring(2, 50), 'binary').toString('hex').substring(0, 10)) + '), holding connection (' + obj.remoteaddrport + ').'); return; }
202
203 // Use our server private key to sign the ServerHash + AgentNonce + ServerNonce
204 obj.agentnonce = msg.substring(50, 98);
@@ -223,7 +223,7 @@ module.exports.CreateMeshAgent = function (parent, db, ws, req, args, domain) {
223
224 // Check the agent signature if we can
225 if (obj.unauthsign != null) {
226 - if (processAgentSignature(obj.unauthsign) == false) { console.log('Agent connected with bad signature, holding connection (' + obj.remoteaddr + ').'); return; } else { completeAgentConnection(); }
226 + if (processAgentSignature(obj.unauthsign) == false) { console.log('Agent connected with bad signature, holding connection (' + obj.remoteaddrport + ').'); return; } else { completeAgentConnection(); }
227 }
228 }
229 else if (cmd == 2) {
@@ -238,7 +238,7 @@ module.exports.CreateMeshAgent = function (parent, db, ws, req, args, domain) {
238 obj.unauth.nodeCertPem = '-----BEGIN CERTIFICATE-----\r\n' + new Buffer(msg.substring(4, 4 + certlen), 'binary').toString('base64') + '\r\n-----END CERTIFICATE-----';
239
240 // Check the agent signature if we can
241 - if (obj.agentnonce == null) { obj.unauthsign = msg.substring(4 + certlen); } else { if (processAgentSignature(msg.substring(4 + certlen)) == false) { console.log('Agent connected with bad signature, holding connection (' + obj.remoteaddr + ').'); return; } }
241 + if (obj.agentnonce == null) { obj.unauthsign = msg.substring(4 + certlen); } else { if (processAgentSignature(msg.substring(4 + certlen)) == false) { console.log('Agent connected with bad signature, holding connection (' + obj.remoteaddrport + ').'); return; } }
242 completeAgentConnection();
243 }
244 else if (cmd == 3) {
@@ -279,8 +279,8 @@ module.exports.CreateMeshAgent = function (parent, db, ws, req, args, domain) {
279 ws.on('error', function (err) { console.log('AGENT WSERR: ' + err); });
280
281 // If the mesh agent web socket is closed, clean up.
282 - ws.on('close', function (req) { if (obj.nodeid != null) { obj.parent.parent.debug(1, 'Agent disconnect ' + obj.nodeid + ' (' + obj.remoteaddr + ')'); } obj.close(0); });
283 - // obj.ws._socket._parent.on('close', function (req) { if (obj.nodeid != null) { obj.parent.parent.debug(1, 'Agent TCP disconnect ' + obj.nodeid + ' (' + obj.remoteaddr + ')'); } });
282 + ws.on('close', function (req) { if (obj.nodeid != null) { obj.parent.parent.debug(1, 'Agent disconnect ' + obj.nodeid + ' (' + obj.remoteaddrport + ')'); } obj.close(0); });
283 + // obj.ws._socket._parent.on('close', function (req) { if (obj.nodeid != null) { obj.parent.parent.debug(1, 'Agent TCP disconnect ' + obj.nodeid + ' (' + obj.remoteaddrport + ')'); } });
284
285 // Start authenticate the mesh agent by sending a auth nonce & server TLS cert hash.
286 // Send 384 bits SHA384 hash of TLS cert public key + 384 bits nonce
@@ -294,8 +294,8 @@ module.exports.CreateMeshAgent = function (parent, db, ws, req, args, domain) {
294
295 // Check that the mesh exists
296 var mesh = obj.parent.meshes[obj.dbMeshKey];
297 - if (mesh == null) { console.log('Agent connected with invalid domain/mesh, holding connection (' + obj.remoteaddr + ', ' + obj.dbMeshKey + ').'); return; } // If we disconnect, the agnet will just reconnect. We need to log this or tell agent to connect in a few hours.
298 - if (mesh.mtype != 2) { console.log('Agent connected with invalid mesh type, holding connection (' + obj.remoteaddr + ').'); return; } // If we disconnect, the agnet will just reconnect. We need to log this or tell agent to connect in a few hours.
297 + if (mesh == null) { console.log('Agent connected with invalid domain/mesh, holding connection (' + obj.remoteaddrport + ', ' + obj.dbMeshKey + ').'); return; } // If we disconnect, the agnet will just reconnect. We need to log this or tell agent to connect in a few hours.
298 + if (mesh.mtype != 2) { console.log('Agent connected with invalid mesh type, holding connection (' + obj.remoteaddrport + ').'); return; } // If we disconnect, the agnet will just reconnect. We need to log this or tell agent to connect in a few hours.
299
300 // Check that the node exists
301 obj.db.Get(obj.dbNodeKey, function (err, nodes) {
@@ -349,7 +349,7 @@ module.exports.CreateMeshAgent = function (parent, db, ws, req, args, domain) {
349 obj.parent.wsagents[obj.dbNodeKey] = obj;
350 if (dupAgent) {
351 // Close the duplicate agent
352 - if (obj.nodeid != null) { obj.parent.parent.debug(1, 'Duplicate agent ' + obj.nodeid + ' (' + obj.remoteaddr + ':' + obj.ws._socket.remotePort + ')'); }
352 + if (obj.nodeid != null) { obj.parent.parent.debug(1, 'Duplicate agent ' + obj.nodeid + ' (' + obj.remoteaddrport + ')'); }
353 dupAgent.close(3);
354 } else {
355 // Indicate the agent is connected
@@ -432,7 +432,7 @@ module.exports.CreateMeshAgent = function (parent, db, ws, req, args, domain) {
432 delete obj.agentnonce;
433 delete obj.unauth;
434 if (obj.unauthsign) delete obj.unauthsign;
435 - obj.parent.parent.debug(1, 'Verified agent connection to ' + obj.nodeid + ' (' + obj.remoteaddr + ':' + obj.ws._socket.remotePort + ').');
435 + obj.parent.parent.debug(1, 'Verified agent connection to ' + obj.nodeid + ' (' + obj.remoteaddrport + ').');
436 obj.authenticated = 1;
437 return true;
438 }
@@ -442,7 +442,7 @@ module.exports.CreateMeshAgent = function (parent, db, ws, req, args, domain) {
442 var i;
443 var str = msg.toString('utf8'), command = null;
444 if (str[0] == '{') {
445 - try { command = JSON.parse(str); } catch (ex) { console.log('Unable to parse agent JSON (' + obj.remoteaddr + '): ' + str, ex); return; } // If the command can't be parsed, ignore it.
445 + try { command = JSON.parse(str); } catch (ex) { console.log('Unable to parse agent JSON (' + obj.remoteaddrport + '): ' + str, ex); return; } // If the command can't be parsed, ignore it.
446 if (typeof command != 'object') { return; }
447 switch (command.action) {
448 case 'msg':
meshcentral.js
+2
@@ -416,9 +416,11 @@ function CreateMeshCentralServer(config, args) {
416 var forgeCert = obj.certificateOperations.forge.pki.certificateFromAsn1(obj.certificateOperations.forge.asn1.fromDer(cert.raw.toString('binary')));
417 var hash = obj.certificateOperations.forge.pki.getPublicKeyFingerprint(forgeCert.publicKey, { md: obj.certificateOperations.forge.md.sha384.create(), encoding: 'hex' });
418 xdomain.certhash = hash;
419 + console.log('Loaded RSA web certificate at ' + url + ', SHA384: ' + xdomain.certhash + '.');
420 } catch (ex) {
421 // This may be a ECDSA certificate, hash the entire cert
422 xdomain.certhash = obj.crypto.createHash('sha384').update(cert.raw).digest('hex');
423 + console.log('Loaded non-RSA web certificate at ' + url + ', SHA384: ' + xdomain.certhash + '.');
424 }
425 } else {
426 console.log('Failed to load web certificate at: ' + url);
package.json
+1 -1
@@ -1,6 +1,6 @@
1 {
2 "name": "meshcentral",
3 - "version": "0.2.2-o",
3 + "version": "0.2.2-p",
4 "keywords": [
5 "Remote Management",
6 "Intel AMT",
webserver.js
+16 -21
@@ -178,23 +178,16 @@ module.exports.CreateWebServer = function (parent, db, args, certificates) {
178 // Setup middleware
179 obj.app.engine('handlebars', obj.exphbs({})); // defaultLayout: 'main'
180 obj.app.set('view engine', 'handlebars');
181 + if (obj.args.tlsoffload) { obj.app.set('trust proxy', obj.args.tlsoffload); } // Reverse proxy should add the "X-Forwarded-*" headers
182 obj.app.use(obj.bodyParser.urlencoded({ extended: false }));
182 - if (obj.args.sessiontime != null) {
183 - obj.app.use(obj.session({
184 - name: 'xid', // Recommanded security practice to not use the default cookie name
185 - httpOnly: true,
186 - keys: [obj.args.sessionkey], // If multiple instances of this server are behind a load-balancer, this secret must be the same for all instances
187 - secure: (obj.args.notls != true), // Use this cookie only over TLS
188 - maxAge: (obj.args.sessiontime * 60 * 1000) // Number of minutes
189 - }));
190 - } else {
191 - obj.app.use(obj.session({
192 - name: 'xid', // Recommanded security practice to not use the default cookie name
193 - httpOnly: true,
194 - keys: [obj.args.sessionkey], // If multiple instances of this server are behind a load-balancer, this secret must be the same for all instances
195 - secure: (obj.args.notls != true) // Use this cookie only over TLS
196 - }));
183 + var sessionOptions = {
184 + name: 'xid', // Recommanded security practice to not use the default cookie name
185 + httpOnly: true,
186 + keys: [obj.args.sessionkey], // If multiple instances of this server are behind a load-balancer, this secret must be the same for all instances
187 + secure: (obj.args.notls != true) // Use this cookie only over TLS (Check this: https://expressjs.com/en/guide/behind-proxies.html)
188 }
189 + if (obj.args.sessiontime != null) { sessionOptions.maxAge = (obj.args.sessiontime * 60 * 1000); }
190 + obj.app.use(obj.session(sessionOptions));
191
192 // Session-persisted message middleware
193 obj.app.use(function (req, res, next) {
@@ -283,9 +276,9 @@ module.exports.CreateWebServer = function (parent, db, args, certificates) {
276 function checkUserIpAddressEx(req, res, allowedIpList) {
277 if (allowedIpList == null) { return true; }
278 try {
286 - var ip = null, type = 0;
287 - if (req.connection) { ip = req.connection.remoteAddress; type = 1; } // HTTP(S) request
288 - else if (req._socket) { ip = req._socket.remoteAddress; type = 2; } // WebSocket request
279 + var ip = req.ip, type = 0;
280 + if (req.connection) { type = 1; } // HTTP(S) request
281 + else if (req._socket) { type = 2; } // WebSocket request
282 if (ip.startsWith('::ffff:')) { ip = ip.substring(7); } // Fix IPv4 IP's encoded in IPv6 form
283 if ((ip != null) && (allowedIpList.indexOf(ip) >= 0)) { return true; }
284 if (type == 1) { res.sendStatus(401); }
@@ -343,7 +336,6 @@ module.exports.CreateWebServer = function (parent, db, args, certificates) {
336 user.login = Date.now();
337 obj.db.SetUser(user);
338
346 -
339 // Regenerate session when signing in to prevent fixation
340 //req.session.regenerate(function () {
341 // Store the user's primary key in the session store to be retrieved, or in this case the entire user object
@@ -369,6 +361,7 @@ module.exports.CreateWebServer = function (parent, db, args, certificates) {
361 res.redirect(domain.url);
362 });
363 */
364 + res.redirect(domain.url); // Temporary
365 } else {
366 res.redirect(domain.url);
367 }
@@ -743,7 +736,7 @@ module.exports.CreateWebServer = function (parent, db, args, certificates) {
736 if (obj.args.lanonly == true) { features += 2; } // LAN-only mode
737 if (obj.args.nousers == true) { features += 4; } // Single user mode
738 if (domain.userQuota == -1) { features += 8; } // No server files mode
746 - if (obj.args.tlsoffload == true) { features += 16; } // No mutual-auth CIRA
739 + if (obj.args.tlsoffload) { features += 16; } // No mutual-auth CIRA
740 if ((parent.config != null) && (parent.config.settings != null) && (parent.config.settings.allowframing == true)) { features += 32; } // Allow site within iframe
741 if ((obj.parent.mailserver != null) && (obj.parent.certificates.CommonName != null) && (obj.parent.certificates.CommonName != 'un-configured') && (obj.args.lanonly != true)) { features += 64; } // Email invites
742 if (obj.args.webrtc == true) { features += 128; } // Enable WebRTC (Default false for now)
@@ -1405,7 +1398,7 @@ module.exports.CreateWebServer = function (parent, db, args, certificates) {
1398 if (auth.response === obj.common.ComputeDigesthash(auth.username, amtpass, auth.realm, "POST", auth.uri, auth.qop, auth.nonce, auth.nc, auth.cnonce)) {
1399
1400 // This is an authenticated Intel AMT event, update the host address
1408 - var amthost = req.connection.remoteAddress;
1401 + var amthost = req.ip;
1402 if (amthost.substring(0, 7) === '::ffff:') { amthost = amthost.substring(7); }
1403 if (node.host != amthost) {
1404 // Get the mesh for this device
@@ -1773,6 +1766,7 @@ module.exports.CreateWebServer = function (parent, db, args, certificates) {
1766 // Two more headers to take a look at:
1767 // 'Public-Key-Pins': 'pin-sha256="X3pGTSOuJeEVw989IJ/cEtXUEmy52zs1TZQrU06KUKg="; max-age=10'
1768 // 'strict-transport-security': 'max-age=31536000; includeSubDomains'
1769 + /*
1770 var headers = null;
1771 if (obj.args.notls) {
1772 // Default headers if no TLS is used
@@ -1783,6 +1777,7 @@ module.exports.CreateWebServer = function (parent, db, args, certificates) {
1777 }
1778 if (parent.config.settings.accesscontrolalloworigin != null) { headers['Access-Control-Allow-Origin'] = parent.config.settings.accesscontrolalloworigin; }
1779 res.set(headers);
1780 + */
1781 return next();
1782 }
1783 });