The number one rule in programming is not to trust external data, especially not user data. One of the reasons not to trust user data is the threat of hackers searching for injection possibilities. When you start develloping web applications you’ll soon learn the dangers of SQL injection. This might be the most important form of injection, but by far it is not the only one out there: cross site scripting is another good example. If your application sends out mail, you might want to make sure you sanitize user input as well as the application could be a magnet for spammers who’ll send spam mail using your IP.
Mail is formatted using MIME, a content discription format. In this format, all properties of an email are specified in the header of the message. Examples include ‘From:’, ‘Subject:’ and ‘Date:’ for instance and also ‘To:’ and ‘Cc:’ are headers in the MIME.
Mail is generally sent using SMTP. In contrast to MIME, the message format description, SMTP is a protocol. One can tell a mail server (SMTP) the recipients of an email using this protocol. Therefor these recipients set with SMTP can be different than the ones specified in the MIME message (ever noticed a header like ‘undisclosed recipients’, which is clearly not a valid email address).
Because it is redundant at a high programming level, like PHP, to set recipients twice (once in MIME and once in SMTP), methods are defined for sending mail. PHP’s mail() function for example accepts ‘to’, ’subject’ and ‘message’ parameters. Also, since the number of different MIME headers are virtually infinite, it also accepts an ‘additional headers’ parameter. This is one part of introducing a potential security breach.
The other part is in the function’s handling of the additional headers parameter. Of course it has to be possible to send mail using recipients specified as Cc or Bcc instead of To. To this end mail() examines the parameter for these headers and extracts them. As headers are specified per line in the MIME format, you can inject headers to the ‘additional headers’ parameter if one has access to a field in it, let’s say ‘Date:’ or ‘From:’. Headers are separated using a line feed character (LF), \n in PHP or %0A url encoded.
A MIME email usually has the following layout:
To: you@yourdomain.com From: me@mydomain.com Subject: Hi there I'm just mailing to say hello!
Now if you have your website visitors send you mail and have them set the ‘From:’ header contents for instance, they might fill out an arbitrary email address and add ‘%0ABcc: extra@email.com; extra2@email.com;… (etc)’. Now also an Bcc header is set and your mail form just became a spam robot. Workaround is simple: don’t allow newlines in MIME header fields! Another post about this common pittfall can be found on websiterepairs.net.