emailverifier.dev
Posts

Email Header Injection: Stop CRLF Attacks in Contact Forms

| 5 min read | Usama Ejaz
A malicious subject line splits at a CRLF boundary into an unauthorized Bcc header, while a guarded path blocks the split.

Email header injection happens when untrusted input containing a carriage return or line feed is copied into an email header. Those characters can end the intended field and start another one, such as Bcc. The safe rule is simple: never construct raw headers from form input. Use structured fields in a maintained mail library, and reject every \r or \n in values that must stay on one line.

This is separate from checking whether an email address is valid or reachable. An address can pass verification while another field in the same contact form still tries to alter the message structure.

The extra Bcc header appears in one line break

Consider a contact form that copies its subject field into an outbound message. This is a hypothetical attack value:

Quarterly report\r\nBcc: attacker@example.net

If the application builds the message by concatenating strings, that value produces this raw message:

To: support@example.com
Subject: Quarterly report
Bcc: attacker@example.net

Please send the report.

The attacker has not “broken” the email address. They have supplied a line boundary that the message composer mistakes for structure. Depending on the code and mail transport, the result could add a recipient, replace a field, or simply make the message invalid.

String concatenation crosses the trust boundary

RFC 5322 defines a header field as a field name, a colon, a field body, and a terminating CRLF pair. An empty line separates the header section from the body. That makes line endings control characters in this context, not ordinary text.

Email does allow folded header lines in specific grammar positions, where CRLF is followed by whitespace. That does not make user-supplied folding safe. Your application should not let an untrusted value decide where any header line begins, continues, or ends.

The vulnerable pattern is direct interpolation:

const raw = `Subject: ${req.body.subject}\r\n`;

MITRE tracks this class as CWE-93, where an application fails to neutralize CRLF sequences in data that reaches a line-based protocol. The same risk applies when a wrapper eventually turns a string into raw headers. A “safe” framework route can still pass unsafe data to a lower-level mail composer.

Reject line breaks before message construction

I prefer a small fail-closed guard at the boundary. Reject the request instead of silently deleting line breaks, because deletion can merge text and hide the attempted structural change. This follows the broader OWASP input-validation guidance: validate untrusted data as early as practical, apply both syntactic and semantic rules, and keep validation specific to the field.

export function singleLineHeader(name, value, { maxLength = 200 } = {}) {
  if (typeof value !== "string") {
    throw new TypeError(`${name}_must_be_string`);
  }

  if (value.length === 0 || value.length > maxLength) {
    throw new Error(`${name}_invalid_length`);
  }

  if (/[\r\n]/.test(value)) {
    throw new Error(`${name}_contains_line_break`);
  }

  return value;
}

Then give your mail library structured values:

await mailer.send({
  to: { address: "support@example.com" },
  replyTo: { address: verifiedReplyTo },
  subject: singleLineHeader("subject", req.body.subject),
  text: req.body.message
});

The exact API varies by library. The important boundary is stable: addresses remain address objects, the body remains body content, and untrusted text never becomes a raw header block.

Run the negative tests

I ran this fixture locally with Node's built-in test runner. It proves both sides of the boundary: unsafe concatenation creates a Bcc field, while the guard rejects CRLF, lone LF, and lone CR.

import assert from "node:assert/strict";
import test from "node:test";

const attack = "Quarterly report\r\nBcc: attacker@example.net";

test("unsafe concatenation creates another header", () => {
  const raw = `Subject: ${attack}\r\n\r\nHello`;
  assert.match(raw, /\r\nBcc: attacker@example\.net\r\n/);
});

test("the guard rejects every line ending", () => {
  for (const value of ["ok\r\nBcc: x", "ok\nBcc: x", "ok\rBcc: x"]) {
    assert.throws(
      () => singleLineHeader("subject", value),
      /subject_contains_line_break/
    );
  }
});

test("a normal Unicode subject remains valid", () => {
  assert.equal(
    singleLineHeader("subject", "Résumé received ✓"),
    "Résumé received ✓"
  );
});
tests 3
pass 3
fail 0

The fixture uses reserved example domains and sends no email. Add equivalent cases to the path that actually calls your mail provider, because a helper that is bypassed in production is not a control.

Apply the guard to every header-shaped input

Subject is the obvious field, but it is not the only one. Display names, Reply-To, custom campaign fields, and any application-supplied header value deserve the same single-line rule. Attachment filenames can also reach MIME headers, so let the mail library encode them instead of writing MIME syntax yourself.

A single-line check is necessary, but it is not enough for address fields. Parse From, To, and Reply-To as structured mailbox values, apply the business rule for who may appear there, and keep user input out of the envelope sender. Length limits and type checks should be specific to each field.

Your strongest fair objection might be that a modern mail library already escapes headers. Good libraries do reduce this risk. Keep the boundary test anyway. Dependencies change, wrappers expose raw-header options, and validation placed beside the trust boundary documents what your application permits.

Email verification solves a different boundary

Email validation and verification can evaluate syntax, mail-routing evidence, provider signals, and mailbox evidence. They do not sanitize a subject, authorize a sender, or make arbitrary header text safe. An inconclusive SMTP result should remain inconclusive, and a successful result does not prove that the person submitting a form owns the inbox.

Treat the controls as complementary. Verify address-related evidence where it helps the workflow, then separately constrain every value that can influence message structure. The job is complete when CR, LF, and CRLF tests fail closed before untrusted data reaches the composer.

Continue reading