HIGH dangling dnskoabearer tokens

Dangling Dns in Koa with Bearer Tokens

Dangling Dns in Koa with Bearer Tokens — how this specific combination creates or exposes the vulnerability

A dangling DNS record occurs when a hostname (e.g., internal.api.example.com) previously pointed to an infrastructure endpoint that has been decommissioned, but the DNS entry is not removed or updated. If a Koa application uses such a hostname in its configuration or code, and the application also relies on Bearer Tokens for authorization, the combination can expose the application to security risks during discovery and runtime.

During a black-box scan, middleBrick checks for dangling DNS records as part of its inventory and input validation checks. When a Koa app resolves a dangling hostname at startup or runtime, the request may silently fail or resolve unpredictably, potentially falling back to unintended endpoints. If the app then sends Bearer Tokens in headers (e.g., Authorization: Bearer ) to these unpredictable destinations, tokens can be leaked to unknown network locations. This violates the principle that credentials must only be transmitted to explicitly trusted endpoints.

Moreover, if the dangling DNS record later resolves to a malicious host under attacker control (e.g., via DNS hijacking or a compromised external DNS), any Bearer Token sent by the Koa app can be intercepted. This scenario is particularly dangerous when tokens are long-lived or have broad scopes, as attackers can reuse them to impersonate services or access protected resources. middleBrick’s LLM/AI security checks include tests that probe for unauthenticated endpoints and system prompt leakage; while these focus on model security, they highlight how weak endpoint trust can cascade into broader exposure when tokens are involved.

Another angle is during development or staging, where environment variables or config files may reference dangling hostnames. If a Koa app loads configuration with a dangling DNS entry and includes Bearer Token logic without validating the endpoint’s authenticity, the app may operate in a misconfigured state that is not detected until an integration test or scan. The scanner’s inventory management and property authorization checks aim to surface such misconfigurations by correlating spec definitions with observed runtime behavior.

In summary, the vulnerability arises not from Koa or Bearer Tokens themselves, but from the intersection of unresolved DNS references and implicit trust in network destinations. This can lead to token leakage or unintended authentication to rogue services, which middleBrick detects through its parallel security checks, including input validation, data exposure, and inventory management.

Bearer Tokens-Specific Remediation in Koa — concrete code fixes

Remediation focuses on ensuring that DNS references are valid, that endpoints are explicitly trusted, and that Bearer Tokens are only sent to verified destinations. Below are concrete code examples for a Koa application.

1. Validate DNS and endpoint reachability at startup

Perform a proactive DNS resolution and connectivity check during application initialization. If resolution fails or returns an unexpected IP, the app should refuse to start or load the configuration that references the dangling hostname.

import dns from 'dns';
import axios from 'axios';

async function validateEndpoint(hostname, token) {
  try {
    const resolved = await dns.promises.resolve4(hostname);
    if (!resolved || resolved.length === 0) {
      throw new Error('DNS resolution failed for ' + hostname);
    }
    // Optional: probe the endpoint to confirm it is the expected service
    const response = await axios.get(`https://${hostname}/health`, {
      headers: { Authorization: `Bearer ${token}` },
      timeout: 3000,
    });
    if (response.status !== 200) {
      throw new Error('Unexpected health check response from ' + hostname);
    }
    console.log(`Endpoint ${hostname} is valid and responding.`);
  } catch (err) {
    console.error(`Invalid endpoint configuration: ${err.message}`);
    process.exit(1);
  }
}

// Usage during app bootstrap
const API_HOST = process.env.API_HOST; // e.g., internal.api.example.com
const BEARER_TOKEN = process.env.BEARER_TOKEN;
await validateEndpoint(API_HOST, BEARER_TOKEN);

2. Enforce explicit hostname allowlisting

Instead of relying on dynamic DNS lookups, maintain an allowlist of permitted hostnames and compare the resolved target against it before sending any Bearer Token.

const ALLOWED_HOSTS = new Set([
  'api.example.com',
  'auth.service.example.com',
]);

function isHostAllowed(hostname) {
  return ALLOWED_HOSTS.has(hostname);
}

// In a route or middleware
app.use(async (ctx, next) => {
  const targetHost = new URL(ctx.request.url).hostname;
  if (!isHostAllowed(targetHost)) {
    ctx.status = 403;
    ctx.body = { error: 'Forbidden host' };
    return;
  }
  await next();
});

3. Secure token handling and avoid transmission to unknown endpoints

Ensure that Bearer Tokens are only attached to requests when the endpoint is verified. Avoid conditionally setting headers based on environment variables that may reference dangling hosts.

// Good: explicit endpoint and token usage
const axiosInstance = axios.create({
  baseURL: 'https://api.example.com',
  headers: { Authorization: `Bearer ${process.env.BEARER_TOKEN}` },
});

// Use the instance for known, trusted endpoints
async function fetchUserData(userId) {
  const response = await axiosInstance.get(`/users/${userId}`);
  return response.data;
}

4. Integrate scanning and monitoring

Use middleBrick’s CLI to scan your Koa endpoints and verify that no dangling DNS references are present in your configuration. The dashboard can track changes over time, and the GitHub Action can fail builds if a scan detects issues related to inventory or input validation that could lead to token exposure.

# Example CLI usage
middlebrick scan https://your-api.example.com/openapi.json

Frequently Asked Questions

How can I detect if my Koa app is using a dangling DNS hostname?
Run a DNS health check at startup: resolve the hostname and confirm it points to an expected, trusted IP. middleBrick’s inventory and input validation checks can help identify unresolved or mismatched DNS records during scans.
What is the best practice for storing Bearer Tokens in a Koa application to avoid exposure?
Store tokens in environment variables or a secure secrets manager, never in source code. Ensure tokens are only sent to endpoints that are explicitly validated against an allowlist and confirmed via DNS and connectivity checks.