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:
- $headers="From: $name <$email>\r\n";
- From: MyName <user@domain.tld>
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:
- blah%0ASubject:SpammerSubject%0Abcc:victim@domain2.tld
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:
- <?php
function spamcheck($spammed_field) {
$spammed_field=strtolower($spammed_field);
if((eregi("cc: ",$spammed_field))||(eregi("subject: ",$spammed_field))) {
$spamhost=$_SERVER['REMOTE_HOST'];
$spamrefr=$_SERVER['HTTP_REFERER'];
$spamaddr=$_SERVER['HTTP_X_FORWARDED_FOR'];
if(strlen($spamaddr)<7) { $spamaddr=$_SERVER['HTTP_CLIENT_IP']; }
if(strlen($spamaddr)<7) { $spamaddr=$_SERVER['REMOTE_ADDR']; }
$thisfile=$_SERVER['SCRIPT_NAME'];
$spamtext="FILE: $thisfile \nFROM: $spamrefr \nADDR: $spamaddr \nHOST: $spamhost \nINFO:\n$spammed_field\n";
mail("spamcheck@domain.tld","ALERT: $spamaddr",$spamtext,"From: SpamCheck <spamcheck@domain.tld>\r\n");
die();
}
}
?>
- include('spamcheck.php');
spamcheck($name);
spamcheck($email);
