30 Oct 2007
Summary:
$ ssh -fN -L localport:remoteserver:remoteport hopserver
Optionally combined with agent forwarding and user/hostname mapping in .ssh/config; optionally combined with this in .ssh/config if drilling through a squid proxy:
Host remoteserver Hostname remoteserver ProxyCommand connect-proxy -S dmzproxy.foo.com:1080 %h %p
To setup an ssh tunnel (4 machines):
<br />
hosta$ ssh -fN
-o GateWayPorts=yes
-L P:S:W
user@B
hostc$ some-app A:P<br />
-f – go into background after asking for a password
-N – don’t execute a remote command
-g – gateway (or -o GateWayPorts=yes) – may be required if doing double ssh (ie one tunnel feeding in to a second tunnel); will be required to allow connections to forwarded port from external hosts (ie not localhost)
(image from O’Reilly’s excellent book “SSH Definitive Guide”)
Data between C and A won’t be encrypted; data between A and B will be encrypted; data between B and S won’t be encrypted.
To setup an ssh tunnel (3 machines):
If Host C and Host A are the same machine:
<br />
hosta$ ssh -fN -L P:S:W user@B
hosta$ some-app A:P
If Host B and Host S are the same machine:
hosta$ ssh -fN -o GateWayPorts=yes -L P:B:W user@B
hostc$ some-app A:P
To setup an ssh tunnel (2 machines):
Another common case is where both C and A, and B and S, are the same machines – call them local and remote. There are 2 possible commands:
<br />
local$ ssh -fN -L P:localhost:W remote<br />
local$ ssh -fN -L P:remote:W remote<br />
Both will usually work, but to the destination server (1) appears to come from 127.0.0.1 and (2) appears to come from remote’s ip. (1) would give “connection refused” errors if connections aren’t allowed from localhost (unusual), (2) would give “connection refused” errors if connections aren’t allowed from anything but localhost (eg typically mysql).
To connect, do ssh -p P foo@localhost. Be aware of account name issues ie localhost and remote are different hosts, so a tunnel may succeed but then the ssh command fail due to account name mismatches – hence the foo@localhost.
Some tricks from this article:
$ ssh user@intermediate-server -D 8080 # setup a pseudo socks server; point socks-able apps at localhost:8080
These sites are also interesting:
- this thread where I asked SLUG about reversing an existing tunnel
- alufis35.uv.es SSH, stunnel and a proxy: double stunnel bypass
- rzg ssh tunnelling
- Official SSH FAQ
- gentoo wiki TIP SSH Reverse Tunnel
- samba.org multi-hop ssh with nc for rsync
- sshto – bang-style ssh to do multihop ssh