SSH Tunneling with a MySQL Example

SSH tunnelling can be used to secure communications of non-secure protocols between two computers.

For the purposes of this example I have a server running MySQL which I will call mybigserver.com . The default port for MySQL is 3306 but by default it does not listen to external requests, only to localhost requests.

This is configured in /etc/mysql/my.cnf  with:

# Instead of skip-networking the default is now to listen only on
# localhost which is more compatible and is not less secure.
bind-address           = 127.0.0.1

This directive instructs MySQL to only use the loopback interface rather than answering external requests. If you want to allow MySQL to be accessed externally over port 3306 then comment this line and restart MySQL.

Usually MySQL answering only local requests is not a problem as we could install phpMyAdmin on mybigserver.com . However, I sometimes use a desktop GUI's such as HeidiSQL or Navicat to administer my MySQL databases but doing so from my desktop presents a problem since my desktop machine running HeidiSQL would need to connect to port 3306 on mybigserver.com.

SSH Tunneling

Enter SSH tunnelling. We can connect to mybigserver.com by ssh and ask it to connect a port (e.g. 2345) on my desktop machine to port 3306 on mybigserver.com with:

ssh -L 2345:mybigserver.com:3306 -l jonny -N mybigserver.com

In this example I have asked ssh to bind port 2345 on my local desktop machine to port 3306 on mybigserver.com which hosts the actual MySQL database server. I have used the username jonny to connect to mybigserver.com by ssh. The -N switch tells SSH to not bother running an actual command on the remote end, and just do the forwarding. A single ssh line can have multiple -L entries. More good info on using it for email on Windows is here if you are that way inclined.

Testing It Out

Using HeidiSQL I can create a new connection and specify the connection details as localhost on port 2345 and using the username/password combination expected by mybigserver.com. The connection may be a little slower but the encrypted communication of data is worthwhile.

In this example I used port 2345 on the local desktop machine for illustration purposes but port 3306 could also be used (assuming you are not already running MySQL locally).

Leave a Reply

  • (will not be published)

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>