Mosquitto on EC2 with TLS
<h1>Problem</h1>

<p>I want to setup my MQTT broker on an AWS EC2 instance and connect to it with TLS.</p>

<p>I have the instance running and I can connect (pub/sub) to Mosquitto from my local machine successfully with vanilla unencrypted MQTT. When using TSL, I get the error <code>tlsv1 alert unknown ca</code>.</p>

<p>After many hours of reading and trying different tutorials and examples, I still can't figure this out. Here's what I did and in my (limited) understanding of certificates and encryption should work:</p>

<h1>What I tried</h1>

<p>Let's say my EC2 instance is available at host <code>ec2-x.compute-1.amazonaws.com</code> and IP <code>54.1.1.1</code>. My local network's IP is <code>192.77.77.77</code>.</p>

<p>SSH into EC2 and generate certificates <a href="https://github.com/owntracks/tools/blob/master/TLS/generate-CA.sh" rel="nofollow">using OwnTracks's <code>generate-CA.sh</code></a> in a directory <code>~/iot</code>. I generate the certs issuuing</p>

<p><code>HOSTLIST="ec2-x.compute-1.amazonaws.com" IPLIST="54.1.1.1" bash ./generate-CA.sh ec2-x.compute-1.amazonaws.com</code></p>

<p>Certificate generation results in a bunch of files, namely</p>

<p><code>ca.crt  ca.key  ca.srl  ec2-x.compute-1.amazonaws.com.crt  ec2-x.compute-1.amazonaws.com.csr  ec2-x.compute-1.amazonaws.com.key</code></p>

<p>Now I'm ready to configure my broker with <code>mqtt.conf</code>:</p>

<pre>
# mosquitto.conf
listener 8883
pid_file /var/run/mosquitto.pid
persistence true
persistence_location /var/lib/mosquitto/
cafile ./ca.crt
certfile ./ec2-x.compute-1.amazonaws.com.crt
keyfile ./ec2-x.compute-1.amazonaws.com.key
</pre>

<p>Time to start the broker with <code>mosquitto -c mqtt.conf</code>.</p>

<p>In order to sub to the broker, I copy the content of <code>ca.crt</code> to my laptop and run <code>mosquitto_sub -h ec2-x.compute-1.amazonaws.com -p 8883 --cafile ca.crt -t +</code>.</p>

<h1>Resulting error</h1>

<p>What I get on the subscriber side is </p>

<pre>
Error: A TLS error occurred.
</pre>

<p>The server does realize there is a connection attempt happening but reacts with </p>

<pre>
1475320985: New connection from 192.77.77.77 on port 8883.
1475320986: OpenSSL Error: error:14094418:SSL routines:SSL3_READ_BYTES:tlsv1 alert unknown ca
1475320986: OpenSSL Error: error:140940E5:SSL routines:SSL3_READ_BYTES:ssl handshake failure
1475320986: Socket error on client , disconnecting.
</pre>

<p>I've tried following guides step by step like <a href="http://rockingdlabs.dunmire.org/exercises-experiments/ssl-client-certs-to-secure-mqtt" rel="nofollow">this very good one</a> or <a href="https://primalcortex.wordpress.com/2016/03/31/mqtt-mosquitto-broker-with-ssltls-transport-security/" rel="nofollow">this one</a> but to no avail.</p>