HIGH dns rebindingadonisjsbasic auth

Dns Rebinding in Adonisjs with Basic Auth

Dns Rebinding in Adonisjs with Basic Auth — how this specific combination creates or exposes the vulnerability

DNS Rebinding is an application-layer attack that manipulates DNS responses to make a browser believe a remote host is reachable at an attacker-controlled IP after the initial page load. When Basic Authentication is used inside an AdonisJS application, the combination of long-lived credentials in request headers and per-domain browser same-origin policy allows a malicious site to force the victim’s browser into authenticated requests to the AdonisJS backend that would otherwise be blocked by same-origin checks.

In this scenario, the victim visits a compromised or attacker-controlled site while authenticated to the AdonisJS service over HTTP Basic Auth. The page contains JavaScript that triggers DNS resolutions pointing to internal or loopback addresses (e.g., 127.0.0.1 or internal corporate IPs). Because browsers enforce same-origin based on the resolved IP and port, not the hostname, the browser may allow the embedded script to make requests to the AdonisJS endpoint. Since the browser caches HTTP Basic Auth credentials per origin (authority), these requests include the Authorization header, effectively allowing the attacker’s JavaScript to execute privileged actions on behalf of the victim.

AdonisJS does not inherently prevent DNS Rebinding because it relies on the Node.js HTTP server stack. If the application validates only the presence and correctness of Basic Auth credentials without also validating the request origin or host header, an authenticated attacker can perform sensitive operations through forged intra-network requests. Common patterns that increase risk include using Basic Auth for admin interfaces, health endpoints, or internal APIs that are not intended to be reachable from external networks.

An attacker might chain a DNS Rebinding payload with Basic Auth to bypass IP-based or network-based access controls that assume requests originate from trusted subnets. For example, an endpoint like GET /admin/settings that relies on Basic Auth but does not verify Host headers or enforce strict CORS can be invoked programmatically by a malicious page. Because the credentials are sent automatically by the browser, the attacker can iterate over administrative functions without needing to know or guess usernames and passwords, provided the victim has an active session.

To detect this class of issue, scanning with middleBrick will surface findings in the BOLA/IDOR and Input Validation categories, highlighting missing origin or referer checks alongside Basic Auth usage. The tool cross-references runtime behavior against the OpenAPI specification to identify endpoints that accept credentials without sufficient network-level restrictions, providing prioritized remediation guidance rather than attempting to patch or block traffic itself.

Basic Auth-Specific Remediation in Adonisjs — concrete code fixes

Mitigating DNS Rebinding when using HTTP Basic Auth in AdonisJS requires a defense-in-depth approach: enforce strict host validation, avoid long-lived credentials in browser contexts, and add origin checks where feasible. Below are concrete, working examples that demonstrate secure patterns.

1. Host header validation middleware

Create a middleware that verifies the Host header against an allowlist before processing requests. This prevents the server from responding to unexpected hostnames used in rebinding attacks.

// start/hooks.ts or a dedicated middleware file
import { Exception } from '@poppinss/utils'

export const hostValidation = async (ctx, next) => {
  const allowedHosts = ['api.example.com', 'app.example.com']
  const requestHost = ctx.request.host()
  if (!allowedHosts.includes(requestHost)) {
    throw new Exception('Host not allowed', 403, 'E_INVALID_HOST')
  }
  await next()
}

Register the middleware in start/kernel.ts and apply it to routes that use Basic Auth.

2. Secure Basic Auth implementation with request inspection

The following example shows how to implement Basic Auth in a controller while also checking the request origin and host. It avoids storing credentials in browser-accessible JavaScript and ensures each request is authenticated against a known set of constraints.

// controllers/AuthController.ts
import { HttpContextContract } from '@ioc:Adonis/Core/HttpContext'
import { string } from '@ioc:Adonis/Core/Helpers'

export default class AuthController {
  public async login({ request, response, auth }: HttpContextContract) {
    const username = request.input('username')
    const password = request.input('password')

    // Validate credentials against your user provider
    const user = await auth.use('api').verify(username, password)
    if (!user) {
      return response.unauthorized()
    }

    // Optional: issue a short-lived token instead of continuing with Basic Auth
    return { token: string.generateRandom() }
  }

  public async sensitiveAction({ request, response }: HttpContextContract) {
    const auth = request.auth()
    if (!auth || !auth.user) {
      return response.unauthorized()
    }

    // Additional host and origin checks
    const origin = request.headers().origin
    const referer = request.headers().referer
    if (!origin || !referer || !origin.startsWith('https://app.example.com')) {
      return response.badRequest({ error: 'Invalid origin' })
    }

    // Proceed with business logic
    return response.ok({ data: 'safe operation' })
  }
}

3. Route binding with host constraints

Combine middleware with route definitions to ensure only trusted origins reach sensitive endpoints.

// start/routes.ts
import Route from '@ioc:Adonis/Core/Route'
import HostValidation from '../src/Hooks/hostValidation'

Route.group(() => {
  Route.get('/admin/settings', 'AdminController.settings').middleware([HostValidation])
  Route.post('/admin/reset', 'AdminController.reset').middleware([HostValidation])
}).prefix('/api/v1')

4. Avoid embedding credentials in client-side code

Do not expose Basic Auth usernames or passwords in JavaScript served to browsers. If you must use Basic Auth, restrict it to non-browser clients or use it only over mutually authenticated channels where credentials are not replayable across origins.

These steps reduce the attack surface by ensuring that even if a DNS Rebinding payload forces a browser to make authenticated requests, those requests are rejected due to host or origin mismatches. middleBrick can highlight endpoints that accept credentials without these restrictions, enabling targeted remediation.

Frequently Asked Questions

Can DNS Rebinding bypass CORS if Basic Auth credentials are present?
Yes. Browsers include Basic Auth credentials in cross-origin requests when the target host resolves to the same IP, allowing attackers to perform authenticated actions despite CORS restrictions. Defense should include host validation and avoid storing credentials in browser-executed contexts.
Does middleBrick attempt to fix DNS Rebinding or Basic Auth issues automatically?
No. middleBrick detects and reports findings with remediation guidance. It does not fix, patch, block, or remediate issues automatically.