Dangling Dns in Express with Bearer Tokens
Dangling Dns in Express with Bearer Tokens — how this specific combination creates or exposes the vulnerability
A dangling DNS configuration in an Express application using Bearer Tokens can expose protected routes and enable authorization bypass. This occurs when a hostname or CNAME used during service discovery, internal routing, or external API calls does not resolve to a stable, intended endpoint and is subsequently updated or removed. If the application resolves such a hostname at runtime—such as when building redirect URLs, constructing callback addresses, or selecting an upstream target for a request—and the DNS record is later reassigned or left unresolved, traffic may be misdirected or processed in an insecure context.
When Bearer Tokens are involved, the risk amplifies. An attacker who can influence the target hostname (e.g., via a compromised subdomain, a poisoned hosts file, or a compromised external service configuration) may redirect token validation or token exchange flows to a malicious server. Because Bearer Tokens are typically passed in the Authorization header and accepted implicitly by many frameworks, an Express route that validates tokens against a dynamically resolved host may inadvertently trust responses from an attacker-controlled resolver. For example, if token introspection or user info fetching uses a hostname that can be dangling, an attacker who registers the dangling DNS name could capture or forge token validation responses, leading to authentication or authorization bypass.
Consider an Express service that calls an identity provider’s userinfo endpoint using a hostname stored in configuration or environment variables. If that hostname becomes dangling and is later claimed by an attacker, the service may trust the attacker’s responses and treat maliciously crafted tokens as valid. This pattern is especially common when hostnames are reused across environments or when temporary resources are cleaned up without proper DNS record cleanup. The vulnerability is not in Bearer Token usage itself, but in the combination of dynamic DNS resolution and implicit trust in responses tied to those tokens.
middleBrick detects this class of risk by correlating OpenAPI specifications—including full $ref resolution—with runtime behavior. It identifies endpoints that accept Bearer Tokens and then perform network-based actions dependent on potentially unstable external hosts. The scanner flags cases where hostname resolution is involved in token validation flows or redirect logic, highlighting the exposure as part of its authentication and BOLA/IDOR checks. Findings include severity ratings and remediation guidance, helping teams understand whether the issue lies in configuration, code, or third-party dependencies.
Bearer Tokens-Specific Remediation in Express — concrete code fixes
Remediation focuses on eliminating dynamic resolution of hostnames used in token validation and ensuring that token verification logic does not rely on external or mutable DNS targets. Prefer static, audited endpoints for token introspection and user info. When network calls are required, pin the hostname, verify certificates, and do not trust inferred or redirect-based targets.
Example 1: Unsafe dynamic hostname resolution with Bearer Token validation
const https = require('https');
const express = require('express');
const app = express();
app.get('/user', (req, res) => {
const token = req.headers.authorization?.split(' ')[1];
if (!token) return res.status(401).send('Missing token');
// UNSAFE: hostname from environment or config may be dangling
const userInfoUrl = `https://${process.env.USERINFO_HOST}/userinfo`;
// Perform a request to the dynamic host
https.get(userInfoUrl, (resp) => {
let data = '';
resp.on('data', (chunk) => data += chunk);
resp.on('end', () => {
// UNSAFE: trusting response from a potentially dangling host
const userInfo = JSON.parse(data);
if (userInfo.sub) {
// Token accepted based on possibly malicious response
res.json({ ok: true, user: userInfo });
} else {
res.status(403).send('Invalid token');
}
});
}).on('error', () => {
res.status(502).send('Upstream error');
});
});
app.listen(3000);
Example 2: Secure remediation with static introspection endpoint and strict hostname checks
const https = require('https');
const express = require('express');
const app = express();
const INTROSPECTION_URL = 'https://auth.example.com/oauth/introspect'; // static, pinned host
const ALLOWED_ISSUER = 'https://auth.example.com';
app.get('/user', (req, res) => {
const token = req.headers.authorization?.split(' ')[1];
if (!token) return res.status(401).send('Missing token');
// Use a statically defined, audited endpoint
const postData = new URLSearchParams();
postData.append('token', token);
const options = new URL(INTROSPECTION_URL);
const reqOpts = {
hostname: options.hostname,
port: 443,
path: options.pathname,
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': postData.length
},
// Enforce certificate checks and avoid redirects to dangling hosts
rejectUnauthorized: true,
maxRedirects: 0
};
const req = https.request(reqOpts, (resp) => {
let data = '';
resp.on('data', (chunk) => data += chunk);
resp.on('end', () => {
try {
const result = JSON.parse(data);
if (result.active && result.iss === ALLOWED_ISSUER) {
// Token validated against a trusted, static issuer
res.json({ ok: true, scope: result.scope });
} else {
res.status(403).send('Invalid token');
}
} catch (e) {
res.status(400).send('Invalid response');
}
});
});
req.on('error', () => {
res.status(502).send('Upstream error');
});
req.write(postData.toString());
req.end();
});
app.listen(3000);
Additional practices
- Do not construct authorization or callback URLs from user-supplied or external host values.
- Pin dependencies and DNS records for any service involved in token validation.
- Validate token issuers (iss) and audiences (aud) against known, static values.
- Use environment configuration to store static endpoints rather than resolving them at runtime.
- middleBrick Pro continuous monitoring can help detect unexpected changes in external host resolution that may indicate configuration drift or dangling DNS states.