[solved] MQTT with SSL/TLS not working with Home Assistant

This is a guide I wrote for my future self, enjoy!

  1. Create CA private key (recommended to create password)
    $ openssl genrsa -des3 -out ca.key 2048

  2. Generate CA certificate (valid for 20 years)
    $ openssl req -new -x509 -days 7300 -key ca.key -out ca.crt

  3. Create server-side private key
    $ openssl genrsa -out server.key 2048

  4. Create a configuration file - this you must do on your own, here is an example:

[ req ]
default_bits = 2048
prompt = no
default_md = sha256
distinguished_name = dn
req_extensions = v3_req

[ dn ]
C = XX
ST = Province
L = Cty
O = OrgName
CN = domain.local

[ v3_req ]
subjectAltName = @alt_names

[alt_names]
DNS.1 = domain.local
DNS.2 = 192.168.0.xxx

What to change?
The dn section is the details of your certificate. Available variables can be found at What is a Distinguished Name (DN)? or by googling “distinguished name ssl”
The alt_names section are the FQDNs of the sites that the certificate will be used for. This is used by browsers to confirm that a given certificate was meant for a given site.

Save it as server.cnf

  1. Create a certificate request from a configuration file (this is a file containing all the details for a CA to create a server-side certificate, since we are the ca we’ll generate (sign) it ourselves, hence the name self-signed)
    $ openssl req -new -config server.cnf -key server.key -out server.csr -extensions v3_req

  2. Create the server-side certificate (10 years)
    $ openssl x509 -req -days 3650 -in server.csr -CA ca.crt -CAkey ca.key -CAcreateserial -out server.crt -extfile server.cnf -extensions v3_req

NOTE:
This uses a workaround due to a bug to get x509v3 extensions working (SANs). By the time this was written the bug was fixed and a solution has been created, but not released.

REPLACE
-extfile server.cnf -extensions v3_req
WITH
-copy_extensions copyall

NOTE2:
When creating you first certificate with the CA use the -CAcreateserial flag, however, if this is not your first cert then use -CAserial ca.srl option to load your already existing serial file.

  1. Add CA certificate, Server certificate and server key to the mosquitto.conf file (cafile, certfile, keyfile) and require_certificate false. Add CA certificate to configuration.yaml (certificate). You can use certificate based authentication as well - set require_certificate true in mosquitto.conf and add client_cert: and client_key: in configuration.yaml.