Skip to content

SSH Local Port Forwarding for PostgreSQL

Problem

Need to connect to PostgreSQL (port 5432) running on remote host 10.129.228.195 from local machine.

Solution

Use SSH local port forwarding to tunnel the connection.

Command

ssh -L 5432:localhost:5432 user@10.129.228.195

Run this on: Your local machine (Parrot VM)

Breakdown

  • -L = Local port forward
  • 5432:localhost:5432 = Forward local port 5432 to remote localhost:5432
  • user@10.129.228.195 = SSH into the target as user

How It Works

  1. Your local port 5432 connects through SSH tunnel
  2. SSH forwards traffic to remote machine's localhost:5432
  3. Remote PostgreSQL sees connection as coming from localhost
  4. All traffic encrypted through SSH

Connecting to PostgreSQL

psql -h localhost -p 5432 -U postgres

Run this on: Your local machine (Parrot VM) - NOT on the remote host

  • psql runs locally on your attack box
  • Connects to localhost:5432 which is the tunnel endpoint
  • Traffic goes through tunnel to remote PostgreSQL

Important Notes

  • ~C trick does NOT work - only works if SSH started with -L flag from the beginning
  • Cannot add port forwarding to existing SSH session - must start new connection
  • If local port 5432 already in use, change first number: -L 5433:localhost:5432

Alternative: Background Tunnel

ssh -L 5432:localhost:5432 -N user@10.129.228.195
  • -N = Don't execute commands, just maintain tunnel
  • Useful if you want to keep your existing SSH session open
  • Run in separate terminal