If an attacker can write characters into your logs, they can write fake history into your audit trail and into the SIEM that trusts it. Log injection (MITRE CWE-117, also called log forging) happens when an application builds a log entry from external input without neutralising the characters that the log format, the parser or the viewer treats as structure. This guide is about what that does downstream: forged lines in text logs, broken fields in syslog, CEF and JSON pipelines, script execution in browser-based log viewers, and detection rules that fire on the wrong user or not at all. It covers prevention in code, structured logging, parser and viewer hardening, testing and measurement, and how log forging differs from Log4Shell. It is written for application security engineers, platform teams who run logging pipelines, and detection engineers who depend on the data. All guidance is defensive.
Key takeaways
- The sink is the problem, not the input. CWE-117 is an output neutralisation weakness: the same string is harmless in a database column and dangerous in a newline-delimited log, a CEF extension or an HTML log viewer.
- Structured logging with an escaping encoder is the main fix. Write each untrusted value into its own field through a JSON or RFC 5424 encoder that escapes it, instead of concatenating text into a line.
- Parameterised logging is not enough on its own. Constant message templates stop template tampering, but OWASP notes they do not stop CR and LF injection when the layout is unstructured.
- Log4Shell was a different bug. CVE-2021-44228 was code execution inside the logging library; log forging corrupts the record itself. Patching Log4j does not fix CWE-117 in your own code.
- Detection engineers own half of the risk. Parsers that split on delimiters, extract the last match or trust free-text fields for identity will believe forged data, so field provenance matters as much as encoding.
What log injection is, and what it is not
MITRE describes CWE-117 as a product that builds a log message from external input but does not neutralise, or incorrectly neutralises, special elements when the message is written to a log. Its parents are CWE-116 (improper encoding or escaping of output) and CWE-20 (improper input validation), and it can follow CWE-93 (CRLF injection). CAPEC-93 (Log Injection-Tampering-Forging) is the matching attack pattern; CAPEC-81 and CAPEC-268 cover tampering with web server and audit logs by an attacker who already has write access, which is a separate problem solved by integrity controls rather than encoding.
| Issue | What goes wrong | Primary fix | Where to read more |
|---|---|---|---|
| Log forging (CWE-117) | Untrusted input adds or alters entries or fields in the log record | Structured logging, field-level escaping, constant templates | This guide |
| CRLF injection into HTTP (CWE-113, CWE-93) | Newlines split headers or responses | Reject CR and LF in header values, framework APIs | CRLF Injection and HTTP Response Splitting Guide |
| Terminal escape sequences | Control sequences hide or rewrite lines when logs are read in a terminal | Strip or render control characters in CLIs and viewers | Terminal Escape Sequence Injection Guide |
| Log4Shell (CVE-2021-44228) | Lookup evaluation in the logging library led to remote code execution | Upgrade Log4j; remove lookups from patterns | Log4j security page |
| Log tampering (CAPEC-268) | An insider or intruder edits or deletes stored records | Append-only storage, forwarding, integrity checks | CIS Control 8 Audit Log Management Guide |
What forged log data does downstream
The OWASP community page lists four consequences: forged entries that make unrelated events appear to have happened, corrupted files that make automated processing fail, script execution when a vulnerable web viewer renders the entry, and exploitation of parsers or tools that read the logs. MITRE adds the non-repudiation impact: an attacker can cover tracks or implicate someone else. In a modern pipeline these show up in specific places.
| Stage | Abuse of the weakness | Effect for defenders |
|---|---|---|
| Line-based text files and shippers | An embedded newline starts a new line that looks like a genuine entry with its own timestamp and user | False successful logins, false admin actions, or a clean-looking gap during an intrusion |
| Key-value and CEF parsing | Unescaped =, | or spaces create extra keys or shift fields | suser, src or outcome fields hold attacker-chosen values; correlation rules key on the wrong entity |
| Syslog (RFC 5424) | Unescaped ", \ or ] break structured data; NUL, backspace or invalid UTF-8 hide content | RFC 5424 section 8.2 warns that NUL can hide information after it and backspace can render parts unreadable |
| Regex extraction in the SIEM | A free-text field contains a string that matches the pattern meant for a later, trusted field | Greedy or last-match extraction picks the attacker's value for user, IP or action |
| Browser-based log viewers and dashboards | Markup in a logged value is rendered as HTML | Script runs in an analyst's session, often one with wide SIEM rights |
| Alerting and volume controls | Very long or high-volume values | Truncation drops the trusted tail of an entry; disk or licence exhaustion suppresses real events |
The common thread is that detection logic trusts structure. A detection that counts failed logins per user.name is only as good as the guarantee that the field came from the authentication system and not from a username the attacker typed. See the Securing the SIEM page for protecting the platform itself.
Prevention in application code
Use structured logging with an escaping encoder
The OWASP Logging Cheat Sheet advises avoiding unstructured text logs, which are vulnerable to CR and LF entry injection, and using a structured format such as JSON. The Apache Log4j security page makes the same point from the library side: unstructured layouts such as Pattern Layout do not protect users from log injection, while structured layouts (JSON, XML, RFC 5424) must keep untrusted content from breaking the document structure, and a failure there is a library defect.
- One value, one field: log
{"event":"authn_login_fail","user":"<value>"}through the encoder, never a sentence with the value spliced in. The encoder escapes quotes, backslashes and control characters for you. - Constant templates: keep the message string a compile-time constant and pass values as parameters. Log4j states developers should use compile-time constants as format strings to prevent message tampering and log injection; the cheat sheet gives the same advice for SLF4J and Logback.
- Know the limit of parameters: a parameterised call still writes the value verbatim into a text layout. OWASP is explicit that parameterised logging alone does not prevent CR and LF injection.
- Use the security event vocabulary: stable event names make forged free text easier to spot. See the Secure Logging Vocabulary and Application Security Events Guide.
Encode for the format when you cannot change it
Legacy pipelines that must emit text, key-value or CEF need context-specific encoding at the point of writing. MITRE's mitigation is to specify an output encoding that downstream log readers handle consistently.
| Format | Characters that carry structure | Rule from the format's own specification or guidance |
|---|---|---|
| Plain text, one entry per line | CR, LF and other line terminators | Replace or escape CR, LF and delimiters (OWASP cheat sheet); also treat Unicode line separators as terminators if any consumer does |
| RFC 5424 structured data | ", \, ] in PARAM-VALUE | Must be escaped as \", \\, \]; senders should avoid octets below 32 in MSG |
| CEF header | | and \ | Escape as \| and \\ |
| CEF extension | =, \, newlines | Escape \= and \\; encode newlines as \n or \r; whole message UTF-8 |
| JSON | ", \, control characters | Use a real JSON encoder, never string building |
| HTML log views | <, >, &, quotes | Encode on display; serve raw log files as text/plain, not HTML (OWASP cheat sheet) |
- Canonicalise first: MITRE points to CWE-180 and CWE-174: decode once, then validate. A URL-encoded newline (the case in CVE-2020-36567, a Go HTTP framework) becomes a real newline if a later stage decodes it.
- Bound the size: the cheat sheet recommends limiting the size of user input used in log messages. Note its caveat that Log4j's
JsonTemplateLayoutmaxStringLengthtruncates string values but does not cap encoded bytes or total event size. - Do not strip silently: if a value fails validation, the cheat sheet suggests replacing or omitting that field and recording the validation failure rather than discarding the whole event. Keep a hash or escaped copy so investigators can still see what was sent.
Validation still helps (accept known good formats for usernames, IDs and IPs), but MITRE warns against relying on denylists. For general encoding patterns see the Input Validation and Output Encoding Guide.
Hardening the pipeline: shippers, parsers and viewers
Code fixes take time to reach every service, and third-party products write their own logs. The pipeline should therefore assume some sources are unsafe.
- Prefer native structured inputs: collect JSON or RFC 5424 rather than re-parsing rendered text. Each re-parse is another chance to split a field.
- Anchor extraction patterns: anchor regexes to the start of the record, match fields in a fixed order, avoid greedy and last-match captures, and reject records where a trusted field appears twice.
- Record field provenance: identity, source IP and outcome fields used in detections should come from the authenticating component or the network layer, not from free text. Keep the raw original (for example an
event.originalstyle field) for forensics, but do not detect on it. - Flag control characters: add a parsing rule that tags records containing CR, LF, NUL, backspace, escape (0x1B) or invalid UTF-8 inside a field value. That tag is both a detection and a data quality metric.
- Harden viewers: SIEM consoles, dashboards and internal log browsers must encode on output and apply a content security policy. Treat them as web applications with privileged users. See the Cross-Site Scripting (XSS) Prevention Guide.
- Sanitise for display in terminals: render control characters visibly in CLI log tools, as covered in the Terminal Escape Sequence Injection Guide.
- Exports: CSV exports of log searches carry their own spreadsheet risk. See the CSV and Formula Injection Guide.
Log forging versus Log4Shell
The two are often confused because both involve attacker-controlled strings reaching a logger. The Log4j security page describes CVE-2021-44228 as allowing an attacker who can control log messages or their parameters to execute arbitrary code loaded from LDAP servers, fixed in 2.15.0 for Java 8 and later (2.12.2 for Java 7, 2.3.1 for Java 6). Follow-ups CVE-2021-45046 and CVE-2021-45105 involved lookups in non-default patterns and recursion, and CVE-2021-44832 needed write access to the logging configuration. CVE-2021-44228 is in the CISA KEV catalogue with known ransomware use.
| Question | Log forging (CWE-117) | Log4Shell (CVE-2021-44228) |
|---|---|---|
| Where is the flaw? | Your code or layout writes untrusted text into a structured record without escaping | The logging library evaluated lookups in logged data |
| Impact | False, hidden or broken log records; downstream parser and viewer abuse | Remote code execution on the logging host |
| Fixed by patching the library? | No, unless the defect is in a structured layout's escaping | Yes, upgrade to a fixed version |
| Library position | Log4j states the frameworks do not trust log messages and that Pattern Layout gives no injection guarantee | Treated as a library vulnerability |
| Main control | Structured logging and encoding | Patch, inventory, remove lookups, egress filtering |
Structured layouts can still have escaping defects: the Log4j page lists CVE-2026-34478, a CRLF log injection in Rfc5424Layout caused by renamed configuration attributes that disabled newline escaping. Track logging library advisories as you would any dependency. See the Software Composition Analysis Guide.
Where identity fits
Many forged entries target identity fields because detections pivot on them. Service accounts, API clients and AI agents generate high volumes of logs and often pass caller-supplied values (tenant names, tool arguments, prompts) into log lines. The Secure Logging Vocabulary guide already advises logging rule IDs and request identifiers rather than full prompts or tool input for MCP events, which also removes an injection path. For agents, take the acting identity from the authenticated token or workload identity, never from model output. See the Agent Observability vs Audit Logging page.
Implementing it: a phased approach
- Inventory sinks (weeks 1 to 2): list every logging format, layout and consumer per application, as ASVS 5.0 V16.1.1 asks of a log inventory. Mark which formats are unstructured and which viewers render HTML.
- Turn on SAST in report mode: MITRE rates static analysis as highly effective for CWE-117 because it traces data flow from input sources to log sinks. Baseline findings for one sprint, then fail builds on new ones.
- Switch layouts for high-value services first: authentication, authorisation, admin and payment services move to a JSON or RFC 5424 layout. Run old and new outputs in parallel and compare parsed field counts before cutting over.
- Update parsers and detections: move detections to structured fields, add the control character tag, and fix greedy extractions. Re-run detection unit tests in your Detection as Code pipeline.
- Harden viewers: confirm output encoding and content security policy on every log UI, and serve raw files as text/plain.
- Test: OWASP recommends including logging in security, fuzz and penetration testing. Use benign marker values containing control characters, delimiters and markup in an authorised test environment and confirm each arrives escaped in one field.
- Roll back safely: keep the previous layout configuration versioned; if a cutover breaks parsing, revert the layout, not the encoder, and keep the control character tag running.
Detection and measurement
- Control characters in fields: alert on CR, LF, NUL, backspace or escape inside identity and outcome fields; investigate the source application.
- Impossible structure: records with duplicate trusted fields, timestamps out of sequence within one stream, or entries whose source host does not match the shipper.
- Parse failures: a rise in unparsed records from one source often means a format break, malicious or not.
- Viewer errors: content security policy violation reports from log UIs.
| Metric | Target |
|---|---|
| Share of security-relevant log volume emitted in a structured format | Above 90% for authentication and admin services |
| Open CWE-117 SAST findings, and median age | Falling each quarter; no high findings older than 30 days |
| Records tagged with control characters per million | Tracked per source; spikes investigated |
| Parse failure rate per source | Below 0.1% |
| Detections that use free-text fields for identity | Zero |
| Log viewers with output encoding and CSP verified | 100% |
Framework mapping
| Framework | Reference | Relevance |
|---|---|---|
| OWASP ASVS 5.0 | V16.4.1 | All logging components appropriately encode data to prevent log injection |
| OWASP ASVS 5.0 | V16.2.4, V16.4.2, V16.4.3 | Common format readable by the processor; logs protected from modification; sent to a separate system |
| MITRE CWE / CAPEC | CWE-117, CWE-93, CWE-116; CAPEC-93 | Weakness and attack pattern |
| NIST SP 800-53 Rev 5 | AU-3, AU-9, AU-10, SI-10, SI-15, SA-11 | Record content, protection of audit information, non-repudiation, input validation, output filtering, developer testing |
| NIST CSF 2.0 | PR.PS-04, DE.AE-02 | Log records generated for monitoring; analysis of adverse events depends on trustworthy records |
| CIS Controls v8.1 | Control 8, Control 16 | Audit log management; application software security |
| ISO/IEC 27001:2022 Annex A | A.8.15, A.8.28 | Logging; secure coding |
| MITRE ATT&CK v20 | T1070 Indicator Removal; T1565.001 Stored Data Manipulation | Adversary goals that forged or corrupted logs can serve |
Common failure patterns
- Trusting parameterised logging: teams move to placeholders, mark CWE-117 as fixed, and keep a Pattern Layout that writes newlines verbatim.
- Encoding for the wrong consumer: values are JSON-escaped at the source and then re-rendered into CEF or HTML by a forwarder that does not escape for its own format.
- Double decoding: a proxy or shipper URL-decodes a field the application already decoded, turning an encoded newline into a real one.
- Detections on free text: a rule extracts the username from the message body instead of the authenticated field, so a crafted username becomes the subject of the alert.
- Silent stripping: control characters are removed without a trace, so the attempt itself is invisible and investigators lose evidence.
- Unhardened log viewers: an internal dashboard renders log values as HTML for analysts with broad SIEM rights.
Practitioner checklist
- Inventory every log format, layout, shipper and viewer per application.
- Emit security events in JSON or RFC 5424 through an escaping encoder, one value per field.
- Keep log message templates as compile-time constants.
- Apply format-specific escaping where text, key-value or CEF output must remain.
- Canonicalise once, bound value length, and record validation failures instead of dropping events.
- Enable CWE-117 SAST rules and track findings to closure.
- Anchor parser patterns, reject duplicate trusted fields and tag control characters.
- Take identity and outcome fields only from authenticated sources, never from free text.
- Verify output encoding and CSP on every log viewer; serve raw logs as text/plain.
- Track logging library advisories, including structured layout escaping defects.
Standards and references
- MITRE: CWE-117 Improper Output Neutralization for Logs
- OWASP: Logging Cheat Sheet
- OWASP: Log Injection
- OWASP: Application Security Verification Standard 5.0
- Apache Logging Services: Log4j Security
- IETF: RFC 5424 The Syslog Protocol
- OpenText ArcSight: CEF Implementation Standard
- CISA: Known Exploited Vulnerabilities Catalog
Related NHI Mgmt Group resources: Secure Logging Vocabulary and Application Security Events Guide · CRLF Injection and HTTP Response Splitting Guide · Terminal Escape Sequence Injection Guide · SIEM Guide