JINNBITSResearch & insights

Log Fields Are Untrusted Input, Even After JSON Parsing

A submitted username can change what an audit report appears to say. Prevent log injection in Python handlers, JSON collectors, and downstream exports.

In a fictional sign-in incident, the authentication service records a failure, yet the audit extract appears to show an administrator signing in successfully. The service escapes a line feed (LF) in the submitted username, and the collector restores it during JSON decoding. The exporter writes the decoded username into a line-oriented report. The reader treats the LF as a record boundary and displays the rest of the username as a separate entry. The service recorded only the failed attempt.

A fixed template still has to render the field

In Python's standard logging module, passing a username as an argument to a fixed format string keeps the percent directives under application control. The default formatter still inserts the string's characters into the message. A stream handler then appends its terminator, leaving a line reader to interpret any LF already inside the message as another end of record.

For a text handler with a one-line contract, a quoted JSON string is a practical display representation for the field.

import json

logger.warning("login failed for %s", json.dumps(username, ensure_ascii=True))

An LF renders as a backslash followed by lowercase n. The literal sequence of backslash and n gains another backslash, so an analyst can distinguish the two inputs. The surrounding quotes mark the field boundary, and an escaped quote inside the username stays inside that boundary. The example covers one field. For a shared handler, enforce the framing contract on the entire rendered record, including exception output, and leave the shared log record intact. Mutating it in the text handler can send display escapes into a structured handler that serializes the same event.

Apache's Log4j security advisory for CVE-2021-44228 documents how affected Log4j Core versions could evaluate lookups in attacker-controlled messages or message parameters. A fixed template controls the interpolation at the call site. Review the formatter and any subsequent substitutions too, because those stages can assign meaning to text interpolated earlier.

The decoder gives the username its line feed back

In this LF-delimited JSON pipeline, the producer serializes a compact object before appending the frame delimiter. The serialized username contains an escape, so each frame contains one literal LF byte, at the end. The collector splits at that byte before handing the object to the JSON decoder. Decoding restores the LF in the username. The report exporter must encode the field again for its own row format.

Figure 1 — Follow the username through the split and decode steps. The report writer inherits a literal line feed inside a field after the collector has safely separated the frames. Illustrative framing sequence, not measured data.

A single read can end mid-frame or contain several frames. Define a frame-size cap in bytes for the serialized object plus its terminating LF. Once the collector has too many bytes to admit the frame, it can stop buffering and scan through the next delimiter. Starting the next frame after that delimiter keeps the discarded frame's suffix from becoming a new event. Disable multiline aggregation on this input because it can merge records the producer already framed independently.

Strict UTF-8 decoding checks only the wire bytes. Python's JSON documentation describes its handling of unpaired surrogates. With ensure_ascii=True, a lone high surrogate can appear on the wire as the ASCII escape \ud800. Strict UTF-8 accepts those bytes, and Python's json.loads can return a string containing the surrogate. Validate decoded keys and string values throughout the object, for example by requiring that each string encode as UTF-8 with errors="strict". At the producer, that check belongs before ASCII-escaping JSON serialization, while the problematic character is still present as a character.

Require an object of the expected shape for each frame. Python's default JSON decoder retains the last value when a name repeats. An object_pairs_hook can reject repeated names before building each dictionary, including nested dictionaries. Schema validation after ordinary parsing sees only the surviving member, so it cannot detect an ambiguity that another consumer might resolve differently.

The event ID belongs to the service

The service sets the outcome, event ID, and producer timestamp from its authentication decision, ID allocator, and clock. It builds those fields explicitly, so a submitted username or request map cannot supply or overwrite them. The collector records its own receipt time in a separate field. That preserves when the service says the attempt happened even if a retry delivers the same record later.

Retain the original event ID across retries so the collector can deduplicate redelivery. If IDs are unique only per producer, use the producer identity and event ID together. Deduplicating by username and outcome would collapse distinct attempts that happen to share both. Tokenized search creates a different ambiguity. A query for a term may match part of a stored username. Export the stored value and the event reference so an analyst can inspect the event without treating the matching term as an exact account identifier.

The OWASP Logging Cheat Sheet treats data exclusion and output encoding as separate controls. Allowlist fields during event construction because request bodies and header maps can reach retry buffers before index redaction runs. When admission fails, emit a bounded diagnostic with a fixed reason and a trusted correlation ID if available. Echoing rejected input into the diagnostic would route it into another logging path.

CSV quoting ends at the cell boundary

MITRE's CWE-117 describes how special characters in log data can acquire structural meaning. In a CSV exchange between services, a dialect-aware writer preserves boundaries when a username contains a separator, a quote, or a line break. A matching CSV parser reads a quoted multiline field as part of the same logical row. A line-by-line importer needs a separately defined visible escape convention for embedded line breaks or a format whose framing it actually supports.

Opening the CSV in a spreadsheet adds a second grammar. OWASP's CSV Injection guidance identifies formula-sensitive prefixes such as =, +, -, and @, along with relevant control and Unicode variants. A quoted username can still be interpreted as a formula after CSV parsing. For a spreadsheet export, write untrusted values as explicit text cells in a typed workbook. If CSV is required, one option for an investigation-only export is to prepend a visible, fixed alphabetic marker to every untrusted text cell before passing it to the CSV writer. That places formula-sensitive characters after known text and makes the display transformation consistent across usernames. Verify that the supported import path retains the marker and reads the cell as text, including after a save and reopen if that workflow is supported.

A browser dashboard has separate markup and display boundaries. Inserting the username as a text node keeps angle brackets literal. Render the value in a bidirectionally isolated element and show bidirectional controls as visible escapes so they cannot reorder adjacent labels or obscure the order of characters within the username. In a terminal, a bare carriage return can move the cursor to the start of the line, where subsequent output can overwrite the visible prefix. Show controls and Unicode line separators as visible escapes there too. Escape literal backslashes in both views so someone comparing two usernames can tell which one contains an actual control character.

The queue charges for escaped bytes

In an illustrative sizing model, the ASCII envelope takes 200 bytes, including the quotes around the username and the terminating LF. The username contains 300 copies of é, a two-byte UTF-8 character in the U+0080–U+07FF range. With Python's ensure_ascii=False, the username contributes 600 bytes and the frame totals 800 bytes. With ensure_ascii=True, each é takes six bytes as \u00e9, and the frame grows to 2,000 bytes. The username triples in size and the full frame grows by a factor of 2.5.

A hostile username composed of U+0001 characters expands sixfold with either setting. Each character takes one byte in raw UTF-8 and six as \u0001 in JSON. With 300 copies, either setting produces the same 2,000-byte frame as the ASCII-escaped é example. The cap on the final serialized frame limits how many bytes that input can add to the queue.

Assume the frame-size cap admits both sizes and the producer offers a steady 1,000 frames per minute, all of the same size in each scenario. At 800 and 2,000 bytes per frame, the queue needs 0.8 MB and 2 MB of new payload storage per minute, using decimal units. At minute zero, forwarding halts and all 10 MB of usable payload capacity is free. The queue fills after 12.5 minutes with 800-byte frames and after 5 minutes with 2,000-byte frames. By minute 15, total arrivals account for 12 MB and 30 MB respectively, including the bytes that no longer fit.

Figure 2 — With forwarding halted, the larger frames use up the 10 MB queue in 5 minutes. The smaller frames take 12.5 minutes. The lines track bytes offered to the queue, including arrivals after it fills. Illustrative outage calculation, not measured data.

Reserve enough space for the mandatory fields and an omission marker. If an optional username would put the event over the cap, omit it, set the marker, and serialize again. Check the complete byte count before enqueueing. A byte slice of the original serialization can leave an incomplete escape or object that the collector has to reject. For the outage budget, use the admitted byte rate under burst conditions and reserve separate space for queue metadata. A per-frame limit still leaves the queue exposed to a burst of individually admissible events.

One failed sign-in should yield one failed row

Replay the fictional failure through the investigation team's exporter and line-oriented reader. Compare a username containing an LF with one containing the literal backslash-and-n sequence. Each attempt should yield one row with its own service-assigned event ID and failure outcome, and the username column should render the two values distinctly. That check follows the evidence to the point where an analyst uses it. The reader must preserve both what the service decided and exactly where the submitted text belongs.