HIGH out of bounds writebearer tokens

Out Of Bounds Write with Bearer Tokens

How Out Of Bounds Write Manifests in Bearer Tokens

Bearer tokens are typically transmitted in the Authorization header as a string. When a service parses that header, it often copies the token value into a fixed‑size buffer for further processing (e.g., validation, signing, or storage). If the copy operation does not validate the token length against the buffer size, an attacker can supply an excessively long token and trigger an out‑of‑bounds (OOB) write.

This pattern appears in code paths that:

  • Extract the token with strstr or similar and then use strcpy, memcpy, or sprintf without length checks.
  • Parse the token in a C‑based module (NGINX, Envoy, custom API gateway) where a static array like char token[256] is used.
  • Handle the token in a language that allows unsafe pointer arithmetic (e.g., Go with unsafe.Pointer or Rust std::ptr::write) when interfacing with native libraries.

An OOB write can corrupt adjacent memory, leading to crashes, information disclosure, or arbitrary code execution. In the context of Bearer tokens, the corrupted memory may include:

  • Validation flags that allow a malformed token to be accepted.
  • Function pointers or vtables that enable control‑flow hijacking.
  • Adjacent buffers holding other request data, which can be leaked in error responses.

Real‑world examples include CVE‑2021-22986 (F5 BIG‑IP iControl REST), where an overly long authentication token caused a heap overflow in the token‑parsing routine, allowing unauthenticated remote code execution. The vulnerability is classified under CWE‑787: Out‑of‑Bounds Write and maps to OWASP API Security Top 10 2023 category API8:2023 Injection.

/* Vulnerable C snippet – fixed buffer */
char token[256];
const char *hdr = get_header("Authorization"); /* e.g., "Bearer AAAAA…" */
if (strncmp(hdr, "Bearer ", 7) == 0) {
    strcpy(token, hdr + 7);   // No length check → OOB write if token >255 bytes
}

The same issue can appear in higher‑level languages when they call unsafe native functions. For instance, a Go wrapper that uses C.CString and then passes the result to a C library without limiting length:

// Go – unsafe conversion
cToken := C.CString(token)   // allocates C string based on Go string length
// If the C library expects a max of 256 bytes and copies with strcpy,
// a token longer than 255 bytes will overflow.
C.process_token(cToken)

Bearer Tokens‑Specific Detection

Detecting an OOB write in Bearer‑token handling requires probing the unauthenticated attack surface with tokens that exceed expected lengths and observing abnormal behavior (crashes, error codes, or delayed responses). middleBrick performs this automatically as part of its black‑box scan:

  • It sends a series of requests with the Authorization: Bearer header containing tokens of increasing size (e.g., 256, 512, 1024, 2048 bytes).
  • Responses are monitored for signs of memory corruption: HTTP 500/502, empty bodies, connection resets, or unusually long latency.
  • If a crash or abnormal response is detected, middleBrick flags the finding under the Input Validation category with severity high and provides the exact header value that triggered the issue.

Example of invoking the middleBrick CLI to manually reproduce the test:

# Generate a 3000‑byte Bearer token
TOKEN=$(python3 -c "print('A'*3000)")
middlebrick scan https://api.example.com \
    --header "Authorization: Bearer $TOKEN" \
    --output json

The scanner will return a JSON report similar to:


{
  "findings": [
    {
      "id": "OOBW-001",
      "title": "Potential Out‑Of‑Bounds Write in Bearer Token Parsing",
      "severity": "high",
      "description": "The endpoint crashed when receiving a Bearer token longer than 256 bytes.",
      "remediation": "Validate token length before copying into fixed buffers; use length‑limited copy functions."
    }
  ]
}

Because the test is unauthenticated and requires no agents or configuration, it can be run in CI/CD pipelines (via the GitHub Action) or directly from an IDE using the MCP Server integration.

Bearer Tokens‑Specific Remediation

Fixing an OOB write in Bearer‑token handling involves ensuring that any copy or manipulation of the token respects the destination buffer’s size. The remediation varies by language but follows the same principle: validate length first, then use a safe copy operation.

C / C++

Replace unchecked strcpy/memcpy with length‑limited variants and explicitly check the token length against the buffer size.

/* Fixed C implementation */
#define MAX_TOKEN_LEN 255
char token[MAX_TOKEN_LEN + 1];   // +1 for terminator
const char *hdr = get_header("Authorization");
if (strncmp(hdr, "Bearer ", 7) == 0) {
    const char *value = hdr + 7;
    size_t len = strlen(value);
    if (len > MAX_TOKEN_LEN) {
        /* Reject overly long token */
        return HTTP_BAD_REQUEST;
    }
    strncpy(token, value, MAX_TOKEN_LEN);
    token[MAX_TOKEN_LEN] = '\0';   // ensure null‑termination
    /* Proceed with validation */
}

Alternatively, allocate a buffer dynamically based on the actual token length:

size_t len = strlen(value);
char *token = malloc(len + 1);
if (!token) return HTTP_INTERNAL_SERVER_ERROR;
memcpy(token, value, len);
token[len] = '\0';

Go

Go strings are immutable and bounds‑checked, but when interfacing with C code you must limit the length passed to the native function.

// Go – safe wrapper for C library
const maxTokenLen = 255
if len(token) > maxTokenLen {
    return fmt.Errorf("token too long")
}
// Convert to C string with explicit length limit
cToken := C.CString(token[:len(token)]) // slice is safe
C.process_token(cToken)
C.free(unsafe.Pointer(cToken))

Node.js

Buffers are safe when created with Buffer.from; just validate length before any downstream native addon use.

const MAX_TOKEN_LEN = 255
const auth = req.headers.authorization
if (!auth?.startsWith('Bearer ')) return res.sendStatus(400)
const token = auth.slice(7)
if (Buffer.byteLength(token, 'utf8') > MAX_TOKEN_LEN) {
    return res.sendStatus(400)
}
// Safe to pass to any native addon
const buf = Buffer.from(token, 'utf8')
// ... use buf

After applying the fix, rerun the middleBrick scan (via CLI, GitHub Action, or MCP Server) to confirm that the finding no longer appears. The remediation guidance provided by middleBrick includes the exact code pattern to replace and references to the relevant language‑specific safe‑copy functions.

Frequently Asked Questions

Can middleBrick detect an Out‑Of‑Bounds Write in Bearer‑token parsing without any credentials or agents?
Yes. middleBrick performs unauthenticated black‑box scanning. It sends progressively longer Bearer tokens in the Authorization header and monitors for crashes, error responses, or abnormal latency that indicate memory corruption. No agents, configuration, or credentials are required.
What is the recommended remediation for an OOB write found in a C‑based API gateway that processes Bearer tokens?
Replace unchecked copies (e.g., strcpy, memcpy) with length‑checked alternatives. First verify that the token length does not exceed the buffer limit (e.g., 255 bytes). If it does, reject the request with HTTP 400. Otherwise, use strncpy or memcpy with the exact length and ensure null‑termination, or allocate a dynamic buffer sized to the token length plus one for the terminator.