CWE-787 in Aspnet
How Cwe 787 Manifests in Aspnet
CWE-787 (Out-of-bounds Write) in ASP.NET occurs when code writes data beyond the allocated buffer boundaries, potentially corrupting memory or allowing arbitrary code execution. In ASP.NET applications, this vulnerability typically manifests through unsafe array operations, improper string handling, or unchecked user input that overflows buffers.
Common ASP.NET-specific scenarios include:
- Unsafe Array Operations: Using fixed-size arrays without bounds checking when processing user input or parsing data streams.
- MemoryStream/Buffer Manipulation: Writing beyond the allocated buffer when handling file uploads or binary data processing.
- StringBuilder Misuse: Appending data without proper capacity management in high-throughput scenarios.
- Unsafe Unmanaged Code Interop: P/Invoke calls to native libraries that don't properly validate buffer sizes.
Consider this vulnerable ASP.NET code pattern:
public void ProcessUserData(string userInput) {
char[] buffer = new char[100];
userInput.CopyTo(0, buffer, 0, userInput.Length); // Vulnerable if input > 100 chars
// Process buffer...
}This code fails to validate that userInput.Length doesn't exceed the 100-character buffer capacity, creating an out-of-bounds write condition.
Another ASP.NET-specific manifestation occurs in HttpPostedFileBase handling:
public ActionResult UploadFile(HttpPostedFileBase file) {
byte[] buffer = new byte[1024];
int bytesRead = file.InputStream.Read(buffer, 0, buffer.Length);
// No validation of bytesRead vs buffer size
ProcessBuffer(buffer, bytesRead); // Potential out-of-bounds if bytesRead > 1024
return Json(new { success = true });
}The vulnerability arises when bytesRead exceeds the buffer capacity due to malicious file uploads or network issues.
ASP.NET-Specific Detection
Detecting CWE-787 in ASP.NET applications requires a multi-layered approach combining static analysis, runtime monitoring, and automated scanning.
Static Code Analysis: Use tools like SonarQube, Roslyn analyzers, or Visual Studio's Code Analysis to identify unsafe array operations and buffer manipulations. Look for patterns like:
// Dangerous patterns to flag
Array.Copy(source, destination, count); // No bounds checking
Buffer.BlockCopy(src, 0, dst, 0, size); // Size validation needed
Runtime Monitoring: Implement bounds checking in critical code paths using ASP.NET's built-in validation features:
public void SafeArrayCopy(string source, char[] destination) {
if (source.Length > destination.Length) {
throw new ArgumentException("Source exceeds destination capacity");
}
source.CopyTo(0, destination, 0, source.Length);
}Automated Scanning with middleBrick: The middleBrick CLI tool can scan your ASP.NET API endpoints for out-of-bounds write vulnerabilities by testing boundary conditions and analyzing request/response patterns. The scanner specifically looks for:
- Buffer overflow conditions in file upload endpoints
- Array index validation failures in API controllers
- Unsafe string manipulation in request processing
- Memory stream boundary violations
Run middleBrick against your ASP.NET API:
middlebrick scan https://yourapi.com/api/upload
middlebrick scan https://yourapi.com/api/process-data
The scanner performs black-box testing by sending boundary-value inputs and analyzing responses for signs of memory corruption or unexpected behavior.
ASP.NET Core Specific Detection: In ASP.NET Core, use the built-in MemoryPool and ArrayPool with proper bounds checking:
public void ProcessRequestWithPooling(byte[] input) {
byte[] buffer = ArrayPool<byte>.Shared.Rent(input.Length);
try {
if (input.Length > buffer.Length) {
throw new InvalidOperationException("Input exceeds pooled buffer");
}
Buffer.BlockCopy(input, 0, buffer, 0, input.Length);
// Process buffer safely
} finally {
ArrayPool<byte>.Shared.Return(buffer);
}
}ASP.NET-Specific Remediation
Remediating CWE-787 in ASP.NET requires adopting safe coding practices and leveraging the framework's built-in security features.
Safe Array Operations: Always validate array bounds before copying or manipulating data:
public void SafeCopyWithValidation(string source, char[] destination) {
if (string.IsNullOrEmpty(source)) return;
int copyLength = Math.Min(source.Length, destination.Length);
source.CopyTo(0, destination, 0, copyLength);
// Clear remaining buffer if needed
if (copyLength < destination.Length) {
Array.Clear(destination, copyLength, destination.Length - copyLength);
}
}File Upload Security: Implement proper buffer management for file uploads in ASP.NET MVC:
public async Task<ActionResult> SecureUpload(IFormFile file) {
const int maxBufferSize = 1024 * 1024; // 1MB
using var memoryStream = new MemoryStream();
await file.CopyToAsync(memoryStream);
if (memoryStream.Length > maxBufferSize) {
return BadRequest("File exceeds maximum size");
}
byte[] buffer = memoryStream.ToArray();
// Process buffer safely with bounds checking
ProcessUploadedData(buffer);
return Ok();
}ASP.NET Core Memory Safety: Use Span
public void ProcessWithSpan(ReadOnlySpan<byte> input) {
Span<byte> buffer = stackalloc byte[1024];
if (input.Length > buffer.Length) {
throw new ArgumentException("Input exceeds stack buffer");
}
input.CopyTo(buffer);
// Safe processing with bounds-checked operations
ProcessBuffer(buffer);
}Input Validation Middleware: Create ASP.NET Core middleware to validate request sizes:
public class BoundsCheckingMiddleware {
private readonly RequestDelegate _next;
private readonly int _maxRequestSize;
public BoundsCheckingMiddleware(RequestDelegate next, int maxRequestSize = 1048576) {
_next = next;
_maxRequestSize = maxRequestSize;
}
public async Task InvokeAsync(HttpContext context) {
if (context.Request.ContentLength > _maxRequestSize) {
context.Response.StatusCode = 413; // Payload Too Large
await context.Response.WriteAsync("Request exceeds maximum size");
return;
}
await _next(context);
}
}
// In Startup.cs or Program.cs
builder.Services.AddTransient<BoundsCheckingMiddleware>();
app.UseMiddleware<BoundsCheckingMiddleware>();
Regular Security Scanning: Integrate middleBrick into your CI/CD pipeline to catch out-of-bounds vulnerabilities before deployment:
# .github/workflows/security.yml
name: Security Scan
on: [push, pull_request]
jobs:
security:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Run middleBrick Scan
run: |
npm install -g middlebrick
middlebrick scan https://staging.yourapp.com/api --fail-below B