Skip to main content

RabbitMQ and SSL

RabbitMQ is an AMQP provider i.e. it can reliably queue, service and maintain messages according to a range of policies and parameters.

By default, it listens to plain old TCP connections and sends and receives messages over plaintext. This feature just works "out of the box". For users who wish to use SSL over TCP aka TLS, it requires a bit more work on their part.

  1. First, let's create a bunch of certificates and sign them with our own CA. For this, we'll use easyrsa3. Easyrsa is a CLI tool to create, sign and manage your own certification authorities. It's maintained by OpenVPN team.
  2. Download easyrsa using your native package manager i.e. yum or apt-get
    $cp -Rp /usr/share/easy-rsa ~/easy-rsa-3 
    $cd ~/easy-rsa-3
    $./easyrsa init-pki
    $./easyrsa build-ca
    $./easyrsa build-server-full broker [nopass]
    $./easyrsa build-client-full client1 [nopass]
    This creates three entities (collection of private keys, public keys and certificates) for a CA, a server named broker and a client named client1. Private keys are stored in ./private/, certificates are stored in ./issued. You may move the files to any suitable place you like for it's required that we link them up at appropriate places. Be careful about the keys, as they to be kept secret. Using nopass switch will disable PEM password, might be useful when you don't to prompt user for PEM password.
  3. Now, let's configure RabbitMQ for using certificate we just created. RabbitMQ uses configuration stored at /etc/rabbitmq/rabbitmq.config. The relevant additions needed are as follows, 
    [
      {rabbit, [
         {ssl_listeners, [5671]},
         {ssl_options, [{cacertfile,"/path/to/easyrsa/ca.crt"},
                        {certfile,"/path/to/server/broker.crt"},
                        {keyfile,"/path/to/server/broker.key"},
                        {password, "password-used-to-encrypt-broker.key"},
                        {verify, verify_peer},
                        {fail_if_no_peer_cert, false}]}
       ]}
    ].
    Things to note,
    1. Make sure user "rabbitmq" has access to the certificates otherwise you'll see "eacess" errors being raised while trying to connect. What worked for me was to chown these files to rabbitmq user and chmod read access to others (o+r) to all the directories above the file.
    2. You might want to tail rabbitmq log file, for knowing what is happening where. The log files are at, /var/log/rabbitmq/.
    3. After every change in rabbitmq configuration, you'll need to restart the service using systemctl/service directive, as the case maybe.
  4. To test if the connections are proper, we may use openssl.
    $ openssl s_client -connect localhost:5671 -cert  /etc/rabbitmq/ssl/client/cert.pem -key /etc/rabbitmq/ssl/client/key.pem -CAfile /etc/rabbitmq/ssl/certificate_auth/cacert.pem
    Make sure to keep an eye on the rabbitmq log file and the console output. Any errors here will indicate a problem with the configuration.
  5. Now, let's delve into the actual client code. Let's look at Python first, 
    1. PYTHON
      import ssl
      import pika

      connection = pika.BlockingConnection(pika.ConnectionParameters(host='localhost', port=5671, ssl=True, ssl_options=dict(
              ssl_version=ssl.PROTOCOL_TLSv1,
              ca_certs="/path/to/ca.crt",
              certfile="/path/to/client.crt",
              keyfile="/path/to/client.key",
              cert_reqs=ssl.CERT_REQUIRED
      )))
      channel = connection.channel()
    2. JAVA
      Before doing anything, you'll first need to import the broker/server certificate into your client's truststore. Truststores are JDK's way of specifing and storing trusted certificates. To import broker's certificate into a truststore file,
      $ keytool -import -alias server1 -file /path/to/server/cert.pem -keystore /path/to/rabbitstore
      Also, we'll need client public and private key and certificates combined in p12 format. For that we'll again use easyrsa3,
      ./easyrsa export-p12 client
      The Java code to connect to broker is as follows,
      import java.io.*;
      import java.security.*;
      import javax.net.ssl.*;
      import com.rabbitmq.client.*;


      char[] keyPassphrase = "MySecretPassword".toCharArray();
      KeyStore ks = KeyStore.getInstance("PKCS12");
      ks.load(new FileInputStream("/path/to/client/keycert.p12"), keyPassphrase);

      KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
      kmf.init(ks, passphrase);

      char[] trustPassphrase = "rabbitstore".toCharArray();
      KeyStore tks = KeyStore.getInstance("JKS");
      tks.load(new FileInputStream("/path/to/trustStore"), trustPassphrase);

      TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509");
      tmf.init(tks);

      SSLContext c = SSLContext.getInstance("TLSv1.2");
      c.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);

      ConnectionFactory factory = new ConnectionFactory();
      factory.setHost("localhost");
      factory.setPort(5671);
      factory.useSslProtocol(c);

      Connection conn = factory.newConnection();

    This should enable SSL in rabbitmq and you can use the connection object thus formed to send messages to the broker.

Comments

Popular posts from this blog

PC Power supply and hacks

For posterity and myself, I'm leaving some tips and tricks of PC Power Supply Unit (PSU) whcih is an SMPS (Switched Mode Power Supply). There are a variety of uses of a +12V, +5V and +3V DC power supply like lighting up an LED strip or powering a raspberry pi. There are various colored cables in a typical ATX 12V SMPS. I'll list out the various color lines and what they mean, Sr. No Cable color Number of cables in a PSU Use 1 Green exactly one (1) Wake up signal from motherboard. Pressing PC power button makes this signal carry wake up signal to PSU to start. Green needs to be touched with the any ground to make the SMPS start. For self-starting PSUs, green needs to be connected with one black all the time. 2 Blue exactly one (1) -12V 3 Purple exactly one (1) +5V standby. When power supply is on standby mode (not on by signalling green), this line can give 1-2 A current. 4 Gray exactly one (1) Power good signal. When PSU levels has reached specificati...

Google Input Tools Offline Installers

Google offers excellent non-latin character input software which works on transliteration rather than explicit keyboards which is very hard to do specially when the US keyboard layout had virtually overtaken the computer industry. Google Input Tools (GIT) installer from the official site is online, i.e. it downloads a small stub and later depending upon the configuration and setting will download the larger installer. If someone needs an offline installer for GIT, you can download it from the following links, Hindi (Devnagri) : http://dl.google.com/transliteration-ime/1.0.4.0/googlehindiinputsetup.exe Malayalam (Malayalam) : http://dl.google.com/transliteration-ime/1.0.4.0/googlemalayalaminputsetup.exe Sanskrit (Devnagri) : http://dl.google.com/transliteration-ime/1.0.4.0/googlesanskritinputsetup.exe Basically, just replace the from the url and enter your desired language name.

Motorola XT502 Custom ROMs

I purchased an Android Phone in the early days of it coming to Indian market and I able to afford it ( just got a job), during mid 2010. The recent and popular version was Éclairs. I just went up to the shop and bought a nice and shiny Motorola Quench XT3 (XT502). When in other places XT502 was having Andriod Donut, I got as a special offer Éclairs. I was happy as hell. The Droid A couple of year passes, and newer versions of Android came from Éclairs to Froyo to Gingerbread then to the bigger version upgrades like Honeycomb, Ice Cream Sandwich and then Jelly Bean. By the end of 2012, I was literally surviving on my Motorola with Éclairs. I had to upgrade, anyhow. Now more that Motorola denied any upgrades for Quench XT3 . A trivia, Android version names are taken from sugary desserts with lexicographic sequencing. So, I did up-gradation from Éclairs to Gingerbread using a custom ROM from Cyanogenmod . An excellent community of enthusiast who develop their own custom ROMs oft...