Principle Explanation

SSH port forwarding establishes an SSH connection tunnel on a specified computer to forward data. Since SSH communication itself is encrypted, there is some security guarantee, but it does not mean absolute security (such as man-in-the-middle attacks). Therefore, when establishing a connection for the first time, the remote host will send the public key fingerprint to the connecting endpoint. To avoid man-in-the-middle attacks, the remote server’s public key fingerprint can be provided to the client in advance, so the client can identify whether there is a man-in-the-middle during the connection establishment.

Local Port Forwarding

$ ssh -L [local_host:]local_port:target_host:target_port [username@]SSH_server

# For example, listen on local port 3306, then forward data through SSH to port 3306 on example.com.
$ ssh -L 3306:example.com:3306 [email protected]

Note: The target host is relative to the SSH server. For example, the target host above can be localhost, which is example.com itself.

After pressing enter, the subsequent process is the same as a normal SSH connection.

Remote Port Forwarding

Remote Port Forwarding

As shown in the figure above, Server 1 needs to access Server 2’s services, but they cannot communicate directly. Server 3 can communicate with both Server 1 and Server 2, but because Server 3 is in an internal network, Server 1 cannot access Server 3. In this case, remote port forwarding is needed to allow Server 1 to forward data to the corresponding port on Server 2 through Server 3.

$ ssh -R [remote_host:]remote_port:target_host:target_port [username@]SSH_server

# Execute the following command on Server 3, which will listen on port 3306 on Server 1, and then forward data through Server 3 to port 3306 on Server 2.
$ ssh -R 3306:server2:3306 user@server1

Dynamic Port Forwarding

This method is often used for proxy requests.

$ ssh -D [local_host:]local_port [username@]SSH_server

# Executing this command will create a SOCKS tunnel
$ ssh -D 8080 -N -f [email protected]

All data to port 8080 will be forwarded through SOCKS to the example.com proxy.

I hope this is helpful, Happy hacking…