How-To Guides
Integration Guides
Install the Mosquitto MQTT Broker on Ubuntu
11min
review the following guide for installing the mosquitto mqtt broker on ubuntu once installed, you can connect to the following connectors in manufacturing connect edge mqtt generic tcp mqtt generic over ssl before you begin make sure you do the following verify the ubuntu os is 19 10 use a virtual machine on virtualbox 6 0 to install ubuntu verify that the virtual machine has two configured network adapters that are set as follows adapter 1 is set to bridged adapter adapter 2 is set to nat step 1 install net tools to install net tools from a command prompt, enter sudo apt install net tools , and press enter if asked to provide your password, enter the password and press enter enter ifconfig and press enter for this use case, the ip needed is for the bridged adapter (enp0s3) it is 192 168 1 11 step 2 install mqtt broker to install the mqtt broker from a command prompt, enter sudo apt get update and press enter if asked to provide your password, enter the password and press enter enter sudo apt get install mosquitto and press enter enter y and press enter to continue the mqtt broker is installed step 3 install mqtt client you can install the mqtt client to test the mqtt broker configuration to install the mqtt client enter sudo apt get install mosquitto clients and press enter enter y and press enter to continue the mqtt client is installed step 4 test initial installation you can verify that the mqtt broker and client are correctly installed to test the initial installation enter mosquitto sub t "test" and press enter right click the terminal icon and select new window to open a second terminal window select the second terminal window enter mosquitto pub m "message from mosquitto pub client" t "test" and press enter select the first terminal window to view the message sent from the second terminal window you should see message from mosquitto pub client press ctrl+c to exit the first terminal window step 5 set up username and password to set up a username and password enter sudo mosquitto passwd c /etc/mosquitto/passwd \<username> and press enter for example sudo mosquitto passwd c /etc/mosquitto/passwd johnsmith enter a password for the username at the prompt and press enter re enter the password and press enter enter sudo nano /etc/mosquitto/conf d/default conf and press enter to edit the default conf file the default conf file opens in the nano editor you can enforce refusal of connections from anonymous users and provide the path of the file holding all users and passwords from this file copy or enter the following two lines into the file allow anonymous false password file /etc/mosquitto/passwd press ctrl+o to save the changes verify the file name press enter the changes are verified press ctrl+x to exit the nano editor from the terminal window, enter sudo ufw allow 1883 and press enter the rule is applied this rule ensures that the firewall allows connections on port 1883 this is the default port for the mosquitto mqtt broker and is used for a connection using the username and password enter sudo systemctl restart mosquitto and press enter mosquitto restarts so the new configuration and rule can be used step 6 test username and password requirements to test the username and password requirements enter mosquitto sub t "test" u "\<username>" p "\<userpassword>" and press enter for example mosquitto sub t "test" u "johnsmith" p "xyzcorp\@1" open a second terminal window if you have closed it and select it enter mosquitto pub t "test" m "message from mosquitto pub client" and press enter to try to connect a publisher without using the correct username and password the connection is refused you should see connection error connection refused not authorized enter mosquitto pub t "test" m "message from mosquitto pub client" u "\<username>" p "\<password>" and press enter to connect using the correct username and password select the first terminal window view the message message from mosquitto pub client in the first terminal window press ctrl+c to exit the subscription stage in the first terminal window step 7 enable ssl/tsl you can create certificates and keys in the ubuntu system home directory important if you decide not to use the bash file for the following task and instead use either the commands individually or follow other guides available, you must use the fqdn (fully qualified domain name) for the cn (common name) never use the ip address refer to the following content for step 2 \#!/usr/bin/env bash \#(@)generate ca sh create ca key pair and server key pair signed by ca \# copyright (c) 2013 2016 jan piet mens \<jpmens()gmail com> \# all rights reserved \# \# redistribution and use in source and binary forms, with or without \# modification, are permitted provided that the following conditions are met \# \# 1 redistributions of source code must retain the above copyright notice, \# this list of conditions and the following disclaimer \# 2 redistributions in binary form must reproduce the above copyright \# notice, this list of conditions and the following disclaimer in the \# documentation and/or other materials provided with the distribution \# 3 neither the name of mosquitto nor the names of its \# contributors may be used to endorse or promote products derived from \# this software without specific prior written permission \# \# this software is provided by the copyright holders and contributors "as is" \# and any express or implied warranties, including, but not limited to, the \# implied warranties of merchantability and fitness for a particular purpose \# are disclaimed in no event shall the copyright owner or contributors be \# liable for any direct, indirect, incidental, special, exemplary, or \# consequential damages (including, but not limited to, procurement of \# substitute goods or services; loss of use, data, or profits; or business \# interruption) however caused and on any theory of liability, whether in \# contract, strict liability, or tort (including negligence or otherwise) \# arising in any way out of the use of this software, even if advised of the \# possibility of such damage \# \# usage \# /generate ca sh 	 creates ca crt and server {key,crt} \# /generate ca sh hostname	 creates hostname {key,crt} \# /generate ca sh client email	 creates email {key,crt} \# \# set the following optional environment variables before invocation \# to add the specified ip addresses and/or hostnames to the subjaltname list \# these contain white space separated values \# \# iplist="172 13 14 15 192 168 1 1" \# hostlist="a example com b example com" set e export lang=c kind=server if \[ $# ne 2 ]; then 	kind=server 	host=$(hostname f) 	if \[ n "$1" ]; then 	 host="$1" 	fi else 	kind=client 	client="$2" fi \[ z "$user" ] && user=root dir=${target =' '} \# a space separated list of alternate hostnames (subjaltname) \# may be empty "" althostnames=${hostlist} altaddresses=${iplist} ca org='/o=owntracks org/ou=generate ca/emailaddress=nobody\@example net' ca dn="/cn=an mqtt broker${ca org}" cacert=${dir}/ca server="${dir}/${host}" server dn="/cn=${host}$ca org" keybits=2048 openssl=$(which openssl) mosquittouser=${mosquittouser =$user} \# signature algorithm to find out which are supported by your \# version of openssl, run `openssl dgst help` and set your \# signature algorithm here for example \# \# defaultmd=" sha256" \# defaultmd=" sha512" function maxdays() { 	nowyear=$(date +%y) 	years=$(expr 2032 $nowyear) 	days=$(expr $years ' ' 365) 	echo $days } function getipaddresses() { 	/sbin/ifconfig | 	 grep v tunnel | 	 sed en '/inet6? /p' | 	 sed ee 's/inet6? (addr )?//' | 	 awk '{print $1;}' | 	 sed e 's/\[%/] //' | 	 egrep v '( 1|127\\ 0\\ 0\\ 1)'	 \# omit loopback to add it later } function addresslist() { 	alist="" 	for a in $(getipaddresses); do 	 alist="${alist}ip $a," 	done 	alist="${alist}ip 127 0 0 1,ip 1," 	for ip in $(echo ${altaddresses}); do 	 alist="${alist}ip ${ip}," 	done 	for h in $(echo ${althostnames}); do 	 alist="${alist}dns $h," 	done 	alist="${alist}dns\ localhost" 	echo $alist } days=$(maxdays) if \[ n "$cakillfiles" ]; then 	rm f $cacert ??? $server ??? $cacert srl fi if \[ ! f $cacert crt ]; then 	\# 	\# / | / \ 	\# | | / \ 	\# | | / \\ 	\# \\ / / \\ \\ 	\# 	\# create un encrypted (!) key 	$openssl req newkey rsa ${keybits} x509 nodes $defaultmd days $days extensions v3 ca keyout $cacert key out $cacert crt subj "${ca dn}" 	echo "created ca certificate in $cacert crt" 	$openssl x509 in $cacert crt nameopt multiline subject noout 	chmod 400 $cacert key 	chmod 444 $cacert crt 	chown $mosquittouser $cacert 	echo "warning the ca key is not encrypted; store it safely!" fi if \[ $kind == 'server' ]; then 	\# 	\# / | 	\# \\ \ / \ ' \ \ / / \ ' | 	\# ) | / | \ v / / | 	\# | / \\ | | \\ / \\ | | 	\# 	if \[ ! f $server key ]; then 	 echo " creating server key and signing request" 	 $openssl genrsa out $server key $keybits 	 $openssl req new $defaultmd \\ 	 out $server csr \\ 	 key $server key \\ 	 subj "${server dn}" 	 chmod 400 $server key 	 chown $mosquittouser $server key 	fi 	if \[ f $server csr a ! f $server crt ]; then 	 \# there's no way to pass subjaltname on the cli so 	 \# create a cnf file and use that 	 cnf=`mktemp /tmp/cacnf xxxxxxxx` || { echo "$0 can't create temp file" >&2; exit 1; } 	 sed e 's/^ %%% //' > $cnf <<\\!endconfig 	 %%% \[ jpmextensions ] 	 %%% basicconstraints \= critical,ca\ false 	 %%% nscerttype \= server 	 %%% keyusage \= nonrepudiation, digitalsignature, keyencipherment 	 %%% nscomment \= "broker certificate" 	 %%% subjectkeyidentifier \= hash 	 %%% authoritykeyidentifier \= keyid,issuer\ always 	 %%% subjectaltname \= $env subjaltname 	 %%% # issueraltname \= issuer\ copy 	 %%% ## nscarevocationurl \= http //mqttitude org/carev/ 	 %%% ## nsrevocationurl \= http //mqttitude org/carev/ 	 %%% certificatepolicies \= ia5org,@polsection 	 %%% 	 %%% \[polsection] 	 %%% policyidentifier \= 1 3 5 8 	 %%% cps 1 \= "http //localhost" 	 %%% usernotice 1 \= @notice 	 %%% 	 %%% \[notice] 	 %%% explicittext \= "this ca is for a local mqtt broker installation only" 	 %%% organization \= "owntracks" 	 %%% noticenumbers \= 1 !endconfig 	 subjaltname="$(addresslist)" 	 export subjaltname 	 \# use environment because i can ; ) 	 echo " creating and signing server certificate" 	 $openssl x509 req $defaultmd \\ 	 in $server csr \\ 	 ca $cacert crt \\ 	 cakey $cacert key \\ 	 cacreateserial \\ 	 caserial "${dir}/ca srl" \\ 	 out $server crt \\ 	 days $days \\ 	 extfile ${cnf} \\ 	 extensions jpmextensions 	 rm f $cnf 	 chmod 444 $server crt 	 chown $mosquittouser $server crt 	fi else 	\# 	\# / | ( ) | | 	\# | | | | |/ \ ' \\| | 	\# | | | | | / | | | | 	\# \\ | | |\\ | | | |\\ | 	\# 	if \[ ! f $client key ]; then 	 echo " creating client key and signing request" 	 $openssl genrsa out $client key $keybits 	 cnf=`mktemp /tmp/cacnf req xxxxxxxx` || { echo "$0 can't create temp file" >&2; exit 1; } 	 \# mosquitto's use identity as username takes the cn attribute 	 \# so we're populating that with the client's name 	 sed e 's/^ %%% //' > $cnf <\<!endclientconfigreq 	 %%% \[ req ] 	 %%% distinguished name	 \= req distinguished name 	 %%% prompt 	 \= no 	 %%% output password 	 \= secret 	 %%% 	 %%% \[ req distinguished name ] 	 %%% # o \= owntracks 	 %%% # ou \= mqtt 	 %%% # cn \= suzie smith 	 %%% cn \= $client 	 %%% # emailaddress \= $client !endclientconfigreq 	 $openssl req new $defaultmd \\ 	 out $client csr \\ 	 key $client key \\ 	 config $cnf 	 chmod 400 $client key 	fi 	if \[ f $client csr a ! f $client crt ]; then 	 cnf=`mktemp /tmp/cacnf cli xxxxxxxx` || { echo "$0 can't create temp file" >&2; exit 1; } 	 sed e 's/^ %%% //' > $cnf <<\\!endclientconfig 	 %%% \[ jpmclientextensions ] 	 %%% basicconstraints \= critical,ca\ false 	 %%% subjectaltname \= email\ copy 	 %%% nscerttype \= client,email 	 %%% extendedkeyusage \= clientauth,emailprotection 	 %%% keyusage \= digitalsignature, keyencipherment, keyagreement 	 %%% nscomment \= "client broker certificate" 	 %%% subjectkeyidentifier \= hash 	 %%% authoritykeyidentifier \= keyid,issuer\ always !endclientconfig 	 subjaltname="$(addresslist)" 	 export subjaltname 	 \# use environment because i can ; ) 	 echo " creating and signing client certificate" 	 $openssl x509 req $defaultmd \\ 	 in $client csr \\ 	 ca $cacert crt \\ 	 cakey $cacert key \\ 	 cacreateserial \\ 	 caserial "${dir}/ca srl" \\ 	 out $client crt \\ 	 days $days \\ 	 extfile ${cnf} \\ 	 extensions jpmclientextensions 	 rm f $cnf 	 chmod 444 $client crt 	fi fi to enable ssl/tsl from a terminal window, enter nano and press enter copy the content above and paste it into the nano editor press ctrl+o to save the changes enter generate ca sh to provide the file name and press enter the file is created press ctrl+x to exit the nano editor the file is in your default directory enter sudo chmod 774 \<filename> and press enter to set permissions for example sudo chmod 774 generate ca sh enter sudo /\<filename> and press enter execute the bash file and create the certificates for example example sudo /generate ca sh the bash file is executed you should see johnsmith\@johnsmith virtualbox $ /generate ca sh generating a rsa private key the certificates and key files are in your home directory enter sudo cp ca crt /etc/mosquitto/ca certificates and press enter to copy the ca crt to the correct folder enter sudo cp \<your fqdn> crt /etc/mosquitto/certs and press enter to copy the file containing the fqdn crt to the correct folder for example sudo cp johnsmith virtualbox crt /etc/mosquitto/certs enter sudo cp \<your fqdn> key /etc/mosquitto/certs to copy the server certificate which has the file name \<your fqdn> key for example sudo cp johnsmith virtualbox key /etc/mosquitto/certs enter sudo nano /etc/mosquitto/conf d/default conf and press enter to allow for ssl encryption the default conf file opens move your cursor down using the arrow keys and paste the following lines # plain mqtt protocol listener 1883 \# end of plain mqtt configuration \# mqtt over tls/ssl listener 8883 cafile /etc/mosquitto/ca certificates/ca crt certfile /etc/mosquitto/certs/\<your fqdn> crt keyfile /etc/mosquitto/certs/\<your fqdn> key require certificate false \# end of mqtt over tls/sll configuration press ctrl+o to save the changes press enter , and then press ctrl+x to exit the nano editor enter sudo ufw allow 8883 and press enter to allow ssl encrypted connections on port 8883 the rule is applied enter sudo systemctl restart mosquitto and press enter to run the mosquitto broker using the new configuration and rule step 8 test certificates, username, and password requirements to test the certificates, username, and password requirements enter mosquitto sub cafile /etc/mosquitto/ca certificates/ca crt h \<host ip> t "test" p8883 d u "\<username>" p "\<password>" and press enter to create a subscription for example mosquitto sub cafile /etc/mosquitto/ca certificates/ca crt h 192 168 1 11 t "test" p 8883 d u "johnsmith" p "xyzcorp\@1" open a second terminal window if previously closed and select it enter mosquitto pub h \<host ip> t "test" m "hello" p 8883 d u "\<username>" p "\<password>" cafile /etc/mosquitto/ca certificates/ca crt and press enter to publish a message for example mosquitto pub h 192 168 1 11 t "test" m "hello" p 8883 d u "johnsmith" p "xyzcorp\@1" cafile /etc/mosquitto/ca certificates/ca crt select the first terminal window to view the message hello press ctrl+c to exit the subscription stage in the first terminal window