devutils/ATFQ/book ATFQ git

Part III · Shell and commands

29.3 SSH tunnels and port forwarding

alsossh tunnelssh tunnelsport forwardinglocal forwardingremote forwardingsocks proxytunnel

TL;DR

  • -L: a port on your machine leads to a port reachable from the server. Reach a database that only listens on the server's localhost.
  • -R: a port on the server leads back to your machine. Show a local web app to someone who can reach the server.
  • -D: a SOCKS proxy; your browser's traffic leaves from the server.
ssh -N -L 5433:localhost:5432 db       # local 5433 → db's PostgreSQL
ssh -N -R 8080:localhost:3000 server   # server's 8080 → your 3000
ssh -N -D 1080 server                  # SOCKS proxy on localhost:1080

On your machine

alice@laptopexample
$ atfq 29.3
  TCP       0.0.0.0:22      all interfaces     user root
  TCP       [::]:22         all interfaces     user root
  TCP       127.0.0.1:631   this machine only  user root
  TCP       127.0.0.1:8080  this machine only  supervisor (PID 4100)
  UDP       0.0.0.0:5353    all interfaces     user avahi
  note: the process of a socket owned by another user needs root: sudo ss
  -tulpn

An example: Alice's laptop, one of the test machines. In your terminal, this block shows your own machine, read live.

Pitfalls

Deep dive 2 questions

What travels where?

Your client accepts a connection on the local port, sends its bytes inside the encrypted SSH session, and sshd opens a connection to the target from the server's side. The target sees a connection from the server; only the leg between client and server is protected by SSH, the last hop is ordinary traffic.

Tunnel or VPN?

A tunnel forwards one port per option, for one person, using an account you already have. A VPN (WireGuard, OpenVPN) carries all traffic of whole networks and needs setting up on both ends. For reaching one service now, a tunnel; for a team reaching many, a VPN.

Commands
ssh ss
See also
29.2 ~/.ssh/config, jump hosts and host keys
19.1 Who listens on which port