Log injection
| Class | Injection |
|---|---|
| Also known as | Log forging |
| CWE | CWE-117: Improper Output Neutralization for Logs |
| OWASP Top 10 | A09:2025 Security Logging and Alerting Failures |
| Typical severity | Low to Medium; Critical when the logging library evaluates the text |
| Affects | Code that writes request values into plain-text logs, and the viewers and scripts that read those logs |
A Python application that records a failed sign-in writes a line such as WARNING:root:User login failed for: 'guest'. When the username sent with the request holds a line break followed by the text of a second entry, the log shows two failed sign-ins, the second for administrator, from a single request.1 This is log injection, also called log forging: the application builds a log message from outside input and writes it without neutralizing the characters that have a meaning in the log's format.2 Line breaks are the usual case. Field delimiters, HTML in a log viewer and the template syntax of the logging library itself can serve the same purpose.34
Forged lines
Most application logs are plain text with one event per line, so a person or a script reading the file treats each line break as the start of a new event. The two characters that end a line are carriage return and line feed, written \r and \n in code. A Java handler that fails to parse a number and logs "Failed to parse val = " + val shows the effect. A request with the value twenty-one%0a%0aINFO:+User+logged+out%3dbadguy leaves this in the file:2
INFO: Failed to parse val=twenty-one
INFO: User logged out=badguyNothing in the second line shows that a visitor typed it. CVE-2020-36567, in a Go HTTP framework, allowed log injection through an encoded %0a, and in CVE-2006-4624 injected entries carried fake timestamps.2
A fixed message template with the value passed as an argument does not stop this by itself. In logging.warning("User login failed for: '%s'", user) the template never changes, but a line break inside user still reaches the file as a line break.13
Consequences
Forged entries can hide an attacker's tracks or put the blame on another user.2 A crafted username can make a failed sign-in appear as a successful one in an audit log.1 When a program processes the log, broken formatting can make the whole file unreadable for it, and an entry can carry commands aimed at a flaw in that program.2
A log viewer that shows entries in a web page without escaping them becomes a target for cross-site scripting: a script tag placed in a logged value runs in the browser of whoever opens the log.5 PHP code written into a log, such as <?php echo phpinfo(); ?>, may run in some setups when the log file sits in a public folder that can be requested over HTTP; this is called log file poisoning.5
An attacker who forges nothing can still flood the log until it fills a disk that the database also uses, or until no room is left for the entries that follow.3
Log4Shell
The worst case is a logging library that reads the logged text as instructions. Log4j 2 up to version 2.14.1 resolved lookup expressions inside log messages and their parameters. One kind, the JNDI lookup, could reach an LDAP directory server named in the text, so anyone able to put text into a log entry could make the application load and run code from a server they chose. A failed sign-in or an exception trace was enough. The advisory for CVE-2021-44228 was published on 10 December 2021 with critical severity. Version 2.15.0 did not close every path; 2.16.0 turned JNDI off by default and removed message lookups entirely.4 Log4j's own threat model now assumes that an attacker sends control characters such as CR, LF and NUL, very long values, and input that imitates its lookup syntax.6 Its severity score is discussed in Common Vulnerability Scoring System.
When escaping fails
Escaping done the wrong way, or in the wrong order, fails as well. The .NET logging library log4net fixed three such flaws in versions 3.5.0 and 3.6.0. Its RemoteSyslogAppender deleted every character outside visible ASCII instead of escaping it, so a username holding a zero-width space was recorded as admin. In FileAppender and three other appenders, text already escaped for an XML log was then converted to a single-byte encoding, which turned fullwidth characters such as U+FF1C into < and let an attacker write a complete fake event, for example an audit entry. AdoNetAppender passed a NUL character to the database unchanged; PostgreSQL refused the insert and the event was lost.7
Prevention
A structured format such as JSON removes the line problem at its source.3 JSON requires every control character inside a string, line feed included, to be written as an escape sequence, so one event stays on one line whatever the user typed.8 Some logging frameworks do not treat line breaks injected into plain-text logs as a bug of theirs and will not change that.3
// Node.js: one JSON object per line
console.log(JSON.stringify({
event: "login_failed",
user: req.body.username // a line break is written as the two characters \n
}));Where a plain-text log stays, check the value against what it should look like and write anything else in escaped form. Python's %r writes the value's representation, in which CR and LF appear as escapes:1
import logging, re
_ALLOWED_USER = re.compile(r"^[A-Za-z0-9._-]{1,64}$")
if not _ALLOWED_USER.fullmatch(user):
logging.warning("Rejected login attempt: invalid username=%r", user)
else:
logging.warning("User login failed for: '%s'", user)The message template is a constant in the code. In Log4j, joining request values into it with + bypasses the library's own handling of arguments.9 CR, LF and the format's delimiter characters are removed or escaped before writing, and each value is encoded for where the log ends up: HTML escaping in a web viewer, and parameterized queries when entries go into a database.3
Each logged user value is cut to a fixed length. Log4j's JsonTemplateLayout takes a maxStringLength setting that shortens each string value, though not the event as a whole.3 A malformed field is replaced and the validation failure recorded, while the rest of the security event is kept.3 Log4j accepts any message content for the same reason: rejecting user input would turn a malicious value into a denial of service.6
For Python, the CodeQL query py-log-injection finds the pattern; Bandit 1.7.5 has no check for it.1
Prompt for a coding agent
Find every place in this project that writes a value from a request, a form, a header, a cookie or an external service into a log, including console.log, logger calls, print statements and error handlers. Switch the logger to structured JSON output with one object per line, so that line breaks in values are escaped. Keep every log message template a fixed string and pass values as separate fields or arguments, never joined into the message with + or template strings. Where plain-text logs remain, escape carriage returns, line feeds and other control characters in logged values. Cap logged user values at 500 characters. If the project has a page that shows logs, make sure it HTML-escapes every entry. List each file and line you changed.
See also
- Security logging and alerting
- Audit logs
- Personal data in logs
- Cross-site scripting
- SQL injection
- Command injection
- Category: Injection
References
- a b c d e OpenSSF Best Practices Working Group. "pyscg-0022: Neutralize Untrusted Data in Logs". Secure Coding Guide for Python.
- a b c d e "CWE-117: Improper Output Neutralization for Logs". Common Weakness Enumeration. MITRE.
- a b c d e f g h "Logging Cheat Sheet". OWASP Cheat Sheet Series.
- a b GitHub (10 December 2021). "Remote code injection in Log4j" (GHSA-jfh8-c2jp-5v3q, CVE-2021-44228). GitHub Advisory Database.
- a b "Log Injection". OWASP Community. OWASP Foundation.
- a b Apache Logging Services. "Security". Apache Log4j 2 documentation.
- back Apache Logging Services. "Security". Apache Logging Services.
- back Bray, T., ed. (December 2017). "RFC 8259: The JavaScript Object Notation (JSON) Data Interchange Format". IETF.
- back Apache Logging Services. "Log4j API". Apache Log4j 2 documentation.
External links
- Logging Cheat Sheet, OWASP Cheat Sheet Series
- Security (threat model), Apache Log4j 2 documentation