How to fix Command Injection
in .NET 8 Web API
Executive Summary
Stop concatenating strings into shell commands. Command injection in .NET 8 occurs when untrusted input is fed directly into a process's argument string, allowing attackers to escape the intended context using shell metacharacters like ';', '&', or '|'. If you are using Process.Start with raw string interpolation, your host is compromised.
The Vulnerable Pattern
[HttpGet("ping")]
public IActionResult Ping(string host) {
var process = new Process {
StartInfo = new ProcessStartInfo {
FileName = "ping",
Arguments = $"-c 4 {host}", // VULNERABLE: String concatenation allows command chaining
RedirectStandardOutput = true,
UseShellExecute = false
}
};
process.Start();
return Ok(process.StandardOutput.ReadToEnd());
}
The Secure Implementation
The exploit vector relies on the shell parsing the 'Arguments' string. By switching to the 'ArgumentList' property (available since .NET Core 2.1), you bypass the shell's command-line parser entirely. Each entry in 'ArgumentList' is treated as a literal argument passed directly to the executable's argv array. Additionally, setting 'UseShellExecute = false' ensures the process is spawned directly via the OS's CreateProcess or execve system calls, rather than through a shell intermediary like /bin/sh or cmd.exe.
[HttpGet("ping")] public IActionResult Ping(string host) { var process = new Process { StartInfo = new ProcessStartInfo { FileName = "ping", RedirectStandardOutput = true, UseShellExecute = false // Ensure shell execution is disabled } }; // SECURE: ArgumentList handles escaping and prevents shell interpretation process.StartInfo.ArgumentList.Add("-c"); process.StartInfo.ArgumentList.Add("4"); process.StartInfo.ArgumentList.Add(host);process.Start(); return Ok(process.StandardOutput.ReadToEnd());
}
Your .NET 8 Web API API
might be exposed to Command Injection
74% of .NET 8 Web API apps fail this check. Hackers use automated scanners to find this specific flaw. Check your codebase before they do.
Free Tier • No Credit Card • Instant Report
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.