# Log Forging

#### Tools recognizing this:

<kbd>Opengrep</kbd> <kbd>Fortify</kbd> <kbd>Checkmarx</kbd> <kbd>SonarQube</kbd> <kbd>Snyk</kbd> <kbd>Semgrep</kbd> <kbd>CodeQL</kbd>

## What is Log Forging

Log Forging, also known as Log Injection, is a security vulnerability that allows attackers to manipulate log files, leading to misleading entries, log poisoning, or even system exploits. This guide covers log forging vulnerabilities, examples, prevention methods, and how to fix log injection attacks effectively.

The vulnerability occurs when an application writes untrusted user input to log files without proper validation or encoding.

An attacker can exploit this vulnerability by injecting malicious content into logs, which can lead to:

* Insertion of fake log entries
* Manipulation of log data
* Cross-site scripting (XSS) if logs are displayed in web interfaces
* Log file corruption
* Potential system compromise through log analysis tools

## One Simple Example

Consider this common logging scenario:

{% code overflow="wrap" %}

```java
logger.info("User login attempt for username: " + username);
```

{% endcode %}

Assuming the value of `username` comes from user's input, an attacker could provide this input as the username:

<mark style="color:red;">`admin%0D%0ALogin successful`</mark>

`%0D%0A` is the new-line character, resulting in the following log entry:

```
User login attempt for username: admin 
Login successful
```

This creates a false log entry suggesting a successful login, potentially misleading security analysts or automated log monitoring systems.

## Real-world Occurrences of Log Forging

#### Log4Shell Vulnerability in Apache Log4j ([CVE-2021-44228](https://nvd.nist.gov/vuln/detail/cve-2021-44228))

In December 2021, a critical vulnerability known as Log4Shell was discovered in Apache Log4j, a widely used Java-based logging framework. This vulnerability allowed attackers to perform log injection by crafting malicious input that, when logged by the application, could lead to remote code execution.

The vulnerability had a widespread impact, affecting numerous applications and services that utilized Log4j for logging. Exploitation of this vulnerability allowed attackers to execute arbitrary code on affected systems, leading to potential data breaches and system compromises.

Reference: [Log4Shell - Wikipedia](https://en.wikipedia.org/wiki/Log4Shell)

#### Spring Security Log Injection ([CVE-2021-22060](https://spring.io/security/cve-2021-22060))

A log forging vulnerability in Spring Security allowed an attacker to inject malicious characters into authentication logs, potentially altering log records or bypassing security checks.

Impact: Attackers could manipulate logs to make it appear as if a different user performed specific actions, covering their tracks during exploitation.

## Fixing Log Forging

The most effective way to prevent Log Forging is to properly encode or sanitize all user-supplied data before writing it to log files. This can be achieved by:

1. Using proper encoding for special characters
2. Removing or replacing newline characters
3. Utilizing built-in logging framework security features
4. Implementing input validation

### Code Samples

{% tabs %}
{% tab title="Java" %}
**Vulnerable Code**

```java
String userInput = request.getParameter("username");
logger.info("User input: " + userInput);
```

**Fixed Code**

```java
String userInput = request.getParameter("username");
String sanitized = userInput.replace('\n', '_').replace('\r', '_');
logger.info("User input: {}", sanitized);
```

**Fix Explanation**

The vulnerable code directly writes user input to logs.\
The fix sanitizes the input by replacing newline characters.\
Uses proper logging framework placeholder to prevent string concatenation.\
Ensures log entries cannot be split across multiple lines.
{% endtab %}

{% tab title="JavaScript" %}
**Vulnerable Code**

```javascript
console.log("User action: " + userInput);
```

**Fixed Code**

```javascript
const sanitized = userInput.replace(/[\n\r\t]/g, '_');
console.log("User action: %s", sanitized);
```

**Fix Explanation**

The vulnerable code directly logs user input.\
The fix removes all newline and tab characters.\
Uses proper string formatting instead of concatenation.\
Prevents log injection through special characters.
{% endtab %}

{% tab title="Python" %}
**Vulnerable Code**

```python
logging.info("User input: " + user_input)
```

**Fixed Code**

```python
import html
sanitized = user_input.replace('\n', '_').replace('\r', '_')
logging.info("User input: %s", html.escape(sanitized))
```

**Fix Explanation**

The vulnerable code concatenates unvalidated input.\
The fix escapes HTML and removes newline characters.\
Uses proper string formatting.\
Prevents both log injection and XSS in web interfaces.
{% endtab %}

{% tab title="C#" %}
**Vulnerable Code**

```csharp
_logger.LogInformation("User input: " + userInput);
```

**Fixed Code**

```csharp
var sanitized = userInput.Replace("\n", "_").Replace("\r", "_");
_logger.LogInformation("User input: {UserInput}", sanitized);
```

**Fix Explanation**

The vulnerable code uses string concatenation with raw input.\
The fix sanitizes input by replacing newline characters.\
Uses structured logging with named parameters.\
Prevents log injection attacks.
{% endtab %}

{% tab title="PHP" %}
**Vulnerable Code**

```php
error_log("User input: " . $userInput);
```

**Fixed Code**

```php
$sanitized = str_replace(["\n", "\r"], '_', $userInput);
error_log(sprintf("User input: %s", $sanitized));
```

**Fix Explanation**

The vulnerable code directly concatenates user input.\
The fix removes newline characters.\
Uses proper string formatting.\
Ensures log integrity is maintained.
{% endtab %}

{% tab title="C/C++" %}
**Vulnerable Code**

```cpp
syslog(LOG_INFO, "User input: %s", userInput);
```

**Fixed Code**

```cpp
string sanitized = regex_replace(userInput, regex("\n|\r"), "_");
syslog(LOG_INFO, "User input: %s", sanitized.c_str());
```

**Fix Explanation**

The vulnerable code logs raw user input.\
The fix sanitizes input using regex replacement.\
Removes potentially dangerous characters.\
Maintains log file structure integrity.
{% endtab %}
{% endtabs %}


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.mobb.ai/mobb-user-docs/fixing-guides/log-forging-fix-guide.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
