how to use plain openssh to do remote port forwarding
Find a file
2026-10-08 23:32:39 +02:00
LICENSE Initial commit 2021-02-18 20:07:07 +01:00
README.md according to claude autossh is better then I thought but still not perfect 2026-10-08 23:32:39 +02:00

ssh-port-forwarding

(how to use plain openssh to do remote port forwarding)

There are many good reasons to do secure port forwarding through ssh. For example if you own two servers in different datacenters and you want to connect them to a single service which is less restricted when accessed locally (e.g. port 25 for SMTP) or you want to forward a service from a system behind a firewall (e.g. a web service on your home server).
Traditionally you would use autossh to manage permanent ssh connections. In many hours of testing I ran into several problems with such a setup, though. Most guides use autossh with a monitoring port (-M port); when several tunnels to the same server use the same monitoring port, they interfere and at least one connection gets terminated. There also were cases when sshd kept running on the server while the client was actually disconnected, and the client could not restore the connection because the old process still blocked its ports. And by default neither autossh nor ssh check whether all forwardings were set up successfully, which leads to incomplete connections with only some of the port forwardings working (e.g. if a port on the server is still in use by another process).
Not all of this is autossh's fault: the hanging sshd is a server side issue, and incomplete forwardings can be prevented by an ssh option. OpenSSH can handle all of it by itself: it offers built-in monitoring without additional ports, it can quit when a forwarding fails, and sshd can drop dead connections. However, there are quite a few options that you should know about in order to improve security and reliability of such a setup. This is the motivation behind this tutorial.
If you prefer autossh, you can use it with -M 0 together with the ssh options of this tutorial. This turns off its monitoring ports, so autossh only restarts ssh when it exits, which is essentially what the simple loop shown below does. Note that by default autossh gives up if the very first connection fails within 30 seconds (e.g. because a port on the server is still blocked), unless you set AUTOSSH_GATETIME=0.

Disclaimer

When you follow this guide, you can make otherwise protected services accessible to the public Internet (when using ssh -R). This might be an attack vector into your protected network.
When you don't set restrictions properly, an attacker might gain access to your server, either via direct shell access or through forwarding the port of your unprotected service (e.g. a database on localhost).

Server configuration

First become root through sudo su - or su -.

/etc/ssh/sshd_config

Add the following lines at the end of the file (a Match block applies to everything below it, so it has to be the last section):

Match User ssh-port-forwarding
    GatewayPorts clientspecified
    ClientAliveInterval 5
    ClientAliveCountMax 3

GatewayPorts clientspecified allows the user ssh-port-forwarding to forward their local ports to an unprivileged public port on the server (ssh -R). You have to restrict this later on through the permitlisten variable in the authorized_keys file. Don't set it globally: other accounts without a shell but with TCP forwarding (e.g. SFTP-only users) could then open public ports on your server, too.

The other two variables specify how often the server should send keep alive messages and how many missed messages from the client it will tolerate. This is crucial for reliable reconnects: if the client vanishes without closing the connection (e.g. network outage, power loss), the old sshd process on the server keeps running and keeps the forwarded ports bound. Every reconnect would then fail because of ExitOnForwardFailure (see below). With these settings the server drops the dead connection and frees the ports after about 15 seconds, which is well below the 30 seconds the client waits before reconnecting. The same has to be set on the client side, but there it can be done as a command line parameter.

special user account

on debian you can run the following:

adduser ssh-port-forwarding --system
su ssh-port-forwarding -s '/bin/bash' -c 'mkdir ~/.ssh/; chmod 700 ~/.ssh/; touch ~/.ssh/authorized_keys'

/etc/passwd should look similar to this:
ssh-port-forwarding:x:1001:65534::/home/ssh-port-forwarding:/usr/sbin/nologin
and ls -lsha ~ssh-port-forwarding/.ssh/ should look like this:

4,0K drwx------ 2 ssh-port-forwarding nogroup 4,0K 18. Feb 22:18 .
4,0K drwxr-xr-x 3 ssh-port-forwarding nogroup 4,0K 18. Feb 22:18 ..
   0 -rw-r--r-- 1 ssh-port-forwarding nogroup    0 18. Feb 22:18 authorized_keys

Configuring access rights

This is all done in /home/ssh-port-forwarding/.ssh/authorized_keys.

First use the ssh-keygen -t ed25519 command to create a private and public key pair on the client side. Don't type any password! Then use cat ~/.ssh/id_ed25519.pub to display the content of your newly created public key. After that add a new line in the authorized_keys file on the server. Use the following line as an example. Your client's public key starts at AAAA... and this all needs to be in a single line per key.
restrict,command="",port-forwarding,permitlisten="localhost:9999",permitopen="localhost:80" ssh-ed25519 AAAA...

  • restrict: this disables port, agent and X11 forwarding, PTY allocation and execution of ~/.ssh/rc, including any restrictions added in future OpenSSH versions (we will whitelist what we need)
  • command="": don't allow client to send a command, set an empty forced command instead
  • port-forwarding: allow port forwarding
  • permitlisten="localhost:9999": permit client to create a listening socket (via ssh -R) on port 9999 on the server, which forwards requests to a service on the client
  • permitopen="localhost:80": permit client to access (via ssh -L) port 80 on server, which will then be offered as a local port on the client

permitlisten requires OpenSSH 7.8 or newer on the server. The permitopen and permitlisten options can be used multiple times in a row. The syntax is as follows:

  • permitlisten="[host:]port
    • port is the port on the server that you want to open locally or towards the Internet
    • host specifies on which interface the server should listen for incoming connections. You should either specify localhost or *
      • localhost binds the port to the loopback device and can only be used by processes on the same server
      • * allows access from everywhere (e.g. from the Internet, if your firewall allows that) if GatewayPorts clientspecified is set in /etc/ssh/sshd_config
  • permitopen="host:port"
    • host is the hostname or IP address (as seen from the server) that the client should be allowed to connect to via your server, e.g. localhost for the server itself or another host in the server's network
    • port is the port number on the host that will be forwarded to the client

Client side configuration

First connect to your server manually without BatchMode (e.g. ssh ssh-port-forwarding@myserver.example.com), in order to accept the server's host key!
You should run the client side ssh command in a loop because it is tuned to terminate as soon as errors are detected. Don't worry, this is well tested. If you are old school you simply put this into /etc/rc.local:

#!/bin/bash

(while true; do
        ssh ...
        sleep 30
done) &
disown

exit 0

Don't forget to mark the script as executable: chmod +x /etc/rc.local

The client side ssh command looks like:
ssh ssh-port-forwarding@myserver.example.com -TNnqakx -o "TCPKeepAlive yes" -o "ServerAliveInterval 5" -o "ServerAliveCountMax 3" -o "ExitOnForwardFailure yes" -o "BatchMode yes" -R [bind_address:]port:host:hostport -L [bind_address:]port:host:hostport

  • -T disable pseudo terminal allocation
  • -N don't execute any command on the server
  • -n redirect stdin to /dev/null (necessary as we run this command in background)
  • -q disable most output
  • -a don't forward the authentication agent connection
  • -k disable forwarding of GSSAPI credentials
  • -x disable X11 forwarding
  • -o "TCPKeepAlive yes" enable TCP keepalive messages on the operating system level (default anyway; the actual connection monitoring is done by the ServerAlive* options below)
  • -o "ServerAliveInterval 5" send test messages every five seconds
  • -o "ServerAliveCountMax 3" mark connection as failed after 3 lost test messages
  • -o "ExitOnForwardFailure yes" quit ssh process if any of the forwardings cannot be set up (this is a crucial feature missing in autossh); a connection that dies later is detected by the ServerAlive* options
  • -o "BatchMode yes" never prompt for passwords or host key confirmation, fail instead (the loop must never hang waiting for input)
  • -4 (not shown above) is optional to force ssh to use IPv4 only (in case of problems with IPv6)
  • -g (not used here) allows other hosts to connect to ports forwarded with -L (same as setting [bind_address:] to *:); it has no effect on -R, where only [bind_address:] and GatewayPorts on the server decide
  • -R [bind_address:]port:host:hostport (see above -> permitlisten; can be repeated multiple times)
    • [bind_address:] address on the server, that the port should be bound to; defaults to localhost:, can be set to *: (optional)
    • port port on the server that should opened for incoming connections
    • host hostname or address that the client should forward the connection to (e.g. localhost)
    • hostport existing port on the host that should be forwarded
  • -L [bind_address:]port:host:hostport (see above -> permitopen; can be repeated multiple times)
    • [bind_address:] address on the client, that the port should be bound to; defaults to localhost:, can be set to *: (optional)
    • port port on the client that should be opened
    • host host that the client wants to access through the server (e.g. localhost on the server itself)
    • hostport existing port that should be forwarded to the client

Please beware that the hostname part in the -L and -R options must be spelled exactly the same as in the permitlisten and permitopen variables on the server ("Localhost", "localhost" and "127.0.0.1" are treated different). Note that ExitOnForwardFailure only catches a rejected -R forwarding. A -L forwarding that is not covered by permitopen is still set up on the client and only fails when a connection is opened through it ("administratively prohibited"). So test each -L forwarding manually once.

Example

In this example we forward a http based service running on the client (port 80) to the server (port 2280). The server can then deliver the service via its own webserver. Port 2280 on the server is only available locally.
Additionally the client accesses the remote mail server (port 25) and provides local access for applications running on the client (through port 2225). That way an application on the client can send mail via the remote server. It is not necessary to open the remote mail relay to the internet. Requests to port 2225 on the client are treated as if they were done locally on the server.
The last forwarding could be used to publicly offer a service running on the client (port 9999) via the server (port 8080). Port 8080 on the server can be accessed by everyone on the internet and will be forwarded to port 9999 on the client.

Server

/etc/ssh/sshd_config

(added at the end of the file)

Match User ssh-port-forwarding
    GatewayPorts clientspecified
    ClientAliveInterval 5
    ClientAliveCountMax 3

/home/ssh-port-forwarding/.ssh/authorized_keys

(client public key shortened to AAAA...)

restrict,command="",port-forwarding,permitlisten="localhost:2280",permitlisten="*:8080",permitopen="localhost:25" ssh-ed25519 AAAA... root@client

Client

If you were not connected to this server before from your client, connect once without BatchMode (e.g. ssh ssh-port-forwarding@myserver.example.com) to accept the server's host key. Then test the ssh command from the script manually before running the script.

/etc/rc.local

#!/bin/bash

(while true; do
        ssh ssh-port-forwarding@myserver.example.com -TNnqakx -o "TCPKeepAlive yes" -o "ServerAliveInterval 5" -o "ServerAliveCountMax 3" -o "ExitOnForwardFailure yes" -o "BatchMode yes" -R '2280:localhost:80' -L '2225:localhost:25' -R '*:8080:localhost:9999'
        sleep 30
done) &
disown

exit 0