HIGH header injectionazure

Header Injection on Azure

How Header Injection Manifests in Azure

Header Injection in Azure environments typically occurs when untrusted user input is incorporated into HTTP response headers without proper validation. Azure's serverless functions, API Management, and App Services can all be vulnerable to this attack when developers concatenate user input directly into Set-Cookie, Location, or other header fields.

A common Azure-specific scenario involves Azure Functions where developers extract query parameters or request headers and use them to construct redirect URLs or authentication tokens. For example:

// Vulnerable Azure Function code
public static async Task<HttpResponseData> Run(
    [HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = "redirect")] HttpRequestData req,
    FunctionContext executionContext)
{
    var response = req.CreateResponse(HttpStatusCode.Found);
    var targetUrl = req.Query["url"];
    response.Headers.Add("Location", targetUrl); // Vulnerable to header injection
    return response;
}

This pattern is particularly dangerous in Azure API Management policies where response headers are dynamically constructed. An attacker could inject newline characters to add arbitrary headers:

// Malicious input example
http://example.com/valid?url=http://evil.com%0d%0aSet-Cookie:%20session=malicious

The newline injection (%0d%0a) would result in:

Location: http://evil.com
Set-Cookie: session=malicious

Azure's Application Gateway and Front Door services can also be affected when they process headers for routing decisions. If backend services don't properly validate headers that Azure services forward, attackers can manipulate routing or bypass authentication mechanisms.

Another Azure-specific manifestation occurs in Azure Container Instances where environment variables are sometimes used to configure HTTP response headers. If these variables contain user input without sanitization, header injection becomes possible.

Azure-Specific Detection

Detecting header injection in Azure requires both manual code review and automated scanning. Azure's native tools like Application Insights can help identify suspicious patterns in HTTP requests, but they don't specifically look for header injection vulnerabilities.

The middleBrick scanner is particularly effective for Azure environments because it performs black-box scanning of your API endpoints without requiring credentials or configuration. For Azure Functions and API Management endpoints, middleBrick tests for header injection by:

  • Submitting payloads containing newline characters (%0A, %0D) and carriage returns
  • Verifying if additional headers are injected into the response
  • Checking for HTTP response splitting where the response body is manipulated
  • Testing for cookie injection via Set-Cookie header manipulation
  • Scanning for location header injection that could enable open redirect attacks

To scan your Azure API with middleBrick CLI:

npx middlebrick scan https://yourazureapi.azurewebsites.net/api/endpoint

For Azure DevOps integration, you can add middleBrick to your pipeline to automatically scan Azure Functions before deployment:

- name: Scan Azure API
  uses: middleBrick/middlebrick-action@v1
  with:
    url: https://yourazureapi.azurewebsites.net/api/endpoint
    fail-threshold: 80

Azure Security Center can complement these scans by monitoring for suspicious header patterns in your Azure App Service logs, though it doesn't specifically target header injection vulnerabilities.

Azure-Specific Remediation

Remediating header injection in Azure requires input validation and secure header construction. For Azure Functions, use built-in validation and safe header APIs:

// Secure Azure Function implementation
public static async Task<HttpResponseData> Run(
    [HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = "redirect")] HttpRequestData req,
    FunctionContext executionContext)
{
    var response = req.CreateResponse(HttpStatusCode.Found);
    
    // Validate URL against a whitelist
    var targetUrl = req.Query["url"];
    if (!IsValidRedirectUrl(targetUrl))
    {
        return req.CreateResponse(HttpStatusCode.BadRequest);
    }
    
    // Use safe header APIs
    response.Headers.Location = new Uri(targetUrl);
    return response;
}

private static bool IsValidRedirectUrl(string url)
{
    // Validate against allowed domains
    var allowedDomains = new[] { "https://yourdomain.com", "https://yourapp.com" };
    return allowedDomains.Any(domain => url.StartsWith(domain));
}

For Azure API Management policies, use the validate-content policy to sanitize headers:

<policies>
    <validate-content 
        content="$(urlParam)" 
        pattern="^[a-zA-Z0-9:/.-]+$" 
        error-variable-name="urlError"/>
    <choose>
        <when condition="@(urlError == null)">
            <set-header name="Location" exists-action="override">
                <value>@(urlParam)</value>
            </set-header>
        </when>
        <otherwise>
            <return-response>
                <set-status code="400" />
            </return-response>
        </otherwise>
    </choose>
</policies>

Azure App Service users should enable Request Filtering through web.config to block suspicious header patterns:

<configuration>
  <system.webServer>
    <security>
      <requestFiltering>
        <requestLimits maxAllowedContentLength="30000000" />
        <headers>
          <add name="X-Injection-Test" value="^[^\n\r]+$" />
        </headers>
      </requestFiltering>
    </security>
  </system.webServer>
</configuration>

For Azure Container Instances, validate environment variables before using them in headers:

var headerValue = Environment.GetEnvironmentVariable("CUSTOM_HEADER");
if (headerValue != null && headerValue.Contains("
"))
{
    throw new ArgumentException("Invalid header value");
}

Always use Azure's built-in HTTP client libraries rather than manually constructing headers, as they include proper validation and encoding.

Frequently Asked Questions

How does header injection differ in Azure Functions vs traditional web applications?
Azure Functions are stateless and often handle requests differently than traditional ASP.NET applications. The serverless nature means developers might be less familiar with HTTP header handling, leading to more vulnerabilities. Azure Functions also integrate with various triggers and bindings that can introduce unique injection points through binding data.
Can middleBrick scan Azure API Management policies for header injection?
Yes, middleBrick can scan the runtime endpoints exposed by Azure API Management. While it cannot directly analyze the policy XML files, it tests the actual API endpoints that API Management exposes, including any header injection vulnerabilities that might exist in the backend services or in how API Management constructs responses.