Home > front end >  Trying to use mosquitto broker with TLS using paho python
Trying to use mosquitto broker with TLS using paho python

Time:07-19

python code

import time
broker = "test.mosquitto.org"
port=8884
conn_flag= False
def on_connect(client, userdata, flags, rc):
    global conn_flag
    conn_flag=True
    print("connected",conn_flag)
    conn_flag=True
def on_log(client, userdata, level, buf):
    print("buffer", buf)
def on_disconnect(client, userdata, rc):
    print("client disconnected ok")
client1= paho.Client("control")
client1.on_log=on_log
client1.tls_set('C:\etc\mosquitto\certs\mosquitto.org.crt')
client1.on_connect = on_connect
client1.on_disconnect = on_disconnect
client1.connect(broker,port)
while not conn_flag:
    time.sleep(1)
    print("waiting", conn_flag)
    client1.loop()
time.sleep(3)
print("publishing")
client1.publish("house/bulb", "Test")
time.sleep(2)
client1.loop()
time.sleep(2)
client1.disconnect()

I am using the mosquitto.org.crt (PEM format) file gave by test.mosquitto.org, currently can't get to connect on port 8884, conn_flag is always false what should I do?

CodePudding user response:

As per http://test.mosquitto.org the ports are:

8883 : MQTT, encrypted, unauthenticated
8884 : MQTT, encrypted, client certificate required

In your code client1.tls_set('C:\etc\mosquitto\certs\mosquitto.org.crt') you are setting the ca_cert - the params being:

tls_set(ca_certs=None, certfile=None, keyfile=None, cert_reqs=ssl.CERT_REQUIRED, tls_version=ssl.PROTOCOL_TLS, ciphers=None)

This would be sufficient to connect to port 8883 (and your code connects to that port successfully for me). A connection to port 8883 will be encrypted and the client can confirm the identify of the server; however the client does not have to provide a client certificate (to identify itself).

To connect to port 8884 you have to provide a client certificate (used to authenticate the client) - i.e. the certfile and keyfile arguments. An appropriate certificate can be requested here.

  • Related