Log Injection in Aspnet with Bearer Tokens
Log Injection in Aspnet with Bearer Tokens — how this specific combination creates or exposes the vulnerability
Log injection occurs when untrusted input is written directly into application or system logs without proper sanitization, enabling an attacker to forge log entries, obfuscate real events, or inject newline characters that facilitate log forging or log poisoning. In ASP.NET applications that rely on bearer token authentication (e.g., using JWTs in the Authorization: Bearer header), log injection commonly arises when token values or claims derived from tokens are concatenated into log messages without validation or encoding.
Consider an ASP.NET Core controller that logs the value of a bearer token for debugging purposes. If the token string is interpolated directly into a log message, an attacker who can influence the token (for example, via a malformed or crafted token) can inject newline characters or structured log delimiters. This can split a single log entry into multiple lines, making it appear as separate log events or hide subsequent malicious entries. A concrete example is a logging statement such as logger.LogInformation("Bearer token used: {Token}", token), where token contains newline or structured payload data. Such injection can bypass log-based monitoring rules that rely on line-oriented parsing, evade detection heuristics, and complicate forensic analysis.
In the context of the 12 security checks run by middleBrick, log injection intersects with Data Exposure and Input Validation. While the scanner does not inspect internal logging code, it highlights areas where user-supplied data enters observable surfaces. Bearer tokens in requests are part of the unauthenticated attack surface tested by middleBrick: the scanner observes how token formats, lengths, and patterns are handled by the API and whether responses or logs might inadvertently reflect unsafe practices. For instance, if an endpoint reflects token metadata in error responses or verbose logs, middleBrick may flag insecure data handling as a finding. Additionally, because bearer tokens often carry authorization claims, improperly logged claims can expose sensitive information or enable privilege escalation narratives in log-based attacks.
Another relevant concern is the presence of newline characters within token values or related headers. Newline injection can corrupt log structure, and in structured logging formats such as JSON, unescaped control characters can break parsing or lead to log injection chains. Attack patterns like log forging or log injection are commonly mapped to OWASP API Top 10 categories related to Security Misconfiguration and Insufficient Logging & Monitoring. By ensuring tokens are treated as opaque credentials and never directly interpolated into logs, developers reduce the risk of log-based attacks that rely on token manipulation.
middleBrick’s OpenAPI/Swagger spec analysis (supporting OpenAPI 2.0, 3.0, and 3.1 with full $ref resolution) can reveal endpoints that accept bearer tokens. Cross-referencing spec definitions with runtime behavior helps identify whether authentication inputs are validated and whether they surface in diagnostics. While the scanner does not inspect log implementations, it provides a per-category breakdown and prioritized findings that can point developers toward areas where input validation and data handling should be hardened, including logging practices around bearer tokens.
Bearer Tokens-Specific Remediation in Aspnet — concrete code fixes
Remediation focuses on preventing untrusted token values from corrupting logs. The primary approach is to avoid logging bearer tokens in full and to sanitize any data derived from tokens before inclusion in log messages. Below are concrete code examples for ASP.NET Core that demonstrate safe logging patterns and token handling.
First, configure logging to exclude sensitive headers. In Program.cs, you can filter out the Authorization header from being captured by the request logging middleware:
builder.Logging.ClearProviders();
builder.Logging.AddConsole((options) =>
{
options.Filter = (category, level) =>
{
// Avoid logging sensitive headers by customizing the filter
return true;
};
});
// Use built-in filters to exclude headers
builder.Services.Configure<LoggerFilterOptions>(options =>
{
options.Rules.Clear();
options.Rules.Add(new LoggerFilterRule { Category = "Microsoft.AspNetCore.HttpLogging", LogLevel = LogLevel.None });
});
Second, when logging authentication-related events, use sanitized representations such as token type and a hash or truncated value instead of the raw token. For example:
string token = context.Request.Headers["Authorization"].ToString();
string safeToken = "[REDACTED]";
if (!string.IsNullOrEmpty(token) && token.StartsWith("Bearer ", StringComparison.OrdinalIgnoreCase))
{
string tokenValue = token.Substring("Bearer ".Length);
// Use a truncated representation or hash for logging
safeToken = $"Bearer {tokenValue.Substring(0, Math.Min(8, tokenValue.Length))}...";
}
logger.LogInformation("Authenticated request. Token: {Token}", safeToken);
// Alternatively, log the claim type without exposing the token:
var claims = context.User.Claims;
logger.LogInformation("User claims: {Claims}", string.Join(", ", claims.Select(c => $"{c.Type}={c.Value}")));
Third, ensure that any logging within authentication handlers or middleware does not propagate newline characters from token claims. Validate and sanitize claims before including them in structured logs:
foreach (var claim in userClaims)
{
string sanitizedValue = claim.Value?.Replace("\n", "\\n").Replace("\r", "\\r") ?? string.Empty;
logger.LogDebug("Claim: {ClaimType}={SanitizedValue}", claim.Type, sanitizedValue);
}
Fourth, adopt structured logging with JSON and ensure special characters are properly escaped. Using a library like Serilog with appropriate enrichers can help manage this automatically, but manual sanitization remains necessary when integrating with custom logging pipelines.
Finally, apply defense-in-depth by configuring ASP.NET Core to reject malformed bearer tokens early, reducing the chance that malformed input reaches logging code. Combine this with robust input validation and avoid echoing raw token values in responses or logs. middleBrick’s CLI tool can be used to scan your API endpoints with a command such as middlebrick scan <url>, providing a report that highlights endpoints with authentication inputs and related findings, helping you validate that token handling aligns with security best practices without exposing sensitive material in logs.