Possible Security Issue with FILTER_VALIDATE_EMAIL
July 19, 2008 2:03 am PHPJust a few days ago I recommended using filter_var() with the FILTER_VALIDATE_EMAIL argument as a convenient means of validating email address formats. However, Phill Pafford (ReliableSource.org) pointed out at WebDeveloper.com that there was a security bulletin suggesting a potential danger due to this validation allowing linefeeds in certain situations. I did a little testing, and sure enough, I found that if the email ends in a linefeed character, it still passes validation.
<?php
header('Content-Type: text/plain');
$email = 'foo@bar.com';
$len = strlen($email);
for($i = 0; $i <= $len; $i++)
{
$test = substr_replace($email, "\n", $i, 0);
$result = filter_var($test, FILTER_VALIDATE_EMAIL);
var_dump($result);
}?>
Which outputs:
bool(false) bool(false) bool(false) bool(false) bool(false) bool(false) bool(false) bool(false) bool(false) bool(false) bool(false) string(12) "foo@bar.com "
A work-around is to either trim() the value first, or else if you prefer to reject any such entry then do some sort of preg_match() or similar search for newlines and/or carriage returns. You can even stay within the filter function domain by first using the "sanitize" constant:
$email = filter_var(filter_var($_POST['email'], FILTER_SANITIZE_EMAIL),
FILTER_VALIDATE_EMAIL);
if($email === false)
{
// Houston, we have a problem....
}
