Skip to main content

Free 30-min security demo  — We'll scan your real code and show live findings, no commitment Book Now

Offensive360
Academy Log Injection
Beginner · 15 min

Log Injection

See how attackers forge log entries to hide malicious activity and how structured logging prevents it.

1 Log Forging

Log injection (log forging) occurs when unsanitized user input containing newline characters is written to log files. Attackers can inject fake log entries to cover their tracks or frame innocent users.

Vulnerable example (Python):

username = request.form["username"]
logging.info(f"Login attempt: {username}")

An attacker sends username: admin\n[INFO] Login attempt: root - SUCCESS

The log file shows two entries:

[INFO] Login attempt: admin
[INFO] Login attempt: root - SUCCESS

The forged entry makes it appear root logged in successfully, obscuring what actually happened. Attackers use this to remove evidence of intrusion attempts from log analysis tools.

2 Safe Logging

The fix is to encode or strip newline characters from user-controlled values before logging, and to use structured logging that stores data in fields rather than interpolated strings.

Encoding approach (Python):

import re

def sanitize_log(value):
    # Remove newlines and carriage returns
    return re.sub(r"[\r\n]", "_", str(value))

logging.info(f"Login attempt: {sanitize_log(username)}")

Structured logging (best practice):

import structlog

log = structlog.get_logger()
# User input is a field value, not part of the message format
log.info("login_attempt", username=username, ip=request.remote_addr)

Structured logging stores each field separately (often as JSON), so a newline in username stays within the username field and cannot create new log lines.

Knowledge Check

0/3 correct
Q1

What character enables log injection attacks?

Q2

Why do attackers inject entries into log files?

Q3

Which approach provides the strongest defense against log injection?

Code Exercise

Sanitize Log Input

The logger below is vulnerable to log injection. Add a sanitize function that strips newline and carriage return characters before logging.

python