Added MQTT authentication.

Ylian Saint-Hilaire committed Oct 5, 2019 at 14:24 UTC 1db0899a7d4807834a7c23f46b3d39f8ae9f8c88
6 files changed +123 -13
certoperations.js
+15
@@ -241,6 +241,21 @@ module.exports.CertificateOperations = function (parent) {
241 return obj.pki.getPublicKeyFingerprint(publickey, { encoding: "hex", md: obj.forge.md.sha384.create() });
242 };
243
244 + // Return the SHA384 hash of the certificate, return hex
245 + obj.getCertHashSha1 = function (cert) {
246 + try {
247 + var md = obj.forge.md.sha1.create();
248 + md.update(obj.forge.asn1.toDer(obj.pki.certificateToAsn1(obj.pki.certificateFromPem(cert))).getBytes());
249 + return md.digest().toHex();
250 + } catch (ex) {
251 + // If this is not an RSA certificate, hash the raw PKCS7 out of the PEM file
252 + var x1 = cert.indexOf('-----BEGIN CERTIFICATE-----'), x2 = cert.indexOf('-----END CERTIFICATE-----');
253 + if ((x1 >= 0) && (x2 > x1)) {
254 + return obj.crypto.createHash('sha1').update(Buffer.from(cert.substring(x1 + 27, x2), 'base64')).digest('hex');
255 + } else { console.log('ERROR: Unable to decode certificate.'); return null; }
256 + }
257 + };
258 +
259 // Return the SHA384 hash of the certificate, return hex
260 obj.getCertHash = function (cert) {
261 try {
meshcentral.js
+1 -1
@@ -826,7 +826,7 @@ function CreateMeshCentralServer(config, args) {
826 obj.apfserver = require('./apfserver.js').CreateApfServer(obj, obj.db, obj.args);
827
828 // Create MQTT Broker to hook into webserver and mpsserver
829 - if (obj.config.settings.mqtt != null) { obj.mqttbroker = require("./mqttbroker.js").CreateMQTTBroker(obj, obj.db, obj.args); }
829 + 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); }
830
831 // Start the web server and if needed, the redirection web server.
832 obj.webserver = require('./webserver.js').CreateWebServer(obj, obj.db, obj.args, obj.certificates);
meshuser.js
+48
@@ -2876,6 +2876,54 @@ module.exports.CreateMeshUser = function (parent, db, ws, req, args, domain, use
2876 }
2877 break;
2878 }
2879 + case 'getmqttlogin': {
2880 + var err = null;
2881 + if (parent.parent.mqttbroker == null) { err = 'MQTT not supported on this server'; }
2882 + if (common.validateString(command.nodeid, 1, 1024) == false) { err = 'Invalid nodeid'; } // Check the nodeid
2883 +
2884 + // Handle any errors
2885 + if (err != null) { if (command.responseid != null) { try { ws.send(JSON.stringify({ action: 'getmqttlogin', responseid: command.responseid, result: err })); } catch (ex) { } } break; }
2886 +
2887 + var nodeid = command.nodeid;
2888 + if ((nodeid.split('/').length == 3) && (nodeid.split('/')[1] == domain.id)) { // Validate the domain, operation only valid for current domain
2889 + // Get the device
2890 + db.Get(nodeid, function (err, nodes) {
2891 + 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; } }
2892 + var node = nodes[0];
2893 +
2894 + // Get the device group for this node
2895 + var mesh = parent.meshes[node.meshid];
2896 + if (mesh) {
2897 + // Check if this user has rights to do this
2898 + if ((mesh.links[user._id] != null) && (mesh.links[user._id].rights == 0xFFFFFFFF)) {
2899 + var token = parent.parent.mqttbroker.generateLogin(mesh._id, node._id);
2900 + var r = { action: 'getmqttlogin', responseid: command.responseid, nodeid: node._id, user: token.user, pass: token.pass };
2901 + const serverName = parent.getWebServerName(domain);
2902 +
2903 + // Add MPS URL
2904 + if (parent.parent.mpsserver != null) {
2905 + r.mpsCertHashSha384 = parent.parent.certificateOperations.getCertHash(parent.parent.mpsserver.certificates.mps.cert);
2906 + r.mpsCertHashSha1 = parent.parent.certificateOperations.getCertHashSha1(parent.parent.mpsserver.certificates.mps.cert);
2907 + r.mpsUrl = 'mqtts://' + serverName + ':' + ((args.mpsaliasport != null) ? args.mpsaliasport : args.mpsport) + '/';
2908 + }
2909 +
2910 + // Add WS URL
2911 + var xdomain = (domain.dns == null) ? domain.id : '';
2912 + if (xdomain != '') xdomain += "/";
2913 + var httpsPort = ((args.aliasport == null) ? args.port : args.aliasport); // Use HTTPS alias port is specified
2914 + r.wsUrl = "ws" + (args.notls ? '' : 's') + "://" + serverName + ":" + httpsPort + "/" + xdomain + "mqtt.ashx";
2915 + r.wsTrustedCert = parent.isTrustedCert(domain);
2916 +
2917 + try { ws.send(JSON.stringify(r)); } catch (ex) { }
2918 + } else {
2919 + if (command.responseid != null) { try { ws.send(JSON.stringify({ action: 'getmqttlogin', responseid: command.responseid, result: 'Unable to perform this operation' })); } catch (ex) { } }
2920 + }
2921 + }
2922 + });
2923 + }
2924 +
2925 + break;
2926 + }
2927 case 'amt': {
2928 if (common.validateString(command.nodeid, 1, 1024) == false) break; // Check nodeid
2929 if (common.validateInt(command.mode, 0, 3) == false) break; // Check connection mode
mqttbroker.js
+31 -9
@@ -16,26 +16,46 @@ module.exports.CreateMQTTBroker = function (parent, db, args) {
16 obj.handle = obj.aedes.handle;
17 obj.connections = {}; // NodesID --> client array
18
19 + // Generate a username and password for MQTT login
20 + obj.generateLogin = function (meshid, nodeid) {
21 + const meshidsplit = meshid.split('/'), nodeidsplit = nodeid.split('/');
22 + const xmeshid = meshidsplit[2], xnodeid = nodeidsplit[2], xdomainid = meshidsplit[1];
23 + const username = 'MCAuth1:' + xnodeid + ':' + xmeshid + ':' + xdomainid;
24 + const nonce = Buffer.from(parent.crypto.randomBytes(9), 'binary').toString('base64');
25 + 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") };
26 + }
27 +
28 // Connection Authentication
29 obj.aedes.authenticate = function (client, username, password, callback) {
21 - // TODO: add authentication handler
22 - obj.parent.debug("mqtt", "Authentication with " + username + ":" + password + ":" + client.id + ", " + client.conn.xtransport + "://" + cleanRemoteAddr(client.conn.xip));
30 + obj.parent.debug("mqtt", "Authentication User:" + username + ", Pass:" + password.toString() + ", ClientID:" + client.id + ", " + client.conn.xtransport + "://" + cleanRemoteAddr(client.conn.xip));
31
32 + // Parse the username and password
33 var usersplit = username.split(':');
25 - if (usersplit.length != 5) { callback(null, false); return; }
34 + var passsplit = password.toString().split(':');
35 + 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; }
36 + if (usersplit[0] !== 'MCAuth1') { obj.parent.debug("mqtt", "Invalid auth method, " + client.conn.xtransport + "://" + cleanRemoteAddr(client.conn.xip)); callback(null, false); return; }
37 +
38 + // Check authentication
39 + 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; }
40 + 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; }
41
42 // Setup the identifiers
28 - var xnodeid = usersplit[1];
43 + const xnodeid = usersplit[1];
44 var xmeshid = usersplit[2];
30 - var xdomainid = usersplit[3];
45 + const xdomainid = usersplit[3];
46 +
47 + // Check the domain
48 + 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; }
49
50 // Convert meshid from HEX to Base64 if needed
33 - if (xmeshid.length == 96) { xmeshid = Buffer.from(xmeshid, 'hex').toString('base64'); }
34 - if ((xmeshid.length != 64) || (xnodeid.length != 64)) { callback(null, false); return; }
51 + if (xmeshid.length === 96) { xmeshid = Buffer.from(xmeshid, 'hex').toString('base64'); }
52 + if ((xmeshid.length !== 64) || (xnodeid.length != 64)) { callback(null, false); return; }
53
54 client.xdbNodeKey = 'node/' + xdomainid + '/' + xnodeid;
55 client.xdbMeshKey = 'mesh/' + xdomainid + '/' + xmeshid;
56
57 + //console.log(obj.generateLogin(client.xdbMeshKey, client.xdbNodeKey));
58 +
59 // Check if this node exists in the database
60 db.Get(client.xdbNodeKey, function (err, nodes) {
61 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) {
95 // Check if a client can publish a packet
96 obj.aedes.authorizePublish = function (client, packet, callback) {
97 // TODO: add authorized publish control
98 + //console.log(packet);
99 obj.parent.debug("mqtt", "AuthorizePublish, " + client.conn.xtransport + "://" + cleanRemoteAddr(client.conn.xip));
100 callback(null);
101 }
@@ -82,13 +103,14 @@ module.exports.CreateMQTTBroker = function (parent, db, args) {
103 // Check if a client can publish a packet
104 obj.aedes.authorizeSubscribe = function (client, sub, callback) {
105 // TODO: add subscription control here
85 - obj.parent.debug("mqtt", "AuthorizeSubscribe, " + client.conn.xtransport + "://" + cleanRemoteAddr(client.conn.xip));
106 + obj.parent.debug("mqtt", "AuthorizeSubscribe \"" + sub.topic + "\", " + client.conn.xtransport + "://" + cleanRemoteAddr(client.conn.xip));
107 callback(null, sub);
108 }
109
89 - // Check if a client can publish a packet
110 + // Check if a client can forward a packet
111 obj.aedes.authorizeForward = function (client, packet) {
112 // TODO: add forwarding control
113 + //console.log(packet);
114 obj.parent.debug("mqtt", "AuthorizeForward, " + client.conn.xtransport + "://" + cleanRemoteAddr(client.conn.xip));
115 //return packet;
116 return packet;
views/default.handlebars
+24
@@ -2274,6 +2274,24 @@
2274 QV('agentInvitationLinkDiv', true);
2275 break;
2276 }
2277 + case 'getmqttlogin': {
2278 + if ((currentNode == null) || (currentNode._id != message.nodeid) || (xxdialogMode != null)) return;
2279 + var x = "These settings can be used to connect MQTT for this device.<br /><br />";
2280 + delete message.action;
2281 + delete message.nodeid;
2282 + x += '<textarea readonly=readonly style=width:100%;resize:none;height:100px;overflow:auto;font-size:12px readonly>' + JSON.stringify(message) + '</textarea>';
2283 + /*
2284 + x += addHtmlValue('Username', '<input style=width:230px readonly value="' + message.user + '" />');
2285 + x += addHtmlValue('Password', '<input style=width:230px readonly value="' + message.pass + '" />');
2286 + x += addHtmlValue('WS URL', '<input style=width:230px readonly value="' + message.wsUrl + '" />');
2287 + if (message.mpsUrl && message.mpsCertHash) {
2288 + x += addHtmlValue('MPS URL', '<input style=width:230px readonly value="' + message.mpsUrl + '" />');
2289 + x += addHtmlValue('MPS Cert Hash', '<input style=width:230px readonly value="' + message.mpsCertHash + '" />');
2290 + }
2291 + */
2292 + setDialogMode(2, "MQTT Credentials", 1, null, x);
2293 + break;
2294 + }
2295 case 'stopped': { // Server is stopping.
2296 // Disconnect
2297 autoReconnect = false;
@@ -4280,6 +4298,9 @@
4298 x += '<a href=# onclick=p10clickOnce("' + node._id + '","WSCP",22) title="Requires Microsoft ClickOnce support in your browser.">WinSCP</a>&nbsp;';
4299 }
4300 }
4301 +
4302 + // MQTT options
4303 + if ((meshrights == 0xFFFFFFFF) && (features & 0x00400000)) { x += '<a href=# onclick=p10showMqttLoginDialog("' + node._id + '") title="Get MQTT login credentials for this device.">MQTT Login</a>&nbsp;'; }
4304 x += '</div><br>'
4305
4306 QH('p10html3', x);
@@ -4664,6 +4685,9 @@
4685 setDialogMode(2, "MeshCentral Router", 1, null, x, "fileDownload");
4686 }
4687
4688 + // Request MQTT login credentials
4689 + function p10showMqttLoginDialog(nodeid) { meshserver.send({ action: 'getmqttlogin', nodeid: nodeid }); }
4690 +
4691 // Show MeshCmd dialog
4692 function p10showMeshCmdDialog(mode, nodeid) {
4693 if (xxdialogMode) return;
webserver.js
+4 -3
@@ -1505,6 +1505,7 @@ module.exports.CreateWebServer = function (parent, db, args, certificates) {
1505 if ((domain.auth == 'sspi') || (domain.auth == 'ldap')) { features += 0x00080000; } // LDAP or SSPI in use, warn that users must login first before adding a user to a group.
1506 if (domain.amtacmactivation) { features += 0x00100000; } // Intel AMT ACM activation/upgrade is possible
1507 if (domain.usernameisemail) { features += 0x00200000; } // Username is email address
1508 + if (parent.mqttbroker != null) { features += 0x00400000; } // This server supports MQTT channels
1509
1510 // Create a authentication cookie
1511 const authCookie = obj.parent.encodeCookie({ userid: user._id, domainid: domain.id, ip: cleanRemoteAddr(req.ip) }, obj.parent.loginCookieEncryptionKey);
@@ -1617,7 +1618,7 @@ module.exports.CreateWebServer = function (parent, db, args, certificates) {
1618 }
1619
1620 // Return true if it looks like we are using a real TLS certificate.
1620 - function isTrustedCert(domain) {
1621 + obj.isTrustedCert = function(domain) {
1622 if (obj.args.notls == true) return false; // We are not using TLS, so not trusted cert.
1623 if ((domain != null) && (typeof domain.trustedcert == 'boolean')) return domain.trustedcert; // If the status of the cert specified, use that.
1624 if (typeof obj.args.trustedcert == 'boolean') return obj.args.trustedcert; // If the status of the cert specified, use that.
@@ -2886,7 +2887,7 @@ module.exports.CreateWebServer = function (parent, db, args, certificates) {
2887 res.set({ 'Cache-Control': 'no-cache, no-store, must-revalidate', 'Pragma': 'no-cache', 'Expires': '0', 'Content-Type': 'text/plain', 'Content-Disposition': 'attachment; filename="' + scriptInfo.rname + '"' });
2888 var data = scriptInfo.data;
2889 var cmdoptions = { wgetoptionshttp: '', wgetoptionshttps: '', curloptionshttp: '-L ', curloptionshttps: '-L ' }
2889 - if (isTrustedCert(domain) != true) {
2890 + if (obj.isTrustedCert(domain) != true) {
2891 cmdoptions.wgetoptionshttps += '--no-check-certificate ';
2892 cmdoptions.curloptionshttps += '-k ';
2893 }
@@ -3350,7 +3351,7 @@ module.exports.CreateWebServer = function (parent, db, args, certificates) {
3351 // For example: https://localhost/createLoginToken.ashx?user=admin&pass=admin&a=3
3352 // It's not advised to use this to create login tokens since the URL is often logged and you got credentials in the URL.
3353 // Since it's bad, it's only offered when an untrusted certificate is used as a way to help developers get started.
3353 - if (isTrustedCert() == false) {
3354 + if (obj.isTrustedCert() == false) {
3355 obj.app.get(url + 'createLoginToken.ashx', function (req, res) {
3356 // A web socket session can be authenticated in many ways (Default user, session, user/pass and cookie). Check authentication here.
3357 if ((req.query.user != null) && (req.query.pass != null)) {