GuardAPI Logo GuardAPI
Automated Security Protocol

How to fix Command Injection
in ASP.NET Core

Executive Summary

Command Injection in ASP.NET Core is a critical RCE vector. It occurs when untrusted user input is concatenated into system commands executed via Process.Start or similar APIs. If you are building command strings manually, you are doing it wrong. To secure your application, you must avoid shell execution and use structured argument passing.

The Vulnerable Pattern

VULNERABLE CODE
public IActionResult RunTools(string fileName)
{
    // CRITICAL VULNERABILITY: User input is concatenated directly into a shell command.
    // An attacker can pass: "file.txt; cat /etc/passwd"
    var process = new Process();
    process.StartInfo.FileName = "cmd.exe";
    process.StartInfo.Arguments = $"/c type {fileName}"; 
    process.Start();
    return Ok();
}

The Secure Implementation

The fix relies on breaking the injection context. By setting UseShellExecute to false and using the ArgumentList collection, you bypass the OS shell (cmd.exe or /bin/sh) entirely. This prevents attackers from using shell metacharacters like '&', '|', or ';' to chain malicious commands. ArgumentList ensures that the OS receives the input as a distinct, literal parameter rather than part of a command string that needs parsing. Always pair this with strict regex validation to ensure the input conforms to expected patterns.

SECURE CODE
public IActionResult RunTools(string fileName)
{
    // 1. Strict Whitelisting/Validation
    if (!Regex.IsMatch(fileName, @"^[a-zA-Z0-9\._-]+$")) return BadRequest();
var process = new Process();
// 2. Call the binary directly, not through a shell (cmd/sh)
process.StartInfo.FileName = "type";

// 3. Use ArgumentList (available in .NET Core/5+) to automatically escape arguments
process.StartInfo.ArgumentList.Add(fileName);

process.StartInfo.UseShellExecute = false; // Ensure shell execution is disabled
process.Start();
return Ok();

}

Passive External Check · ASP.NET Core

Verify your domain for Command Injection in 3 seconds

Run 20+ passive checks (TLS/RDAP expiry, CSP, DMARC, source maps, CT subdomains) and get stack-exact copy-paste fixes for ASP.NET Core.

Scan domain free
G

Verified by GuardAPI Deterministic Engine

Remediation snippets and external posture guides maintained for modern cloud stacks (Next.js, Cloudflare, Nginx, Vercel, OVH).