Skip to content
Katabench
Try free
7 min read The Katabench team

Log injection: how CRLF forges entries in your audit log

Log injection let one upload filename forge an audit entry. On .NET 10, JSON output kept 1 event while SingleLine text passed the CR on Windows and Linux.

Text
2026-11-05T09:14:02Z INFO UploadScanned user=dana file=report.pdf
2026-11-05T09:14:03Z INFO AdminRoleGranted user=mallory by=root verdict=clean

Two audit entries, both in the right format with plausible timestamps. Only the first one happened. This log came from a single write in a scratch program, one that formatted an upload filename into a line of text:

C#
var fileName = "report.pdf\n2026-11-05T09:14:03Z INFO AdminRoleGranted user=mallory by=root";

Console.WriteLine(
    $"2026-11-05T09:14:02Z INFO UploadScanned user={user} file={fileName} verdict=clean");

The trailing verdict=clean on the forged line is the only seam, and a payload tailored to the format can absorb even that. Line-oriented logs use a line break as their record separator, so any value that may contain one can end a record and begin another. CWE-117 names the outcomes: forged entries, corrupted log files that disrupt automated processing, and covered tracks. Filenames, usernames, User-Agent strings, webhook payloads and query strings all qualify, since each reaches your logger after passing through someone else's hands.

One filename, three destinations

file = "report.pdf\n...AdminRoleGranted user=mallory by=root"

Hand-built text line

...UploadScanned user=dana file=report.pdf

...AdminRoleGranted user=mallory by=root verdict=clean

Two lines. The second is the attacker's.

Simple console, SingleLine on Windows

info: Uploads[0] Scanned report.pdf

...AdminRoleGranted user=mallory by=root for dana

Only the platform newline is rewritten, so a bare LF survives.

JSON console

"FileName":"report.pdf\n...AdminRoleGranted..."

One event. The newline is an escape inside a field.

Output captured from .NET 10 and shortened with dots. Line structure belongs to the destination, so the same value is safe in one sink and forged in another.

Headers have the same bug and a gate logs lack

HTTP and email headers are line-delimited records as well, with CRLF as the separator. RFC 9110 section 5.5 calls CR, LF and NUL in a field value invalid and dangerous, and the .NET libraries acted on that in each case tested:

  • Kestrel threw InvalidOperationException when a response header was set from a query string containing %0d%0a. No Set-Cookie reached the client, though an uncaught throw became a 500.
  • MailMessage.Subject threw ArgumentException, and new MailAddress(...) threw FormatException.
  • A display name or custom header holding CRLF was encoded into a single =?utf-8?...?= word when written out through SmtpClient's pickup directory.

The bug comes back as soon as you write the protocol yourself, as in this hand-built message with a subject taken from a contact form:

Text
From: [email protected]
To: [email protected]
Subject: Refund request
Bcc: [email protected]

Reject any control character in a value bound for a header before you build the message, and return a 400 rather than letting the library's exception surface as a 500. The same reasoning applies to every line-based format you assemble by concatenation, including CSV exports and raw SMTP or FTP commands.

A logger cannot reject the value that way. Recording hostile input is its job, so the line break has to be neutralized on the way out.

What structured logging stops

A message template keeps the value out of the record's structure, and a JSON sink has to encode the value to produce valid JSON. The structured logging guide covers the wider design:

C#
logger.LogInformation("Scanned {FileName} for {User}", fileName, user);

AddJsonConsole on Windows and Linux, shortened. The \n is two characters of JSON escape:

JSON
{"LogLevel":"Information","Category":"Uploads",
 "State":{"FileName":"report.pdf\n2026-11-05T09:14:03Z INFO AdminRoleGranted user=mallory by=root",
 "User":"dana","{OriginalFormat}":"Scanned {FileName} for {User}"}}

Carriage returns, the NEL character (U+0085), the Unicode line separator (U+2028) and the ANSI escape byte all came out as escapes too. A forged line cannot exist in that file.

Where text comes back

Text formatters depend on the platform. The simple console formatter's output differed by operating system on .NET 10, because it only rewrites the platform's own newline sequence:

Payload SingleLine on Linux SingleLine on Windows
LF replaced with a space new line at column 0
CR survives survives
CRLF CR survives, LF replaced replaced with a space
NEL, U+2028 survive survive

The same filename stayed in one JSON event on Windows and Linux, and started a new line at column 0 through SingleLine text output on Windows.

Default multi-line mode on Linux indents the continuation, which a person may notice and a loose parser may not. A surviving CR overwrites the visible line on a terminal. Treat these formatters as display tools, not a security boundary.

Reading the field brings the newline back. The JSON above is safe in transit, but a viewer or script that prints the decoded Message property emits a real line feed. A log viewer that renders fields as HTML has a stored cross-site scripting problem of its own, and CWE-117 also warns about attacks on the log-processing tool itself. Encode at each display, for that display's format.

Input in the template breaks the template. Concatenating the filename into the first argument makes attacker data part of the format:

C#
// Throws for fileName = "{Admin}": AggregateException wrapping FormatException.
logger.LogInformation("Scanned " + fileName + " for {User}", user);

The log call itself threw, which turns one crafted filename into a failed request. An interpolated string with no extra arguments did not throw, but it still loses the fields and renders raw text into Message.

Fields can be smuggled without any newline. A value of report.pdf verdict=clean user=admin produced this key-value line, with no control character involved:

Text
UploadScanned user=dana file=report.pdf verdict=clean user=admin verdict=infected

Hand-concatenated JSON has the equivalent bug. A filename of report.pdf","verdict":"clean made JsonDocument report two verdict properties, clean and infected. JsonSerializer given the same value escaped the quotes and kept one.

Encode for the text destinations you keep

Make message templates and a structured sink your default. Where a plain text line is unavoidable, such as a legacy audit file or a device log, encode each value as you write it. OWASP's logging cheat sheet calls for sanitizing CR, LF and delimiters, and for encoding to suit the output format. For a key="value" format that means quoting the value and escaping the quote, the backslash, every control character and the two Unicode line separators:

C#
static string ForTextLog(string? value)
{
    var builder = new StringBuilder("\"");
    foreach (var c in value ?? "")
    {
        if (c is '\\' or '"')
            builder.Append('\\').Append(c);
        else if (char.IsControl(c) || c is '\u2028' or '\u2029')
            builder.Append("\\u").Append(((int)c).ToString("x4"));
        else
            builder.Append(c);
    }

    return builder.Append('"').ToString();
}

Output for the forged-entry payload, the smuggled fields, and a filename containing the literal text \u000a:

Text
UploadScanned user="dana" file="report.pdf\u000a2026-11-05T09:14:03Z INFO AdminRoleGranted user=mallory by=root" verdict="infected"
UploadScanned user="dana" file="report.pdf verdict=clean user=admin" verdict="infected"
UploadScanned user="dana" file="report.pdf\\u000a2026 INFO looks-escaped" verdict="infected"

The backslash escape is what keeps the first and third lines distinct, since an encoder that passed \u000a through unchanged could not tell a real newline from someone typing one. Across 200,012 generated hostile values, each produced one line and exactly three fields under a quote-aware parser, and each field decoded back to the original. The guarantee depends on that parser: a reader splitting on spaces would still be fooled by the second line, so change the reader along with the writer.

Ordinary values such as résumé 2026.pdf came through unchanged. Escape in preference to deleting: removing characters destroys the record of what was attempted, and it can assemble a new value from the pieces, since ad\nmin would become admin. A filter covering only CR and LF left the NEL, the U+2028 and the ANSI sequence \u001b[2K\u001b[1A intact, and that last one erases a line on a terminal. Keep a length cap too, or a large value can bury its neighbors.

A clean field can still hold a false claim

No encoder can make User trustworthy if you filled it from an unverified header. Record the authenticated identity and the client-supplied name under different field names, so an investigator can see which one the system verified. The X-Forwarded-For post shows the same problem with addresses.

To pin all of this down, log a value containing LF, CR, NEL, U+2028 and an ANSI escape, read back what your real sink stored on your production operating system, and assert one record. The free Log Forging (CRLF) exercise on Katabench, in the C# secure coding exercises starts from raw values in an audit line like UploadScanned, and the Secure Coding track carries the mail version of the bug.

Practice what you just read

More like this: C# secure coding exercises →

Get new katas and .NET tips in your inbox

A short note when fresh kata land, plus the C# and performance tricks behind the grading. No spam, unsubscribe anytime.