SSH Tunnel operation concept
SSH tunneling allows you to establish an encrypted connection between two computers over an unsecured network. The SSH tunnel is based on the transmission of TCP/IP packets from one computer’s port to another, which is why this technology is sometimes also called “SSH Port Forwarding”.
An important advantage of SSH tunnels is the ease of configuration – since the connection is established with the SSH service on the server, which in most cases is already running, no additional actions are required.
Syntax
When creating a tunnel, you can use two main modes: Local and Remote.
To create a local tunnel, the -L parameter is used, and the command may look like this:
ssh -L local_port:local_host:remote_port remote_host
Instead of the remote host name, you can use the user_ssh@ip_server address pair, and if the ssh command is run on behalf of a user who matches the ssh user, it is enough to specify only the IP address.
The syntax of the remote tunnel creation command looks similar, but uses the -R parameter.:
ssh -R remote_port:local_host:local_port remote_host
Please note that the computer running the remote tunnel (SSH client) may be located behind a firewall or may not accept incoming connections at all. In this way, a remote tunnel can provide a connection to a computer that is inaccessible from the global network. For this reason, remote tunnels are also often referred to as Reverse tunnels.
A full description of the ssh command syntax can be obtained by using the “man ssh” command.
Examples of working with SSH tunnels
1. Connect to the service on the server (local SSH tunnel).
Let’s say a PostgreSQL database service is running on a server with IP address 1.2.3.4, listening on local port 5432. It is not possible to connect to this port from the outside, but port 22 is open on the server, which is listening to the SSH service (sshd). SSH connection is open for the user. In this case, you can run the command on the local computer to access the database.
ssh -L 5555:localhost:5432 user@1.2.3.4
Now port 5555 is forwarded from the local computer to port 5432 on the server and you can connect to the remote database by running the command
psql -h localhost -p 5555
2. Remote port forwarding
Now let’s complicate the task a bit. Suppose our database is installed on a server without Internet access, for example, with a “gray” IP address, but we want to access it from a local computer with the “white” address 6.7.8.9 and an SSH service running. In this case, you can run the following command on the server::
ssh -R 5555:localhost:5432 user@6.7.8.9
After that, port 5555 on the server will be forwarded to port 5432 on the local computer, which will allow us to execute the same psql command.
You can check the connection on the remote server with the command “lsof -i -P -n | grep LISTEN” or “ss -nlpt”:

The last two lines in the output of this command mean that the server is listening for local connections on port 5555, as expected.
Of course, we have given the PostgreSQL service only as an example. In this way, you can arrange remote access to any service, such as a web server. To organize such a port forwarding, let’s change our team a bit.:
ssh -R 4433:localhost:4430 user@6.7.8.9
Here we assume that a web server on a computer with an SSH client listens on port 4430, to which port 4433 is forwarded from the remote server. Note that by default, port 4433 is only accessible from the local IP address 127.0.0.1 (localhost). In order for clients from the Internet to connect to our web server, we can enable port forwarding to external network interfaces (GatewayPorts yes) in the SSH service settings (ssh_config). In this case, clients will need to specify the port number in the browser’s address bar to log in to the web server.:
https://6.7.8.9:4433
To use the standard port 443 and not change SSH settings, you can additionally forward external connections from port 443 to internal port 4433 using a proxying service, for example, nginx.
To make the SSH tunnel accessible after restarting the computer, it is convenient to use the systemd service on the side invoking the ssh -L or ssh -R command. In order to create our own service, add a file in the /etc/system/system directory, for example, ssh-tunnel.service with something like this content:
[Unit]
Description=SSH tunnel
After=network-online.target
[Service]
ExecStart=/usr/bin/ssh -i /home/user/.ssh/ssh-tunnel-key -NT \
-o ServerAliveInterval=60 -o ExitOnForwardFailure=yes \
-R 4433:localhost:4430 user@6.7.8.9
RestartSec=15
Restart=always
[Install]
WantedBy=network-online.target
Here we have specified several additional parameters for launching the tunnel:
-i /root/.ssh/ssh-tunnel-key — specifies the location of the ssh-tunnel-key private SSH key.
-N — do not execute the remote command.
-T — disable the pseudo-terminal.
-o ServerAliveInterval=60 and -o ExitOnForwardFailure=yes are options that allow you to restart the service after losing the connection.
Thus, the ssh-tunnel service will be automatically activated when the server is started after the network interface establishes a connection (network-online.target) and restarted after a possible connection break.
After creating the ssh-tunnel file, you need to run the commands sequentially:
sudo systemctl daemon-reload
sudo systemctl start ssh-tunnel.service
sudo systemctl enable ssh-tunnel.service
You can check the service status using the standard method.:
sudo systemctl status ssh-tunnel.service
SOCKS-proxy server and dynamic port forwarding
SSH supports another extremely useful feature that allows you to gain secure access to network nodes through an insecure network. This mode is often referred to as SOCKS proxy.
Suppose we have a server running SSH service and IP address 1.2.3.4. The server has the ability to connect directly to the Internet resources we are interested in. In this case, it is enough to run the following command on the local computer:
ssh -D 8888 user@1.2.3.4
The -D parameter here means dynamic port forwarding. When an application establishes a connection to port 8888, it is redirected via a secure channel to the 1.2.3.4 server, and then the application uses the SOCKS protocol to create a connection to the desired node from the remote server.
Using your own SOCKS proxy server has a serious advantage: when working via SSH, you can safely enter passwords, access codes, credit card numbers, and other sensitive data, which is strongly discouraged when using public proxy servers.
Multiple tunnels and switching multiple hosts
In order not to create separate connections with the same server, you can create multiple tunnels through a single connection by specifying several -L parameters, for example:
ssh -L 5555:server1:5432 -L 4433:server2:4430 user@server3
In this case, when accessing localhost:5555, we will get to server1:5432, and when accessing localhost:4433, the connection will be redirected to server2:4430. In both cases, the target servers are located behind the server3 node.
Jumping across hosts
If your network is divided into segments (subnets), you can use the -J (Proxy Jump) option to connect to a computer outside your subnet. This option is also useful, for example, for accessing servers in the cloud that are located behind a NAT and do not have access from the Internet.
The command syntax is very simple:
ssh -J <jump server> <remote target>
Since the jump server is used to access a private subnet, it is often referred to as a “bastion”. In large infrastructures, for security reasons, a separate server is used as a bastion, which performs only one task — proxying calls to internal services. Such services can be web servers, DNS servers, mail, FTP and VPN servers, and so on.
If necessary, there may be several jump servers, for example:
ssh -J host1,host2,host3 user@host4
In this case, SSH will create a tunnel to the host4 server through the host1 server chain…host3.
It is worth noting that when connecting via an intermediate server, the authorization keys of this server are used, and not the computer from which you connected to it. To forward keys from your computer to the server, you can use SSH Agent Forwarding technology, for example, using the -A parameter (ssh-agent authentication agent forwarding):
ssh -A user@host
Security note: when forwarding keys, local authorization data is not stored in the file system of the intermediate server, but is still available in the environment variables. Therefore, we do not recommend using ForwardAgent on servers that you do not control. We also do not recommend using the “ForwardAgent yes” parameter in the local configuration file ~/.ssh/config on a permanent basis.
SSH Tunnel Security
SSH is based on cryptography, an algorithm for encrypting traffic that requires special keys to decrypt it. Despite the high reliability of this method, we can recommend some additional security measures.:
- Disabling password login. We strongly recommend using a key instead of logging in with an open password.
- Disabling root access. Remote access of the superuser, in case of compromise, gives the attacker unlimited access to the server. That is why robots that perform Brute Force attacks first try to find the password to the root account. It is easy to verify this by viewing SSH service log entries about failed login attempts on almost any server with Internet access. Therefore, instead of root access, we recommend using a connection on behalf of an unprivileged user, if necessary, a member of the wheel group specified in the sudoers file.
- Limit SSH login attempts. To reduce the risk of a successful brute force attack on the server, it is recommended to use non-standard user names, as well as limit the number of authorization attempts. This can be done using the built-in SHH tools, for example, by reducing the MaxAuthTries value in the /etc/ssh/sshd_config configuration file, or using external tools such as fail2ban.
