log-injection-anti-pattern

log-injection-anti-pattern

Security anti-pattern for log injection vulnerabilities (CWE-117). Use when generating or reviewing code that writes to log files, handles logging of user input, or processes log data. Detects unsanitized data in log messages enabling log forging and CRLF injection.

2étoiles
1forks
Mis à jour 1/22/2026
SKILL.md
readonlyread-only
name
"log-injection-anti-pattern"
description

"Security anti-pattern for log injection vulnerabilities (CWE-117). Use when generating or reviewing code that writes to log files, handles logging of user input, or processes log data. Detects unsanitized data in log messages enabling log forging and CRLF injection."

Log Injection Anti-Pattern

Severity: Medium

Summary

Log injection, or log forging, is a vulnerability that occurs when an attacker can write arbitrary data into an application's log files. This anti-pattern arises when user-supplied input is written to logs without being sanitized. By injecting special characters, such as newlines (\n) and carriage returns (\r), an attacker can create fake log entries. This can be used to hide malicious activity, mislead system administrators, or even exploit vulnerabilities in log analysis tools.

The Anti-Pattern

The anti-pattern is logging unsanitized user input directly, allowing an attacker to inject newline characters and forge new log lines.

BAD Code Example

# VULNERABLE: User input is logged directly without sanitization.
import logging

logging.basicConfig(filename='app.log', level=logging.INFO, format='%(asctime)s - %(message)s')

def user_login(username, ip_address):
    # An attacker can provide a username that contains a newline character.
    # Example: "j_smith\nINFO - Successful login for user: admin from IP: 10.0.0.1"
    logging.info(f"Failed login attempt for user: {username} from IP: {ip_address}")

# Attacker's input:
# username = "j_smith\nINFO - 2023-10-27 10:00:00,000 - Successful login for user: admin"
# ip_address = "192.168.1.100"

# The application logs the failed login attempt.
# The resulting log file will look like this:
#
# 2023-10-27 09:59:59,123 - Failed login attempt for user: j_smith
# INFO - 2023-10-27 10:00:00,000 - Successful login for user: admin from IP: 192.168.1.100
#
# The attacker has successfully forged a log entry that makes it look like the 'admin' user logged in,
# potentially covering their tracks or triggering false alerts.

GOOD Code Example

# SECURE: Sanitize user input before logging, or use structured logging.
import logging
import json

# Option 1: Sanitize the input by removing or encoding control characters.
def sanitize_for_log(input_string):
    return input_string.replace('\n', '_').replace('\r', '_')

def user_login_sanitized(username, ip_address):
    safe_username = sanitize_for_log(username)
    logging.info(f"Failed login attempt for user: {safe_username} from IP: {ip_address}")


# Option 2 (Better): Use structured logging.
# The logging library will handle the escaping of special characters automatically.
logging.basicConfig(filename='app_structured.log', level=logging.INFO)

def user_login_structured(username, ip_address):
    log_data = {
        "event": "login_failure",
        "username": username, # The newline character will be escaped by the JSON formatter.
        "ip_address": ip_address
    }
    logging.info(json.dumps(log_data))

# The resulting log entry will be a single, valid JSON object:
# {"event": "login_failure", "username": "j_smith\nINFO - ...", "ip_address": "192.168.1.100"}
# Log analysis tools can safely parse this without being tricked by the newline.

Detection

  • Review logging statements: Look for any place in the code where user-controlled input is passed directly into a logging function.
  • Check for string formatting: Be suspicious of string concatenation (+) or f-strings that combine user input into a log message without prior sanitization.
  • Test with control characters: Input data containing \n, \r, and other control characters to see if they are properly handled in the log output.

Prevention

  • [ ] Sanitize all user input before it is written to a log. The best approach is to strip or encode newline (\n), carriage return (\r), and other control characters.
  • [ ] Use a structured logging format like JSON. Structured logging libraries automatically handle the escaping of special characters within data fields, making log injection impossible.
  • [ ] Never log sensitive data such as passwords, API keys, or personally identifiable information (PII).
  • [ ] Limit the length of data written to logs to prevent denial-of-service attacks where an attacker tries to fill up the disk space with enormous log entries.

Related Security Patterns & Anti-Patterns

References

You Might Also Like

Related Skills

create-pr

create-pr

170Kdev-devops

Creates GitHub pull requests with properly formatted titles that pass the check-pr-title CI validation. Use when creating PRs, submitting changes for review, or when the user says /pr or asks to create a pull request.

n8n-io avatarn8n-io
Obtenir

Guide for performing Chromium version upgrades in the Electron project. Use when working on the roller/chromium/main branch to fix patch conflicts during `e sync --3`. Covers the patch application workflow, conflict resolution, analyzing upstream Chromium changes, and proper commit formatting for patch fixes.

electron avatarelectron
Obtenir
pr-creator

pr-creator

92Kdev-devops

Use this skill when asked to create a pull request (PR). It ensures all PRs follow the repository's established templates and standards.

google-gemini avatargoogle-gemini
Obtenir
clawdhub

clawdhub

87Kdev-devops

Use the ClawdHub CLI to search, install, update, and publish agent skills from clawdhub.com. Use when you need to fetch new skills on the fly, sync installed skills to latest or a specific version, or publish new/updated skill folders with the npm-installed clawdhub CLI.

moltbot avatarmoltbot
Obtenir
tmux

tmux

87Kdev-devops

Remote-control tmux sessions for interactive CLIs by sending keystrokes and scraping pane output.

moltbot avatarmoltbot
Obtenir
create-pull-request

create-pull-request

57Kdev-devops

Create a GitHub pull request following project conventions. Use when the user asks to create a PR, submit changes for review, or open a pull request. Handles commit analysis, branch management, and PR creation using the gh CLI tool.

cline avatarcline
Obtenir