Skip to main content

Free 30-min security demo  — We'll scan your real code and show live findings, no commitment Book Now

Offensive360
Academy Email Header Injection
Beginner · 15 min

Email Header Injection

Learn how attackers abuse form fields to inject CC and BCC headers for spam relay.

1 Email Header Injection

When a web application builds email headers from user-supplied data (like a "From" or "Subject" field) without stripping newline characters, attackers can inject additional headers such as CC, BCC, or even a new message body.

Vulnerable PHP mailer:

$from = $_POST["email"];
$subject = $_POST["subject"];
mail("[email protected]", $subject, $message, "From: " . $from);

An attacker submits email: [email protected]\r\nBcc: [email protected],[email protected]

The additional header injects BCC recipients, turning the server into a spam relay. Attackers can also inject Content-Type: text/html to change the message body format.

2 Prevention

The primary defense is to validate and strip newline characters from all values that will be used in email headers. Additionally, validate that email addresses match an expected format.

Safe implementation (PHP):

function sanitizeHeader($value) {
    // Remove CRLF characters
    return preg_replace("/[\r\n]/", "", $value);
}

$from = sanitizeHeader($_POST["email"]);
$subject = sanitizeHeader($_POST["subject"]);

// Also validate email format
if (!filter_var($from, FILTER_VALIDATE_EMAIL)) {
    die("Invalid email address");
}

Using a proper mail library:

# Python: use email.message module or a library like sendgrid
from email.message import EmailMessage
msg = EmailMessage()
msg["From"] = user_email  # Library handles header escaping
msg["To"] = "[email protected]"

Defense checklist:

  • Strip \r and \n from all header values
  • Validate email addresses with a regex or library
  • Use a reputable mail library instead of raw header construction
  • Allowlist acceptable subjects and senders

Knowledge Check

0/3 correct
Q1

What is the primary risk of email header injection?

Q2

Which characters must be stripped from email header values?

Q3

What additional validation helps prevent email injection in a "From" field?

Code Exercise

Sanitize Email Headers

The mailer function uses user-provided values in email headers. Add sanitization to strip newline characters and validate the email format.

javascript