πŸ”§SSH Tunneling Complete Guide

Overview

SSH tunneling is one of the most reliable and commonly used methods for pivoting and port forwarding. SSH provides encrypted tunnels that can bypass firewalls and access internal services.


SSH Tunnel Types

1. Local Port Forwarding (-L)

Purpose: Forward local port to remote destination through SSH server

Syntax:

ssh -L [local_ip:]local_port:destination_host:destination_port user@ssh_server

# Common usage
ssh -L 8080:192.168.1.100:80 user@10.10.10.50

Traffic Flow:

[Your Machine] β†’ [SSH Server/Pivot] β†’ [Target Service]
localhost:8080 β†’ 10.10.10.50:22 β†’ 192.168.1.100:80

Real-world Examples:

# Access internal web server
ssh -L 8080:192.168.1.100:80 user@pivot.com
# Then browse: http://localhost:8080

# Access internal RDP
ssh -L 3389:192.168.1.50:3389 user@pivot.com
# Then RDP to: localhost:3389

# Access database server
ssh -L 1433:db.internal.com:1433 user@jumpbox.com

# Forward multiple ports
ssh -L 8080:web.internal:80 -L 3389:dc.internal:3389 user@pivot.com

2. Remote Port Forwarding (-R)

Purpose: Forward remote port back to local machine (reverse tunnel)

Syntax:

Traffic Flow:

Use Cases:

3. Dynamic Port Forwarding (-D)

Purpose: Create SOCKS proxy for multiple connections

Syntax:

Configuration:


SSH Options and Flags

Essential Flags

Practical Combinations


Advanced SSH Tunneling

Multiple Hops (ProxyJump)

SSH Config File

Persistent Tunnels with autossh


Troubleshooting SSH Tunnels

Common Issues

1. Permission Denied

2. Port Already in Use

3. Connection Refused

4. GatewayPorts Issue

Debugging Commands


SSH Tunneling in Different Scenarios

Scenario 1: Web Application Testing

Scenario 2: Database Access

Scenario 3: RDP/VNC Access


SSH Tunneling with Metasploit

Using SSH Sessions


Security Considerations

SSH Server Configuration

Key Management

Firewall Evasion


Best Practices

  1. Always test basic SSH connectivity first

  2. Use key-based authentication when possible

  3. Clean up tunnels after use (kill background processes)

  4. Monitor tunnel stability with autossh

  5. Use compression (-C) for slow connections

  6. Employ least privilege (specific ports only)

  7. Log tunnel activities for documentation


Quick Reference

Task

Command

Local forward

ssh -L 8080:target:80 user@pivot

Remote forward

ssh -R 8080:localhost:80 user@target

SOCKS proxy

ssh -D 1080 user@pivot

Background tunnel

ssh -fNT -L 8080:target:80 user@pivot

Multiple ports

ssh -L 8080:web:80 -L 3389:dc:3389 user@pivot

Through jump host

ssh -J jump.com -L 8080:target:80 user@final


References

  • SSH Manual: man ssh

  • SSH Config: man ssh_config

  • OpenSSH Cookbook: https://en.wikibooks.org/wiki/OpenSSH

  • HTB Academy: Pivoting, Tunneling & Port Forwarding

Last updated