HIGH dangling dnshapiapi keys

Dangling Dns in Hapi with Api Keys

Dangling Dns in Hapi with Api Keys — how this specific combination creates or exposes the vulnerability

A dangling DNS configuration in a Hapi server can expose behavior that differs depending on whether requests are authenticated with API keys. When route handlers perform hostname resolution only after validating an API key, the key check may succeed while the subsequent DNS lookup points to an unintended or attacker-controlled host. This creates a situation where authenticated access gates a lookup that is not safely constrained, effectively exposing an uncontrolled redirect or SSRF-like path tied to the authenticated context.

Consider a Hapi route that first checks an API key header and then uses the node dns module to resolve a hostname provided by the client or derived from request parameters. If the API key is valid but the DNS resolution is not scoped to a controlled endpoint, the authenticated request may resolve to a dangling or malicious host. This pattern is problematic because the presence of the API key gives a false sense of authorization while the underlying DNS resolution remains untrusted. The authentication layer does not protect against a malicious or dangling DNS outcome, only the identity of the caller.

In a black-box scan, middleBrick tests unauthenticated surfaces and authenticated probes where API keys are supplied. For Hapi APIs, this means it will attempt to exercise routes with valid and invalid keys while monitoring where DNS resolution leads. The LLM/AI Security checks include active prompt injection-style probes adapted to backend workflows, looking for scenarios where authenticated steps lead to uncontrolled external interactions such as dangling DNS. Input Validation checks will flag missing hostname allowlists, and Property Authorization checks will highlight mismatches between authentication and downstream trust boundaries.

Real-world analogs include misconfigured internal service names or stale CNAME records that resolve to external IPs. For example, a hostname like internal-service.legacy.example might have been internally scoped but now resolves externally. If Hapi resolves this after a successful API key check, the API can be used to probe internal infrastructure or exfiltrate data through a dangling pointer. The scanner maps findings to frameworks such as OWASP API Top 10 and SOC2, noting that authenticated entry points do not automatically sanitize downstream dependencies.

middleBrick’s OpenAPI/Swagger analysis helps identify such mismatches by correlating spec definitions of authentication requirements with runtime behavior. When a path defines a security scheme based on API keys but downstream steps invoke DNS lookups without host constraints, the cross-reference highlights the control gap. This is especially useful for specs using extensive $ref resolution across components and security schemes.

Api Keys-Specific Remediation in Hapi — concrete code fixes

To remediate dangling DNS risks in Hapi when using API keys, ensure DNS resolution is constrained before authentication proceeds, or that the resolution target is statically defined and validated. Do not allow client-supplied hostnames to directly drive DNS lookups after an API key succeeds. Instead, use a strict allowlist of endpoints and resolve only internal service names that are verified at deploy time.

Below are concrete Hapi examples that demonstrate safe patterns. The first shows how to validate API keys and then resolve a fixed, trusted hostname using the built-in dns.promises API. The second demonstrates rejecting requests that attempt to influence the target host, keeping resolution out of the request path entirely.

// Safe pattern: fixed trusted host, API key validation, no client hostname
const Hapi = require('@hapi/hapi');
const dns = require('dns').promises;

const trustedHost = 'api.internal.example.com';

const validateApiKey = (request, h) => {
  const key = request.headers['x-api-key'];
  if (key !== process.env.API_KEY) {
    return h.response({ error: 'Unauthorized' }).code(401);
  }
  return h.continue;
};

const init = async () => {
  const server = Hapi.server({ port: 4000, host: 'localhost' });

  server.ext('onPreAuth', validateApiKey);

  server.route({
    method: 'GET',
    path: '/data',
    handler: async (request, h) => {
      // Resolve a fixed, trusted host only
      const addresses = await dns.resolve4(trustedHost);
      return { resolved: addresses, source: 'trusted' };
    }
  });

  await server.start();
  console.log('Server running on %s', server.info.uri);
};

init().catch(err => {
  console.error(err);
  process.exit(1);
});

The second example rejects any attempt to specify a host while still enforcing API key checks, making the flow explicit and preventing accidental use of dangling references.

// Explicit rejection of dynamic host parameters
const validateHostParam = (request, h) => {
  if (request.query.host) {
    return h.response({ error: 'Host parameter not allowed' }).code(400);
  }
  return h.continue;
};

server.ext('onPreAuth', validateHostParam);
server.ext('onPreAuth', validateApiKey);

server.route({
  method: 'GET',
  path: '/lookup',
  handler: async (request, h) => {
    // Always use a predefined host
    const addresses = await dns.resolve4('services.default.example.com');
    return { addresses };
  }
});

For API-key-authenticated endpoints, middleBrick’s CLI can verify that your routes do not leak control to untrusted resolution logic. Run middlebrick scan <url> with a valid API key to see whether authenticated scans surface uncontrolled DNS behavior. In the dashboard, per-category breakdowns will highlight Input Validation and Property Authorization findings, while the GitHub Action can gate CI/CD if risk scores exceed your chosen threshold. Remediation guidance in reports will point to host allowlists, fixed endpoints, and removal of dynamic host parameters.

Frequently Asked Questions

Why does a valid API key not prevent a dangling DNS issue?
Authentication and authorization are separate from downstream trust. A valid API key confirms who is making the request, but does not constrain what external host the application resolves to. If DNS resolution is not restricted to a known set of endpoints, authenticated requests can still reach unintended or dangling hosts.
How can I test my Hapi API for dangling DNS using middleBrick?
Supply the public URL of your Hapi service to middleBrick via the Web Dashboard, CLI (middlebrick scan <url>), or GitHub Action. Include a valid API key in requests if authentication is required. The scan will check for missing hostname allowlists and mismatches between authentication and DNS behavior, surfacing findings with remediation guidance.