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

## Protect Against Log Injection

Log injection allows attackers to forge log entries, hide their tracks, or inject malicious control characters.

**Incorrect (unsanitized logging):**

```go
func Handler(w http.ResponseWriter, r *http.Request) {
    user := r.FormValue("user")
    slog.Info("User logged in: " + user)
    // Attacker: "admin\n[ERROR] Payment failed for user: victim"
}
```

**Correct (sanitized structured logging):**

```go
// 1. Use structured logging (automatically handles quotes/escaping in key-value pairs)
slog.Info("User logged in", "username", sanitizeForLog(user))

// 2. Sanitize input
func sanitizeForLog(input string) string {
    // Replace CRLF/tabs with space
    replacer := strings.NewReplacer("\r", " ", "\n", " ", "\t", " ")
    return replacer.Replace(input)
}

// 3. Recommended: Use JSON logger in production
logger := slog.New(slog.NewJSONHandler(os.Stdout, nil))
logger.Info("User logged in", "username", user)
```

**Tools:** `log/slog`, `zap`, `gosec`
