Formula Injection in Aspnet with Mutual Tls
Formula Injection in Aspnet with Mutual Tls
Formula Injection in ASP.NET applications occurs when untrusted data from requests is concatenated into formulas evaluated on the server, commonly in spreadsheet generation or financial calculations. When Mutual TLS (mTLS) is used, the transport is authenticated and encrypted, which may create a false sense of security. mTLS ensures the client is who they claim to be, but it does not sanitize inputs. If an API endpoint accepts parameters such as cell expressions or numeric values from authenticated mTLS clients and embeds them directly into formulas, an attacker can inject malicious payloads like ="1+2" & cmd("calc.exe") or structured references that cause remote code execution or logic manipulation during evaluation.
In an mTLS-enabled ASP.NET endpoint, the server validates the client certificate before processing the request. This check happens at the transport layer, before the application parses parameters. Because the certificate handshake succeeds, the application may trust the request body implicitly. For example, an endpoint that generates Excel files using a library like EPPlus might read a formula from JSON:
{
"formula": "=A1+B1"
}
If the formula field is taken directly from the client and written into a generated sheet, an attacker could supply:
{
"formula": "=HYPERLINK("http://evil.example", "Click")"
}
This is a formula injection payload. In the context of mTLS, the request passes authentication, so the server processes the malicious formula. When the generated file is opened by a downstream user, the injected hyperlink can lead to phishing or data exfiltration. Additionally, numeric injection can manipulate calculations, leading to financial discrepancies. Because mTLS does not validate input content, the vulnerability persists despite strong transport security.
Another scenario involves CSV or data exports where column values are built by concatenating user-controlled fields into Excel formulas. If an attacker controls a field like accountNumber and the endpoint produces:
string formula = $"=VLOOKUP({accountNumber}, Sheet2!A:B, 2, FALSE)";
and accountNumber is set to 1;CMD("powershell.exe"), the resulting formula can trigger unintended behavior in spreadsheet software. The mTLS assurance means the request is considered authorized, but the application must still treat all data as untrusted.
To detect this with middleBrick, you can scan the unauthenticated attack surface of an ASP.NET endpoint even when mTLS is in use. The scanner submits requests without client certificates to observe behavior, then authenticated probes when certificates are provided, highlighting where formula fields are accepted and whether outputs reflect injection attempts. This helps identify gaps between transport-layer assurance and application-layer sanitization.
Mutual Tls-Specific Remediation in Aspnet
Remediation focuses on treating mTLS as an authentication boundary, not an input validation boundary. In ASP.NET, you should validate and sanitize all incoming data regardless of mTLS status. Use strongly typed models with explicit allow-lists for expected values, and avoid embedding raw request data into formulas.
Example of a vulnerable controller that trusts mTLS and uses raw input in a formula:
[ApiController]
[Route("api/[controller]")]
public class CalculationController : ControllerBase
{
[HttpPost("generate")]
public IActionResult Generate([FromBody] FormulaRequest request)
{
// Vulnerable: raw formula used directly
var formula = request.Formula;
var package = new ExcelPackage();
var sheet = package.Workbook.Worksheets.Add("Report");
sheet.Cells[1, 1].Formula = formula;
var stream = new MemoryStream();
package.SaveAs(stream);
return File(stream.ToArray(), "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
}
}
Secure version with input validation and no direct formula injection:
[ApiController]
[Route("api/[controller]")]
public class CalculationController : ControllerBase
{
private static readonly HashSet<string> AllowedFunctions = new() { "SUM", "AVERAGE", "COUNT" };
[HttpPost("generate")]
public IActionResult Generate([FromBody] FormulaRequest request)
{
if (!AllowedFunctions.Contains(request.FunctionName?.ToUpperInvariant()))
{
return BadRequest("Invalid function");
}
// Build safe formula using parameters, not raw expression
string safeFormula = $"={request.FunctionName}({request.CellRange})";
// Validate cell range format, e.g., A1:B10
if (!System.Text.RegularExpressions.Regex.IsMatch(request.CellRange, "^[A-Z]+\d+:[A-Z]+\d+$"))
{
return BadRequest("Invalid range");
}
var package = new ExcelPackage();
var sheet = package.Workbook.Worksheets.Add("Report");
sheet.Cells[1, 1].Formula = safeFormula;
var stream = new MemoryStream();
package.SaveAs(stream);
return File(stream.ToArray(), "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
}
}
Configure mTLS in Program.cs or Startup.cs to require client certificates without relying on them for data validation:
// Program.cs for ASP.NET Core
var builder = WebApplication.CreateBuilder(args);
// Enforce HTTPS and mTLS
builder.WebHost.ConfigureKestrel(serverOptions =>
{
serverOptions.ListenAnyIP(5001, listenOptions =>
{
listenOptions.UseHttps(httpsOptions =>
{
httpsOptions.ClientCertificateMode = ClientCertificateMode.RequireCertificate;
httpsOptions.AllowAnyClientCertificate(); // or use a custom validator
});
});
});
var app = builder.Build();
app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
app.Run();
For production, replace AllowAnyClientCertificate with a validator that checks thumbprints or issuer:
httpsOptions.ClientCertificateValidation = (cert, chain, errors) =>
{
if (errors != SslPolicyErrors.None) return false;
return cert.Thumbprint == "A1B2C3D4E5F6...";
};
These steps ensure mTLS secures the channel while inputs are validated independently, preventing formula injection regardless of transport guarantees.
middleBrick can support this workflow by scanning endpoints with and without mTLS to compare behavior. Use the CLI to run scans:
middlebrick scan https://api.example.com/calculate
Or integrate the GitHub Action to fail builds when formula-related findings appear.