Restrict SSH local forwarding with a dedicated account

Restrict SSH local forwarding with a dedicated account

Binding a database to loopback and accessing it through an SSH tunnel is a common administration pattern on dedicated servers running multiple services. Reusing an administrator account for the tunnel, however, also grants shell access, file access, and unrestricted forwarding privileges. A better approach is to create a dedicated tunnel account, allow it to reach only one explicit address and port, and use denial tests to prove that the restrictions hold.

This guide uses Debian 12 and requires OpenSSH server and Python 3 on the server, plus SSH and curl on the client. All ports are explicitly chosen for this exercise; they are not delivery defaults. Credentials for NetAmd servers are available in the console after payment. When multiple IPv4 addresses are assigned, use the first address for the management connection.

1. Define the tunnel boundaries

The goal is to let the client access 127.0.0.1:18080 on the server without granting a shell or allowing remote forwarding. The dedicated account is named tunnel-a; it does not replace the existing administrator account.

For local forwarding, the server initiates the connection to the destination. The loopback address here therefore refers to the server itself, not the administrator's computer. PermitOpen restricts the destination specified in an SSH forwarding request. It does not control access to the application or replace database authentication.

Do not expose the backend service on a public address just to enable a tunnel. Restricting the forwarding account, binding the backend to loopback, and retaining application authentication are three independent boundaries.

Before starting, keep a verified working administrator session open, back up the SSH configuration, and confirm that you can log in again from a second session. This exercise only adds an account and rules; it does not change the administrator's authentication method.

2. Prepare a dedicated key and a loopback service

Transfer only the public key

Generate a dedicated key for this exercise on the client. If a file with the same name already exists, choose another filename to avoid overwriting it:

ssh-keygen -t ed25519 -f ./tunnel-a

Use the existing management connection to place tunnel-a.pub at /root/tunnel-a.pub on the server. Keep the private key on the client and set a passphrase according to your organization's requirements. Run the following server commands with administrator privileges, after confirming that the account and directory do not already exist:

useradd --create-home --shell /bin/sh tunnel-a
install -d -m 700 -o tunnel-a -g tunnel-a /home/tunnel-a/.ssh
{
  printf '%s ' 'restrict,port-forwarding,permitopen="127.0.0.1:18080"'
  cat /root/tunnel-a.pub
} > /home/tunnel-a/.ssh/authorized_keys
chown tunnel-a:tunnel-a /home/tunnel-a/.ssh/authorized_keys
chmod 600 /home/tunnel-a/.ssh/authorized_keys

restrict disables a set of key capabilities, and port-forwarding then re-enables forwarding. The permitted direction still needs to be restricted on the server. The public key must remain one complete record; copying it must not introduce line breaks that split it into multiple records.

Test with an endpoint containing no sensitive data

Run the following in the foreground in a separate administrator terminal on the server:

install -d -m 700 /var/tmp/tunnel-fixture
printf '%s\n' 'tunnel-ok' > /var/tmp/tunnel-fixture/probe.txt
python3 -m http.server 18080 --bind 127.0.0.1 \
  --directory /var/tmp/tunnel-fixture

If the port is already in use, identify the process first; do not terminate an unfamiliar service. This directory must contain only the test text. Never use a production data directory as the HTTP document root.

3. Restrict forwarding on the server

Review the existing rules in /etc/ssh/sshd_config and its included files to make sure there are no conflicting settings for this account. Back up the main file, then append the following complete block to its end:

Match all
Match User tunnel-a
    AuthenticationMethods publickey
    PasswordAuthentication no
    KbdInteractiveAuthentication no
    AllowTcpForwarding local
    PermitOpen 127.0.0.1:18080
    PermitListen none
    AllowStreamLocalForwarding no
    AllowAgentForwarding no
    X11Forwarding no
    PermitTTY no
    PermitTunnel no
    GatewayPorts no
    MaxSessions 0
Match all

MaxSessions 0 blocks shell, remote-command, and subsystem sessions while leaving forwarding channels available, so the client must use -N. Disabling terminal allocation alone does not prevent remote commands, and restricting TCP forwarding alone does not cover Unix socket forwarding.

Check the syntax first, then inspect the effective configuration for the specified identity:

/usr/sbin/sshd -t
/usr/sbin/sshd -T \
  -C user=tunnel-a,host=client,addr=192.0.2.10 |
  grep -E 'authenticationmethods|allowtcpforwarding|permitopen|permitlisten|maxsessions|allowstreamlocalforwarding'

The address here is a documentation address used as an input to the configuration check, not an actual connection destination. If any rules match on source address, repeat the check with the real client address. The results must match your expectations; do not assume that values appended to the end of the file necessarily override existing rules.

Once both the syntax and effective values pass inspection, run systemctl reload ssh, then verify a new administrator login. Reloading does not automatically revoke existing tunnels, so acceptance testing must use new connections.

4. Test both allowed and denied access

On the client, read in the actual address and SSH port to avoid mistaking example values for the server's connection details:

read -r -p 'Server IPv4: ' HOST
read -r -p 'SSH port: ' SSHPORT
ssh -p "$SSHPORT" -i ./tunnel-a -o IdentitiesOnly=yes \
  -o ExitOnForwardFailure=yes -N \
  -L 127.0.0.1:28080:127.0.0.1:18080 "tunnel-a@$HOST"

On the first connection, verify the host key against an existing trusted record. Do not disable host identity checking. Leave this command running and make the following request from another terminal on the client:

curl --fail --max-time 5 http://127.0.0.1:28080/probe.txt

The response must be tunnel-ok. Then test each of the following:

Run each test separately and close the connection afterward. Save the client diagnostics and corresponding server logs. An out-of-scope destination should produce evidence of a policy denial, not merely “connection refused,” which may only mean that no service is running at the destination.

ExitOnForwardFailure does not connect to every local forwarding destination in advance. A running SSH process or a listening local port is no substitute for a real application request.

5. Switch to production and verify revocation

When replacing the test endpoint with the actual database endpoint, update the destination restrictions both on the server and in the public key. The two layers enforce their intersection; missing either update will cause connections to fail. Keep the destination restricted to an exact address and port, without wildcards that allow arbitrary destinations. If multiple services are needed, record the purpose and owner of each one.

The deployment record should retain at least the account, public key fingerprint, allowed destinations, effective configuration, and results of both positive and negative tests. Sharing one tunnel identity across multiple services weakens attribution. Split identities by administrative purpose rather than opening an entire internal address range.

To revoke access, first remove the public key and confirm that all existing SSH connections for that identity have ended. Then verify that the old key cannot establish a new tunnel. Removing the public key alone does not terminate authenticated connections; long-lived application connections also need to be checked separately.

After the exercise, stop the foreground HTTP service and delete the files and directories confirmed to belong to the test. Final acceptance requires that the allowed service is reachable, unauthorized destinations have clear evidence of denial, shell access and remote listeners are unavailable, and the original management access still works.

Frequently asked questions

Can an SSH tunnel work with MaxSessions set to zero?

Yes. MaxSessions 0 blocks shell, command, and subsystem sessions without blocking forwarding channels. Use ssh -N and apply separate destination restrictions.

Does ExitOnForwardFailure validate the destination service?

No. For local forwarding, it primarily catches setup failures such as a local listener failing to bind. Send a real request through the tunnel to test PermitOpen and the service.

AMD EPYC 7543P Dedicated Server

From $468/month. Total due = monthly total × number of months.

Configure the number of IP addresses for your needs

Each server includes 1 dedicated IPv4 address, with up to 255 additional addresses available. Total due = monthly total × number of months.