---
title: Protect Against Log Injection
impact: HIGH
impactDescription: prevents log forging and exploitation
tags: logging, injection, sanitization, security, php
---

## Protect Against Log Injection

Log injection occurs when an application includes untrusted data in its logs without proper sanitization. Attackers can use this to forge log entries, hide malicious activities, or inject content that could exploit log-viewing tools.

**Incorrect (unsanitized logging):**

```php
// Log injection vulnerability
$username = $_POST['username'];
error_log("User logged in: " . $username);
// Attacker input: "admin\n[ERROR] Database wiped by: victim"
```

**Correct (sanitized structured logging):**

```php
// Sanitize input before logging
function sanitizeForLog($input) {
    if (!is_string($input)) return $input;
    // Remove newlines and carriage returns
    return str_replace(["\r", "\n", "\t"], ' ', $input);
}

$username = $_POST['username'];
error_log("User logged in: " . sanitizeForLog($username));

// Using structured logging (e.g., Monolog in Laravel)
// Structured logging handles most injection issues as the data is kept separate from the message
Log::info('User logged in', [
    'username' => $username, // Still good practice to sanitize or use a secure formatter
    'ip' => $_SERVER['REMOTE_ADDR']
]);
```

**Best Practices:**
1. Avoid multi-line log entries.
2. Neutralize newlines and tab characters in user-controlled input before logging.
3. Use structured logging (JSON) instead of plain text strings.
4. Limit the length of data included in logs to prevent log-overflow or denial of service on log management systems.

**Tools:** PHPStan, Psalm, SonarQube, Monolog Safe Formatters
