2

I have read the following comment in the official documentation of php about mail() function:

Although it is not documented, for the parameters $to and $subject the mail() function changes at least \r and \n to space. So these parameters are safe against injection of additional headers. But you might want to check $to for commas as these separate multiple addresses and you might not want to send to more than one recipient.

Is it correct? Also, I have always considered the $message parameter safe against injection, is it also correct?

I know how to protect myself against injection, I just want to know if I can avoid to filter those parameters.

Funk Forty Niner
  • 74,450
  • 15
  • 68
  • 141
Joy
  • 267
  • 1
  • 4
  • 13
  • Depends on what you mean by injection. If you let the user give values for the recipient, of course they can give whatever values they want. – Sami Kuhmonen Mar 06 '17 at 13:54
  • Duplicated with this: http://stackoverflow.com/questions/8071916/escape-string-to-use-in-mail – Đào Minh Hạt Mar 06 '17 at 13:54
  • @SamiKuhmonen no, I mean injection of additional headers (email injection vulnerability). – Joy Mar 06 '17 at 14:01
  • @ĐàoMinhHạt it is not a duplicate, I know how to protect myself against injection, I just want to know if I can avoid to filter those parameters. – Joy Mar 06 '17 at 14:03
  • If you're familiar enough with C to follow the logic, you can see exactly what is replaced here: http://lxr.php.net/source/xref/PHP-MASTER/ext/standard/mail.c#284 – IMSoP Mar 06 '17 at 14:25

2 Answers2

1

Yes, that's true, but it's also incomplete. In the engine source code, the function php_mail_build_headers ensures headers comply with RFC 2822 § 3.6 requirements for maximum number of values. Particularly, the following headers are checked for single value:

  • orig-date
  • from
  • sender
  • reply-to
  • to
  • bcc
  • message-id
  • in-reply-to
  • subject

Yes, the message parameter is safe from header injection by definition: the message part is inserted after the separating new line between headers and body, so any header-like text inserted as part of the message will appear as literal text within the message body.

Community
  • 1
  • 1
bishop
  • 37,830
  • 11
  • 104
  • 139
0

For your comment that you don't want to apply those filters.

I think you can get it done automatically by using Zend_Mail as I commented.

$ composer require zendframework/zend-mail

I'm pasting this from their documentation:

use Zend\Mail\Message;
use Zend\Mail\Transport\Sendmail as SendmailTransport;

$message = new Message();
$message->addTo('matthew@example.org');
$message->addFrom('ralph@example.org');
$message->setSubject('Greetings and Salutations!');
$message->setBody("Sorry, I'm going to be late today!");

$transport = new SendmailTransport();
$transport->send($message);
Đào Minh Hạt
  • 2,742
  • 16
  • 20