GuardAPI Logo
GuardAPI
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();

}

Protect your ASP.NET Core API

Don't rely on manual checks. GuardLabs detects Command Injection and logic flaws in seconds.

Run Free Audit

Verified by Ghost Labs Security Team

This content is continuously validated by our automated security engine and reviewed by our research team. Ghost Labs analyzes over 500+ vulnerability patterns across 40+ frameworks to provide up-to-date remediation strategies.