Understanding SSH Port Forwarding Types

Understanding SSH Port Forwarding Types

SSH supports three distinct types of port forwarding, each serving different use cases and presenting unique security considerations. Understanding these mechanisms enables informed decisions about when and how to deploy port forwarding securely.

Local Port Forwarding creates a secure tunnel from the client to a remote destination through the SSH server. This technique commonly provides encrypted access to services behind firewalls or on private networks:

# Basic local port forwarding syntax
ssh -L [local_addr:]local_port:remote_host:remote_port user@ssh_server

# Example: Access remote database through SSH tunnel
ssh -L 3306:database.internal:3306 [email protected]

# Bind to specific local interface
ssh -L 127.0.0.1:8080:webapp.internal:80 [email protected]

# Multiple forwards in single connection
ssh -L 3306:db.internal:3306 \
    -L 6379:redis.internal:6379 \
    -L 5432:postgres.internal:5432 \
    [email protected]

Remote Port Forwarding (reverse tunneling) exposes local services through the remote SSH server, useful for providing access to services behind NAT or firewalls:

# Basic remote port forwarding syntax
ssh -R [remote_addr:]remote_port:local_host:local_port user@ssh_server

# Example: Expose local web server through remote host
ssh -R 8080:localhost:80 [email protected]

# Bind to all interfaces on remote (requires GatewayPorts yes)
ssh -R 0.0.0.0:8080:localhost:80 [email protected]

# Persistent reverse tunnel with autossh
autossh -M 0 -f -N -R 8080:localhost:80 \
    -o "ServerAliveInterval 30" \
    -o "ServerAliveCountMax 3" \
    [email protected]

Dynamic Port Forwarding creates a SOCKS proxy through the SSH connection, providing flexible forwarding for multiple destinations:

# Create SOCKS proxy
ssh -D 1080 [email protected]

# Bind to specific interface
ssh -D 127.0.0.1:1080 [email protected]

# Use with applications
curl --socks5 localhost:1080 http://internal-site.example.com