Log Injection in APIs
What is Log Injection?
Log injection is a security vulnerability where an attacker injects malicious data into application logs, potentially causing log forgery, log injection, or log injection-based attacks. This occurs when user-supplied input is written directly to log files without proper sanitization or encoding.
The vulnerability exploits the fact that logs are often used for monitoring, auditing, and security analysis. When attackers can manipulate log content, they can create false trails, hide malicious activity, or trigger automated systems based on log patterns.
Common log injection vectors include:
- Log forging: Inserting fake log entries to cover tracks
- Log injection: Adding malicious content that breaks log parsing
- Log injection-based attacks: Triggering automated responses based on injected data
Log injection is particularly dangerous in distributed systems where logs are aggregated and analyzed centrally, as a single injection point can affect the entire logging infrastructure.
How Log Injection Affects APIs
APIs are particularly vulnerable to log injection because they process high volumes of user requests and often log detailed request/response data for debugging and monitoring. Attackers can exploit this to achieve several malicious objectives:
Log Forgery: An attacker can inject fake authentication events, making it appear as if they successfully logged in when they actually failed. This can help them evade detection during reconnaissance phases.
Log Flooding: By injecting log entries with specific patterns, attackers can trigger automated alerting systems, causing alert fatigue and making it harder to spot real threats.
Log Parsing Attacks: If logs are parsed by automated systems, attackers can inject specially crafted content that breaks parsers or causes them to misinterpret data, potentially leading to security bypasses.
Information Disclosure: Log injection can be used to exfiltrate data through log files, especially when logs are accessible to other systems or users.
Compliance Violations: In regulated industries, log injection can create false audit trails, potentially leading to compliance violations and legal issues.
How to Detect Log Injection
Detecting log injection requires both static analysis and runtime monitoring. Here are the key approaches:
Static Code Analysis: Review code that writes to logs to ensure user input is properly sanitized. Look for patterns like:
logger.info(request.params.userInput) // VulnerableRuntime Monitoring: Monitor for unusual log patterns, such as:
- Sudden spikes in log volume from specific users
- Log entries with unexpected formatting or control characters
- Multiple failed attempts followed by successful events that seem inconsistent
Input Validation Testing: Test API endpoints by submitting inputs containing log injection payloads like:
username=admin
[INFO] User admin logged in successfullymiddleBrick Detection: middleBrick's Log Injection detection specifically tests for unescaped user input being written directly to logs. The scanner sends payloads containing newline characters, special formatting, and control sequences to see if they appear verbatim in log outputs. It also checks for log injection in error messages and stack traces that might be exposed through API responses.
Log Aggregation Analysis: Monitor aggregated logs for patterns that suggest injection, such as:
- Multiple users logging in from the same IP in rapid succession
- Log entries with inconsistent timestamps or formatting
- Unexpected log levels or categories
Prevention & Remediation
Preventing log injection requires a defense-in-depth approach:
Input Sanitization: Always sanitize user input before logging. This includes:
const sanitizeLogInput = (input) => {
return input
.replace(/\n/g, ' ') // Remove newlines
.replace(/\r/g, ' ') // Remove carriage returns
.replace(/\t/g, ' ') // Remove tabs
.replace(/\[.*?\]/g, '') // Remove log-like patterns
.trim();
};
logger.info(`User ${sanitizeLogInput(username)} logged in`);
Structured Logging: Use structured logging formats (JSON, key-value pairs) instead of plain text. This makes it harder to inject malicious content that affects log parsing:
logger.info({
event: 'login',
username: sanitizeLogInput(username),
ip: req.ip,
success: true
});
Log Level Control: Ensure log levels are properly controlled and cannot be manipulated through user input. Never allow users to set log levels via parameters.
Log Content Policies: Establish policies about what should and shouldn't be logged. Avoid logging sensitive data, and use placeholders for PII:
logger.info(`User ${username} performed action ${action}`);
// Instead of logging full objects or sensitive data
Log Monitoring: Implement monitoring for unusual log patterns and set up alerts for potential injection attempts.
Testing: Include log injection testing in your security testing suite. Use tools like middleBrick to automatically scan for log injection vulnerabilities.
Real-World Impact
While specific public CVEs for log injection are rare (as it's often a component of larger attacks), log injection has been implicated in several high-profile security incidents:
APT Attacks: Advanced persistent threat groups often use log injection to cover their tracks during long-term intrusions. By injecting fake login events and system activities, they can hide their presence for months.
Insider Threats: Malicious insiders have used log injection to falsify their activities, making it appear as if they were performing legitimate work while actually exfiltrating data.
Compliance Violations: Companies have faced regulatory penalties when log injection was used to falsify compliance-related audit trails, particularly in financial services and healthcare.
Incident Response Failures: Log injection has been used to trigger false positives in incident response systems, causing teams to waste resources investigating non-existent threats while real attacks proceed undetected.
The OWASP API Security Top 10 includes related concepts under "Improper Inventory Management" and "Insufficient Logging & Monitoring," highlighting how critical proper logging practices are for API security.