---
title: Protect Against Log Injection
impact: HIGH
impactDescription: prevents log forging, track hiding, and malicious content injection
tags: logging, injection, sanitization, security, kotlin
---

## Protect Against Log Injection

Log injection occurs when user-controlled data is written to a log file without sanitization. An attacker can inject newline characters to forge log entries or inject malicious payloads that could be executed by log analysis tools.

**Incorrect (unsanitized logging):**

```kotlin
// Log injection vulnerability
val username = request.getParameter("username")
logger.info("User logged in: $username")

// Attacker input: "admin\n[2024-01-01] ERROR Database connection failed"
// Results in two lines in the log, one of which is fake.
```

**Correct (structured and sanitized logging):**

```kotlin
// Use structured logging (automatically handles many injection risks)
logger.info("User logged in", StructuredArguments.value("username", sanitize(username)))

// Sanitize manual log input
fun sanitize(input: String?): String {
    if (input == null) return ""
    return input
        .replace("[\r\n\t]".toRegex(), " ") // Replace newlines/tabs with space
        .take(255) // Limit length to prevent log bloating attacks
}

// Logback configuration can also be set to replace newlines automatically:
// %-5p [%d] %c: %replace(%m){'[\r\n]', ''}%n
```

**Prevention Strategies:**
- Always use structured logging (e.g., Logstash Logback Encoder).
- Sanitize any user-controlled input before logging by stripping or replacing CRLF characters.
- Configure log appender to escape control characters.
- Limit the size of logged variables.

**Tools:** SonarQube (S2245), Semgrep, OWASP ESAPI (for Java/Kotlin), Manual Audit
