PHP's mail() function is a very useful and powerful function, even to the point that it is very easy to exploit. A way hackers exploit this function is a method called email header injection. Let's look at a simple (injectable) PHP mail function...
<?php
if(isset($_POST['submit']))
{
$message = $_POST['message'];
$reply_to = $_POST['replyto'];
$name = $_POST['name'];
$to = 'myemail@emailhost.com';
$subject = 'My Subject';
#headers start here
$headers = "Cc: whatever@anotherhost.com\r\n";
$headers .= "Reply-To: $reply_to";
$headers .= "From: $name";
mail($to, $subject, $message, $headers);
}
?>
I'm sure most of you can already tell that's not going to be pretty since we didn't check the user input and so forth. PHP provides us with functions such as filter_var which will validate user input and either return false if the validation fails or return the filtered data.
Small example of how we can use the filter_var function. ( Don't use die in instances like these because it is not user friendly. Instead use a redirect 'header("location: whatever.html");'. )
$reply_to = filter_var($reply_to, FILTER_VALIDATE_EMAIL);
if(!$reply_to)
die("Invalid Email");
...
Header Injections
Make a simple mailing form which the fields Name, Email and Message. After doing so enter data into Name and Email but in the Message field enter this...
"Subject:Mail%20Injection%0ABcc:myemail@emailhost.com%0AFrom:A%20Random%20Guy%0ASecure%20your%20mail%20function"
Notice how the mail function behaves when this is entered into the message field. A blind copy would have been sent to myemail@emailhost.com and the Subject and From fields would have been overridden.
For reference
%0A == newline ( \n )
%20 == space ( )
Preventing Header Injections
Preventing such attacks is as simple as replacing the following characters, \r, %0D, \n, %0A and stripping the slashes.
function sanitize(&$array)
{
foreach($array as &$data)
$data = str_replace(array("\r", "\n", "%0a", "%0d"), '', stripslashes($data));
}
}
Conclusion
Imagine someone using a library such as cURL to send automated $_POST data to your mailing script blotted with header injections...not pretty. Always sanitize user input no matter what!!
Other Functions for Data Validation
PCRE functions





MultiQuote







|