SSH tunneling for forwarding, Reverse and Dynamic

Forward tunneling is to pull their resource to us

Example
Get their 80 resource on my localhost:8080

ssh -L 8080:RemoteServer:80 root@RemoteServer

 

Example
Map my localhost:8080 to remote’s localhost:80

ssh -L 8080:localhost:80 root@RemoteServer

 

Example
Map my IP_Address:8080 to remote:80

ssh root@RemoteServer -L 192.168.1.X:8080:RemoteServer:80

 

Example
Map my localport:443 port to remote:3389 ports
Get their 3389 resource on my port 443

ssh root@RemoteServer
-L 192.168.1.142:443:RemoteServer:3389
-L 192.168.1.142:444:RemoteServer1:3389
-L 192.168.1.142:445:RemoteServer2:445
-L 192.168.1.142:1433:RemoteServer3:1433

 

 

Example with private-key
Map local address:X ports to remote address:X ports

ssh -i private-key root@RemoteServer
-L 192.168.1.142:443:RemoteServer:3389
-L 192.168.1.142:444:RemoteServer1:3389
-L 192.168.1.142:445:RemoteServer2:445
-L 192.168.1.142:1433:RemoteServer3:1433

 

Reverse tunneling is for sharing your resources to others

Remote host will listen on 8888, providing resource of localhost:80

ssh -R 8888:localhost:80 root@RemoteServer

In order to bind to all interfaces on RemoteServer

ssh -R \*:8080:localhost:80 -N root@RemoteServer

You need to add below at your remote server on Internet /etc/ssh/sshd_config to enable GatewayPorts 

sudo nano /etc/ssh/sshd_config
GatewayPorts yes #Add this line at the end of the file
sudo service sshd restart

 

Keep SSH tunnel open persistently

autossh -f -M 22222 root@RemoteHost -L 192.168.1.X:8080:RemoteHostX:80 -nNT

Flag -f (autossh: background)
Flag -M (autossh: monitoring port)
Flag -n (ssh: Redirects stdin)
Flag -N (ssh: Do not execute remote command. Just forwarding ports)
Flag -T (ssh: Disable pseudo-terminal allocation)
Flag -L (ssh: Local forwarding)

 

**** -nNT flags ****
Example
Only port forwarding. No allocation of ssh tty

ssh -nNT root@RemoteServer -L 192.168.1.X:8080:RemoteServer:80

 

SSH tunneling (dynamic)

 

How to monitor established, listening and tunneling

netstat -pnt
netstat -lpnt
netstat -lpnt | grep ssh

netstat -l (listening)
netstat -p (port)
netstat -n (numerical addresses)
netstat -t (tcp?)

 

WARNING: REMOTE HOST IDENTIFICATION HAS CHANGED!

If you get this error, either you remove ~/.ssh/known_hosts file or update it with below command

Remove or move old known_hosts if you only have 1 entry

su root
rm ~/.ssh/known_hosts
mv .ssh/known_hosts .ssh/known_hosts_old

Overwrite and update known_hosts

sudo ssh-keygen -R x.x.x.x

Leave a Reply

Your email address will not be published. Required fields are marked *

Scroll to top