HIGH out of bounds writeaspnetfirestore

Out Of Bounds Write in Aspnet with Firestore

Out Of Bounds Write in Aspnet with Firestore — how this specific combination creates or exposes the vulnerability

An Out Of Bounds Write occurs when an application writes data to a memory location or resource outside the intended allocation boundaries. In the context of an ASP.NET application integrating with Google Cloud Firestore, this typically manifests through unchecked index-based operations on arrays, lists, or structured data that is later mapped to Firestore documents or batches. Because Firestore operations are often built from in-memory data structures before being committed, a vulnerability in the construction phase can lead to invalid writes that bypass expected schema constraints or overwrite adjacent data.

ASP.NET applications frequently handle dynamic input that is deserialized into objects, which are then translated into Firestore document updates. If input validation is insufficient, an attacker can supply array indices or collection positions that fall outside valid ranges. When these values are used to index into C# lists or arrays, the application may write to unintended memory locations within the runtime process. Although Firestore itself does not expose raw memory, the corrupted in-memory state can cause malformed write requests to be sent, resulting in writes to unexpected document fields or incorrect entity mutations.

The risk is compounded when batch writes are used, as a single corrupted index can affect multiple documents. For example, if an attacker manipulates an index controlling which Firestore documents receive updates, they may overwrite records they should not access or inject data into system-critical fields. Because Firestore enforces security rules at the document level, an out-of-bounds write that successfully reaches the server might still violate rule logic, but the damage occurs at the application layer before validation can fully intervene.

Real-world attack patterns include scenarios where an API endpoint accepts a list of values to update a Firestore document array. If the endpoint uses direct array indexing without bounds checking, an index like -1 or a very large integer can cause the runtime to write to unintended memory. This can corrupt the batch payload, leading to unauthorized field updates or data leakage across entities. Such vulnerabilities align with OWASP API Top 10 categories such as Broken Object Level Authorization (BOLA) and Injection, and may map to compliance frameworks like PCI-DSS and SOC2 when sensitive data is involved.

middleBrick detects this class of issue by correlating OpenAPI/Swagger specifications with runtime behavior. The scanner identifies endpoints that accept array indices or numeric identifiers, then probes them with out-of-range values to observe whether invalid memory writes occur upstream of Firestore operations. Because the scan is unauthenticated and runs in 5–15 seconds, it can quickly surface these risks without requiring credentials or disrupting production systems.

Firestore-Specific Remediation in Aspnet — concrete code fixes

To prevent Out Of Bounds Write vulnerabilities in ASP.NET applications using Firestore, developers must enforce strict input validation and avoid unsafe indexing patterns. All user-supplied indices should be validated against the actual size of the collection before any Firestore operation is constructed. The following code examples demonstrate secure practices.

Consider an endpoint that updates a list of scores stored as an array in a Firestore document. Instead of directly using an index from the request, validate the index and ensure it falls within the bounds of the list.

// Secure example: validate index before using it
[HttpPut("scores/{documentId}")]
public async Task UpdateScore(string documentId, [FromBody] ScoreUpdateRequest request)
{
    if (request.Index < 0)
    {
        return BadRequest("Index must be non-negative.");
    }

    DocumentReference docRef = _firestoreDb.Document($"scores/{documentId}");
    DocumentSnapshot snapshot = await docRef.GetSnapshotAsync();
    if (!snapshot.Exists)
    {
        return NotFound();
    }

    List<int> scores = snapshot.GetValue<List<int>>();
    if (request.Index >= scores.Count)
    {
        return BadRequest("Index out of range.");
    }

    scores[request.Index] = request.Value;
    WriteBatch batch = _firestoreDb.StartBatch();
    batch.Set(docRef, new { Scores = scores });
    await batch.CommitAsync();

    return Ok();
}

For operations involving dynamic field updates, use dictionary-based access with key validation rather than numeric indices. This approach eliminates the risk of out-of-bounds writes entirely.

// Secure dictionary-based update
[HttpPatch("profile/{userId}")]
public async Task<IActionResult> UpdateProfileFields(string userId, [FromBody] Dictionary<string, object> updates)
{
    DocumentReference docRef = _firestoreDb.Document($"profiles/{userId}");
    DocumentSnapshot snapshot = await docRef.GetSnapshotAsync();
    if (!snapshot.Exists)
    {
        return NotFound();
    }

    Dictionary<string, object> currentData = snapshot.ToDictionary();
    foreach (string key in updates.Keys)
    {
        if (!currentData.ContainsKey(key))
        {
            return BadRequest($"Field '{key}' does not exist.");
        }
    }

    WriteBatch batch = _firestoreDb.StartBatch();
    batch.Set(docRef, updates, SetOptions.MergeAll);
    await batch.CommitAsync();

    return Ok();
}

When using Firestore arrays, always retrieve the document first and operate on the in-memory list rather than constructing writes based on unchecked input. This ensures that all indices are validated against the actual data structure before any Firestore interaction occurs.

// Safe array manipulation pattern
public class ProfileController : ControllerBase
{
    private readonly FirestoreDb _firestoreDb;

    public ProfileController(FirestoreDb firestoreDb)
    {
        _firestoreDb = firestoreDb;
    }

    [HttpPut("tags/{docId}")]
    public async Task<IActionResult> AddTag(string docId, [FromBody] string newTag)
    {
        DocumentReference docRef = _firestoreDb.Document($"items/{docId}");
        DocumentSnapshot snapshot = await docRef.GetSnapshotAsync();
        if (!snapshot.Exists) return NotFound();

        List<string> tags = snapshot.GetValue<List<string>>();
        if (tags == null) tags = new List<string>();

        // Validate that the tag is not already present
        if (tags.Contains(newTag))
        {
            return BadRequest("Tag already exists.");
        }

        tags.Add(newTag);

        WriteBatch batch = _firestoreDb.StartBatch();
        batch.Set(docRef, new { Tags = tags });
        await batch.CommitAsync();

        return Ok();
    }
}

Additionally, enable model validation in ASP.NET Core to automatically reject malformed requests before they reach business logic. This provides a second layer of defense against out-of-bounds conditions.

// Startup configuration for model validation
public void ConfigureServices(IServiceCollection services)
{
    services.AddControllers(options =>
    {
        options.Filters.Add(new ValidateModelStateFilter());
    });
    services.AddFirestore();
}

By combining strict input validation, safe data access patterns, and runtime checks, ASP.NET applications can effectively mitigate Out Of Bounds Write risks when interacting with Firestore. These practices ensure that all writes remain within expected boundaries and comply with security and compliance requirements.

Frequently Asked Questions

How does middleBrick detect Out Of Bounds Write vulnerabilities in ASP.NET with Firestore?
middleBrick correlates your OpenAPI/Swagger specification with runtime probing. It sends controlled out-of-range indices and large numeric values to endpoints that accept array or list parameters, then observes whether the application constructs invalid write operations before communicating with Firestore. The scanner identifies missing bounds checks and unsafe indexing patterns without requiring authentication.
Can Firestore security rules alone prevent Out Of Bounds Write vulnerabilities in ASP.NET applications?
No. Firestore security rules validate document-level access but cannot prevent application-layer memory corruption caused by out-of-bounds indexing in ASP.NET code. An attacker can craft requests that pass security rules while exploiting invalid array indices in your application logic, making server-side input validation essential.