PHP mail() Email Injection Attack Allows Spammers to Send Email

19:29.13 - Tuesday 14th February 2006   (Link to This Entry)


I was at a client's last week and the guy who handles the email mentioned that they were getting a lot of spam from the same email addresses, all of which were at the default name of our server. I had a quick look and, sure enough, email was being sent through a mail script on the back end of my client's Contact Us page. Because the To: address is hardwritten into the script, my client received copies of the spam as well as the injected recipients.

How the Email Injection Attack works...
The injection attack works with any mailing script that uses the PHP mail() function. If the script accepts a name and email address, and formats those into the From: field of your email, then they can be used to insert extra email addresses anonymously.

Ordinarily you would take a name ($name) and an email address ($email) and create a string like so:which creates: followed by a '\r\n', or Character Return+Line Feed.

Using a form on another server, or even the existing form if there's no client-side length checking, the spammer submits the following as $name:PHP's mail() function puts these into the headers as usual, but the headers now contain an extra Subject: and Bcc: field that were not there before. Either the $name or $email variables (in our example) can be used for this, and there's nothing to stop them attaching files using MIME.

So How to I Protect Against Email Header Injection Attacks?
Thankfully, protecting yourself is quite easy - probably the easiest way is for you to check the vulnerable fields for illegal content on receipt by your processing script. My approach was to write a simple function using a regular expression, thus: All you have to do to check the vulnerable fields is include the function and call it for each one: If either 'Cc:', 'Bcc:' or 'Subject:' is found somewhere it shouldn't be, the script generates an email containing the name of the script and the spammer's IP address, sends it to spamcheck@domain.tld and promptly dies.


[ 0 comments pending ]