HIGH command injectionaspnetmutual tls

Command Injection in Aspnet with Mutual Tls

Command Injection in Aspnet with Mutual Tls — how this specific combination creates or exposes the vulnerability

Command Injection in an ASP.NET application using Mutual TLS (mTLS) often arises when an API endpoint accepts external input and passes it to a system shell or a native process, even while the transport is protected by client certificates. mTLS ensures that both client and server authenticate each other via X.509 certificates, which strengthens identity and confidentiality in transit. However, it does not constrain what the server does with untrusted data once it is received and validated at the application layer.

Consider an endpoint that accepts a filename or a host identifier from the client, validates the mTLS client cert, and then constructs a system command using string concatenation or interpolation. An attacker who presents a valid client certificate can supply malicious payloads such as ; id or | whoami that are appended to the command. Because the server executes the command with the privileges of the application process, this leads to arbitrary command execution. The presence of mTLS may give a false sense of security, leading developers to skip rigorous input validation and allowlist checks.

Real-world patterns include using System.Diagnostics.Process or System.Management.Automation to run external utilities. If the input is not rigorously validated, encoded, or passed as arguments rather than as shell metacharacters, the application becomes vulnerable. For example, an endpoint that forwards a user-supplied host parameter to a ping or traceroute command can be exploited even when mTLS is enforced. The vulnerability is not in mTLS itself but in the insecure use of external input within the application logic after mTLS authentication has succeeded.

Additionally, mTLS configurations that accept any client certificate without verifying revocation or mapping certificates to least-privilege identities can increase risk. If the server trusts a broad set of client certs and does not enforce strict authorization, an attacker who compromises a valid certificate can more easily experiment with command injection techniques. Therefore, treating mTLS as an authentication mechanism rather than an authorization or input validation control is essential to avoid conflating transport security with safe data handling.

Mutual Tls-Specific Remediation in Aspnet — concrete code fixes

Remediation focuses on secure handling of external input and strict certificate validation rather than relying on mTLS alone. Use allowlists for known-safe values, avoid shell injection primitives, and validate certificate properties explicitly.

1. Avoid shell invocation; use process arguments

Prefer ProcessStartInfo with explicit arguments and UseShellExecute = false. This prevents the shell from interpreting metacharacters. Never concatenate user input into a command string that is passed to a shell.

// Safe: arguments are passed directly, no shell involved
var startInfo = new ProcessStartInfo
{
    FileName = "ping",
    Arguments = $"-n 2 {EscapeHost(host)}", // host validated against allowlist
    UseShellExecute = false,
    RedirectStandardOutput = true,
    CreateNoWindow = true
};
using var process = Process.Start(startInfo);
process.WaitForExit();

2. Strict client certificate validation and mapping

Validate the client certificate fields and map them to application-specific permissions. Do not rely solely on the presence of a certificate.

// In Program.cs or Startup configuration
builder.WebHost.ConfigureKestrel(serverOptions =>
{
    serverOptions.ConfigureHttpsDefaults(httpsOptions =>
    {
        httpsOptions.ClientCertificateMode = ClientCertificateMode.RequireCertificate;
        httpsOptions.AllowedClientCertificates.Add(new X509Certificate2("trusted-ca.crt"));
    });
});

// Custom validation in middleware or a service
app.Use(async (context, next) =>
{
    var cert = context.Connection.ClientCertificate;
    if (cert == null || !IsValidClientCertificate(cert))
    {
        context.Response.StatusCode = 403;
        return;
    }
    // Map certificate thumbprint or subject to roles/scopes
    context.Items["ClientScopes"] = MapCertificateToScopes(cert);
    await next();
});

bool IsValidClientCertificate(X509Certificate2 cert)
{
    // Example: enforce extended key usage and revocation checks
    var chain = new X509Chain();
    chain.ChainPolicy.RevocationMode = X509RevocationMode.Online;
    chain.ChainPolicy.ExtraStore.Add(new X509Certificate2("trusted-ca.crt"));
    chain.ChainPolicy.VerificationFlags = X509VerificationFlags.NoFlag;
    bool isValid = chain.Build(cert);
    if (!isValid) return false;
    // Additional policy checks, e.g., subject, SAN, EKU
    return cert.GetNameInfo(X509NameType.SimpleName, false) switch
    {
        "trusted-client" => true,
        _ => false
    };
}

3. Input validation and safe parameterization

Use allowlists for identifiers such as hostnames or filenames. Encode or sanitize data before using it in system commands. When interfacing with LLM endpoints, ensure that user input does not leak into prompts or tool calls that could be abused.

string EscapeHost(string host)
{
    // Allow only alphanumeric and hyphens; reject shell metacharacters
    if (!System.Text.RegularExpressions.Regex.IsMatch(host, "^[a-zA-Z0-9-]+$"))
        throw new ArgumentException("Invalid host");
    return host;
}

These practices, combined with runtime security scans that test authentication, authorization, and input validation (such as those provided by middleBrick), help ensure that mTLS deployments remain robust against command injection while preserving the confidentiality and integrity benefits of mutual authentication.

Related CWEs: inputValidation

CWE IDNameSeverity
CWE-20Improper Input Validation HIGH
CWE-22Path Traversal HIGH
CWE-74Injection CRITICAL
CWE-77Command Injection CRITICAL
CWE-78OS Command Injection CRITICAL
CWE-79Cross-site Scripting (XSS) HIGH
CWE-89SQL Injection CRITICAL
CWE-90LDAP Injection HIGH
CWE-91XML Injection HIGH
CWE-94Code Injection CRITICAL

Frequently Asked Questions

Does mTLS prevent command injection in ASP.NET?
No. mTLS authenticates peers in transit but does not validate or sanitize application-layer input. Command injection must be addressed through input validation, allowlists, and safe process invocation.
How can I verify my ASP.NET app is safe against command injection while using mTLS?
Use runtime security scans that test unauthenticated attack surface and authenticated scenarios, validate client certificates strictly, avoid shell commands, and prefer process arguments over shell invocation. Tools that provide actionable findings with remediation guidance can help assess your risk posture.