Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

node.js mqtt client using TLS

I am trying to implement a node.js mqtt client with TLS using the package below;

https://www.npmjs.com/package/mqtt#client

The code for running mqtt client without TLS is as follows;

var mqtt = require('mqtt')
var client  = mqtt.connect('mqtt://test.mosquitto.org')

client.on('connect', function () {
  client.subscribe('presence')
  client.publish('presence', 'Hello mqtt')
})

client.on('message', function (topic, message) {
  // message is Buffer 
  console.log(message.toString())
  client.end()
})

How should the above code be modified to use TLS on the mqtt client?

The mosca MQTT broker was run as a stand-alone using the command below;

mosca --key ./tls-key.pem --cert ./tls-cert.pem --http-port 3000 --http-bundle --http-static ./ | pino
like image 664
guagay_wk Avatar asked Oct 13 '16 10:10

guagay_wk


People also ask

Does MQTT support TLS?

MQTT Modules can be enabled to use SSL/TLS to encrypt the communication between MQTT clients which is useful if used on a public network. MQTT communications are not encrypted by default and enabling SSL/TLS is highly recommended on a public network.

What is TLS in Nodejs?

The node:tls module provides an implementation of the Transport Layer Security (TLS) and Secure Socket Layer (SSL) protocols that is built on top of OpenSSL. The module can be accessed using: const tls = require('node:tls');

What is SSL in MQTT?

Transport Layer Security (TLS) and Secure Sockets Layer (SSL) provide a secure communication channel between a client and a server. At the core, TLS and SSL are cryptographic protocols which use a handshake mechanism to negotiate various parameters to create a secure connection between the client and the server.


2 Answers

Should be enough to change the protocol part of the URL to mqtts://

mqtts://test.mosquitto.org.

Self-signed certificates

You can pass the following option to the connect function when using self-signed certificates (for testing purposes only):

mqtt.connect('mqtts://test.mosquitto.org', {
    rejectUnauthorized: false
});
like image 187
notion Avatar answered Sep 21 '22 00:09

notion


You need to provide the mqtt.connect() function with an options object which includes the CA certificate to use to verify the connection.

The options object needs to include a ca key that points to the certificate used to sign the brokers certificate. As it looks like your using a self signed certificate this will be the same one used by the broker.

The ca key is described here

Or you can allow any certificate with the rejectUnauthorized key as mentioned in @notion's answer. But that makes it impossible to detect if somebody is impersonating your broker

like image 37
hardillb Avatar answered Sep 18 '22 00:09

hardillb