Mosquitto MQTT

Mosquitto MQTT

I've recently started experimenting with MQTT, in particular the Mosquito broker. After quite a bit of trial & error and plenty of man page reading I've managed to get things working nicely.

Features enabled:

  • SSL/TLS connections
  • Websockets proxied through Apache (ws:// and wss://)
  • ACLs for anonymous access
  • ACLs for username/password access
  • Bridging selected local topics to the service

A visualisation of the topics I currently have is shown followed by configuration sections for the various options.

If you want to secure your connection using SSL/TLS then I recommend Let's Encrypt, to install the certificates see here

MQTT Topic Tree

All configuration is based on an Ubuntu installation of Mosquitto.

Basic Server Config /etc/mosquitto/mosquitto.conf

pid_file /var/run/

persistence true
persistence_location /var/lib/mosquitto/

log_dest file /var/log/mosquitto/mosquitto.log
#log_type all

acl_file /etc/mosquitto/acl.conf
password_file /etc/mosquitto/passwords

include_dir /etc/mosquitto/conf.d

ACLs /etc/mosquitto/acl.conf

# only allow anonymous users specific access
topic read #
topic read $SYS/broker/messages/#

# Allow user web to read anywhere
user web
topic read #
topic read $SYS/#

# Allow user sensor to write anywhere
user sensor
topic readwrite #

Generate your password file using mosquitto_passwd.

Set permissions and group on the password file as:

-rw-r----- 1 root mosquitto 229 Feb 4 20:18 /etc/mosquitto/passwords

ie: u+rw,g+r for root:mosquitto

Secure/Insecure MQTT config /etc/mosquitto/conf.d/01-default.conf

listener 1883
listener 8883
cafile /path/to/chain-ca.pem
certfile /path/to/cert.pem
keyfile /path/to/privkey.pem

Secure/Insecure Websockets config /etc/mosquitto/conf.d/02-websockets.conf

listener 8080
protocol websockets

listener 8083
protocol websockets
cafile /path/to/chain-ca.pem
certfile /path/to/cert.pem
keyfile /path/to/privkey.pem

Bridge config /etc/mosquitto/conf.d/03-adafruit-bridge.conf

connection bridge_adafruit
remote_username <username>
remote_password <aio key>
start_type automatic
bridge_protocol_version mqttv311
bridge_capath /etc/ssl/certs/

notifications false
try_private false

topic throttle in 0 <username>/feeds/
topic welcome-feed both 0 <username>/feeds/

Apache config for proxying

Place this within your <Virtualhost *:80> or <Virtualhost *:443> directive.

If your VHost is a secure one then the SSL/TLS websocket connection will be handled by Apache and transparently proxied to the local MQTT broker. All communication between the browser and Apache will be secured.

This requires the mod_proxy_wstunnel module to be enabled.

        <Location "/mqtt">
                ProxyPreserveHost On
                ProxyPass ws://localhost:8080/mqtt
                ProxyPassReverse ws://localhost:8080/mqtt

Related Article