Ssh – forward port 3306 from firewalled machine to desktop using SSH

debian-lennylinux-networkingport-forwardingsshssh-tunnel

Here's the network setup:

Machine A (my PC) SSH 22 => Machine B (Linode with root access) SSH 21343 => Machine C (MySQL server).

I want to forward port 3306 from C through B to A, so I can use SQL Workbench on A to execute commands on C.

Note that C is only accessible over SSH port 21343 and only from B (we cannot change the firewall on C to open any more ports, but we can change its SSH settings).

Is this possible? I've read about tunnels and ProxyCommand. But I need a simple step-by-step example.

All machines are debian Lenny.

Best Answer

On the machine A:

ssh -L 3307:C:3306 user@B

This allocated a socket listen to port 3307 on A. And whenever a connection is made to this port, it is forwarded over ssh tunnel to C:3306.

You can then connect to MySQL server on C with:

mysql -u <user> -p -h 127.0.0.1 -P 3307

(127.0.0.1 to connect via TCP/IP instead of a socket)


No, I cannot connect to MySQL on C from B. Only SSH listening on 21343 is open to B.

If the firewall on C only allow to connect from localhost, something like this:

iptables -A INPUT -p tcp -s 127.0.0.1 --dport 3306 -j ACCEPT
iptables -A INPUT -p tcp --dport 3306 -j DROP

so, AFAIK, there is no way to do this. If you try to connect over ssh tunnel, you will get the below errors:

ERROR 2013 (HY000): Lost connection to MySQL server at 'reading initial communication packet', system error: 0
Related Topic