Practical technical guides

Log Injection: User Input With Newlines Forges Log Entries

Measured with Python 3.13 logging: newline, CR, NEL and U+2028 in a logged value. Structured logs, reversible encoding and tests that catch it.

By Sandeep Belgavi · Published 2026-12-06

Flow from Untrusted value arrives, to Encode or structure it, to One record per call.
Original conceptual diagram by Sandeep Belgavi.

A log line is a record boundary

Most text logs are parsed line by line. A log shipper reads until a newline and turns what it read into one event. A person reading the file in a terminal treats each line as one thing that happened. An alert rule matches lines. That makes the newline character a record separator, and any value written into a log line that can contain a newline can create a record.

OWASP calls this log injection, and MITRE lists it as CWE-117, improper output neutralization for logs. The attack does not need any special access: a customer at Belgavi's Book Store types a name or a return note, the application logs it, and the log now contains a line the application never wrote.

Measured with Python 3.13 logging

I ran Python 3.13.5's standard logging module with an ordinary formatter, %(asctime)s %(levelname)s %(message)s, and logged a customer-supplied name with %s:

import logging
logging.basicConfig(format="%(asctime)s %(levelname)s %(message)s", level=logging.INFO)
log = logging.getLogger("returns")

name = "Jenya\n2026-12-06 10:00:00 INFO refund approved case=CASE-7781 amount=4999 by=Geetha"
log.info("return note added customer=%s", name)

The handler wrote two lines. The second is a complete, well-formed record that says a refund for CASE-7781 was approved by Geetha. Nothing in the file distinguishes it from a line the application wrote. Anyone searching the log for approved refunds finds it, and an alert that counts approvals counts it.

The newline is not the only separator. The same probe logged values containing carriage return, the C1 control NEL (U+0085) and the Unicode line separator (U+2028). Python's logging wrote each record as one physical line ending in \n. But Python's own str.splitlines() splits all three, so a tool that reads the log with splitlines() sees two records where a tool splitting on \n sees one:

Character in the valueLines by \n splitLines by str.splitlines()
LF (U+000A)22
CR (U+000D)12
NEL (U+0085)12
LINE SEPARATOR (U+2028)12
ESC (U+001B)11

The escape character does not split records, but it carries terminal control sequences. A value with ESC [2J clears the screen of a person reading the log with tail in a terminal, and other sequences can rewrite or hide earlier output. Log readers disagree about where records end, and the attacker only needs one reader in the pipeline that splits where the writer did not.

Three defences, in order of strength

Structured logs. Write each record as one JSON object per line. JSON encoding escapes control characters in strings, so the record above becomes one line with \n inside a string value, and the injected text stays inside the customer field where it belongs. The same probe confirmed one physical line. This is the strongest fix because it removes the ambiguity rather than filtering it, and it also makes logs easier to query.

import json, logging

class JsonFormatter(logging.Formatter):
    def format(self, record):
        doc = {"ts": self.formatTime(record), "level": record.levelname, "event": record.getMessage()}
        doc.update(getattr(record, "fields", {}))
        return json.dumps(doc, ensure_ascii=True)

log = logging.getLogger("returns")
log.info("return_note_added", extra={"fields": {"customer": "Jenya\nINFO forged", "case": "CASE-7781"}})

With ensure_ascii=True the output is pure ASCII, so U+2028 and NEL are escaped as \u2028 and \u0085 and no reader can split on them. Keep the event name a constant and put untrusted values only in fields.

Encoding at the boundary. Where plain text logs must stay, encode untrusted values before they reach the formatter. The %r conversion in Python is the quick version: it renders the value with repr, quoting it and escaping control characters, and the probe confirmed one line with a visible \n. A dedicated function is clearer and covers what repr leaves alone:

import unicodedata

def log_safe(value: str, limit: int = 200) -> str:
    out = []
    for ch in value[:limit]:
        cat = unicodedata.category(ch)
        if ch == "\\":
            out.append("\\\\")
        elif cat in ("Cc", "Zl", "Zp") or ch == "\u0085":
            out.append(f"\\u{ord(ch):04x}")
        else:
            out.append(ch)
    if len(value) > limit:
        out.append("...")
    return "".join(out)

assert log_safe("Jenya\nINFO forged") == "Jenya\\u000aINFO forged"
assert "\u2028" not in log_safe("Hansini\u2028INFO forged")

Escaping the backslash first keeps the encoding reversible, so an investigator can tell an injected \u000a from a real one. Truncation keeps a single field from filling the log.

Removal. Stripping control characters is the weakest choice. It loses information an investigator may need, and it is easy to miss a category, which is exactly what a filter for \r and \n only does with NEL and U+2028.

Where values enter logs

Untrusted text reaches logs through more paths than the obvious one:

  • Request fields logged on validation failure, which are by definition the values that did not match expectations.
  • Headers such as User-Agent and Referer logged by access logs and middleware.
  • Exception messages that embed input, for example a parser error that quotes the offending value.
  • Agent and model output. A help-desk agent that logs the model's draft reply logs text the model produced from customer input, and a prompt injection can ask the model to include a newline and a forged record. Treat model output as untrusted in logs exactly as you treat user input.

What changes downstream

Fixing the writer is half the work. The shipper, the parser and the alert rules must agree on the record format. When moving from text to JSON lines, run both formats side by side for a period, and update alert rules to match on fields rather than on text patterns that an attacker can write. An alert that fires on the substring refund approved in a message is satisfiable by anyone who can put text in a message; an alert on event == "refund_approved" with an authenticated actor field is not.

Size, rate and placement

Two more properties of untrusted values matter in logs. Size: a single request with a 10 MB field can fill a disk or a log pipeline's per-event limit, and some shippers drop or split oversize events, which reintroduces the boundary problem. Truncate untrusted fields to a documented length and record that truncation happened. Rate: an attacker who can trigger a log line per request controls the volume of your logs. Sample or aggregate repeated validation failures rather than logging each in full.

Placement matters as well. Put untrusted values at the end of a text line, after the fixed fields, and never inside the part of the line that parsers use to find the timestamp, level or event name. In structured logs, keep untrusted values out of field names: a field name built from user input can collide with or impersonate fields such as level or actor. Use fixed keys and put the untrusted text in values.

Failure modes

  • Forged records accepted as evidence during an incident review, because they are syntactically perfect.
  • Filters that strip LF only while a downstream reader splits on CR, NEL or U+2028.
  • Terminal escape sequences hiding lines from someone reading logs interactively.
  • Encoding applied in one logger while another path, such as an exception handler, logs the raw value.
  • JSON written with ensure_ascii=False and then read by a tool that splits on Unicode line separators.

Incident response when forged lines are suspected

If logs may already contain forged records, do not trust the text log alone to reconstruct events. Cross-check each suspicious record against a source the attacker could not write: the database row for the refund, the payment provider's records, or an audit table written by the service that performed the action. A forged "refund approved" line with no matching refund row is evidence of injection, not of a refund. Then find the request that wrote it: forged text arrives inside a field of a real request, so the line just before it, or the request whose field length is unusually large, usually identifies the source.

Verification

Write a test that logs each separator above through every logging path you have, including exception handlers, and asserts that the output has exactly one record per call when read by each parser you run: \n split, splitlines(), and your shipper's parser if you can run it locally. The companion example contains that test for the standard library, the encoder and the JSON formatter. Then search existing logs for records whose timestamp is out of order with the lines around them; forged records often carry a timestamp the attacker guessed.

Primary references and authorship

Sources read December 6, 2026. Original explanations, measurements and synthetic examples by Sandeep Belgavi. Companion code: Sandeep-BA/agent-decision-lab/examples/python/log_injection_encoding. Views are my own and do not represent any employer, past or present.