Thursday, April 12, 2018

SSH Tunnel

There are two ways to create an SSH tunnel, local and remote port forwarding (there's also dynamic forwarding, but we won't cover that here).

local port forwarding

forwarding to remote server

Imagine you’re on a private network which doesn’t allow connections to a specific server. Let’s say you’re at work and imgur.com is being blocked. To get around this we can create a tunnel through ssh server which isn’t on our network and thus can access Imgur.

$ ssh -L 9000:imgur.com:80 user@example.com //local port is targeting at imgur.com's port 80 with help of ssh server user@example.com .

Now open your browser and go to http://localhost:9000 , nobody is going to see what sites you’re visiting, they’ll only see an SSH connection to your server.

forwarding to ssh server

ssh -L 9000:localhost:5432 user@example.com

For here, the tunnel is localhost:9000 and ssh_server:5432; for easy maintain, local port and ssh port can be the same. the ssh_server can accept multiple connections at same port.

Remote port forwarding

Say that you’re developing a Rails application on your local machine, and you’d like to show it to a friend. Unfortunately your ISP didn’t provide you with a public IP address, so it’s not possible to connect to your machine directly from the internet.

Sometimes this can be solved by configuring NAT (Network Address Translation) on your router, but this doesn’t always work, and it requires you to change the configuration on your router, which isn’t always desirable. This solution also doesn’t work when you don’t have admin access on your network.

To fix this problem you need to have another computer, it can be any server on the internet or your company We’ll tell SSH to make a tunnel that opens up a new port on the server, and connects it to a port on your machine:

$ ssh -R 9000:localhost:3000 user@example.com
The syntax here is very similar to local port forwarding, with a single change of -L for -R. First you need to specify the port on which th remote server will listen, which in this case is 9000, and next follows localhost for your local machine, and the local port, which in this case is 3000.

There is one more thing you need to do to enable this. SSH doesn’t by default allow remote hosts to forwarded ports. To enable this open /etc/ssh/sshd_config and add the following line somewhere in that config file.
GatewayPorts yes
Make sure you add it only once!
$ sudo vim /etc/ssh/sshd_config
And restart SSH
$ sudo service ssh restart

For more info, refer to https://blog.trackets.com/2014/05/17/ssh-tunnel-local-and-remote-port-forwarding-explained-with-examples.html

No comments:

Post a Comment