Log injection

Prevent untrusted text from forging log-record boundaries

Description

In a line-oriented log, a carriage return (\r) or line feed (\n) in user input can make one event look like several. A logging placeholder still passes these characters to the configured provider.

Potential impact

Split records can obscure audit events and disrupt alerts, searches and investigations. Control characters can also distort what operators see. Very long values consume storage and processing time.

Remediation

  1. Configure a supported logging provider and layout for the actual output format. A line-oriented layout must remove or visibly escape every CR and LF in messages and arguments. CSV, JSON, HTML and terminals each have their own encoding rules.
  2. Apply that policy in a shared filter or formatter. For fields with a few known values, use a fixed allow-list of separator-free literals. Cap the length after handling separators.
  3. Exclude passwords, session IDs and access tokens. Redact identifying data where needed. Check that one event remains one record in the collector and viewer.

Apache Commons Text’s StringEscapeUtils.escapeJava can represent CR and LF visibly in plain text. Use an encoder for the destination format elsewhere.

Examples

Before

{0} substitutes the username, including any line breaks it contains.

java
import jakarta.servlet.http.HttpServletRequest;
import java.util.logging.Level;
import java.util.logging.Logger;

final class VulnerableAuditLogExample {
    private static final Logger LOGGER =
            Logger.getLogger(VulnerableAuditLogExample.class.getName());

    static void recordFailedLogin(HttpServletRequest request) {
        String untrustedUser = request.getParameter("username");
        LOGGER.log(Level.WARNING, "Failed login for {0}", untrustedUser);
    }
}

After

The revised call removes each CR and LF from untrustedUser and uses an empty string for a missing value.

java
import jakarta.servlet.http.HttpServletRequest;
import java.util.logging.Level;
import java.util.logging.Logger;

final class SafeAuditLogExample {
    private static final Logger LOGGER =
            Logger.getLogger(SafeAuditLogExample.class.getName());

    static void recordFailedLogin(HttpServletRequest request) {
        String untrustedUser = request.getParameter("username");
        String safeUser = untrustedUser == null ? "" : untrustedUser.replaceAll("[\\r\\n]", "");
        LOGGER.log(Level.WARNING, "Failed login for {0}", safeUser);
    }
}

A pattern that matches only a CRLF pair leaves standalone CR or LF characters in the log.

References

Use a supported logging library instead of the end-of-life Log4j 1.x.