Skip to content

SSH Tunneling

January 12, 2012
By Administrator in All, Linux administration, SSH server

Forwarding ports over SSH or the so called SSH tunneling is a very convenient capability of the OpenSSH server. It allows you to establish a secure connection to a service that does not support secure connections provided that you have SSH access to the same machine and tunneling is permitted.

Let’s start with a short and straight-forward description of how SSH tunneling works. Let’s say that you have a remote MySQL server to connect to and it does not support SSL connections. The same server, however, also runs an OpenSSH daemon that you have access to. Using SSH tunneling to connect to the MySQL service securely, pretty much consists of the following:

  • Your SSH client application binds to a local port on your client machine. If the convention is followed, for MySQL that would be local port 3306. This would mean that on your local machine, you should not have other applications (such as an instance of a MySQL) listening on that port.

  • The SSH client establishes a connection to the remote SSH server.
  • The SSH server will forward the data received from the SSH client to the MySQL service.
  • You use your MySQL client application to connect to the local MySQL port on your own machine. Then, the SSH client starts securely transporting your MySQL commands to the remote machine where the SSH server is forwarding them to the MySQL service locally. This way, none of your data is transported in plain text over the network.

The following command is used to establish the tunnel:

[email protected]:~$ ssh -f -N -L3306:server:3306 -l user server

Of course, you need to replace server with your SSH server hostname or IP address and user with your own username :).

Once the tunnel is established, you can start using it:

[email protected]:~$ mysql -h -u dbuser -p

Note: In this particular case with MySQL, make sure that you use and not localhost to establish the connection. This is necessary because, by default, the MySQL client will try to establish the connection to localhost using a UNIX socket instead of using the necessary TCP socket.

Second Note: You need to make sure that the remote MySQL service will accept the forwarded connection. You may need to comment out the bind-address = line from the my.cnf configuration file so that the MySQL service would listen on all network interfaces.

Third Note: You may use any free local port of your choice instead of 3306 in the -L3306 section of the command. Then, you will just have to instruct your client application to connect to the specified port number instead of 3306.

Tags: , , , ,

Comment Feed

No Responses (yet)

Some HTML is OK

or, reply to this post via trackback.