stunnel for mysql – server and client

We needed to set up an stunnel to the mysql server (mysql.example.com), so that the client (client.example.com) and the server can communicate over an encrypted tunnel. Stunnel was already installed on both linux machines – it is avaialble from http://stunnel.org. The steps taken on mysql.example.com 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/stunnel.pid
    debug = 7
    output = stunnel.log
    [mysqls]
    accept = 3309
    connect = 3306

  4. stunnelis started

The steps taken on client.example.com 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/stunnel.pid
    setuid = nobody
    setgid = nobody
    debug=7
    output=stunnel.log
    client = yes
    [3309]
    accept = 3309
    connect = mysql.example.com:3309

  3. stunnel is started
  4. The mysql client is invoked with the following:
    mysql -h mysql.example.com -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 mysql.example.com by an administrator).

We had another requirement: we had to establish tunneled mysql connections from mysql.example.com to topmysql.example.com. So we created on mysql.example.com 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

topmysql.example.com 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.