How To Own A Web Server By Writing An Email

March 8, 2017

PHPMailer allows website visitors to send emails to the website's owners or admins. Recently, there was vulnerability discovered that allows remote attackers to execute code.

PHPMailer validates email addresses using RFC 3696. However, according to the specifications, blank spaces and double-quotes are allowed. By crafting an email address string containing blank spaces and double-quotes, an attacker can then inject code that would have PHPMailer's mail() function call /usr/bin/sendmail differently.

Test Website

For our tests, we crafted a webpage using the following html form:

Fig. 1

The HTML code is shown as:

Fig. 2

While send_form_email.php is as follows:

Fig. 3

Running The Exploit

We attempt to exloit the vulnerability by typing in the following to the web page:

Fig. 4

This generates a file named phpcode.php in /var/www/html/cache/. Looking at the file, we will see that one line contains the php code we placed in the comments section:

Fig. 5

By entering the URL to the generated file, we will see the following in the browser:

Fig. 6

Owning

So far, we know the following:

  1. From Fig. 2, there is a limit to the number of characters we can send in the message.
  2. From Fig. 5, the injected code is placed in one line in the generated file.
  3. We cannot yet "execute" random code.

Basically, our next step would then require us to send code that is:

  1. Short enough to fit the character limit.
  2. Does not require line breaks.
  3. Allow us to have a means to "execute" code.

By using libcurl, we can have the web server download other files for us.

Fig. 7

The above, when executed, would download a file and save it as backdoor.php. Executing the generated phpcode.php file in the browser, we would see only the following:

Fig. 8

However, in the background, the web server is then instructed to download a file and save it as backdoor.php.

Going to backdoor.php, we see the following:

Fig. 9

This is basically a PHP backdoor we can use to execute instructions.

Prevention Methods:

A simple regular expression check can be used to verify the email address as follows:

Fig. 10

SonicWALL Threat Research Team has researched this vulnerability and have the following signatures in place to protect their customers:

  • WAF:9016 - PHP Injection Attack
  • WAF:9039 - PHP Injection Attack 2