Log Forging & Log Injection: Attack Examples, Detection & Prevention Guide
Log Forging & Injection: Detection & Prevention
Application Security

Log Forging & Log Injection: Attack Examples, Detection & Prevention Guide

Log forging occurs when untrusted input changes how a log record is represented, allowing attackers to inject fake-looking entries, split one event into multiple lines or manipulate downstream parsing. The root problem is treating attacker-controlled data as log structure instead of a field value.

Guide overviewAttack Defense Guide
Primary sinkLogs/audit records
Common vectorCR/LF + delimiters
Best defenseStructured logging
RiskFalse evidence + parser abuse
Quick answer: Prevent log forging with structured logging APIs, fixed schemas, safe serialization/escaping, server-derived identity/timestamps/severity, event-size limits and protected log pipelines. Detection looks for unexpected control characters, impossible trusted-field combinations, parser failures and inconsistencies between application logs and independent identity/network/cloud telemetry.

What Is Log Forging / Log Injection?

Log injection occurs when attacker-controlled input is interpreted as log structure instead of one field value. Log forging is the resulting ability to create misleading entries or alter the apparent meaning/order of audit data.

The weakness appears in line-oriented logs, CSV-like formats, syslog-style messages and even structured logs when applications let clients control field names, severity, timestamps or nested trusted metadata.

Defensive Log Injection Example

Unsafe string concatenation can blur the line between field value and record structure:

log("login failed user=" + username + " ip=" + request_ip)

Prefer structured parameters so the logging library serializes external values as data:

logger.warn("login_failed", {"user": username, "source_ip": trusted_ip})

The goal is not a blacklist of attack strings; it is to prevent external values from becoming delimiters or trusted audit metadata.

CRLF and Newline Injection

Carriage return and line feed are common record delimiters, so they frequently appear in log-forging attacks. Other formats have different structural characters such as commas, tabs, quotes or property names.

Validate/encode for the destination. Globally stripping newlines from all input can corrupt legitimate data; the logging layer should serialize safely while preserving forensic value.

Related Ammune reading: Centralized SIEM log forwarding formats and HTTP security headers.

Why Structured Logging Helps

Structured logs with a fixed schema make it harder for a username or URL to become a new record because values are serialized as fields. But structured logging is not automatically safe: external values must not overwrite trusted keys such as timestamp, severity, tenant or authenticated user.

FieldTrusted source
timestampServer/collector clock
authenticated_userVerified session/token
source_ipTrusted proxy/network context
event_typeApplication enumeration
message/parameterPotentially attacker-controlled
severityApplication/security logic

Keep Security Context Separate

Do not let a client submit role=admin and have the log parser interpret it as the authenticated role. Separate observed/request values from trusted identity/tenant/security context.

Also avoid logging passwords, session cookies, authorization tokens or unnecessary request bodies solely for forensic convenience.

How to Detect Log Forging

  • Alert on control characters or multiline values in fields expected to be single-line.
  • Detect duplicate/impossible trusted fields.
  • Compare authenticated identity with request-supplied identity values.
  • Watch parser failures and sudden field-cardinality changes.
  • Detect timestamps far outside collector/server time.
  • Monitor unusual log-volume spikes.
  • Use tamper-evident controls for high-value audit records where required.

SIEM and Log Pipeline Security

Centralized logging adds agents, collectors, queues, parsers, enrichment and SIEM storage as trust boundaries. Authenticate/encrypt transport, restrict parser-rule administration and separate ingestion credentials from administrative credentials.

Treat parser/configuration changes like production code: version, test and roll back safely.

When Logs May Be Forged

Do not treat one source as authoritative. Correlate reverse proxies, identity providers, databases, cloud audit logs, endpoint/network events and traces. Preserve the rawest available representation; normalized SIEM records can hide the delimiter that caused the issue.

Secure API Logging

  • Generate/validate correlation IDs.
  • Log authenticated subject and authorization outcome separately from request parameters.
  • Normalize forwarding headers at trusted proxies.
  • Do not log secrets/cookies.
  • Use fixed event types.
  • Record object/tenant identifiers only as needed.
  • Centralize logs with retention/access controls.

Ammune can add API runtime/forensic context, while secure serialization and trusted-field construction remain application/log-pipeline responsibilities.

Protecting Audit-Log Integrity After Ingestion

Safe serialization prevents an application value from forging record structure, but audit integrity also depends on what happens after the record is emitted. Attackers with host or logging-platform access may delete, reorder or modify events, so high-value audit trails should be forwarded promptly to a more restricted system and protected by retention and access controls.

Where the threat model justifies it, use append-only or immutable storage, cryptographic integrity mechanisms or a platform that records administrative changes separately from data ingestion. These controls do not make every log statement trustworthy—the application may still log false business context—but they make later tampering harder and more detectable.

Synchronize time across systems and preserve original event timestamps plus ingestion timestamps. A forged client-supplied time should never overwrite the collector’s trusted view of when the event arrived.

ThreatControl
Application newline injectionStructured serialization
Client supplies fake identity/timeTrusted server-derived fields
Compromised host deletes local logsRemote forwarding
SIEM admin changes parserChange/audit controls on pipeline
Stored audit events alteredImmutable/append-only retention where warranted
Clock manipulationIndependent time synchronization and ingestion timestamps

Different Log Formats, Different Injection Boundaries

Log injection is context-specific. A newline is dangerous in line-oriented text; commas and quotes matter in CSV-like logs; arbitrary keys and nested objects matter in JSON; syslog has its own structured fields and framing rules. One universal “sanitize logs” helper is therefore easy to get wrong.

FormatPrimary boundarySafer pattern
Plain textRecord delimiter / key=value syntaxParameterized logger + escaped controls
JSONField names/types and serialized valuesFixed schema + trusted keys + JSON serializer
CSVComma/quote/newline structureStandards-compliant CSV writer; protect spreadsheet exports
SyslogHeader/structured-data/message framingProtocol-aware library and protected transport

Security-sensitive logs should use a stable event schema so detection rules are not forced to parse free-form attacker-controlled messages.

How to Test Log Forging Defenses Safely

Testing should prove that untrusted data remains one field value through application logging, transport, parsing and SIEM ingestion. Use controlled strings containing newlines, quotes and format delimiters in a test environment, then verify how the raw event and parsed event appear.

  • Confirm one application event remains one ingested event.
  • Verify trusted fields such as authenticated user, timestamp and severity cannot be overwritten.
  • Test maximum-length values and truncation behavior.
  • Check that parser failures are visible rather than silently dropping events.
  • Validate redaction so secrets are not exposed during negative testing.
  • Test export paths such as CSV separately because their injection boundaries differ.

The pass condition is stable record structure and trustworthy metadata—not merely the absence of a particular CRLF string in the stored log.

Log Forging Prevention Checklist

  • Use structured logging instead of concatenation.
  • Fixed schemas for audit events.
  • Escape/serialize external values.
  • Safely handle record delimiters.
  • Build identity/time/severity from trusted context.
  • Prevent client overwrite of trusted fields.
  • Limit event size.
  • Protect log transport/storage/parser administration.
  • Monitor parser failures/impossible fields.
  • Correlate independent evidence.
  • Redact secrets/sensitive data.

Frequently Asked Questions

What is log forging?

Creating misleading or fake-looking log records by causing external data to be interpreted as log structure.

Is log injection the same as CRLF injection?

CR/LF is one common vector; other delimiters and trusted-field manipulation can also cause log injection.

Does JSON logging prevent it?

It helps, but applications must still prevent external data from controlling trusted field names or metadata.

How do you detect forged logs?

Look for control characters, parser failures, impossible field combinations, timestamp anomalies and discrepancies across independent telemetry.

Should APIs log request bodies?

Only when justified and minimized; bodies can contain credentials, PII or regulated data.

Primary References

Make API Security Events Trustworthy and Actionable

Use safe structured logging for application evidence, then enrich investigations with runtime API visibility, correlated identities and threat context.

© Ammune.ai — API security guidance for modern application environments.