Log Injection on Azure
How Log Injection Manifests in Azure
Log injection occurs when untrusted data is written directly into application logs without proper sanitization, allowing an attacker to forge log entries, inject control characters, or execute arbitrary code in log‑processing pipelines. In Azure environments this frequently appears in:
- Azure Functions (C#) – developers often log request payloads or query strings using
ILogger.LogInformationwith string interpolation:
public async Task Run([HttpTrigger(AuthorizationLevel.Function, "get", "post")] HttpRequest req,
ILogger log)
{
string userId = req.Query["user"];
log.LogInformation("User {UserId} accessed the function", userId); // vulnerable if userId contains newlines or JSON
}
app.get('/api/data', (req, res) => {
const filter = req.query.filter;
winston.info(`Request received with filter: ${filter}`); // filter may contain \n or \r
res.send(...);
});
logging module with %s formatting:import logging
logging.basicConfig(level=logging.INFO)
def process_item(item):
logging.info("Processing item: %s", item) # item could contain newlines that break log lines
When an attacker supplies values containing newline (\n), carriage return (\r), or JSON/JavaScript snippets, the resulting log file can be corrupted. If logs are later ingested by Azure Monitor, Log Analytics, or SIEM tools that parse JSON or execute scripts, the injected payload may trigger unintended actions—such as executing arbitrary Kusto queries, injecting malicious dashboard widgets, or bypassing log‑based alerting. This pattern maps to OWASP API Security Top 10 2023: API8:2023 – Injection, and has been observed in real‑world incidents like CVE-2021-44228 (Log4Shell), where log‑based JNDI lookup led to remote code execution.
Azure-Specific Remediation
The safest way to eliminate log injection in Azure applications is to treat all external data as untrusted and to use Azure‑native logging facilities that enforce proper encoding and structure. Below are language‑specific remediations that rely on built‑in Azure libraries and services.
1. Azure Functions (C#) – Structured Logging with ILogger
Instead of interpolating raw strings, pass user data as named arguments; the logger will serialize them safely.
public async Task Run([HttpTrigger(AuthorizationLevel.Function, "get", "post")] HttpRequest req,
ILogger log)
{
string userId = req.Query["user"];
// Safe: userId is treated as a property, not part of the format string
log.LogInformation("User accessed the function", new { UserId = userId });
}
If you need to include the value in the message, use System.Text.Json to escape it:
string safe = JsonSerializer.Serialize(userId);
log.LogInformation("User {UserId} accessed the function", safe);
2. Azure App Service (Node.js) – Winston with format.combine and format.printf
Configure Winston to JSON‑encode all meta fields, preventing newline injection.
const winston = require('winston');
const logger = winston.createLogger({
level: 'info',
format: winston.format.combine(
winston.format.timestamp(),
winston.format.json() // ensures safe serialization
),
transports: [new winston.transports.Console()]
});
app.get('/api/data', (req, res) => {
const filter = req.query.filter;
logger.info('Request received', { filter }); // filter is safely JSON‑encoded
res.send('OK');
});
3. Azure SDK for Python – logging with extra dict and JSONFormatter
Use the azure-monitor-opentelemetry exporter or a custom JSON formatter to keep logs structured.
import logging, json
from pythonjsonlogger import jsonlogger
logger = logging.getLogger()
handler = logging.StreamHandler()
formatter = jsonlogger.JsonFormatter()
handler.setFormatter(formatter)
logger.addHandler(handler)
logger.setLevel(logging.INFO)
def process_item(item):
logger.info('Processing item', extra={'item': item}) # item is serialized as JSON
4. Leveraging Azure Monitor Diagnostic Settings
Enable diagnostic logs for Function Apps or App Services and route them to a Log Analytics workspace with a defined schema. Because the workspace expects JSON, any non‑JSON payload will be rejected at ingestion time, providing an additional defensive layer.
By combining these practices—structured logging, proper escaping, and Azure‑native log ingestion—you eliminate the injection vector while retaining full observability. middleBrick’s rescans will then show the finding resolved, and the security score will improve accordingly.
], "faq": [ { "q": "Can middleBrick fix log injection vulnerabilities in my Azure API?", "a": "No. middleBrick only detects and reports security issues, including log injection. It provides detailed findings and remediation guidance, but you must apply the fixes in your code or configuration." }, { "q": "Does middleBrick require any agents or credentials to scan an Azure Function?", "a": "No. middleBrick performs unauthenticated, black‑box scanning from the outside. You simply provide the public URL of the Function App or API Management endpoint; no agents, installation, or credentials are needed." } ], "meta_description": "Learn how log injection appears in Azure apps, how to detect it with middleBrick, and how to fix it using Azure-native logging.", "risk_summary": { "severity": "medium", "category": "Input Validation" } }