Re-routing Traffic via a Remote Server

This isn't a great long guide to using ssh for port forwarding, it just covers the one instance I needed.

Normally I connect my mail program running on c1 (my Mac at home) to server s3 port p3 (my mail server at work).
But today I can't get traffic from c1 to s3 because s3's corporate firewall has blocked me. So I need to re-route all the traffic destined for s3 port p3 via a separate server s2, which fortunately is in another country and I have ssh access to it.

You change your local mail program, instead of connecting to s3 port p3, to connect to "localhost" port p1 (some port on your Mac/PC you haven't used for anything else, e.g. 2000).

Then in a Terminal window you do
    ssh -v -L p1:s3:p3 @s2

To give you a concrete example, my IMAP server I want to talk to is at imap.work.com port 993.
My remote server (to which I have ssh access) which I want to route all traffic via, is called ssh.mydomain.com and it listens on port 22 as usual. I have an account there with username jkf.
On my local Mac running my Mail client, I've decided to route IMAP traffic via port 2000 as it's an unused port. That "2000" is pretty much any number in the range 1024-65535 that seems to work. If you hit one that doesn't work or produces an error, guess again.

I would type this:
    ssh -v -L 2000:imap.work.com:993 jkf@ssh.mydomain.com
If the ssh server on ssh.mydomain.com ran on port 2222 instead of the default port 22, I would just have to add "-p 2222" to that command.

So your traffic from your mail program (set to talk to localhost port p1 which is 2000 in my case) does this:
c0 ==> s1 (==localhost) port p1 ==> s2 port 22 ==> s3 port p3

You will need to set up more than 1 of these as you'll probably want to re-route SMTP traffic as well. So just open another Terminal window and run another similar command in there, for the appropriate SMTP port.

The commands will look like they have just logged you in to your remote ssh server (ssh.mydomain.com) but they will have set up all the magic before they did it. The "-v" in the ssh commands makes it show you more detail of what is going on.
Comments