Mosquitto SSL Configuration -MQTT TLS Security

configure-tls-mosquittoIn this tutorial we will configure the mosquitto MQTT broker to use TLS security.

We will be using openssl to create our own Certificate authority (CA), Server keys and certificates.

We will also test the broker by using the Paho Python client to connect to the broker using a SSL connection.

You should have a basic understanding of PKI, certificates and keys before proceeding. See SSL and SSL Certificates Explained

The steps covered here will create an encrypted connection between the MQTT broker and the MQTT client just like the one between a web browser client and a Web Server.

In this case we only need a trusted server certificate on the Client.

We do not need to create client certificates and keys but this is covered in Creating and Using Client Certificates with MQTT and Mosquitto

Important Note: Many other tutorial on the web also configure username and password authentication at the same time. I don’t recommend you do this as errors could be cause by either SSL or authentication. Only do one thing at one time when testing.

Client Requirements

  • A CA (certificate authority) certificate of the CA that has signed the server certificate on the Mosquitto Broker.

Broker Requirements

  • CA certificate of the CA that has signed the server certificate on the Mosquitto Broker.
  • CA certificated server certificate.
  • Server Private key for decryption.

Creating and Installing Broker Certificates and keys

To create these certificates and keys we use the openssl software.

For windows you will find the install download files here.

On Linux you can install openssl using :

sudo apt-get install openssl

Although the commands to create the various certificates and keys are given in this Mosquitto manual page. Here is a quick snapshot:


There is a problem with the page because openssl no longer comes with a CA certificate, and so you will need to create your own self signed CA certificate.

You should also note that when you generate keys you shouldn’t use encryption (the -ds3 switch) for the server certificate as this creates a password protected key which the broker can’t decode.

Note the certificates and keys created can be used on the Mosquitto broker/server, and also on a web server, which is why you see the term server used in the Mosquitto manual and not broker.

Overview of Steps

  1. Create a CA key pair
  2. Create CA certificate and use the CA key from step 1 to sign it.
  3. Create a broker key pair don’t password protect.
  4. Create a broker certificate request using key from step 3
  5. Use the CA certificate to sign the broker certificate request from step 4.
  6. Now we should have a CA key file,a CA certificate file, a broker key file, and a broker certificate file.
  7. Place all files in a directory on the broker e.g. certs
  8. Copy the CA certificate file to the client.
  9. Edit the Mosquitto conf file to use the files -details below
  10. Edit the client script to use TLS and the CA certificate. -details below

Note: when entering the country, organisation etc in the form don’t use exactly the same information for the CA and the server certificate as it causes problems. Here is a screen shot of a comment from a reader that brought it to my attention:

Detailed Steps

Note this as done on a windows XP machine.

The same commands and procedures apply to linux but the folder locations will be different and you may need to change permissions, as well as using the sudo command.

Step 1:

First create a key pair for the CA

Command is:   openssl genrsa -des3 -out ca.key 2048


Note: it is OK to create a password protected key for the CA.

Step 2:

Now Create a certificate for the CA using the CA key that we created in step 1

Command is:  openssl req -new -x509 -days 1826 -key ca.key -out ca.crt


Step 3:

Now we create a server key pair that will be used by the broker

Command is: openssl genrsa -out server.key 2048


Step 4:

Now we create a certificate request .csr. When filling out the form the common name is important and is usually the domain name of the server.

Because I’m using Windows on a local network I used the Windows name for the computer that is running the Mosquitto broker which is ws4.

You could use the IP address or Full domain name. You must use the same name when configuring the client connection.

Command is: openssl req -new -out server.csr -key server.key


Note: We don’t send this to the CA as we are the CA

Step 5:

Now we use the CA key to verify and sign the server certificate. This creates the server.crt file

Command is:  openssl x509 -req -in server.csr -CA ca.crt -CAkey ca.key -CAcreateserial -out server.crt -days 360


Step 6:

The above steps created various files. This is what the directory looks like now:


Note: We don’t need to copy the CA.key file. This file is used when creating new server or client certificates.

Step 7:

Copy the files ca.crt, serever.crt and server.key to a folder under the mosquitto folder. I have used a folder called certs.

on Linux you should already have a ca_certificates folder under /etc/mosquitto/ and also a certs folder.

Use the ca_certificates folder for the CA certificate and the certs folder for the server certificate and key.

Step 8:

Copy the CA certificate file  ca.crt to the client.

Step 9:

Edit the mosquitto.conf file as shown:



  1. I’ve used the default listener but you could also add an extra listener.
  2.  The ca path is not used as I told it the file location instead.
  3. On my Linux install the entire TLS section of the mosquitto.conf file was missing I had to copy it from my windows install and then edit it. Here is the mosquitto.conf file documentation

Step 10 -Client Configuration:

Edit the client to tell it to use TLS and give it the path of the CA certificate file that you copied over.

I’m using the python client and the client method is tls_set(). Although there are several parameters that you can pass the only one you must give is the CA file as shown below.


The python client will default to TLSv1.

You shouldn’t need to change it as the mosquitto broker also defaults to TLSv1.( before v 1.6)

However to change it to TLSv1.2 use:


The pub and subscribe scripts that come with the mosquitto broker default to TLSv1.2.

Problems I Encountered and Notes

While creating and working through these procedures i encountered the following problems

  1. Error when connecting due to the common name on the server certificate not matching.
  2. I password protected the server key and the broker couldn’t read it. I found this command which will remove the passphrase from the key –  openssl rsa -in server.key -out server-nopass.key.
  3. Not using the correct name for the broker. I used the IP address and not the name that I entered into the certificate.You can use the tls_insecure_set(True) option to override name checking as a temporary measure.
  4. Authentication errors as I had previously configured my broker to require passwords. Therefore try to start with a clean conf file and beware that the errors you are getting may not be SSL related.

Self Signed Certificates

Currently the Paho python client require a CA certificate file and so it is not possible to use a self signed certificate. I came across a couple github threads relating to this but no real solution.


If all goes well you should be able to publish and subscribe to topics as normal, but now the connection between client and broker is encrypted.

Unfortunately there is no easy way of seeing this.

This is the Python script I used:


To test using the mosquitto_pub client use:


Failure Example

This shows that the common name you enter on the certificate must match the name used by the client when it connects. If not it doesn’t work.


Video -Configuring SSL on the Mosquitto MQTT Broker

TLS Versions

Starting with v1.6 I  the support for tlsv1.1 was removed . You need to add the line

tls_version tlsv1.2

to your configuration file and when testing set the version e.g.

C:\mos>mosquitto_pub -h -p 8883 -t test -m test --cafile c:/python34/steve/mqtt-demos/ca.crt --tls-version tlsv1.2

You can see the change log here -

Reported Problems and Solutions

  • Wrong/Old openssl version reported on Centos 7. Update openssl fixed it.
  • Problems when using capath on mosquitto_pub tool. Use cafile instead -mosquitto_pub -h -u username -P password -t test/topic -p 8883 –cafile ~/keys/ca.crt -m message
  • Problems with Server name on certificate. Use the tls_insecure_set(True) on the python client or the –insecure switch in the mosquitto_pub tool.

Useful OpenSSL Commands

Verify that a server certificate is signed by a particular CA. Use the Ca.crt file and the server.crt file.

openssl verify -CAfile ca.crt server.crt

it should return

server.crt: OK

Shell Scripts

To save you typing I’ve created two Linux shell scripts that run the commands and create server and client certificates and keys as in this tutorial and the client certificate tutorial.

Download scripts

Mosquitto Configuration Tutorials

Other Related Articles and Resources:

Please rate? And use Comments to let me know more
[Total: 25   Average: 4.6/5]


  1. Above you said that “shouldn’t use encryption (-ds3)”
    But in detail you said “Note: it is OK to create a password protected key for the CA.”.
    So what I have to do ?

  2. Hi Steve,

    I have a ev ssl certificate signed by entrust and the .csr was generated from IIS, windows. I retrieved the private key from the certificate manager and used Root.crt as cafile and the signed certificate.crt as certfile. However, I am getting this error on the broker -> OpenSSL Error[0]: error:14094416:SSL routines:ssl3_read_bytes:sslv3 alert certificate unknown this error when I try to connect my client (with .pfx) to my broker.

    1. Hi
      Try and create your own cert and keys and get it working then move back to the entrust ones once you are happy with the procedure.

  3. Hi Steve.
    Your articles are amazing and have helped me many times!!

    I have a ubuntu server configured with ip x.x.x.x and i have installed mosquitto broker here. Also I followed the steps to configure TLS from this article.
    Now my client is an ubuntu desktop with ip y.y.y.y and I have copied the ca.crt file from my broker to this machine.
    When I run the python script i get “Unable to connect : TLS error occured ” Also the script gives me “Socket error”
    What am I doing wrong?

    The mosquitto config file is same as your’s . Please help!

  4. This is a very helpful tutorial, Steve, Thanks so much.
    I followed the steps you explained and I was successful running the broker with the TLS options. However, I had a problem connecting clients to the broker using mosquitto_sub/mosquitto_pub commands. when I run:
    mosquitto_pub -t “test” –cafile mqtt-ca.crt -m “HELLO THERE ON THE OTHER SIDE” -h mqtt-broker
    I get: Unable to connect (Lookup error.). on the client side and:
    1597295923: New connection from on port 8883.
    1597295923: OpenSSL Error[0]: error:14094438:SSL routines:ssl3_read_bytes:tlsv1 alert internal error
    1597295923: Socket error on client , disconnecting.
    On the server side (They are actually the same PC).

    However, using the –insecure option works fine. Tha same for mosquitto_sub. I believe I have a problem in the host name but I don’t know how to fix it. In the certificate signature requests (for both CA and server) I used the same common name “mqtt-broker”. I also tried two different CNs for CA and server certs but I got the same output error.

    I also tried connecting from another PC in the network and the same scenario happened.


    1. The name you need to use is the name you use to connect to the broker. So on a local network it may be mqtt-broker.local.
      if you can ping the broker using
      ping mqtt-broker
      then it should work but you are correct that the -insecure means a naming issue.

      1. Thanks so much, I found out that the CN should be the same as the PC name itself (it was a stupid of me). So, when I renamed my PC to mqtt-broker, the connection was successful without the –enable option but in my case it was mqtt-broker.fios-router.home as the hostname. I think I have to do some work on my router.

        Many thanks!

  5. Steve, props to the wonderful tutorials you provide for MQTT functionality. These helped me more than everything else on the web.

    This system was working perfectly fine when I was using 9001 port with ws then ……. SSL had to come into play (policies).

    BUT….I am running into a problem with the SSL setup and connecting to the broker via WS for my webapp.

    1. Mosquitto.config
    #start (default) listener on port 1883
    port 1883

    #start listener on port 8883 with SSL
    listener 8883
    certfile /etc/mosquitto/certs/……pem
    cafile /etc/mosquitto/ca_certificates/……pem
    keyfile /etc/mosquitto/certs/…….key

    listener 8083
    protocol websockets
    certfile /etc/mosquitto/certs/……pem
    cafile /etc/mosquitto/ca_certificates/……pem
    keyfile /etc/mosquitto/certs/…….key

    2. The following command works and sends
    mosquitto_pub -h -t smth/smth –cafile /etc/mosquitto/ca_certificates/….pem -m “test” -p 8883

    3. The following command does not work
    mosquitto_pub -h -t smth/smth –cafile /etc/mosquitto/ca_certificates/….pem -m “test” -p 8083
    ERROR- A network protocol error occurred when communicating with the broker.

    4. For my webapp I am using MQTT package with React

    This will not connect
    import React from ‘react’;
    import ‘./index.css’;
    const mqtt = require(‘mqtt’)

    const websocketUrl = “wss://″

    var options={
    rejectUnauthorized : false,
    ca: ‘./…….crt’ (in client same as used above)

    const client = mqtt.connect(websocketUrl, options)

    As I said above the 9001 worked with ws none SSL site and now this change is not working.
    Might you have any ideas what I am doing wrong?

    1. I don’t think the mosquitto_pub tool supports websockets. Ytu using mqttbox which is a chrome extension as it support websockets with ssl

      1. Thanks for your input Steve! I tried MQTTBox and it is for sure an interesting tool. I will get more in depth with it later.

        To test the Mosquitto side of things I use MQTT-Explorer and the server allows connection on all ports I configured in the Mosquitto.conf file including the SSL secured ports. For the SSL secured ports you simply add the CA cert in MQTT-Explorer within the advanced settings area and it connects with no problems.

        My problem is that the MQTTjs library for some reason will not connect to the SSL port client side to my MQTT broker. I think it has to do with the formatting of the CA cert I am giving the library to work with, but I am not for certain since the same format was used in MQTT-Explorer. I need to figure out what format the library is requiring.

    2. I am getting this below error at client side:
      Client mosq-8EeICay0nUa53G4DIA sending CONNECT
      OpenSSL Error[0]: error:14094418:SSL routines:ssl3_read_bytes:tlsv1 alert unknown ca
      Error: A TLS error occurred.
      i just copied server CA certificate to client but not signed the client certificate with it.
      my client certificate is signed with its own ca certificate.
      i am using below command.
      mosquitto_pub –cafile –cert –key –insecure …
      do i need to sign client certificate with copiedCA certificate ? if yes is there any way to avoid this(i used –insecure option still same problem)
      i also tried multiple combination for this command but i think probem is with ca certifciate only at client side.

        1. Hi Steve,
          Thanks for the response.
          Yes i saw that tutorial and yes plain ssl is working.

          I also tried by setting require_certificate flag to false in mosquitto.conf at broker and in this case client is validation server correctly.
          so this scenario is working fine.
          but i want client validation at server/broker side for which i need to set require_certificate flag to true (as per mosquitto.conf man page).
          But when i set require_certificate to true at broker side, i am getting error: “tlsv1 alert unknown ca”
          i have just copied CA certficate of broker to client and passing it to command mosquitto_pub –cafile
          The thing is we dont want to copy server/broker CA key at client, we can just copy server/broker CA.crt to client.

          At server/broker:
          1. broker has its own ca so server_ca.crt, server_ca.key and from this CA cert signed server.crt, server.key
          mosquitto.conf at broker
          cafile server_ca.crt
          certfile server.crt
          keyfile server.key
          require_certifcate true
          (no other flags are set here; i tried setting use_subject_as_username/use_identity_as_username but still same problem)

          At client:
          client has its own ca so client_ca.crt, client_ca.key and from this CA cert signed client.crt, client.key
          in addition to that CA certificate(server_ca.crt) copied server/broker

          and from client hitting below command:
          mosquitto_pub -d -p 8883 -h -m “Hello” -t test –repeat 10 –cafile –cert client.crt –key client.key

          getting error:
          sending CONNECT
          OpenSSL Error[0]: ……. :tlsv1 alert unknown ca


          1. The client ca should be the same as the server ca.Try using my scripts and create some new keys and see if that works any better

  6. Hi Steve,
    i m using mqtt node js client to connect with same configuration as you mentioned here, but what i have observed is i’m able to connect to broker with any client certificate. And when i change the configuration to required_certificate : true. , i m getting this error : error:1417C0C7:SSL routines:tls_process_client_certificate:peer did not return a certificate.

    1. That is probably correct as until you set the require certificate the broker doesn’t check them. If you enable require certificate then you need a valid one.

  7. Hi steve,
    I am getting this error “OpenSSL Error: error:14094418:SSL routines:ssl3_read_bytes:tlsv1 alert unknown ca”.

    pub command executed:
    mosquitto_pub -h -t “test_subscribe” -p 8883 -m “hi” –cafile “/etc/mosquitto/certs/m2mqtt_ca.crt”

    My .conf file:
    listener 1883

    listener 8883
    cafile /etc/mosquitto/certs/m2mqtt_ca.crt
    keyfile /etc/mosquitto/certs/m2mqtt_srv.key
    certfile /etc/mosquitto/certs/m2mqtt_srv.crt

    listener 8083
    protocol websockets
    cafile /etc/mosquitto/certs/m2mqtt_ca.crt
    certfile /etc/mosquitto/certs/m2mqtt_srv.crt
    keyfile /etc/mosquitto/certs/m2mqtt_srv.key

    the common names point to and i am using linux
    Can you help me out please?

    1. Try using the –insecure option and if it works then it is a problem with the ca name. If not then copy the ca.crt file into your local folder and try again as it maybe a permissions problem.

  8. Thanks for the great tutorial.
    I’m trying to use an intermediate certificate to sign client certificates but can’t get it to work, do you know if thats possible?
    So ca.crt signs the mqtt server.crt and ca.crt signs intermediate.crt which signs client.crt and then conactenate the intermediate.crt and client.crt into a clientbundle.crt

  9. Hi Steve, thanks for this brilliant tutorial!
    Any clue why the certificates generated for CN= would give rise to:

    ssl.SSLCertVerificationError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: IP address mismatch, certificate is not valid for ‘’. (_ssl.c:1108)

    on the client side?

    Thanks for your time!

    1. Hi
      You need to use either the IP address of the broker or the domain name as the common name on the certificate and the client has to use this when it connects to the broker.
      So if you use the ip addess then the client has to connect with the iP address.

      1. I created a ca.crt and a server.crt with both CN: . Then I started a Broker on my osx. But always when I try to connect with `mosquitto_pub -t test/ -m “hi” –cafile ./ca.crt -h -p 8883` I get the error:
        OpenSSL Error[0]: error:1416F086:SSL routines:tls_process_server_certificate:certificate verify failed
        Error: A TLS error occurred.

        The broker says:
        1594220727: OpenSSL Error[0]: error:14094418:SSL routines:ssl3_read_bytes:tlsv1 alert unknown ca
        1594220727: Socket error on client , disconnecting.

  10. Hi Steve,
    thanks a lot for you tutorials,
    do you think it’s possible to communicate between mqtt and react-native with SSL?
    I follow you tutorial about SSL and I success to establish a communication between my python client and mqtt but not with react-native in android device.
    thanks in advance if you can help me with SSL between broker mqtt and react native.

    My configuration:

    // web sockets configuration
    listener 9001
    websockets protocol
    cafile /usr/local/etc/mosquitto/certs_ws/ca.crt
    keyfile /usr/local/etc/mosquitto/certs_ws/server.key
    certfile /usr/local/etc/mosquitto/certs_ws/server.crt
    require_certificate true // doesn’t work with true or false in android

    listener 8883
    protocol mqtt
    cafile /usr/local/etc/mosquitto/certs_mqtt/ca.crt
    keyfile /usr/local/etc/mosquitto/certs_mqtt/server.key
    certfile /usr/local/etc/mosquitto/certs_mqtt/server.crt

    my broker is installed in raspberry pi 4

    1. Hi
      Sorry but I’ve never worked with react native. But I would suspect that it is an SSL issue and you need to add the ca to a certificate store or try without SSL.

          1. Thanks Steve,
            I will try this solution.

            if I can’t do it and you know someone who can make my request, I’m ready to pay it to make me an industrial solution that allows SSL to work with reac_native_mqtt lib.
            I can create a upwork project or in a other website working development .

            Thank you

  11. hello Steve,

    What is the differnce between CA cert & self signed cert ?
    some client tools I use like MQTTBox uses self signed and it worked

  12. Hi Steve,
    Thank you for all these helpful information about this subject. I am trying to run the mosquitto broker and client on the local machine with SSL. I have followed your instructions to create the CA certificate, server certificate and the server key. I placed these files in the folder and changed the configuration file accordingly as below:

    cafile C:\mosquitto\certs\ca.crt
    certfile C:\mosquitto\certs\server.crt
    keyfile C:\mosquitto\certs\server.key
    port 8883
    tls_version tlsv1

    Then I restart the mosquitto broker. However, following test failed:
    mosquitto_pub -h 9XLMZY2 -t test/topic –cafile C:\mosquitto\certs\ca.crt -m “Hello” -p 8883

    The error message is “Error: No connection could be made because the target machine actively refused it.”.

    But, when I try following test, it success.

    mosquitto_pub -t test/topic -m “Hello”

    Seems the configuration is not taking effect. The broker is still working at non-SSL mode. What I have done wrong?

    Thanks a lot.

    1. Hi
      That error message is common when the port is blocked by a firewall or not open on the target machine.
      Are you running mosquitto from the command line? When testing I always run mosquitto from my home folder and use the -c switch to load the configuration file
      mosquitto -c ssl.conf
      that way you can see the console and know straight way if the ports are open

  13. Hi Steve,

    I followed your page to create the keys for connections between Flutter and Ejabberd, and copied ca.crt to client side. But I am getting the following errors for iOS, but it is good on Android.

    flutter: Socket Connection failed: HandshakeException: Handshake error in client

    It seems the verify is ok, but it got some errors. Is it because it is self signed? For more details of my questions, please visit


    1. If it works ok on ANdroid then it is unlikely to be a problem with self signed. It could be an SSL version problem on IOS But I don’t use Apple and so can’t check it.

      1. Thank you Steve. You are right, it is very likely a SSL version problem. Even though I still cannot figure out how it works on IPhone X simulator, it can work on my physical iPhone 6S, which is good enough for me. Thank you for your answer, otherwise I would have wasted much time on looking at self-signed. 🙂

  14. Hello Steve,
    Thanks for this tutorial, I have tried this step and successfully.
    I Have some questions:
    1. Does each client need to be made a certificate?
    2. How can I create a certificate for each client?


  15. Hi,
    I created the tls certificate as per your tutorial. while trying run A TLS error occurred.
    mosquitto_pub -h localhost -t ‘test/topic’ –cafile /home/pi/Documents/iotmaster/ca.crt -m ‘helloWorld’ -p 1883
    ERROR:Unable to connect (A TLS error occurred.).
    this is my config file

    # Place your local configuration in /etc/mosquitto/conf.d/
    # A full description of the configuration file is at
    # /usr/share/doc/mosquitto/examples/mosquitto.conf.example

    pid_file /var/run/

    #persistence true
    persistence_location /var/lib/mosquitto/

    log_dest file /var/log/mosquitto/mosquitto.log

    #include_dir /etc/mosquitto/conf.d
    port 1883
    #listener 1883
    cafile /etc/mosquitto/certs/ca.crt
    keyfile /etc/mosquitto/certs/server.key
    certfile /etc/mosquitto/certs/server.crt
    #tls_version tlsv1

  16. Hello Steve,
    I actually configured Mosquitto to work over TLS but PUB/SUB is only working for localhost only.Can you please help me out in PUB/SUB using another IP address.I work on Ubuntu virtual machine please help me out?

  17. Thanks for the tutorial, you have made things much clearer!
    I was following your explaination and i think it should work fine, but somehow mosquitto does not recognize the ca.crt file.

    1581661924: mosquitto version 1.6.8 starting
    1581661924: Config loaded from /mosquitto/config/mosquitto.conf.
    1581661924: Opening ipv4 listen socket on port 8883.
    1581661924: Opening ipv6 listen socket on port 8883.
    1581661924: Error: Unable to load CA certificates. Check cafile “/home/pi/docker/mosquitto/config/ca.crt”.
    1581661924: Error: No such file or directory

    On my raspi I tried to “sudo nano /home/pi/docker/mosquitto/config/ca.crt” and of course i could open it.
    Any ideas, why mosquitto has these problems?

    Additionally: The ca.crt ca I use for all my clients, correct? So if mosquitto runs on the Raspi, I use the ca.crt to access with MQTTfx and also copy the certificate into my esp8266 code?


  18. Hi
    I am using paho client on Raspberry PI to connect to a mosquito broker.
    My code to connect is as follows:

    def mySens(sensorid,subscriberID):
    clientID = sensorid
    client = mqtt.Client(client_id=clientID)
    client.on_connect = when_connect
    client.on_message = on_message
    x = client.connect(host, port)
    print(x, host,port)
    flag = True
    while(flag == True):
    x = client.publish(topic=”MASTER/HELLO”, payload=”hello”)
    x = client.publish(topic=”DEVICE/WELCOME”, payload=json_string)

    When x = client.connect(host, port) executes I get the following error

    Exception in thread figure01
    Traceback (most recent call last):
    File “/usr/lib/python3.5/”, line 914, in _bootstrap_inner
    File “/usr/lib/python3.5/”, line 862, in run
    self._target(*self._args, **self._kwargs)
    File “”, line 35, in sensorsimulator
    x = client.connect(host, port)
    File “/home/pi/.local/lib/python3.5/site-packages/paho/mqtt/”, line 937, in connect
    return self.reconnect()
    File “/home/pi/.local/lib/python3.5/site-packages/paho/mqtt/”, line 1100, in reconnect
    File “/usr/lib/python3.5/”, line 996, in do_handshake
    File “/usr/lib/python3.5/”, line 641, in do_handshake
    ssl.SSLError: [SSL: SSLV3_ALERT_HANDSHAKE_FAILURE] sslv3 alert handshake failure (_ssl.c:720)

    Tried googling not able to find out the root cause or a solution. _ Can you help me ?

    1. I noticed you used
      are you using authentication and certificates? If so have you tried without them

      1. Hi Steve,
        Thanks for your response. I had disabled the password based authentication and tested only with certificate and the problem is still there.
        My observations.
        1. This problem is seen only with Raspberry Pi, on windows the same python program which uses paho library is working fine with Certifcate and Password based authentication
        2. Same is working on ESP8266 with password and certificate.
        3. I When I disable the certificate and use only password based authentication the it works on Raspberry Pi. But I cannot use as the user name and password are transmistted as clear text in MQTT.
        For the deployment I Am working, I need to User name and password plus, TLS .

        My guess is the TLS library with RPi is having a bug


  19. Hi Steve,
    Thanks for all these helpful informations about this subject. I use a broker and a publisher on same machine, Raspberry Pi and have a subscriber on Windows machine. I followed your descriptions and it worked fine in command prompt.
    I can also publish with python script on Raspberry and get the message on Windows command prompt. (C:\Program Files\mosquitto>mosquitto_sub -h -t konu –cafile certs/ca.crt -p 8883)
    But my can not see the message despite using tls.set() method. I see an error like this:

    ssl.SSLCertVerificationError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: IP address mismatch, certificate is not valid for ‘’. (_ssl.c:1076)

    Here is my

    import paho.mqtt.client as mqtt

    def on_message(client, userdata, msg):
    print(msg.topic + ” ” + str(msg.payload))

    def on_disconnect(client, userdata, rc):
    mqtt.connect(“”, 8883, 60)
    #mqtt.connect(“”, 1883, 60)

    def on_connect(client, userdata, flags, rc):

    mqtt = mqtt.Client()
    mqtt.tls_set(“c:/Program Files/mosquitto/certs/ca.crt”,tls_version=2)
    mqtt.on_disconnect = on_disconnect
    mqtt.on_connect = on_connect
    mqtt.on_message = on_message
    mqtt.connect(“”, 8883, 60)


    Note: I had a copy of ca.crt which I created on Raspberry C:\Program Files\mosquitto\certs\ca.crt on Windows

    Thank you so much again i’ll be waiting for your return.

    1. Hi
      It is because you are using the ip address and not the name that is on the certificate
      uncomment this line.
      If it works then that is the reason

      1. Step 4 :You could use the IP address or Full domain name. You must use the same name when configuring the client connection.

        As you mentioned above i used my broker’s ip adress as common name on step 2 and step 4. I also uncomment the line you said but it didnt work. What should I do now? I appreciate your help..

        Note: I want you to remind that it worked fine for command prompt but it doesn’t work with subscriber python script.

        1. Hi
          remove the tls version here
          mqtt.tls_set(“c:/Program Files/mosquitto/certs/ca.crt”,tls_version=2)
          Can you use the ask steve page if you still have errors and we can deal with it with email as it s easier

  20. Hi,
    I created the tls certificate as per your tutorial. while trying mosquitto_pub –cafile /etc/mosquitto/certs/ca.crt -p 8883 -h -t ‘test’ -m “tstmsg” –insecure
    I am getting A TLS error occurred.

    Could you help me to resolve this problem.

    This is my configuration file.

    persistence_location /var/lib/mosquitto/

    log_dest file /var/log/mosquitto/mosquitto.log

    #port 1883
    #listener 1884

    port 1883
    listener 8883

    require_certificate true

    #tls_version tlsv1.1

    cafile /etc/mosquitto/certs/ca.crt
    keyfile /etc/mosquitto/certs/server.key
    certfile /etc/mosquitto/certs/server.crt

      1. Hi steve,

        Thanks for the help.

        I am able to connect using python with ssl. In case of java able to connect normally but not with tls., can you refer some sample application for java.

  21. Have setup mosquitto on AWS ES2 and on the same machine mosquitto_sub without -cafile connection is fine, with inclusion New connection from on port 8883.
    1572703961: Client disconnected due to protocol error Any help would be appreciated.
    Followed all above said steps, and in this case ca.crt would be the same fine..

      1. Thanks for the response, tested with broker and client on the same machine, this means same ca.crt file, still the same error. Without SSL the setup is working just fine,


        1. I had same issue and this was caused by “listener” in mosquitto.conf file. I have replaced “listener 8883” with “port 8883” and it worked.

  22. hey steve, thank you for this tutorial
    i want to ask how to subscribe the topic from other device using mosquitto mqtt tls? i try to add command “–cafile certs\ca.crt” to subscribe, but it doesn’t work
    cause i want to subscribe from other device
    I’ve install and configuring tls too from other device, but it doesn’t work to subscribe

      1. I use rasp pi for publisher and PC for subscriber,
        If sending message without tls it work normally , but in this problem I want to sending message with TLS,
        Can you tell me, how to subscribe for other device?
        Sorry my english so bad

  23. Hi Steve,
    I really enjoy your tutorials and insight to the MQTT topic. How would this certificate process be different if you want to use an F5 load balancer to offload the TLS workload?

    1. Glad You find the tutorials useful but sorry I can’t offer any insights into the question as I’m not really involved with load balancing.

  24. Hi Steve.
    I use vitural server AWS EC2 and mosquitto , when i create CA key , i put the common name ( random , ex mytest ) , in Server.crt I put common name is public DNS of server , but when i test with MQTTFx it not working with error:
    1568099939: New connection from on port 8883.
    1568099939: Socket error on client , disconnecting.
    And MqttFx show MQTTException.
    How can i fix it?

    1. Hi
      Have you tried using mosquitto_pub tool?
      You would need to send me your files and access details for me to take a look. You can use the ask steve page.

  25. Thank you so much for the great article. Beside SSL or username/Password authentification can I use other authentification factors? if it’s possible how can I modify the mosquitto.conf file ? thank you in advance.

  26. Hi Steve,
    Thanks a lot for all your great articles on MQTT.
    I followed your instructions, except the commen name in step 2 and step 4 is I use the ip address. Everything is fine, I check on MQTT.fx quite perfectly, but when I check on it is not very good.
    On, I only set up the “HOST” as the server’s ip address and “SSL/TLS Certificate Type” the type is: CA signed server certificate. I haven’t been able to issue CA.crt yet, it can connect. Can you explain help me? Thank you very much.

    1. Not sure as I don’t use either of those tools. It may be using port 1883. Take a look to see if it is enabled on the broker.

  27. If I am running mosquitto on ‘localhost’, can I use the same (localhost) for my server certificate common name?
    Each help would helpful.
    Best Regards,

    1. Hi
      The name you use is the name you would use when you ping the machine from another machine on the network.
      Because many home/test networks don’t use dns then you could use the ip address or if it is a windows network the computer name.
      For a test network you can also tell the client to ignore the common name which isn’t secure but it isn’t a problem on a test network
      If you use the name localhost it will not work correctly from another machine.

  28. I am trying to connect with TLS 1.2 to CloudMqtt Broker which I can do w/o a problem when no security protocol involved…(using M2Mqtt library)

    You said that:
    In this case we only need a trusted server certificate on the Client.
    We do not need to create client certificates and keys but this is covered in Creating and Using Client Certificates with MQTT and Mosquitto
    So how the MqttClient constructor should look like?
    I tried this and it goes through… but later the Connect call throws communication exception:

    X509Certificate caCert = X509Certificate.CreateFromCertFile(mCaServerCertFIle);
    //X509Certificate clientCert = X509Certificate.CreateFromCertFile(clientCertFile);

    mqttClient = new MqttClient(serverProfile.ServerAddress,

    1. Leon
      You only need to use the ca from cloud mqtt which is on your machine as it is a public ca.
      However you can also download it as I needed to do with Python. here is what they say:


      How do I connect using TLS (SSL)? Where do I find cert and key files?

      If you connect by TLS/SSL, add –capath or –cafile and point it to a cert store. Our server cert is signed by Comodo, which has the AddTrust CA as root. Most OSs comes with it by default, so can you point to your default trust/CA store. (example: –cafile=/etc/ssl/certs/ca-certificates.crt) If you don’t have a trust store you can download the AddTrust/Comodo root cert from

      More information can be found here, under Certificate based SSL/TLS Support. You also need to use the port for MQTT over TLS (see above).
      I would download it and then get it to work that way.
      Let me know how you get on

  29. After the fifth step this is the error I am getting:
    unable to load CA Private Key
    1995601392:error:06065064:digital envelope routines:EVP_DecryptFinal_ex:bad decrypt:../crypto/evp/evp_enc.c:536:
    1995601392:error:0906A065:PEM routines:PEM_do_header:bad decrypt:../crypto/pem/pem_lib.c:439:
    Why does this error occur?

    1. Is this error occurring when you execute the command in step 5?
      openssl x509 -req -in server.csr -CA ca.crt -CAkey ca.key -CAcreateserial -out server.crt -days 360


        1. Hi
          You probably made an error in an earlier step. The easiest thing is to start again and see if it works.

  30. Hi Steve, thank you so much about SSL posts. I have a question about hostname, I use IP address for CA, and I know the hostname CA need to match. But have a problem, my address is dynamic and it can’t match anytime. You said we could use –insecure to ignore checking it with python, but I use Node-red on each server. How can I pass it without checking the hostname, thank you so much!

    1. Hi
      There is an option on the ssl settings of the mqtt node called verify server certificate. This is the same as the insecure option.

  31. Great tutorial. Could the client certificate be created from the server certificate instead of from the CA certificate (if we want to be able to generate certificates dynamically on the server but not store the CA key there)?

  32. Hello Steve,
    first of all thank you for your work. I followed every step and installed mosquitto on a raspberry pi (jessie). At the moment I can’t get it to work, so ask for your help.
    Some information:
    – my broker certificate common name is fsMQTTbroker and my CA certificate common name is fsCA
    – my raspi has manually assigned IP (
    – the internet connection works
    – my mosquitto.conf is the following:
    d_file /var/run/
    persistence true
    persistence_location /var/lib/mosquitto/
    log_dest file /var/log/mosquitto/mosquitto.log
    port 8883
    cafile /etc/mosquitto/ca_certificates/ca.crt
    keyfile /etc/mosquitto/certs/server.key
    certfile /etc/mosquitto/certs/server.crt
    tls_version tlsv1

    The problem is:
    – when testing with
    mosquitto_pub -h fsMQTTbroker -t topic/example –cafile /etc/mosquitto/ca_certificates/ca-crt -m “test” -d
    i get the error “Unable to connect (Lookup error.).”
    – when I try
    mosquitto_pub -h fsMQTTbroker -t topic/example –cafile /etc/mosquitto/ca_certificates/ca-crt -m “test” -d
    i get the error
    Client mosqpub|2261-raspberryp sending CONNECT
    Error: host name verification failed.
    OpenSSL Error: error:14090086:SSL routines:SSL3_GET_SERVER_CERTIFICATE:certificate verify failed
    Error: A TLS error occurred.

    every suggestion will be useful.


    1. Didn’t spot a difference in the commands used.
      The name or ip used to connect to the broker must match the common name on the certificate otherwise you get that error.
      There is a –insecure option that tells the client to ignore that check. Use this to see if it works

  33. hey! great tutorial but i didn’t get it to work. Not sure what I am doing wrong…
    My set up is using MQTT.Fx to access the broker @

    1- Lets say the name of my pc is “My-PC” and the server I want to connect to is “”. Would I enter “My-PC” in the common name for CA.crt and enter “” in the common name for server.crt??

    2- when asked to add extra fields (optional password etc.) I just press enter and move along. I don’t bother putting a period there…is that ok?

    3- Then when I have completed generating CA and signing the server certificate, I would open MQTT.Fx and use the signed ca.crt with the broker address “” and use “My-PC” as the client name. Is that correct?

    Thanks for looking!

    1. 1.The common name of the server.crt should match the domain name of the server that it is installed on.
      The name of your PC isn’t important and not used on the certificates. The common name for the Ca would be usually be a company name.
      2. Hitting enter should be ok
      3.yes but the client name could be anything.

  34. Hi Steve,
    Your tutorial is excellent!
    I have followed all the steps and it feels that everything is going well. However, I have a problem that I am trying to resolve.
    When I run your script to check the paho client I get the following error:
    “Traceback (most recent call last):
    File “Desktop/”, line 21, in
    client1.tls_set(‘/Home/Downloads/Python-3.6.1/mqtt-demos/ca.crt’, tls_version=2)
    File “/usr/local/lib/python2.7/dist-packages/paho_mqtt-1.4.0.dev0-py2.7.egg/paho/mqtt/”, line 772, in tls_set
    IOError: [Errno 2] No such file or directory”

    I have installed Python-3.6.1, while python 2.7 was already installed on Ubuntu. Does the cause of the error is that I installed paho client on Python-3.6.1 and not on python 2.7?

    Thank you in advance!


    1. Tks for the nice comment
      It could be. When you have multiple versions of Python when you do a PIP
      install it might get installed for the new version.
      You need to check if the mqtt client is installed for 3.6 which you can do
      by using
      pip show paho-mqtt
      to see where pip will install use
      pip –version.

      Can you confirm that you can pub/sub without ssl?
      You also need to check the location of you ca file when using ssl
      You might find this useful
      I created it because I had the same problems when I started.
      Let me know how you get on

  35. Hi Steve!
    THANK YOU for this really cool howto! It works great!
    I have a question:
    When i verify and sign the server certificate with “-days 360”, does this mean, that i have to update the files on the clients physically every 360 days?
    Please don’t lought, my client are 100 km away. I don’t want to go there by car.
    I’m the absolute dud on such server things, so …
    Greetings from austria!

  36. Steve,
    When apply this: openssl req -new -x509 -days 1826 -key ca.key -out ca.crt
    I get some error like this:
    Enter pass phrase for ca.key:
    Can’t load ./.rnd into RNG
    7240:error:2406F079:random number generator:RAND_load_file:Cannot open file:cryp
    You are about to be asked to enter information that will be incorporated
    into your certificate request.
    What you are about to enter is what is called a Distinguished Name or a DN.
    There are quite a few fields but you can leave some blank
    For some fields there will be a default value,
    If you enter ‘.’, the field will be left blank.
    Country Name (2 letter code) [AU]:CN
    State or Province Name (full name) [Some-State]:Guangdong
    Locality Name (eg, city) []:ShenZhen
    Organization Name (eg, company) [Internet Widgits Pty Ltd]:Harman
    Organizational Unit Name (eg, section) []:Pro T&V
    Common Name (e.g. server FQDN or YOUR name) []:Yongxiang
    Email Address []
    Looks like I can get the ca.crt, but How can I resolve the error?
    I use the laptop do this, OS is win7 64BIT

  37. Has anyone been able to solve the “tlsv1 alert unknown ca” message? I’ve been through the tutorial several times and can not find out what is causing the problem.
    Error: A TLS error occurred.

    1540843163: New connection from on port 8883.
    1540843163: OpenSSL Error: error:14094418:SSL routines:ssl3_read_bytes:tlsv1 alert unknown ca
    1540843163: OpenSSL Error: error:140940E5:SSL routines:ssl3_read_bytes:ssl handshake failure
    1540843163: Socket error on client , disconnecting.

  38. Hey,
    I justed wanted to say thanks for the tutorial. It was the only one the net which let me enable secure communication successfully 🙂 I think the other instructions fail to mention how important the domain is. I added the local ip address and it worked just fine. I also tested it with home assitant and it worked 🙂

    So, a big thank you for this!

    best regards

  39. Hi Steve , just to clarify ,from a comment made by vicky on 11 April 2018 , it was mentioned that if the input field of step 2 and step 4 were identical , the ca.crt would not work ,hence only the server.crt is applicable. If the input fields of step 2 and 4 were of different values , it means that the ca.crt would work fine without error?Further more if i am using mosquitto library , can the ca.crt and server.crt certificates be used? Or is there a need to create a pem version?


    1. Yes if the forms ca.crt and server.crt are identical then it can cause problems.
      The server.crt is not applicable as it need a ca.crt on the client so you would be best to create the and server.crt again.
      You don’t need a pem version as you aready have one as pem is encoding and I ‘m pretty sure the tutorial create a pem version. See this guide

      1. Hi, steve
        thanks for explaining , so i can assume that ca.crt = ca.pem? i googled and some people are using the .pem and i am getting a little confused


        1. Yes and no. The easiest way is to open the certificate in a text editor and if you can read it and it starts with BEGIN CERTIFICATE the it is in perm format.
          I was as well confused by all of the different extensions as there isn’t really a fixed relationship.
          On your own setup I would stick to the .crt and .key extensions which seem more common.
          If you have a ca.pem certificate then you can rename it to ca.crt and it will work as normal.

          1. Hi, thanks for explaining once again.Followed your guide and it work . However ,when i tried using openssl (s_client -connect domainname:8883 -showcerts) to test the connectivity, i was return with an error,
            “Verification error: self signed certificate in certificate chain” . Can i seek your opinion and guidance on this?


  40. Hi steve
    I have a question about mqtt security at all. As we know MQTT designed the way that any client who subscribe to a topic can receive the messages that publish on that topic. So a question is that in a big network with lots of users and devices connected to that how should we prevent a user to sniff or publish messages to other users devices? for example we have user1 with device1 belonging to that and user2 with device2. for example we have a topic for device1 that lets user1 control it, how should we prevent user2 which is connected to that broker to publish or subscribe to device1 topics? considering there’s lots of devices and users.
    Thanks in advance

    1. Any security you will need to build into the clients like using access tokens etc. However the brokers also provide various degrees of security like ACLs and username and passwords.
      Personally I like message encryption as it is end to end see here

      1. Thanks for your articles and answering questions. Those were great. I agree with you, message encryption is a better way to go but we should also use TLS if we want to secure the topics as well. Also considering that ACLs and username and passwords need another service to control the brokers resources

          1. Yes that’s a good way. Just a problem is that if some one sniffs the packets, can find the topic and start to send huge data to that topic and cause the devices not to work properly.

  41. If you’re getting “Socket error on client , disconnecting.” you should look in your config if allow_anonymous is set to False. In this case, using certificate, set it to True or provide username during logging.

  42. I was using certificate generation process mentioned on CentOS 7. Configured mosquitto for websockets, when starting mosquitto broker, I am getting ‘OpenSSL doesn’t support ECDH’ error.

    1. Both are certificates. You can consider them as the same as passports.
      The server certificate contains the public keys for that server.
      The CA certificate contains the public keys of the certificate authority which can be self signed or signed by an higher certificate authority.
      The ca private signature key is used to sign the server certificate. It is the trusted authority.
      When a client connects to a server to use SSL the server sends the client its certificate which contains its public key (which has been signed by a CA (trusted authority) and the client uses the public signature key in the CA certificate to verify that the server public key is valid.
      For this to work the client must have a copy of the CA certificate.
      CA certificates for public certificate authorities like verisign are included with your browser.
      Does this make sense?

      1. OK got it ..Thank you. Is it possible to provide client side authentication using MQTT ? I read to your reply ,it says – YES but complexity is more. I want to know whats the complexity inovolved?

  43. Hey Steve, thanks for this great tutorial, it was my starting point in securing my mosquitto broker communication. Just a question, do you think its a good idea to buld and use for each client a different private key (ca.crt)? Additionally I want to use user-id and password autentification.

    Kind regards,

    1. The Ca.crt is the certificate authority certificate and Usually you only use 1 for all your clients.
      You can use certificate authentication which means giving each client it’s own key but It would probably be too difficult to manage and I haven’t tried it.
      The tutorial for username password is here
      I would recommend getting ssl to work then getting username./password to work and then combine them at the end

  44. Hi Steve,

    Really helpful article. I followed all the steps listed but I am receiving an error that says “Error: Problem setting TLS options”. The command I am running is mosquitto_sub -t home/livingroom -v -d –cafile ca_certificates/ca.crt -h -p 8883. The CN on both CA and server certificate is I also tried using the option –tls-version tlsv1.

    My mosquitto.conf file has the following contents
    port 8883

    cafile /etc/mosquitto/ca_certificates/ca.crt
    keyfile /etc/mosquitto/certs/server.key
    certfile /etc/mosquitto/certs/server.crt
    tls_version tlsv1

    Can you point out where I could be going wrong?

    Thank you.

    1. Try the full path for the certificate file and also try the –insecure option and comment out the tls_version in the conf file otherwise looks ok

    2. Im my case I had to put the mqtt version as well:

      mosquitto_sub -V mqttv311 -h -p 8883 -t “test” –cafile /etc/mosquitto/ca_certificates/ca.crt


      mosquitto_pub -t “test” -m “hi2” –cafile /etc/mosquitto/ca_certificates/ca.crt -p 8883 -h “raspberrypi” –insecure -V mqttv311

      (@Steve: Great tutorial!)

  45. In log i get error: Error: Unable to load CA certificates. Check cafile “/root/jbre/SSL/ca.crt”
    I i comment out server.key it loads mosquitto or if i comment out ca.crt, mosquitto works, so i guess those two files are not compatible….hm… i did generate keys with step 2 and 4 with slightly different value… but i also leave some fields empty, like mail, maybe thats problem?

  46. Hey.
    First, really nice and useful blog. So i did everything exactly like you wrote in this configuration but when i try to connect with client to broker i get “Error: Connection refused”. I am trying simple with “mosquitto_sub -d -v -h –insecure –cafile /home/ubuntu/jbre/SSL/ca.crt -t test -p 8883”.

    Maybe any idea?
    Thank you in advance.

    1. Connection refused is often when you use the wrong port or IP address the command you are using looks OK I would check the broker.

      1. Thank you for fast answer. I see now that when i add in mosquitto.conf cafile, certfile, keyfile mosquitto broker can’t start or is in failed status:
        Jun 28 07:07:19 kibernetmq mosquitto[1776]: 1530169639: mosquitto version 1.4.15 (build date 2018-05-05 12:54:33+0000) starting
        Jun 28 07:07:19 kibernetmq mosquitto[1776]: 1530169639: Config loaded from /etc/mosquitto/mosquitto.conf.
        Jun 28 07:07:19 kibernetmq mosquitto[1776]: 1530169639: Opening ipv4 listen socket on port 8883.
        Jun 28 07:07:19 kibernetmq systemd[1]: mosquitto.service: main process exited, code=exited, status=1/FAILURE
        Jun 28 07:07:19 kibernetmq systemd[1]: Unit mosquitto.service entered failed state.
        Jun 28 07:07:19 kibernetmq systemd[1]: mosquitto.service failed.

        When i comment this lines out mosquitto starts normally and is active:
        Jun 28 07:06:46 kibernetmq mosquitto[1766]: 1530169606: mosquitto version 1.4.15 (build date 2018-05-05 12:54:33+0000) starting
        Jun 28 07:06:46 kibernetmq mosquitto[1766]: 1530169606: Config loaded from /etc/mosquitto/mosquitto.conf.
        Jun 28 07:06:46 kibernetmq mosquitto[1766]: 1530169606: Opening ipv4 listen socket on port 8883.
        Jun 28 07:06:46 kibernetmq mosquitto[1766]: 1530169606: Opening ipv6 listen socket on port 8883.

        Any idea?
        Thanks again,

        1. The most likely cause is that it can’t find one of the files or there is a syntax error in the conf file.
          When testing I would start the broker manually from the command line using
          mosquitto -c myconfile.conf.
          Place the myconfile in the home directory as it is easier than having to edit the conf file in the etc folder.
          You can move it there when done.

        2. Btw in mosquitto.conf i only have:
          port 8883
          cafile /root/jbre/SSL/ca.crt
          certfile /root/jbre/SSL/server.crt
          keyfile /root/jbre/SSL/server.key
          require_certificate true

  47. Some stuff i found out following your tutorial:
    – Common name MUST be you computer name. I couldn’t find out how to use wildcards to make it work on a PC in a domain (PC at work), but on a non network managed computer (my home computer) it finally worked.

    – If you set ‘tls_version tlsv1’ in the mosquitto.conf file, you MUST use ‘–tls-version tlsv1’ on the pub/sub command line or it will default to TLS v1.2
    > mosquitto_sub -h DESKTOP-09SCS82 -p 8883 –cafile ca.crt -t hello/world –tls-version tlsv1

    1. Quick update, got it working on a managed network. Here’s the deal, your System window (windows key + pause break) has three informations:
      – Computer Name
      – Full Computer Name
      – Domain

      You should use “*” as your CN so you can estabilish a connection from every computer in the network that has the certifcate. When stabilishing a connection, your host must be the “Full Computer Name” information like mosquitto_sub -h -p 8883 –cafile ca.crt -t hello/world –tls-version tlsv1

      1. Thank you so much! This solved my issue.
        Common name is so important. When generating Certificate Sign Request, we have to use “*” or “” as the common name. Then when doing the client connection, host has to be “”.
        That is how the TLS certificate works!

  48. If you’re seeing this error: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed

    I’d suggest use the server.crt on the client side. Someone named Vicky from comments above has explained why it could be the thing.


  49. when I run mosquitto broker I don’t get
    “enter pem passphrase:” prompt as I have seen in other youtube video.

    1. It is because you have password protected one or more of the files.There is a note in the tutorial about this. It should still work ok

  50. I tried wireshark to see where it is going wrong and found that
    Server hello is successfully done
    Client sends Client key Exchange, Change Cipher spec, Encrypted handshake Message
    that Server replys with RST and abruptly drops communication

  51. Steve
    Thanks for reply, yes I tried –insecure I didn’t try paho-client, yes broker is running on Windows,
    I have checked following things
    – firewall is not blocking TCP traffic
    – tried different port number
    – running mosquitto_pub on separate admin cmd (console window) ,
    – running mosquitto_pub on vmware
    – can establish mqtt communication without TLS/SSL
    – make sure that password file is not mentioned and password required is off
    – make sure allow allow_anonymous true (i.e default but tried explicitly set)

    Difference from defualt/original mosquitto.conf is following
    – #port 1883 -> port 8883
    – cafile c:\mosquitto\certs\ca.crt
    – keyfile c:\mosquitto\certs\server.key
    – certfile c:\mosquitto\certs\server.crt
    tried server key with/without passphrase

    I have Win32OpenSSL-1_1_0g installed.
    from this installation I have copied following dlls to mosquitto folder

    I have run following command and don’t get any error except
    openssl s_client -showcerts -connect MyTest-PC:8883

    Protocol : TLSv1.2
    Verify return code: 18 (self signed certificate)

    1. I have found the problem after debugging through mosquitto and openssl source code.
      When creating CA and Server certificate I provided exactly same (I mean exactly identical input for all fields) detail in step 2 and 4. If we do this then SSL thinks it is single certificate solution, and compare ca.crt and server.crt because both have different SH1 thumbprint so it fails it. in this case if we use same certificate (i.e server.crt ) both on client and server then it probably works. Here in this article example slightly different information is provided, for example field “organization name” has different value provided in step 2 and 4, this is crucial even single character difference will work fine 🙂 and I failed to notice this, on a bright side it gave me chance to look into source code mosquitto broker and openssl source code 🙂

      1. Tks for that I do remember a while ago reading something about that but it wasn’t really that clear. I’ll update the tutorial to make everyone aware.

        1. Hi , regarding to what vicky said , does it mean that as long the input for all field are different in step 2 and 4 in mosquitto_pub i can call ca.crt instead of server.crt ? Currently it works without error when i use server.crt

          1. Hi
            Only one field needs to be slightly different.On the client you use the ca.crt certificate not the server .crt

  52. I followed steps in this tutorial. Tried out on Windows.
    I am getting error
    ” New connection from on port 8883″
    “Socket error on client , disconnecting.” on server and on client side I get “A TLS error occured”.
    I am using CN=My computer name where I am rung mosquitto server. I tried client from VMWare and on same local machine where mosquitto sever is running both gives same error.

    1. Use the tls_insecure_set(True) on the python client or the –insecure switch in the mosquitto_pub tool.
      To eliminate problems with the server name on the certificate.
      Is your broker also running on Windows?

  53. Hi Steve, I am having some problems with this. Perhaps a second pair of eyes would help:

    My key generation process is basically a copy paste of the commands you have in your setup. The only change I have is instead of using ws4, I am using my local computer name (computer name is ubuntu)

    The same computer is running the MQTT Broker and the Client:

    My configuration file TLS section is as follows:
    listener 8883
    cafile /home/edyza/Desktop/tls/ca.crt
    keyfile /home/edyza/Desktop/tls/server.key
    certfile /home/edyza/Desktop/tls/server.crt
    require_certificate false
    tls_version tlsv1

    Here is my python code:
    import paho.mqtt.client as mqtt
    import ssl

    broker = “ubuntu”
    port = 8883

    def on_connect(client, userdata, flags, rc):
    print(“Connected with result code “+str(rc))
    client.subscribe(“#”, qos=1)

    def on_message(client, userdata, msg):
    print(msg.topic+” “+str(msg.payload))

    def on_log(client, userdata, level, buf):

    id = “123456123456”

    client = mqtt.Client(
    client_id=””, clean_session=True, userdata=None, protocol=mqtt.MQTTv311

    client.on_log = on_log
    client.on_connect = on_connect
    client.on_message = on_message

    ca_certs=”/home/edyza/Desktop/tls/ca.crt”, tls_version=ssl.PROTOCOL_TLSv1

    client.connect(broker, port)

    Here is my traceback:
    Traceback (most recent call last):
    File “/home/edyza/edyza-gateway/server/mqtt_services/mqtt_bridge/mqtt_bridge/”, line 36, in
    client.connect(broker, port)
    File “/home/edyza/miniconda3/envs/mqtt_bridge/lib/python3.5/site-packages/paho/mqtt/”, line 768, in connect
    return self.reconnect()
    File “/home/edyza/miniconda3/envs/mqtt_bridge/lib/python3.5/site-packages/paho/mqtt/”, line 927, in reconnect
    File “/home/edyza/miniconda3/envs/mqtt_bridge/lib/python3.5/”, line 996, in do_handshake
    File “/home/edyza/miniconda3/envs/mqtt_bridge/lib/python3.5/”, line 641, in do_handshake
    ssl.SSLError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:719)

    And the error message from console of the broker is:

    edyza@ubuntu:~/edyza-gateway$ mosquitto -c ./server/configs/mosquitto.conf -v
    1520979358: mosquitto version 1.4.15 (build date Wed, 28 Feb 2018 11:29:47 +0000) starting
    1520979358: Config loaded from ./server/configs/mosquitto.conf.
    1520979358: Opening ipv4 listen socket on port 8883.
    1520979358: Opening ipv6 listen socket on port 8883.
    1520979359: New connection from on port 8883.
    1520979359: OpenSSL Error: error:14094418:SSL routines:ssl3_read_bytes:tlsv1 alert unknown ca
    1520979359: OpenSSL Error: error:140940E5:SSL routines:ssl3_read_bytes:ssl handshake failure
    1520979359: Socket error on client , disconnecting.

    I know this is a lot of trace to parse, but can you please point me to the right direction here?

    1. Hi Steve, I think there is a typo in the tutorial. When I change the line in my python code from




      Everything works as I expect it to

      1. Hi
        The text in the tutorial is correct it should be the CA certificate on the client. However what you call it is really up to you.
        I think that maybe you got the files mixed up. I did it several time when I was creating the files for various machines.

  54. Thanks, a really great blog for using TLS/SSL.

    When following the steps, I got the following error messages when I use ca.crt on the client PC.
    1520070804: OpenSSL Error: error:14094418:SSL routines:ssl3_read_bytes:tlsv1 alert unknown ca
    1520070804: OpenSSL Error: error:140940E5:SSL routines:ssl3_read_bytes:ssl handshake failure

    After changing ca.crt to server.crt, I can sub/pub message from the client.

    1. Frank, you are a lifesaver!
      I recently got an android update on my phone (9 to 10), and suddenly all TLS connections failed. Internal network connections kept going fine, so obviously an TLS or cert problem. I’ve been unsuccessfully trying new code for a day or 2, until I stumbled on this remark! This did the trick for me as well. I would still like to know what the trigger is, but for now I’m going to enjoy the euphoria of having a working app again!

      ps. Thanks Steve for hosting such a great blog.

  55. Hi,

    When i use my mac (client) to send mosquitto_pub -h -t hello/world -p 8883 –cafile /Users//ca.crt -m “hello”
    Error: A TLS error occurred.

    The MQTT broker is returning
    OpenSSL Error: error:14094418:SSL routines:SSL3_READ_BYTES:tlsv1 alert unknown ca
    1517743023: OpenSSL Error: error:140940E5:SSL routines:SSL3_READ_BYTES:ssl handshake failure

    Note i set the CN to the IP address of my Pi (MQTT broker), when generating the certs, because with the name of the pi was causing a resolve error. The mac (client) has the exact copy of ca.crt.

    Do you know what might be causing this? It looks like the server is not accepting the CA that im sending, but it is the one I generated earlier?

    1. I was having same issue. It was corrected after giving different email id for ca certificate and server certificate.

  56. Hi Steve,
    Thanks a lot for all your great articles on MQTT.
    I would like to check with you, if it is possible to set up MQTT (mosquitto broker) with TLS1.2 and the OCSP Stapling is enabled ?
    If I’m getting a TLS certificate from a valid CA (not to create one on my own) for this purpose, do you think it will work without any additional configuration in Mosquitto broker ?

    1. Sorry but I’m not really sure. As far as I am aware the python client doesn’t check and I don’t think it is supported by mosquitto as it is.
      The certificate might work but not with OCSP. I’d be interested to hear how you get on

  57. How to use TLS connection via web client? In javascript library “mqttws31.js”, there is only an option named:useTLS, but no parameter to import ca.crt file, anyone can answer me? thanks.

    1. I think it is because the script uses the certificate store of the browser and so you would need to import the certificate into your browser.
      If it isn’t trusted then you should get an error.

  58. Hi Steve,
    Thanks for the valuable info.
    Do you have any inputs for using the client certificates on IOT devices?


    1. Personally I don’t think devices like sensors will use SSL, especially initially as most are likely to use other protocols other than MQTT.
      I think it will be important between brokers i.e. from the MQTT gateway to the cloud.

  59. My system is

    mosquitto version: 1.4.13 (build date 2017-07-01 11:06:40+0000)

    Firstly, i created a folder where /etc/mosquitto/certs
    Then respectively

    1- openssl genrsa -des3 -out ca.key 2048
    2- openssl req -new -x509 -days 1826 -key ca.key -out ca.crt
    3- openssl genrsa -out server.key 2048
    4- openssl req -new -out server.csr -key server.key
    5- openssl x509 -req -in server.csr -CA ca.crt -CAkey ca.key -CAcreateserial -out server.crt -days 360

    i used hostname for certificates with my domain ip adress

    My mosquitto.conf
    cafile /etc/mosquitto/certs/ca.crt
    keyfile /etc/mosquitto/certs/server.key
    certfile /etc/mosquitto/certs/server.crt
    require_certificate false
    tls_version tlsv1

    i can try to connect mosquitto with;
    mosquitto_pub -h “mydomainipadress” -p 8883 -u “usernam” -P “password” -t temp –cafile /etc/mosquitto/certs/ca.crt -m “testmessage” -d

    This is giving me a errot which “A TLS error occurred.”

    I also try to connect with python3.6 with codes;
    import sys
    import time
    import mail
    import paho.mqtt.publish as publish
    import paho.mqtt.client as paho
    import ssl
    auth = {‘username’:”a”, ‘password’:”*”}
    def on_connect(client, userdata, flags, rc):
    global conn_flag
    conn_flag = True
    port = 8883
    while True:
    text = open(“info.txt”,”r”)
    t = text.readline(2)

    and it gives me a error too like

    File “/usr/lib64/python3.6/”, line 1061, in do_handshake
    File “/usr/lib64/python3.6/”, line 683, in do_handshake
    ssl.SSLError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:749)

    Where am i doing wrong? Can anybody help me ?

    1. You could try the tls_insecure_set(True) on the python client to rule out the domain name on the CA certificate.
      the python error code seems to point to CA file problems
      You should check your mosquitto.conf file that it matched mine in the tutorial.
      The main problems I encountered were the wrong version number and the name on the certificate.
      You are using username/password. I like to test without to make it simpler as I also encountered lots of problems that caused it to fail that were not ssl related.
      If you still have problems you can send me your certificate files and I can try them on my test machine.

      1. I tryed before that tls_insecure_set, without password_file but it still doesn’t work. If you send me your mail adress i can send you certificates.

        1. Oguz fixed the problem as follows:

          I found what where is the problem. Main problem is that openssl version. When i updated openssl version and created new certificates that problem has gone on centos 7. Centos has openssl verison date in 2013 with default, we need to update.

  60. I would like to get this working using a wildcard certificate. I have gotten past the TLS errors and managed to crank up the websocket logging, but I can’t figure out why the broker is dropping mosquitto_sub and mosquitto_pub. I can get to stay connected and pass messages, but not the bundled test tools.

    mosquitto_pub -h -p 8883 -t test –cafile /home/root/local_cert/COMODO_DV_SHA-256_bundle.crt -u “user” -P “password” -m “hello world”

    Details below :

    in mosquitto.conf
    websockets_log_level 2047

    Logs :
    1496460723: mosquitto version 1.4.8 (build date Tue, 23 May 2017 22:14:40 +0100) starting
    1496460723: Config loaded from /etc/mosquitto/mosquitto.conf.
    1496460723: Opening ipv4 listen socket on port 1883.
    1496460723: Opening websockets listen socket on port 8883.
    1496460723: Initial logging level 2047
    1496460723: Libwebsockets version: 1.7.1 unknown-build-hash
    1496460723: IPV6 not compiled in
    1496460723: libev support compiled in but disabled
    1496460723: LWS_DEF_HEADER_LEN : 1024
    1496460723: LWS_MAX_PROTOCOLS : 5
    1496460723: LWS_MAX_SMP : 32
    1496460723: SPEC_LATEST_SUPPORTED : 13
    1496460723: sizeof (*info) : 216
    1496460723: SYSTEM_RANDOM_FILEPATH: ‘/dev/urandom’
    1496460723: default timeout (secs): 20
    1496460723: Threads: 1 each 1024 fds
    1496460723: mem: context: 62808 bytes (58712 ctx + (1 thr x 4096))
    1496460723: mem: http hdr rsvd: 67712 bytes (1 thr x (1024 + 3208) x 16))
    1496460723: mem: pollfd map: 8192
    1496460723: mem: platform fd map: 8192 bytes
    1496460723: LWS_MAX_EXTENSIONS_ACTIVE: 2
    1496460723: mem: per-conn: 808 bytes + protocol rx buf
    1496460723: canonical_hostname = ip-172-31-9-197
    1496460723: Compiled with OpenSSL support
    1496460723: Using SSL mode
    1496460723: SSL ECDH curve ‘prime256v1’
    1496460723: insert_wsi_socket_into_fds: 0x16056b0: tsi=0, sock=8, pos-in-fds=1
    1496460723: Listening on port 8883
    1496460732: accepted new conn port 61718 on fd=9
    1496460732: Accepted 0x16060f0 to tsi 0
    1496460732: lws_adopt_socket: new wsi 0x16060f0
    1496460732: insert_wsi_socket_into_fds: 0x16060f0: tsi=0, sock=9, pos-in-fds=2
    1496460732: inserted SSL accept into fds, trying SSL_accept
    1496460732: SSL_accept failed 2 / error:00000002:lib(0):func(0):system lib
    1496460732: SSL_ERROR_WANT_READ
    1496460732: accepted new SSL conn
    1496460732: lws_header_table_attach: wsi 0x16060f0: ah (nil) (tsi 0)
    1496460732: lws_header_table_attach: wsi 0x16060f0: ah 0x15ee470: count 1 (on exit)
    1496460732: lws_server_socket_service: 0x16060f0: rxpos:0 rxlen:0
    1496460732: lws_server_socket_service: wsi 0x16060f0, ah->rxlen = 55
    1496460732: lws_read: incoming len 55
    1496460732: issuing 55 bytes to parser
    1496460732: WSI_TOKEN_NAME_PART ” (mode=0)
    1496460732: Unknown method – dropping
    1496460732: lws_parse failed
    1496460732: lws_header_table_detach: wsi 0x16060f0: ah 0x15ee470 (tsi=0, count = 1)
    1496460732: closing connection at lws_read bail:
    1496460732: lws_close_free_wsi: shutting down connection: 0x16060f0
    1496460732: lws_server_socket_service: wsi 0x16060f0 read -1
    1496460732: lws_close_free_wsi: real just_kill_connection: 0x16060f0
    1496460732: remove_wsi_socket_from_fds: wsi=0x16060f0, sock=9, fds pos=2, end guy pos=3, endfd=0
    1496460732: not calling back closed mode=0 state=2
    1496460732: lws_free_wsi: 0x16060f0, remaining wsi 1
    1496460761: mosquitto version 1.4.8 terminating

  61. In case this helps, I was running into those same errors as Kirk and Max (I am using mosquitto_pub/mosquitto_sub as the client) I was able to get it working by using the parameter ‘–cafile” rather than “–capath” and specifying the complete path to the cafile. Below is an example:

    mosquitto_pub -h -u username -P password -t test/topic -p 8883 –cafile ~/keys/ca.crt -m message

    Great tutorial Steve, many thanks!

  62. Running into the same issue like ‘Kirk Bailey’.
    Getin this strange error even though i did everything like you.
    I changed the TLS version to 1.1 and 1.2 but without success.
    If anybody solved this, i would appreacate your help.

    Cheers, Max

    1. Use the contact form and send me a screenshot of the broker console. If you send me your certificates and keys I’ll try them on my broker.
      I’ve been trying to reproduce your error. I get a similar one when using different CA files on client and broker. Have you copied over the broker CA to the client.
      Additionally the mosquiito_sub and pub programs default to version 1.2. If you use the python client it defaults to version1.
      If you are using the wrong version the consoles log tells you quite clearly the problem

        1. Can you describe exactly what error message you are seeing and how you are testing. Did you create your own certificates and keys?

          1. Installed the latest version of Mosquitto and Openssl on a server 2012 instance. Works fine, but now trying to enable TLS. I cannot get a purchased nor self signed certificate to work..

            Steps i’ve taken:
            I placed the certificates into a folder and set the following values:
            cafile C:\mosquitto\certs\ca.crt
            certfile C:\mosquitto\certs\server.crt
            keyfile C:\mosquitto\certs\server.key
            Changed the port from 1883 to 8883.
            restarted Mosquitto. It starts up without issue.

            Everytime i try to connect from a client, i get the following message:
            OpenSSL Error: error:14094416:SSL routines:ssl3_read_bytes:sslv3 alert certificate unknown
            OpenSSL Error: error:140940E5:SSL routines:ssl3_read_bytes:ssl handshake failure

            i re imported this certificate about 50 times now. i’ve tried every option possible. I’ve tried using .pem instead of .crt.

          2. Steve
            Here are the notes you sent me by email on how you got it working using a comado certificate.

            1) openssl genrsa -out verCert.key 2048
            2) openssl req -new -key verCert.key -out verCert.csr
            3) Submit the .csr to CA(in my case, its Comado) and complete the registration process.
            4) You will receive a email from Comado containing two files. Besides the .crt file, i also received back a “” file.
            5) open the “” file with notepad++.
            6) Two certificate files are inside the bundle file( Copy the text from the first one(from —–BEGIN CERTIFICATE—– to —–END CERTIFICATE—–) and create a new file called ca.crt with the contents.
            7) The 2nd .crt file is already enclosed in the email from Comado(file should be named (
            8) Copy all three files(ca.crt,, verCert.key) to your mosquitto cert folder.
            9) edit the mosquitto config file(make sure logging is enabled to help troubleshoot)
            Mosquitto config should have the following:
            cafile C:\mosquitto\certs\ca.crt
            certfile C:\mosquitto\certs\
            keyfile C:\mosquitto\certs\verCert.key
            port 8883
            tls_version tlsv1.2

            11) if all settings are correct, you should see valid connection info in the log files when connecting with your mqtt client.

  63. I tried using your certificate-generation technique because it’s simpler than the one that comes with the Mosquitto test code. If I run the broker using these certs, but when I try to connect a client, I get the error (at the broker) “OpenSSL Error: error:14094416:SSL routines:ssl3_read_bytes:sslv3 alert certificate unknown”. The client I used was the “mosquitto_sub” that comes with the package. Everything works if I instead use the certs generated by the cert-generation script that comes with the test code. Any idea why this would be? Do your certs work with your version of mosquitto_sub?

Leave a Reply

Your email address will not be published. Required fields are marked *