How to secure MQTT over websockets

Jeremy Gooch picture Jeremy Gooch · Jun 30, 2014 · Viewed 7.1k times · Source

I'd like to understand the best way to secure Mosquitto when surfacing an MQTT broker over websockets to a browser. I'm currently using Lighttpd for the websocket layer, as per this blog post.

My use case is uni-directional. I only need send messages to the browser. Hence, I can use an ACL to prevent miscreants from publishing messages.

But how can I stop miscreants from subscribing or, better still, making a connection in the first place?

I know I can use an ID/pw for the MQTT connection. So, I guess my app server can send the credentials to the browser once the user has authenticated themselves and the Javascript client can then use these credentials to establish the MQTT/WS connection. But, if I have thousands of clients, how do I manage the IDs and passwords? Or should I just have a handful of IDs and recycle them periodically? Should I hand this bit off to Redis or similar as per the mosquitto-auth-plug?

I wondered if there was a better way, by securing the connection within the webserver layer. The mod_secdownload plug-in for Lighttpd seems to offer a model whereby a URL can be dynamically generated, based on a hash of a shared secret (kept server-side) and a timestamp. Once a user has authenticated, the app server would pass this URL down and the client would then use it to establish the connection up to the MQTT broker. After a while, the URL will expire and the Javascript client can catch this exception and, if the user is still authenticated, can ask for a new WS connection URL. This is similar pattern to a lot of API authentication. Does it have merit here?

Is there a better method?

Thanks, J.

Answer

Teixi picture Teixi · Jul 16, 2014

Instead of the Lighttpd aproach, now you can just build mosquitto with libwebsockets support and then create the X.509 certificates for TLS support.

In this blog post by jpmens you can find the step by step procedure and also a Paho MQTT JavaScript client connecting the Mosquitto broker via Websockets. http://jpmens.net/2014/07/03/the-mosquitto-mqtt-broker-gets-websockets-support/