HIGH regex dosazure

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-analysis

The 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 TypeAzure ContextSeverity
Nested QuantifierAzure Function C#High
Overlapping AlternationLogic App ExpressionMedium
Backtracking ProneAPI Management PolicyHigh

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 backoff

middleBrick's remediation guidance includes specific Azure recommendations:

VulnerabilityAzure RecommendationImplementation Effort
Nested QuantifierReplace with validation libraryLow
Backtracking ProneAdd timeout + safe patternsMedium
Input ValidationUse JSON schema validationLow

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 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

How can I test my Azure Functions for ReDoS vulnerabilities?
Use middleBrick to scan your Azure Function endpoints with the --azure-specific flag. The scanner tests regex patterns with pathological inputs and analyzes your Azure Function code for vulnerable patterns. You can also use Azure Monitor to track execution times and identify functions with abnormally high processing durations.
Are Azure Logic Apps more vulnerable to ReDoS than Azure Functions?
Both have similar vulnerabilities, but Azure Logic Apps may be harder to detect because the regex processing happens in the Logic Apps runtime rather than your code. Logic Apps expressions use regex internally for various operations, and the visual nature of Logic Apps can make it harder to spot dangerous patterns. middleBrick specifically analyzes Logic App definitions for ReDoS vulnerabilities.