PHP and Mail

2007-08-11 04:11:55

As promised, some technical junk about phpmail.

The big problem with email is the danger of spam. In php terms these are "header-injections".

Now there are quite a few websites about this bij subject available. However, some information is very confusing. Now what's the real problem and what are the precautions you have to take to prevent injections?

There are two parts to the problem of php-mail. Both fall under the "header-injection" category, meaning an attacker modifies the header of a to be sent email to make it go to other (unintended) addresses, possibly with a different contents. This can be very effective, up to the point of hiding the original mail altogether.

The first part is about adjusting the headers of the email by adding new custom headers. As far as I can tell (by the official mail standard rfc 882) and as far as I have read the only way to get this to work is to add a newline (CRLF, \r\n, #0A10 or whatever you want to call it). The protocol specifies that each header-line is separated by a newline. A double newline indicates the start of the body (the message). Besides that you'll need a colon because it's part of the specification. But any manipulation requires newlines.

The second part is injecting multiple targets. This often occurs with those pages that have a "send to a friend" link where you can add a personal message. Like in your emailclient you have to add a comma or sometimes a semi-colon (as specified in the standard). So if somebody enters the address ",", the message will be sent to both addresses. Sometimes this is not really what you want.

Furthermore, the body of a message cannot be abused unless the header is abused. There are different opinions on the matter which can be confusing, but the standard specifies that once the body starts, the only non-body property the body has is the end. You could only abuse the body with MIME and subsequently pushing your original message out, but like I said, you need to modify the header for this to work.

So, for as far as I have seen the key for making a safe emailscript in PHP is the removal of the newline, the comma and the semi-colon. Keep in mind there are different ways of encoding data. Especially \n\r AND %0A10. URL-encoded characters are also characters!

Strip newlines, comma's, semi-colons and percent-signs from email addresses and I think you'll be fine...

If I'm wrong, I'll gladly hear about it and probably notice it quickly enough :p