Command Injection in Aspnet with Bearer Tokens
Command Injection in Aspnet with Bearer Tokens — how this specific combination creates or exposes the vulnerability
Command Injection occurs when an application passes untrusted input directly to a system shell or to a process builder without proper validation or sanitization. In ASP.NET applications, this risk can emerge in API endpoints that accept bearer tokens as part of an Authorization header and then misuse token-derived values in operating system commands. Even though bearer tokens are designed for authentication and not for direct data execution, developers sometimes log, echo, or forward token contents into diagnostic scripts, subprocess calls, or external utilities. If an attacker can influence the token format—such as by injecting shell metacharacters—and the application concatenates that token into a command string, the attacker may achieve unintended command execution.
Consider an endpoint that receives an Authorization bearer token and uses its payload or metadata to construct a system command, for example in logging, external tool invocation, or token introspection workflows. If the token value contains characters like ; & | $ ( ) and the code builds a command via string interpolation or concatenation, the shell may interpret these as command separators or argument delimiters. This becomes especially relevant when the application runs under a context where the operating system shell is invoked, such as through System.Diagnostics.Process.Start with a shell-executable path. The presence of bearer tokens does not inherently introduce command injection, but the combination of a dynamic token value and insufficient input validation creates a pathway for an attacker to manipulate the command line.
ASP.NET applications that use token values in diagnostics, health checks, or integration tests are at risk if they construct commands using raw token data. For instance, a developer might write code that runs an external script and passes the token as an argument without escaping or whitelisting. In such cases, an attacker who can supply a maliciously crafted token—perhaps through a compromised client or a token-generation endpoint—can effectively change the semantics of the executed command. This maps to the OWASP API Top 10 category Broken Function Level Authorization and can be related to injection patterns seen in tools like SQLMap when input handling is inconsistent. Real-world analogs include CVE scenarios where log injection or command injection leads to privilege escalation or data exfiltration, emphasizing the need to treat any externally influenced string—including bearer token contents—as untrusted input.
An effective security posture starts by validating that bearer tokens are never used verbatim in system commands. Instead, applications should rely on structured APIs for token validation and introspection, avoiding shell invocation entirely. When external processes are necessary, use parameterized calls with explicit argument lists and avoid passing raw header values into shell strings. This guidance aligns with the broader goal of reducing the attack surface for unauthenticated and authenticated interactions alike, ensuring that security checks such as those run by middleBrick can identify risky patterns before they reach production.
Bearer Tokens-Specific Remediation in Aspnet — concrete code fixes
Remediation focuses on eliminating direct concatenation of bearer token values into command text and ensuring that any external invocation uses safe, platform-native APIs. The following examples demonstrate insecure patterns and their secure replacements in C# for ASP.NET Core.
Insecure pattern using token in a shell command:
// DO NOT DO THIS
var token = HttpContext.Request.Headers["Authorization"].ToString().Replace("Bearer ", "");
var process = new Process {
StartInfo = new ProcessStartInfo {
FileName = "/bin/bash",
Arguments = $"-c \"echo token_value={token}\"",
UseShellExecute = false
}
};
process.Start();
Issues: The token is interpolated directly into the shell command string, enabling shell metacharacters to alter command boundaries.
Secure alternative using structured JSON output and no shell invocation:
// Prefer managed APIs over shell execution
var token = HttpContext.Request.Headers["Authorization"].ToString().Replace("Bearer ", "");
// Validate token format without shell involvement
if (IsValidBearerToken(token)) {
var payload = new { TokenHash = Sha256(token), Timestamp = DateTime.UtcNow };
var json = JsonSerializer.Serialize(payload);
// Write json to a file or pipe using safe file APIs, not shell commands
await File.WriteAllTextAsync("/tmp/token_info.json", json);
}
bool IsValidBearerToken(string token) {
// Basic format check; in practice use a robust library
return !string.IsNullOrWhiteSpace(token) && token.Length <= 512;
}
If an external process must be invoked, use argument arrays and avoid shell metacharacters entirely:
// Secure external process invocation
var token = HttpContext.Request.Headers["Authorization"].ToString().Replace("Bearer ", "");
var process = new Process {
StartInfo = new ProcessStartInfo {
FileName = "dotnet",
ArgumentList.Add("script.dll"),
ArgumentList.Add($"--tokenHash={Sha256(token)}"),
UseShellExecute = false,
RedirectStandardOutput = true
}
};
process.Start();
Additional measures include:
- Never log full bearer tokens; log only hashes or masked representations.
- Apply strict length and character whitelist validation on token material before any processing.
- Use dependency injection for external services rather than spawning processes where possible.
- Integrate middleBrick scans to detect patterns where token values appear in command-related code paths.
Related CWEs: inputValidation
| CWE ID | Name | Severity |
|---|---|---|
| CWE-20 | Improper Input Validation | HIGH |
| CWE-22 | Path Traversal | HIGH |
| CWE-74 | Injection | CRITICAL |
| CWE-77 | Command Injection | CRITICAL |
| CWE-78 | OS Command Injection | CRITICAL |
| CWE-79 | Cross-site Scripting (XSS) | HIGH |
| CWE-89 | SQL Injection | CRITICAL |
| CWE-90 | LDAP Injection | HIGH |
| CWE-91 | XML Injection | HIGH |
| CWE-94 | Code Injection | CRITICAL |