20 January 2017

Email injection attacks in PHP

Image: Pixabay
Email injection is one of the topics I cover in my Zend certification guide.  You can grab a copy on Leanpub - https://leanpub.com/phpforprogrammers/

It is possible for a user to supply hexadecimal control characters that allow them to change the message body or recipient list.

For example, if your form allows the person to enter their email address as a “from” field for the email then the following string will cause additional recipients to be included as cc and blind carbon copy recipients of the message:

sender@example.com%0ACc:target@email.com%0ABcc:anotherperson@emailexample.com,stranger@shouldhavefiltered.com

It is also possible for the attacker to provide their own body, and even to change the MIME type of the message being sent.  This means that your form could be used by spammers to send mail from.

You can protect against this in a couple of ways.

Make sure that you properly filter input that you use when sending mails.  The `filter_var()` function provides a number of flags that you can use to make sure that your input data conforms to a desired pattern.

<?php
$from = $_POST["sender"];
$from = filter_var($from, FILTER_SANITIZE_EMAIL);
// send the email

You could also install and use the Suhosin PHP extension.  It provides the `suhosin.mail.protect` directive that will guard against this.

You could implement a tarpit to slow bots down or trap them indefinitely.  Take a look at msigley/PHP-HTTP-Tarpit on Github  as an example of a tarpit.

Just be careful that when setting up your mail server you must make sure it is not configured as an open relay that allows anybody on the Internet to use it to send mail.  You should also consider closing port 25 (SMTP) on your firewall so that outside hosts are unable to reach your server.

Tip