Regex Dos on Azure
How Regex DoS Manifests in Azure
Regular expression denial of service (ReDoS) attacks exploit catastrophic backtracking in poorly constructed regex patterns. In Azure environments, this vulnerability commonly appears in Azure Functions, Logic Apps, and API Management services where regex processing handles user input. The attack works by crafting input strings that force the regex engine into exponential time complexity, consuming CPU resources until the service becomes unresponsive.
Azure Functions written in C# often use System.Text.RegularExpressions for input validation. Consider this vulnerable pattern in an Azure Function that validates email addresses:
public static async Task<HttpResponseData> Run( HttpRequestData req, FunctionContext executionContext ) {
var email = await req.ReadFromJsonAsync<string>();
// Vulnerable pattern - exponential backtracking on malicious input
var emailPattern = @"^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$";
var regex = new Regex(emailPattern);
if (!regex.IsMatch(email)) {
return req.CreateResponse(HttpStatusCode.BadRequest);
}
return req.CreateResponse(HttpStatusCode.OK);
}An attacker could send an email like "aaa@[aa.com" where the local part contains many repeated characters. The regex engine would attempt numerous backtracking paths, potentially taking seconds or minutes to process a single request.
Azure Logic Apps face similar risks when using regex in expressions. A Logic App that validates JSON payloads with complex patterns can be exploited:
@if( !matches(triggerBody(), '^[\\s\\S]*$') ) {
// Process valid input
} else {
// Reject
}The pattern '^[\\s\\S]*$' appears safe but can be exploited when combined with nested structures or when processing large inputs. Azure API Management policies that use regex for request validation are equally vulnerable:
<choose>
<when condition="matches(/user/email, '^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$')">
<!— Process request —>
</when>
</choose>The Azure-specific context matters because these services run in shared environments where a single malicious request can affect the performance of other functions or apps on the same host. Azure Functions Premium and Dedicated plans provide better isolation, but even these can be overwhelmed by sustained ReDoS attacks.
Azure-Specific Detection
Detecting ReDoS vulnerabilities in Azure requires both static code analysis and runtime monitoring. For Azure Functions, the Azure Monitor Application Insights integration can track function execution times. Sudden spikes in execution duration for specific functions may indicate ReDoS attempts.
middleBrick's Azure-specific scanning identifies ReDoS vulnerabilities by analyzing regex patterns and testing them with pathological inputs. The scanner examines Azure Functions code, Logic Apps definitions, and API Management policies for dangerous patterns:
middlebrick scan https://myazurefunction.azurewebsites.net/api/ValidateEmail
--azure-specific --regex-analysisThe scanner tests common ReDoS patterns including nested quantifiers, overlapping alternations, and backtracking-prone constructs. For Azure Functions, middleBrick analyzes the compiled assembly to find System.Text.RegularExpressions usage and examines the actual regex patterns deployed.
Azure Security Center and Defender for Cloud can detect unusual resource consumption patterns that may indicate ReDoS attacks. Look for:
- Unexpected CPU spikes in Azure Functions metrics
- Increased execution timeouts in Application Insights
- Unusual request patterns targeting validation endpoints
For Logic Apps, the Azure portal provides execution history where you can identify workflows taking unusually long to complete. API Management policies can be analyzed using the built-in policy inspector to find regex-based validations.
middleBrick provides specific findings for Azure environments:
| Finding Type | Azure Context | Severity |
|---|---|---|
| Nested Quantifier | Azure Function C# | High |
| Overlapping Alternation | Logic App Expression | Medium |
| Backtracking Prone | API Management Policy | High |
The scanner also checks for Azure-specific anti-patterns like using regex for path traversal prevention or input sanitization in security-critical contexts.
Azure-Specific Remediation
Remediating ReDoS vulnerabilities in Azure requires both immediate fixes and architectural changes. For Azure Functions, replace vulnerable regex patterns with safer alternatives or validation libraries:
// Instead of vulnerable regex, use built-in validation
public static async Task<HttpResponseData> Run( HttpRequestData req, FunctionContext executionContext ) {
var email = await req.ReadFromJsonAsync<string>();
// Use System.ComponentModel.DataAnnotations for safe validation
var emailAttribute = new EmailAddressAttribute();
if (!emailAttribute.IsValid(email)) {
return req.CreateResponse(HttpStatusCode.BadRequest);
}
return req.CreateResponse(HttpStatusCode.OK);
}For Azure Logic Apps, replace regex-based validation with built-in schema validation:
// Use JSON schema validation instead of regex
@triggerBody()?['email']
// Validate against schema in a separate step
@json('{
"$schema": "http://json-schema.org/draft-07/schema#",
"type": "string",
"format": "email"
}')Azure API Management policies can use the validate-content policy instead of regex:
<validate-content contentType="application/json" schema="@/schemas/email.json" />Implement timeout controls in Azure Functions to limit regex processing time:
using System.Text.RegularExpressions;
public static async Task<HttpResponseData> Run( HttpRequestData req, FunctionContext executionContext ) {
var email = await req.ReadFromJsonAsync<string>();
// Safe pattern with timeout
var regex = new Regex(@"^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$",
RegexOptions.Compiled,
TimeSpan.FromMilliseconds(100)); // 100ms timeout
try {
if (!regex.IsMatch(email)) {
return req.CreateResponse(HttpStatusCode.BadRequest);
}
} catch (RegexMatchTimeoutException) {
return req.CreateResponse(HttpStatusCode.RequestTimeout);
}
return req.CreateResponse(HttpStatusCode.OK);
}For Azure Logic Apps, use the timeout feature in HTTP actions and implement circuit breaker patterns:
// Set timeout for HTTP actions
@parameters('httpTimeout') // 10 seconds
// Add retry policy with exponential backoffmiddleBrick's remediation guidance includes specific Azure recommendations:
| Vulnerability | Azure Recommendation | Implementation Effort |
|---|---|---|
| Nested Quantifier | Replace with validation library | Low |
| Backtracking Prone | Add timeout + safe patterns | Medium |
| Input Validation | Use JSON schema validation | Low |
Consider Azure-specific architectural patterns like using Azure API Management's built-in validation features instead of custom regex in functions. This centralizes security controls and reduces the attack surface across your Azure services.
Related CWEs: inputValidation
| CWE ID | Name | Severity |
|---|---|---|
| CWE-20 | Improper Input Validation | HIGH |
| CWE-22 | Path Traversal | HIGH |
| CWE-74 | Injection | CRITICAL |
| CWE-77 | Command Injection | CRITICAL |
| CWE-78 | OS Command Injection | CRITICAL |
| CWE-79 | Cross-site Scripting (XSS) | HIGH |
| CWE-89 | SQL Injection | CRITICAL |
| CWE-90 | LDAP Injection | HIGH |
| CWE-91 | XML Injection | HIGH |
| CWE-94 | Code Injection | CRITICAL |