Wednesday, July 28, 2010

How to forward port by ssh

There are 3 machine
  1. My machine
  2. Host A with public IP
  3. Target Host B with can be reached from Host A
The goal is that I and my friends want to access target host B services in convenience. We can ssh to Host A with public IP.

Local Forwarding

Run this command on my machine

ssh -L 123:targetB:80 userA@hostA
  • We can access targetB:80 by myMachine:123 instead
  • The traffic will be forward from myMachine:123 through ssh tunnel to hostA and the forward to targetB finally.
Remote Forwarding

Run this command on hostA

ssh -R 123:targetB:80 me@myMachine
  • We can access targetB:80 by myMachine:123 instead
  • It's similar to local forwarding but the ssh tunnel is created by hostA which is the forwarder
  • The traffic will be forward from myMachine:123 through ssh tunnel to hostA and the forward to targetB finally.
Dynamic Forwarding

Run this command on my machine

ssh -D 123 userA@hostA
  • It's similar to local forwarding but it doesn't specify the target:port because the target address and the port will be determined automatically by application protocol such as SOCKS.
  • We can access targetB:80 by SOCKS proxy in browser or OS network settings.
  • Currently SOCKS4 and SOCKS5 protocols are supported.
Remarks
  • There might have firewall issues. It might have to change some port unless the packets will be blocked.
  • This method is for TCP traffic. For UDP, you may have to try other methods.