diff --git a/certoperations.js b/certoperations.js index dcc1663d..56e27460 100644 --- a/certoperations.js +++ b/certoperations.js @@ -241,6 +241,21 @@ module.exports.CertificateOperations = function (parent) { return obj.pki.getPublicKeyFingerprint(publickey, { encoding: "hex", md: obj.forge.md.sha384.create() }); }; + // Return the SHA384 hash of the certificate, return hex + obj.getCertHashSha1 = function (cert) { + try { + var md = obj.forge.md.sha1.create(); + md.update(obj.forge.asn1.toDer(obj.pki.certificateToAsn1(obj.pki.certificateFromPem(cert))).getBytes()); + return md.digest().toHex(); + } catch (ex) { + // If this is not an RSA certificate, hash the raw PKCS7 out of the PEM file + var x1 = cert.indexOf('-----BEGIN CERTIFICATE-----'), x2 = cert.indexOf('-----END CERTIFICATE-----'); + if ((x1 >= 0) && (x2 > x1)) { + return obj.crypto.createHash('sha1').update(Buffer.from(cert.substring(x1 + 27, x2), 'base64')).digest('hex'); + } else { console.log('ERROR: Unable to decode certificate.'); return null; } + } + }; + // Return the SHA384 hash of the certificate, return hex obj.getCertHash = function (cert) { try { diff --git a/meshagent.js b/meshagent.js index 45498310..d7e58fa7 100644 --- a/meshagent.js +++ b/meshagent.js @@ -44,7 +44,6 @@ module.exports.CreateMeshAgent = function (parent, db, ws, req, args, domain) { // Disconnect this agent obj.close = function (arg) { - obj.authenticated = -1; if ((arg == 1) || (arg == null)) { try { ws.close(); if (obj.nodeid != null) { parent.parent.debug('agent', 'Soft disconnect ' + obj.nodeid + ' (' + obj.remoteaddrport + ')'); } } catch (e) { console.log(e); } } // Soft close, close the websocket if (arg == 2) { try { ws._socket._parent.end(); if (obj.nodeid != null) { parent.parent.debug('agent', 'Hard disconnect ' + obj.nodeid + ' (' + obj.remoteaddrport + ')'); } } catch (e) { console.log(e); } } // Hard close, close the TCP socket // If arg == 3, don't communicate with this agent anymore, but don't disconnect (Duplicate agent). @@ -81,9 +80,12 @@ module.exports.CreateMeshAgent = function (parent, db, ws, req, args, domain) { } } else { // Update the last connect time - if (obj.authenticated == 2) { db.Set({ _id: 'lc' + obj.dbNodeKey, type: 'lastconnect', domain: domain.id, time: obj.connectTime, addr: obj.remoteaddrport }); } + if (obj.authenticated == 2) { db.Set({ _id: 'lc' + obj.dbNodeKey, type: 'lastconnect', domain: domain.id, time: obj.connectTime, addr: obj.remoteaddrport, cause: 1 }); } } + // Set this agent as no longer authenticated + obj.authenticated = -1; + // If we where updating the agent, clean that up. if (obj.agentUpdate != null) { if (obj.agentUpdate.fd) { try { parent.fs.close(obj.agentUpdate.fd); } catch (ex) { } } @@ -682,7 +684,7 @@ module.exports.CreateMeshAgent = function (parent, db, ws, req, args, domain) { // Mark when this device connected obj.connectTime = Date.now(); - db.Set({ _id: 'lc' + obj.dbNodeKey, type: 'lastconnect', domain: domain.id, time: obj.connectTime, addr: obj.remoteaddrport }); + db.Set({ _id: 'lc' + obj.dbNodeKey, type: 'lastconnect', domain: domain.id, time: obj.connectTime, addr: obj.remoteaddrport, cause: 1 }); // Device already exists, look if changes have occured var changes = [], change = 0, log = 0; @@ -743,7 +745,7 @@ module.exports.CreateMeshAgent = function (parent, db, ws, req, args, domain) { // Mark when this device connected obj.connectTime = Date.now(); - db.Set({ _id: 'lc' + obj.dbNodeKey, type: 'lastconnect', domain: domain.id, time: obj.connectTime, addr: obj.remoteaddrport }); + db.Set({ _id: 'lc' + obj.dbNodeKey, type: 'lastconnect', domain: domain.id, time: obj.connectTime, addr: obj.remoteaddrport, cause: 1 }); // This node does not exist, create it. var device = { type: 'node', mtype: mesh.mtype, _id: obj.dbNodeKey, icon: obj.agentInfo.platformType, meshid: obj.dbMeshKey, name: obj.agentInfo.computerName, rname: obj.agentInfo.computerName, domain: domain.id, agent: { ver: obj.agentInfo.agentVersion, id: obj.agentInfo.agentId, caps: obj.agentInfo.capabilities }, host: null }; diff --git a/meshcentral.js b/meshcentral.js index 98f09b44..919ca9b0 100644 --- a/meshcentral.js +++ b/meshcentral.js @@ -826,7 +826,7 @@ function CreateMeshCentralServer(config, args) { obj.apfserver = require('./apfserver.js').CreateApfServer(obj, obj.db, obj.args); // Create MQTT Broker to hook into webserver and mpsserver - if (obj.config.settings.mqtt != null) { obj.mqttbroker = require("./mqttbroker.js").CreateMQTTBroker(obj, obj.db, obj.args); } + if ((typeof obj.config.settings.mqtt == 'object') && (typeof obj.config.settings.mqtt.auth == 'object') && (typeof obj.config.settings.mqtt.auth.keyid == 'string') && (typeof obj.config.settings.mqtt.auth.key == 'string')) { obj.mqttbroker = require("./mqttbroker.js").CreateMQTTBroker(obj, obj.db, obj.args); } // Start the web server and if needed, the redirection web server. obj.webserver = require('./webserver.js').CreateWebServer(obj, obj.db, obj.args, obj.certificates); diff --git a/meshuser.js b/meshuser.js index cdfde4bc..bbe1de43 100644 --- a/meshuser.js +++ b/meshuser.js @@ -2876,6 +2876,54 @@ module.exports.CreateMeshUser = function (parent, db, ws, req, args, domain, use } break; } + case 'getmqttlogin': { + var err = null; + if (parent.parent.mqttbroker == null) { err = 'MQTT not supported on this server'; } + if (common.validateString(command.nodeid, 1, 1024) == false) { err = 'Invalid nodeid'; } // Check the nodeid + + // Handle any errors + if (err != null) { if (command.responseid != null) { try { ws.send(JSON.stringify({ action: 'getmqttlogin', responseid: command.responseid, result: err })); } catch (ex) { } } break; } + + var nodeid = command.nodeid; + if ((nodeid.split('/').length == 3) && (nodeid.split('/')[1] == domain.id)) { // Validate the domain, operation only valid for current domain + // Get the device + db.Get(nodeid, function (err, nodes) { + if ((nodes == null) || (nodes.length != 1)) { if (command.responseid != null) { try { ws.send(JSON.stringify({ action: 'getmqttlogin', responseid: command.responseid, result: 'Invalid node id' })); } catch (ex) { } return; } } + var node = nodes[0]; + + // Get the device group for this node + var mesh = parent.meshes[node.meshid]; + if (mesh) { + // Check if this user has rights to do this + if ((mesh.links[user._id] != null) && (mesh.links[user._id].rights == 0xFFFFFFFF)) { + var token = parent.parent.mqttbroker.generateLogin(mesh._id, node._id); + var r = { action: 'getmqttlogin', responseid: command.responseid, nodeid: node._id, user: token.user, pass: token.pass }; + const serverName = parent.getWebServerName(domain); + + // Add MPS URL + if (parent.parent.mpsserver != null) { + r.mpsCertHashSha384 = parent.parent.certificateOperations.getCertHash(parent.parent.mpsserver.certificates.mps.cert); + r.mpsCertHashSha1 = parent.parent.certificateOperations.getCertHashSha1(parent.parent.mpsserver.certificates.mps.cert); + r.mpsUrl = 'mqtts://' + serverName + ':' + ((args.mpsaliasport != null) ? args.mpsaliasport : args.mpsport) + '/'; + } + + // Add WS URL + var xdomain = (domain.dns == null) ? domain.id : ''; + if (xdomain != '') xdomain += "/"; + var httpsPort = ((args.aliasport == null) ? args.port : args.aliasport); // Use HTTPS alias port is specified + r.wsUrl = "ws" + (args.notls ? '' : 's') + "://" + serverName + ":" + httpsPort + "/" + xdomain + "mqtt.ashx"; + r.wsTrustedCert = parent.isTrustedCert(domain); + + try { ws.send(JSON.stringify(r)); } catch (ex) { } + } else { + if (command.responseid != null) { try { ws.send(JSON.stringify({ action: 'getmqttlogin', responseid: command.responseid, result: 'Unable to perform this operation' })); } catch (ex) { } } + } + } + }); + } + + break; + } case 'amt': { if (common.validateString(command.nodeid, 1, 1024) == false) break; // Check nodeid if (common.validateInt(command.mode, 0, 3) == false) break; // Check connection mode diff --git a/mqttbroker.js b/mqttbroker.js index 42ea6cee..238a6a74 100644 --- a/mqttbroker.js +++ b/mqttbroker.js @@ -16,26 +16,46 @@ module.exports.CreateMQTTBroker = function (parent, db, args) { obj.handle = obj.aedes.handle; obj.connections = {}; // NodesID --> client array + // Generate a username and password for MQTT login + obj.generateLogin = function (meshid, nodeid) { + const meshidsplit = meshid.split('/'), nodeidsplit = nodeid.split('/'); + const xmeshid = meshidsplit[2], xnodeid = nodeidsplit[2], xdomainid = meshidsplit[1]; + const username = 'MCAuth1:' + xnodeid + ':' + xmeshid + ':' + xdomainid; + const nonce = Buffer.from(parent.crypto.randomBytes(9), 'binary').toString('base64'); + return { meshid: meshid, nodeid: nodeid, user: username, pass: parent.config.settings.mqtt.auth.keyid + ':' + nonce + ':' + parent.crypto.createHash('sha384').update(username + ':' + nonce + ':' + parent.config.settings.mqtt.auth.key).digest("base64") }; + } + // Connection Authentication obj.aedes.authenticate = function (client, username, password, callback) { - // TODO: add authentication handler - obj.parent.debug("mqtt", "Authentication with " + username + ":" + password + ":" + client.id + ", " + client.conn.xtransport + "://" + cleanRemoteAddr(client.conn.xip)); + obj.parent.debug("mqtt", "Authentication User:" + username + ", Pass:" + password.toString() + ", ClientID:" + client.id + ", " + client.conn.xtransport + "://" + cleanRemoteAddr(client.conn.xip)); + // Parse the username and password var usersplit = username.split(':'); - if (usersplit.length != 5) { callback(null, false); return; } + var passsplit = password.toString().split(':'); + if ((usersplit.length !== 4) || (passsplit.length !== 3)) { obj.parent.debug("mqtt", "Invalid user/pass format, " + client.conn.xtransport + "://" + cleanRemoteAddr(client.conn.xip)); callback(null, false); return; } + if (usersplit[0] !== 'MCAuth1') { obj.parent.debug("mqtt", "Invalid auth method, " + client.conn.xtransport + "://" + cleanRemoteAddr(client.conn.xip)); callback(null, false); return; } + + // Check authentication + if (passsplit[0] !== parent.config.settings.mqtt.auth.keyid) { obj.parent.debug("mqtt", "Invalid auth keyid, " + client.conn.xtransport + "://" + cleanRemoteAddr(client.conn.xip)); callback(null, false); return; } + if (parent.crypto.createHash('sha384').update(username + ':' + passsplit[1] + ':' + parent.config.settings.mqtt.auth.key).digest("base64") !== passsplit[2]) { obj.parent.debug("mqtt", "Invalid password, " + client.conn.xtransport + "://" + cleanRemoteAddr(client.conn.xip)); callback(null, false); return; } // Setup the identifiers - var xnodeid = usersplit[1]; + const xnodeid = usersplit[1]; var xmeshid = usersplit[2]; - var xdomainid = usersplit[3]; + const xdomainid = usersplit[3]; + + // Check the domain + if ((typeof client.conn.xdomain == 'object') && (xdomainid != client.conn.xdomain.id)) { obj.parent.debug("mqtt", "Invalid domain connection, " + client.conn.xtransport + "://" + cleanRemoteAddr(client.conn.xip)); callback(null, false); return; } // Convert meshid from HEX to Base64 if needed - if (xmeshid.length == 96) { xmeshid = Buffer.from(xmeshid, 'hex').toString('base64'); } - if ((xmeshid.length != 64) || (xnodeid.length != 64)) { callback(null, false); return; } + if (xmeshid.length === 96) { xmeshid = Buffer.from(xmeshid, 'hex').toString('base64'); } + if ((xmeshid.length !== 64) || (xnodeid.length != 64)) { callback(null, false); return; } client.xdbNodeKey = 'node/' + xdomainid + '/' + xnodeid; client.xdbMeshKey = 'mesh/' + xdomainid + '/' + xmeshid; + //console.log(obj.generateLogin(client.xdbMeshKey, client.xdbNodeKey)); + // Check if this node exists in the database db.Get(client.xdbNodeKey, function (err, nodes) { if ((nodes == null) || (nodes.length != 1)) { callback(null, false); return; } // Node does not exist @@ -75,6 +95,7 @@ module.exports.CreateMQTTBroker = function (parent, db, args) { // Check if a client can publish a packet obj.aedes.authorizePublish = function (client, packet, callback) { // TODO: add authorized publish control + //console.log(packet); obj.parent.debug("mqtt", "AuthorizePublish, " + client.conn.xtransport + "://" + cleanRemoteAddr(client.conn.xip)); callback(null); } @@ -82,13 +103,14 @@ module.exports.CreateMQTTBroker = function (parent, db, args) { // Check if a client can publish a packet obj.aedes.authorizeSubscribe = function (client, sub, callback) { // TODO: add subscription control here - obj.parent.debug("mqtt", "AuthorizeSubscribe, " + client.conn.xtransport + "://" + cleanRemoteAddr(client.conn.xip)); + obj.parent.debug("mqtt", "AuthorizeSubscribe \"" + sub.topic + "\", " + client.conn.xtransport + "://" + cleanRemoteAddr(client.conn.xip)); callback(null, sub); } - // Check if a client can publish a packet + // Check if a client can forward a packet obj.aedes.authorizeForward = function (client, packet) { // TODO: add forwarding control + //console.log(packet); obj.parent.debug("mqtt", "AuthorizeForward, " + client.conn.xtransport + "://" + cleanRemoteAddr(client.conn.xip)); //return packet; return packet; diff --git a/package.json b/package.json index f7cf3e00..62c4ac79 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "meshcentral", - "version": "0.4.1-u", + "version": "0.4.1-v", "keywords": [ "Remote Management", "Intel AMT", diff --git a/views/default-min.handlebars b/views/default-min.handlebars index 9bf81382..59fc8798 100644 --- a/views/default-min.handlebars +++ b/views/default-min.handlebars @@ -1 +1 @@ -
{{{logoutControl}}}
My Devices | My Account | My Events | My Files | My Users | My Server |
{{{logoutControl}}}
My Devices | My Account | My Events | My Files | My Users | My Server |