lowCWE-117A09:2021

Log Injection

User-supplied input written to logs without sanitization, allowing attackers to forge log entries, hide their tracks, or inject malicious content into log files.

How It Works

If you log raw user input, an attacker can include newlines to insert fake log entries. For example, a username of `admin\n[INFO] User admin logged out successfully` makes it look like admin logged out cleanly in the log file, hiding a real attack. More dangerously, some log viewers render HTML in logs.

Vulnerable Code
// BAD: raw user input in logs
export async function POST(req: Request) {
  const { username } = await req.json();
  console.log(`Login attempt for user: ${username}`);
  // username = 'alice\n[INFO] Login success for: admin'
}
Secure Code
// GOOD: sanitize before logging, use structured logging
export async function POST(req: Request) {
  const { username } = await req.json();
  const safeUsername = username.replace(/[\r\n]/g, '_');
  // Better: use structured logging with a dedicated field
  logger.info('Login attempt', { username: safeUsername });
}

Real-World Example

Log4Shell (CVE-2021-44228) was essentially a log injection that went catastrophically wrong — the log4j library actually executed code embedded in log messages. Pure log injection is lower severity, but log4shell showed what's possible when log handling gets too clever.

How to Prevent It

  • Strip or encode newline characters (\r, \n) from user input before logging
  • Use structured logging (JSON format) with dedicated fields instead of string interpolation
  • Never render raw log content in a web UI without escaping
  • Set up log integrity monitoring to detect tampering

Affected Technologies

nodejsPythonGoJava

Data Hogo detects this vulnerability automatically.

Scan Your Repo Free

Related Vulnerabilities