---
title: Prevent Log Injection
impact: MEDIUM
impactDescription: prevents attackers from corrupting logs or misleading auditors
tags: security, logging, sanitization
---

## Prevent Log Injection

Sanitize all user-input data before including it in log files to prevent attackers from injecting newlines or carriage returns.

**Incorrect (unsafe logging):**

```ruby
# Attacker name: "admin\n[INFO] Login successful for admin"
logger.info "User update attempted by #{params[:user_name]}"
```

**Correct (sanitized logging):**

```ruby
# Replace newlines with spaces or use json logger
sanitized_name = params[:user_name].gsub(/[\n\r]/, " ")
logger.info "User update attempted by #{sanitized_name}"
```

**Tools:** Lograge (default Rails JSON logging avoids this)
---
