Skip to content
Tutorials Center
My learning

Topics

Lesson 19 of 37 ยท VPNs and Tunnelling

SSH Tunnelling and Port Forwarding

Learn SSH local, remote and dynamic port forwarding, jump hosts and key-based login, the security risks of tunnels, and audit an sshd_config in Python.

SSH (Secure Shell) is best known as the way to log in to remote servers, but it is also a general-purpose encrypted tunnel. With a single command you can carry a database connection, a web interface or an entire web browser's traffic through an SSH connection. That makes SSH tunnelling a quick, powerful tool for administrators: reaching an internal service without opening a firewall port, or protecting a legacy protocol that has no encryption of its own.

It is also a double-edged tool. The same feature lets an attacker (or a careless employee) punch a hole through your firewall. Knowing how tunnels work lets you use them well and detect or restrict them. The ssh commands below are read-only examples with documentation addresses; the runnable demos use only your own loopback address.

Authentication first

Before tunnels, get SSH itself right. The server's job is to accept only strong logins.

  • Use key pairs. Generate one with ssh-keygen -t ed25519; protect the private key with a passphrase and an agent. Put the public key in ~/.ssh/authorized_keys on the server.
  • Disable password login (PasswordAuthentication no) once keys work, which ends brute-force guessing as a threat.
  • Disable direct root login (PermitRootLogin no) and log in as a named user who uses sudo.
  • Verify the host key the first time you connect (compare the fingerprint through another channel) and let known_hosts warn you when it changes: that warning can mean a man-in-the-middle.
  • Restrict who may log in with AllowUsers or AllowGroups, and consider limiting the source addresses with a firewall rule or Match Address blocks.
  • Add MFA for sensitive systems, or use short-lived SSH certificates issued by a CA so keys expire automatically.

Local port forwarding (-L)

Local forwarding makes a port on your machine lead to a service reachable from the SSH server.

Terminal
# On your laptop: listen on localhost:5433 and forward through the jump host
# to the database server at 10.1.0.20:5432 (which only the jump host can reach)
ssh -N -L 127.0.0.1:5433:10.1.0.20:5432 [email protected]
# Then connect your client to 127.0.0.1:5433
flowchart LR
    A["App on laptop connects to 127.0.0.1:5433"] --> B["ssh client"]
    B -->|"encrypted SSH connection"| C["Bastion host"]
    C -->|"normal TCP"| D["Database 10.1.0.20:5432"]

The database port is never exposed to the internet. Only SSH to the bastion is.

-N means "do not run a command, just forward"; binding to 127.0.0.1 means other users on the network cannot use your forwarded port.

Remote port forwarding (-R)

Remote forwarding is the reverse: a port on the SSH server leads back to a service on your side.

Terminal
# Make port 8080 on the server reach a development web server on your laptop
ssh -N -R 127.0.0.1:8080:127.0.0.1:3000 [email protected]

This is how people show a local site to a colleague or let a machine behind NAT be reachable. It is also exactly how an insider can create a back door: an outbound SSH connection from inside your network that opens a path from outside back in, bypassing the firewall. By default the remote listener binds only to the server's loopback; GatewayPorts controls whether others may use it.

Dynamic forwarding (-D): a SOCKS proxy

Terminal
ssh -N -D 127.0.0.1:1080 [email protected]

This starts a SOCKS5 proxy on your laptop. A browser configured to use 127.0.0.1:1080 sends all its connections through the SSH server, giving you a quick, encrypted exit point on an untrusted network. It behaves like an ad hoc VPN for applications that support SOCKS.

Jump hosts and agent forwarding

A bastion (jump host) is the single hardened machine that exposes SSH to the internet; everything else is reachable only through it. OpenSSH has built-in support:

Terminal
ssh -J [email protected] admin@10.1.0.20

or in ~/.ssh/config:

TEXT
Host app-internal
    HostName 10.1.0.20
    User admin
    ProxyJump bastion.example.net
    IdentityFile ~/.ssh/id_ed25519

ProxyJump keeps your private key on your laptop: the connection to the target is end-to-end encrypted through the bastion, which only relays bytes. Avoid agent forwarding (ForwardAgent yes) to untrusted hosts, because anyone with root on the intermediate machine can use your forwarded agent while you are connected. ProxyJump is the safer replacement.

A forwarder you can run safely

SSH forwarding is a TCP relay with encryption added. To see the relay part, the Node program below runs a tiny "service" on loopback and a forwarder that listens on another loopback port and copies bytes to the service, just as ssh -L listens locally and relays to the destination. There is no encryption in this demonstration, because the point is the plumbing: the client speaks to the forward port, never to the service directly.

Node.js A local forwarder on loopback (the plumbing of -L)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

In a real tunnel the two ends of the relay sit on different machines and the stretch between them is encrypted and authenticated by SSH, but the structure is identical: a listening port, a relay, a destination.

Defending against unwanted tunnels

Because SSH can tunnel anything, a permissive SSH server is a policy hole. Server-side settings in sshd_config give you control:

  • AllowTcpForwarding no (or local / remote) disables or limits port forwarding. Disable it for accounts that only need a shell.
  • GatewayPorts no keeps remote forwards bound to loopback.
  • PermitTunnel no disables layer-2/3 tunnel devices.
  • X11Forwarding no, AllowAgentForwarding no on hosts that do not need them.
  • Per-key restrictions in authorized_keys: restrict,port-forwarding,permitopen="10.1.0.20:5432" allows only forwarding to that one destination.
  • Egress filtering and monitoring: outbound SSH from servers and workstations to unknown hosts is a classic exfiltration or back-door path. See egress filtering.

Auditing sshd_config

The following program checks a sample sshd_config against a short baseline and prints findings, a technique you can apply to every server in your fleet.

Python Audit an sshd_config against a baseline

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Real tools such as Lynis, OpenSCAP or your configuration management system run the same kind of comparison against a larger baseline.

When to use a tunnel and when not

Good uses: ad hoc admin access through a bastion, protecting a one-off connection, reaching a database for maintenance, a quick SOCKS exit on a hostile network. For many users or long-lived access, a proper VPN or an identity-aware access proxy is easier to manage, log and revoke. Do not use tunnels to circumvent security policy; get the access formally approved.

An SSH tunnel carries encrypted traffic that your network monitoring cannot read. If you need visibility, centralise tunnels through approved bastions with session logging, and alert on unapproved outbound SSH.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does 'ssh -L 127.0.0.1:5433:10.1.0.20:5432 admin@bastion' do?

    Local forwarding listens on your machine and relays connections through the SSH server to the destination it can reach.
  2. 2. Why can remote port forwarding (-R) be a security risk inside a company?

    Remote forwards turn an allowed outbound connection into an inbound back door, so they should be restricted and monitored.
  3. 3. Which is the safer way to reach an internal host through a bastion?

    ProxyJump relays the connection without exposing your key or agent to the intermediate host.
  4. 4. Which sshd_config setting limits port forwarding for an account that only needs a shell?

    AllowTcpForwarding controls forwarding. Port numbers do not restrict tunnels.
  5. 5. In the loopback forwarder demo, what does the client connect to?

    As with ssh -L, the client talks to the local listening port and the relay carries the data onward.

Summary

  • SSH is both a remote shell and a general encrypted tunnel; secure its authentication first (keys, no root, no passwords, host key checking).
  • Local (-L), remote (-R) and dynamic (-D) forwarding cover reaching internal services, exposing local ones and SOCKS proxying.
  • Use jump hosts with ProxyJump and avoid agent forwarding to untrusted machines.
  • Control tunnels with sshd_config, per-key restrictions, egress filtering and logging; audit configuration against a baseline.
  • Prefer a managed VPN or access proxy for many users; use ad hoc tunnels sparingly and with approval.

Next: IDS vs IPS - Detection and Prevention