Email Header Injection (Invicti IAST)
Description
This web application is vulnerable to Email Header Injection, a security flaw that occurs when user-supplied input is incorporated into email headers without proper validation. Attackers can exploit this vulnerability by injecting malicious SMTP/IMAP headers using newline characters (CR/LF), allowing them to manipulate email messages sent by the application. This can result in unauthorized modification of email recipients, subjects, and content, effectively turning the application into a relay for spam or phishing campaigns.
Remediation
Implement strict input validation and sanitization for all user-supplied data used in email composition. Specifically:
1. Remove or reject newline characters: Strip carriage return (CR, \r, 0x0D) and line feed (LF, \n, 0x0A) characters from all input fields used in email headers, particularly the To, From, CC, BCC, and Subject fields.
2. Use safe email libraries: Utilize well-maintained email libraries that automatically handle header injection protection rather than manually constructing email headers.
3. Validate email addresses: Ensure email addresses conform to RFC standards and reject any containing unexpected characters.
Example (PHP):
// Unsafe code
mail($_POST['to'], $_POST['subject'], $message);
// Safe code - sanitize inputs
$to = filter_var($_POST['to'], FILTER_SANITIZE_EMAIL);
$subject = str_replace(array("\r", "\n", "%0a", "%0d"), '', $_POST['subject']);
if (filter_var($to, FILTER_VALIDATE_EMAIL)) {
mail($to, $subject, $message);
}
Example (Python):
import re
# Remove CR/LF characters from headers
def sanitize_header(value):
return re.sub(r'[\r\n]+', '', value)
to_address = sanitize_header(user_input['to'])
subject = sanitize_header(user_input['subject'])
4. Implement allowlisting: Where possible, use predefined values or strict allowlists rather than accepting arbitrary user input for email headers.