1

Hello I have build a email form and I like to know if it is build in a secure way.
I have read the article How to Prevent Email Injection in Your PHP Form to Mail Scripts and applied it to my script. Now I like to know if the variable $to and $bcc are save.

function sendmail($to,$subject,$message,$bcc=NULL){

    //Prevent Email Injection in Your PHP Form to Mail Scripts
    if ( preg_match( "/[\r\n]/", $to ) ||  preg_match( "/[,]/", $to ) || preg_match( "/[\r\n]/", $bcc ) || preg_match( "/[,]/", $bcc ) ) {

        return '<h1>Danger found: possible email Injection Hijacking</h1>';
        return false;

    }else{
        // To send HTML mail, the Content-type header must be set
        $headers  = 'MIME-Version: 1.0' . "\r\n";
        $headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";

        // Additional headers
        $headers .= 'From: No Reply <no-reply@domain.nl>' . "\r\n";
        if(isset($bcc)) $headers .= 'Bcc: ' .$bcc."\r\n";

        // Mail it
        return mail($to, $subject, $message, $headers);
    }
}
sendmail($_REQUEST['email'],'Subjectline', 'message','admin@domain.com');
user1073323
  • 163
  • 3
  • 14

2 Answers2

0

The vulnerability in mail comes from header injection. To prevent it, you can look for newlines in the header values, ie.:

"BCC: " . $email . "
X-OtherHeader: Foo-Bar

If $email contains a newline, like:

webmaster@domain.com
TO: pro@hackerz.ru

You will get an extra TO header, which is potentially malicious. Header injection allows an attacker to send an email from your mailserver to anyone, essentially turning your mailserver into a spam server.

From the looks of it your current script is safe.

Halcyon
  • 57,230
  • 10
  • 89
  • 128
-1

Make sure there are only one e-mail replacing $str (string) using:

$str=str_replace(";","",$str);
$str=str_replace(",","",$str);
ainos
  • 163
  • 1
  • 6
  • They can be valid characters in an email address if quoted: http://haacked.com/archive/2007/08/21/i-knew-how-to-validate-an-email-address-until-i.aspx – SilverlightFox Oct 03 '13 at 09:50