HIGH out of bounds writeadonisjsbasic auth

Out Of Bounds Write in Adonisjs with Basic Auth

Out Of Bounds Write in Adonisjs with Basic Auth

An Out Of Bounds Write occurs when an application writes data past the boundaries of a buffer or data structure, which can corrupt memory, crash services, or lead to arbitrary code execution. When combined with HTTP Basic Authentication in AdonisJS, this risk can become more severe: authentication headers are parsed early, and if the application uses unchecked user input to size buffers (e.g., for tokens, usernames, or dynamically constructed objects), an attacker may supply an abnormally large or malformed value to trigger an out-of-bounds condition. Because Basic Auth transmits credentials in an encoded (not encrypted) header, an attacker may probe endpoints that accept credentials without requiring a valid session, increasing the likelihood of hitting code paths that mishandle input lengths.

Consider an AdonisJS route that reads the Authorization header and passes it to a utility that copies data into a fixed-size buffer:

import { HttpContextContract } from '@ioc:Adonis/Core/HttpContext'
import { base64Decode } from '@ioc:Adonis/Addons/Helpers'

export default class AuthController {
  public async validateBasicAuth({ request, response }: HttpContextContract) {
    const authHeader = request.headers().authorization
    if (authHeader && authHeader.startsWith('Basic ')) {
      const payload = authHeader.split(' ')[1]
      const decoded = base64Decode(payload)
      const [username, password] = decoded.split(':')
      // Unsafe: using username length to size an internal buffer
      const token = unsafeCreateToken(username)
      response.send({ token })
    } else {
      response.unauthorized('Missing credentials')
    }
  }
}

If unsafeCreateToken uses the username length to allocate a buffer or construct a fixed-length string without proper bounds checking, an attacker could supply a username with thousands of characters, causing an out-of-bounds write in native bindings or in adjacent memory. This becomes more feasible when the endpoint does not require prior authentication, allowing unauthenticated attackers to trigger the condition via the Basic Auth header alone. The scanner’s checks for Authentication and BOLA/IDOR highlight whether endpoints expose sensitive functionality without verifying credentials, while the Input Validation check surfaces cases where user-controlled header values are used to size internal structures. An insecure implementation may also interact poorly with SSRF or Unsafe Consumption checks if the attacker can coerce the server into making outbound requests with oversized headers.

To detect such issues, middleBrick runs parallel checks including Authentication, Input Validation, and BOLA/IDOR, examining how the API parses and uses Basic Auth credentials. The scanner reviews OpenAPI/Swagger specs (with full $ref resolution) and correlates spec definitions with runtime behavior to identify mismatches where endpoints accept credentials but do not enforce size or format constraints. This helps surface risky patterns where headers or payload fields are used to drive memory-like structures without adequate validation.

Remediation focuses on ensuring that any data derived from user-controlled headers or inputs is bounded and sanitized before use. Never use raw header lengths to allocate fixed-size buffers, and validate that usernames, passwords, and derived tokens conform to expected length and character constraints. MiddleBrick’s findings include prioritized guidance with severity levels and remediation steps, enabling developers to adjust parsing logic and add explicit length checks.

Basic Auth-Specific Remediation in Adonisjs

Secure remediation in AdonisJS begins with strict validation of the Authorization header and avoiding any direct use of user-supplied lengths for internal buffers. Always treat Basic Auth credentials as untrusted input and enforce maximum lengths for usernames and passwords. Decode and parse the header in a controlled manner, and reject requests that exceed safe thresholds.

Here is a hardened example that validates the header format, decodes safely, and enforces length limits before any further processing:

import { HttpContextContract } from '@ioc:Adonis/Core/HttpContext'
import { base64Decode } from '@ioc:Adonis/Addons/Helpers'

const MAX_USERNAME_LENGTH = 64
const MAX_PASSWORD_LENGTH = 128

export default class AuthController {
  public async validateBasicAuth({ request, response }: HttpContextContract) {
    const authHeader = request.headers().authorization
    if (!authHeader || !authHeader.startsWith('Basic ')) {
      return response.unauthorized('Missing credentials')
    }

    const encoded = authHeader.split(' ')[1]
    if (!encoded) {
      return response.badRequest('Invalid Authorization header')
    }

    let decoded: string
    try {
      decoded = atob(encoded) // or base64Decode from helpers
    } catch (error) {
      return response.badRequest('Invalid credentials encoding')
    }

    const separatorIndex = decoded.indexOf(':')
    if (separatorIndex === -1) {
      return response.badRequest('Invalid credentials format')
    }

    const username = decoded.substring(0, separatorIndex)
    const password = decoded.substring(separatorIndex + 1)

    if (username.length > MAX_USERNAME_LENGTH || password.length > MAX_PASSWORD_LENGTH) {
      return response.forbidden('Credentials exceed allowed length')
    }

    // Proceed with safe authentication logic
    const token = safeCreateToken({ username, passwordLength: password.length })
    response.send({ token })
  }
}

Key practices include:

  • Check for the presence and prefix of the Authorization header before splitting.
  • Use a robust base64 decode routine and handle decode failures gracefully.
  • Explicitly split on the first colon and enforce maximum lengths for both username and password.
  • Avoid using raw user input to size buffers or internal data structures; instead, use bounded strings or typed arrays with fixed capacities.
  • Return consistent error responses to avoid leaking information about internal handling.

middleBrick’s CLI can be used to verify that your endpoints properly reject overlong credentials and that the OpenAPI spec reflects these constraints. With the Pro plan, you can enable continuous monitoring and CI/CD integration to fail builds if a regression introduces missing length checks. The GitHub Action allows you to add API security checks to your pipeline, ensuring that any change to authentication handling is validated before deployment.

Frequently Asked Questions

How does middleBrick detect Out Of Bounds Write risks with Basic Auth in AdonisJS?
middleBrick runs parallel checks including Authentication, Input Validation, and BOLA/IDOR. It reviews how the API parses the Authorization header, whether user-controlled header values influence buffer sizing, and whether OpenAPI/Swagger specs align with runtime behavior. The scanner correlates spec definitions with observed inputs to highlight missing length or boundary checks.
Can I integrate middleBrick into my CI/CD to prevent Basic Auth misconfigurations?
Yes. With the Pro plan, you can add the GitHub Action to your pipeline to fail builds if the security score drops below your chosen threshold. The action scans your API definitions and runtime behavior, helping to catch issues like missing bounds checks on Basic Auth headers before they reach production.