10

Given a contact form that accepts custom user input (e.g. address, subject line, message), what are some security implications and "gotchas" to be careful of?

At a minimum, the user's email address will have to be validated (likely using filter_var() or equivalent). From what I've read, this should also prevent additional headers from being injected into the script.

What about the subject line and message content though? Is any sanitation required for those fields? I figure an email client would prevent things like scripts from running automatically, and I'm not particularly worried about things like HTML tags (if someone wants to spend the time to style an email by hand, that's their prerogative - I just won't be seeing it :P). If sanitation is required, what's the best way of doing it without being too intrusive (i.e. keeping the nature of the email the same)?

Illianthe
  • 343
  • 3
  • 7
  • possible duplicate of [Why shouldn't I use PHP's mail() function?](http://stackoverflow.com/questions/4565066/why-shouldnt-i-use-phps-mail-function) – Rafe Kettler Jan 29 '11 at 00:40
  • 2
    @Rafe not really I think. The OP is asking about sanitation specifically, which the dupe doesn't address – Pekka Jan 29 '11 at 00:41
  • That thread did pique my interest though. I've never found the need to use the mail() function before and kind of suspected that things could get messy very quickly. :P – Illianthe Jan 29 '11 at 00:56

2 Answers2

8

If you are using the fourth argument, the optional headers, watch for inserting of extra headers, if you are doing something like this...

mail($to, $subject, $message, 'From: $email');

If $email comes from user input and is not sanitized, a user could enter something like...

\n\rCC:spammer@spamzilla.com

You can avoid this by filtering out \n and \r, or validating $email using the filter_var($email, FILTER_VALIDATE_EMAIL) function.

alex
  • 479,566
  • 201
  • 878
  • 984
  • But because such gotchas are non-trivial to know about, it is much safer to let a library take care of it that has already thought about such things. – DGM Jan 29 '11 at 01:15
4

Ensure that people cannot inject linebreaks in anything but the body. Additionally make the recipient static and never pass it e.g. through a hidden form field. However, adding such a field is not a bad idea; but block the IP if it's not set to the expected value - then your client is probably a spam bot.

ThiefMaster
  • 310,957
  • 84
  • 592
  • 636
  • Are you sure linebreaks are unsafe in the to and subject fields? Any references? – user1318499 Dec 07 '13 at 02:30
  • Linebreaks are converted to spaces nowadays but before 5.1.2 that was not the case. Anyway, if someone injects headers he's most likely a spammer. You want to detect this so he doesn't even spam whoever the legit recipient of the email is. – ThiefMaster Dec 07 '13 at 12:05