stunnel for mysql – server and client

We needed to set up an stunnel to the mysql server (, so that the client ( and the server can communicate over an encrypted tunnel. Stunnel was already installed on both linux machines – it is avaialble from The steps taken on were:

  1. cd /etc/stunnel
  2. Create a certificate:
    openssl req -x509 -nodes -days 365 -newkey rsa:1024 \
    -keyout stunnel.pem -out stunnel.pem
  3. The stunnel.conf file contains the following lines:

    cert = /etc/stunnel/stunnel.pem
    setuid = nobody
    setgid = nobody
    pid = /tmp/
    debug = 7
    output = stunnel.log
    accept = 3309
    connect = 3306

  4. stunnelis started

The steps taken on were:

  1. Create a certificate as above (not strictly necessary but otherwise the connection is open to a man in the middle attack)
  2. stunnel.conf contains the following lines:

    cert =/etc/stunnel/stunnel.pem
    pid = /tmp/
    setuid = nobody
    setgid = nobody
    client = yes
    accept = 3309
    connect =

  3. stunnel is started
  4. The mysql client is invoked with the following:
    mysql -h -u mysqluser -p -P 3309
    The hostname must be specified so that mysql will not attempt to bind with a local mysqld via a local socket.
    mysqluser needs to be granted rights on the appropriate databases with the host being localhost.localdomain. Something like
    grant all on db.* to mysqluser@'localhost.localdomain' identified by 'SecretPw';
    (this is done on a mysql client running on by an administrator).

We had another requirement: we had to establish tunneled mysql connections from to So we created on the directory /etc/stunnel-client with the client configuration as above. We started a second instance of stunnel, specifying the new config:
stunnel /etc/stunnel-client/stunnel-client.conf was set up as an stunnel server as above, and everything worked as expected.

The only thing left to do is firewall off the unencrypted mysql connections on both servers.

Leave a Comment

You must be logged in to post a comment.