Crlf Injection in Aspnet
How Crlf Injection Manifests in Aspnet
CRLF injection in ASP.NET applications typically occurs when user-controlled data is incorporated into HTTP headers without proper sanitization. The attack exploits the fact that HTTP headers are separated by CRLF sequences ( ), allowing attackers to inject additional headers or split responses.
Common ASP.NET-specific scenarios include:
- Response headers built from user input in Web Forms or MVC controllers
- Custom authentication tokens or cookies containing user data
- File download headers where filenames come from user input
- Redirect URLs constructed from query parameters
- CSV export functionality where user data becomes part of HTTP headers
Here's a vulnerable ASP.NET Web Forms example:
public void ProcessDownload(object sender, EventArgs e)
{
string fileName = Request.QueryString["file"];
Response.ContentType = "application/octet-stream";
Response.AddHeader("Content-Disposition", "attachment; filename=" + fileName);
Response.TransmitFile(Server.MapPath("~/downloads/" + fileName));
}An attacker could request: /download.aspx?file=example.csv%0d%0aContent-Type%3A%20text/html%0d%0a%0d%0a<script>alert(1)</script>
This would inject a new Content-Type header and HTML content, potentially leading to XSS if the response is rendered in a browser.
In ASP.NET Core, similar vulnerabilities appear in:
public IActionResult Download(string file)
{
return File(System.IO.File.ReadAllBytes($"~/downloads/{file}"),
"application/octet-stream",
file);
}The framework's file download helpers don't automatically sanitize filenames, making this a common attack vector.
Aspnet-Specific Detection
Detecting CRLF injection in ASP.NET applications requires both static analysis and runtime scanning. middleBrick's black-box scanner specifically tests for CRLF vulnerabilities by:
- Submitting encoded CRLF sequences (%0D%0A, %0A, %0D) in header values and URL parameters
- Checking if injected headers are reflected in the response
- Verifying if response splitting occurs (multiple HTTP responses returned)
- Testing for XSS in injected content
middleBrick's ASP.NET-specific checks include:
$ middlebrick scan https://yourapi.com/download
...
CRLF Injection (Authentication Headers): FAIL
- Severity: HIGH
- Location: /api/download
- Issue: User-controlled filename parameter allows header injection
- Remediation: Validate and sanitize filename inputFor code-level detection in your ASP.NET projects, use:
var unsafePatterns = new[]
{
"%0a", "%0d", "%0D%0A", "\r", "\n"
};
bool ContainsCrlf(string input) =>
unsafePatterns.Any(p => input.Contains(p));ASP.NET Core's built-in validation can help catch some issues:
services.AddControllers(options =>
{
options.InputFormatters[0].ValidatorOptions.AllowLeadingAndTrailingWhitespace = false;
});middleBrick's continuous monitoring (Pro plan) will periodically re-scan your endpoints, alerting you if new CRLF vulnerabilities are introduced in deployments.
Aspnet-Specific Remediation
ASP.NET provides several native approaches to prevent CRLF injection:
1. Input Validation and Sanitization
public static class CrlfSanitizer
{
private static readonly string[] InvalidChars = { "\r", "\n" };
private static readonly Regex CrlfRegex = new("[\r\n]");
public static string Sanitize(string input) =>
CrlfRegex.Replace(input, string.Empty);
public static void Validate(string input)
{
if (InvalidChars.Any(input.Contains))
throw new ArgumentException("Input contains invalid CRLF characters");
}
}2. ASP.NET Core Model Validation
public class DownloadRequest
{
[RegularExpression(@"^[^\r\n]+$"), Required]
public string File { get; set; }
}3. Safe File Download Implementation
public IActionResult SafeDownload([FromQuery] string file)
{
CrlfSanitizer.Validate(file);
var safeFileName = Path.GetFileName(file); // Prevents path traversal
var filePath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot\downloads", safeFileName);
if (!System.IO.File.Exists(filePath))
return NotFound();
return File(System.IO.File.ReadAllBytes(filePath),
"application/octet-stream",
safeFileName);
}4. ASP.NET Web Forms Protection
protected void Page_Load(object sender, EventArgs e)
{
string file = Request.QueryString["file"];
if (ContainsCrlf(file))
{
Response.StatusCode = 400;
Response.Write("Invalid filename");
Response.End();
return;
}
}5. Header Construction Safety
public static class SafeHeaders
{
public static void AddContentDisposition(this HttpResponse response, string filename)
{
CrlfSanitizer.Validate(filename);
var headerValue = "attachment; filename=" + filename;
response.Headers.Add("Content-Disposition", headerValue);
}
}For comprehensive protection, integrate middleBrick's CLI into your CI/CD pipeline to catch CRLF issues before deployment:
# package.json script
"scripts": {
"security:scan": "middlebrick scan https://staging.yourapp.com"
}The Pro plan's continuous monitoring will automatically re-scan your APIs on a schedule, ensuring CRLF vulnerabilities aren't introduced in future updates.