Safeguard
Application Security•

ASVS 5.0 V5.4.2: Encode Served Filenames

Filenames in headers and email attachments must be encoded under RFC 6266 so quotes, newlines and non ASCII characters cannot break structure. Level 2 guide.

Safeguard Security Team
2 min read

ASVS V5.4.2 requires that any filename you place in an HTTP header or an email attachment is encoded or sanitized, following RFC 6266 for headers, so it cannot break the document structure. It is a Level 2 requirement.

Why it matters

A raw quote, semicolon or line break in a filename can close the header value early and add new parameters or whole new headers. Non ASCII names sent without encoding show up as garbage or get truncated, which users report as bugs and attackers use to disguise extensions.

Header injection through filenames is a classic bug. A name that contains a carriage return and line feed can end the header and start a new one, which lets an attacker set cookies or split the response. Modern servers reject some of this, but not all frameworks do, and email systems have their own rules.

How to implement it

Use your framework helper rather than string concatenation. If you must build it yourself, send an ASCII fallback in filename and the encoded UTF 8 name in filename*.

function contentDisposition(name) {
  const clean = String(name).replace(/[\u0000-\u001f\u007f"\\/;]/g, "_").slice(0, 120) || "download";
  const ascii = clean.replace(/[^\x20-\x7e]/g, "_");
  const utf8 = encodeURIComponent(clean).replace(/['()*]/g, c => "%" + c.charCodeAt(0).toString(16).toUpperCase());
  return `attachment; filename="${ascii}"; filename*=UTF-8''${utf8}`;
}

For email, use a MIME library that encodes attachment names for you instead of writing headers by hand.

How to test it

Upload or create files named a"b.pdf, x;y.pdf, a name with a newline, and résumé.pdf. Download each and inspect the raw response. The header must stay on one line, quotes must be escaped or removed, and the accented name must decode correctly in a browser.

Common mistakes

  • Concatenating the name into a quoted string without escaping.

  • Encoding for URLs but not for headers.

  • Allowing control characters through because the name looked fine in the UI.

  • Forgetting email attachments entirely.

  • Trusting that the framework will always reject bad names. Test it on your actual stack.

Quick check

Why send both filename and filename*?

Older clients only read filename, so it carries an ASCII fallback. Modern clients prefer filename* and decode the real UTF 8 name.

Sources

Never miss an update

Weekly insights on software supply chain security, delivered to your inbox.

Self-healing security runs on Safeguard.

Your first fix PR is minutes away.

No sales call required, even your agent can complete the purchase over MCP.