HIGH out of bounds readfastapibasic auth

Out Of Bounds Read in Fastapi with Basic Auth

Out Of Bounds Read in Fastapi with Basic Auth

An Out Of Bounds Read occurs when an API accesses memory or data structures beyond the intended allocation. In FastAPI with HTTP Basic Authentication, this can arise when index-based iteration over request-bound collections (e.g., arrays, lists, or query parameters) uses unchecked user input as an index. Because Basic Authentication typically provides identity but not authorization, an authenticated user can supply an index that is negative, excessively large, or otherwise invalid, leading to reads outside allocated memory. The server may return adjacent memory contents, structured data from other objects, or sensitive information embedded in the request/response lifecycle. When combined with OpenAPI/Swagger parsing, an unchecked index from a validated but not constrained parameter can also cause the scanner to correlate runtime behavior with spec definitions, exposing paths where bounds checks are missing.

Consider an endpoint that retrieves user preferences by index from a list stored in memory. If the index comes from a query parameter and Basic Auth confirms the user identity, there is no guarantee the index is within the list length. An authenticated attacker can send an index equal to the list length or greater, causing an Out Of Bounds Read. In the context of the 12 security checks, this would surface as a finding under Input Validation and Property Authorization, because the index is user-controlled and the authorization context (Basic Auth identity) does not enforce safe access patterns. The scanner’s runtime probes may trigger such a read by submitting boundary values, and the spec-defined parameter schema may lack explicit constraints like minimum and maximum, allowing the unsafe access to proceed undetected.

Because FastAPI relies on Pydantic for validation, it is possible to define a dependency that performs Basic Authentication and produces an identity, while the path or query parameters are validated separately. If the validation for the index omits bounds constraints, the authenticated request can traverse unintended memory locations. The scanner’s unauthenticated attack surface testing can exercise these endpoints with crafted indices, revealing the absence of guard checks. Even when the OpenAPI spec includes examples with small indices, the absence of runtime enforcement means the actual behavior can diverge, and the scanner’s cross-reference between spec definitions and observed findings will highlight the discrepancy as a high-priority risk.

Basic Auth-Specific Remediation in Fastapi

Remediation centers on constraining user-controlled indices and ensuring authorization logic does not bypass bounds checks. Use explicit integer constraints in Pydantic models or FastAPI parameters, and validate the index against the actual collection length before access. Basic Authentication should remain strictly for identity derivation; authorization decisions must always enforce bounds and ownership independently.

from fastapi import FastAPI, Depends, HTTPException, status
from fastapi.security import HTTPBasic, HTTPBasicCredentials
from pydantic import BaseModel, Field
from typing import List

app = FastAPI()
security = HTTPBasic()

# Example in-memory data store
preferences_store = [
    {"theme": "dark", "notifications": True},
    {"theme": "light", "notifications": False},
]

class UserIdentity:
    def __init__(self, username: str):
        self.username = username

def get_current_user(credentials: HTTPBasicCredentials = Depends(security)) -> UserIdentity:
    # Simplified Basic Auth validation; use a secure verification method in production
    if not credentials.username or not credentials.password:
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="Invalid credentials",
            headers={"WWW-Authenticate": "Basic"},
        )
    # In real applications, verify credentials against a secure store
    return UserIdentity(username=credentials.username)

@app.get("/preferences/{index}")
def get_preference(
    index: int = Field(..., ge=0, le=1000, description="Index into preferences list"),
    user: UserIdentity = Depends(get_current_user),
):
    # Enforce bounds before access
    if index < 0 or index >= len(preferences_store):
        raise HTTPException(status_code=404, detail="Preference not found")
    return preferences_store[index]

In this example, the Field constraints ge=0 and le=1000 provide schema-level validation, but runtime bounds checking against len(preferences_store)

When integrating with the CLI (middlebrick scan <url>) or the GitHub Action to add API security checks to your CI/CD pipeline, such constraints will reduce findings related to improper bounds enforcement. The Pro plan’s continuous monitoring can help detect regressions where bounds checks are accidentally removed, while the Dashboard allows you to track how remediation efforts affect your security scores over time.

Frequently Asked Questions

Can an authenticated user exploit an Out Of Bounds Read even if the endpoint uses Basic Auth?
Yes. Basic Auth provides identity but does not enforce data boundaries. If index or pointer parameters are not strictly constrained, an authenticated user can supply values that trigger reads outside intended memory.
How does middleBrick detect Out Of Bounds Read risks in FastAPI APIs with Basic Auth?
The scanner runs parallel checks including Input Validation and Property Authorization. It probes endpoints with boundary values while authenticated, checking for missing constraints and unsafe access patterns that could lead to out-of-bounds reads.