HIGH dns rebindingexpressbearer tokens

Dns Rebinding in Express with Bearer Tokens

Dns Rebinding in Express with Bearer Tokens — how this specific combination creates or exposes the vulnerability

DNS rebinding is a client-side attack where an attacker forces a victim’s browser to resolve a hostname to an IP address under the attacker’s control, often bypassing same-origin policy and network-based access controls. In Express applications that rely on bearer tokens for authentication, this combination can expose privileged internal endpoints to a malicious site visited by an authenticated user.

Consider an Express service that validates requests using an Authorization header formatted as Bearer <token>. If the service also permits requests to internal or administrative endpoints (for example, /admin/reset or internal service URLs like http://internal-metrics.local/health), a victim’s browser may be tricked into making those requests to an attacker-controlled IP after a DNS rebind. Because the request still carries a valid bearer token, Express may treat the malicious inbound request as legitimate, allowing unauthorized actions or data exposure.

The risk is amplified when token handling is not coupled with strict origin checks, network boundary validation, or robust CORS policies. For instance, an Express route that verifies the presence of a bearer token but does not ensure the request originates from a trusted network or host can be abused. Attackers may use a two-stage IP rebind: the first request resolves to a server under the attacker’s control, and the second resolves to a sensitive internal address, such as a database or internal API, while the browser continues to send the bearer token automatically via cookies or JavaScript.

In practice, this manifests when an Express app uses bearer tokens without additional context checks, such as validating the Origin or Referer headers, or when it trusts host headers that can be manipulated. Tools like middleBrick can detect missing host-based restrictions and insecure token usage patterns during an unauthenticated scan, highlighting the potential for abuse in this specific configuration.

Bearer Tokens-Specific Remediation in Express — concrete code fixes

To mitigate DNS rebinding risks when using bearer tokens in Express, combine token validation with strict origin and host checks, and avoid relying solely on the presence of a bearer token for authorization. Below are concrete, secure coding patterns.

1. Validate Origin and Host headers

Explicitly check the Origin and Host headers before processing requests. This prevents a rebinded host from being trusted implicitly.

const allowedOrigins = ['https://your-app.example.com', 'https://api.your-app.example.com'];

function validateOrigin(req, res, next) {
  const origin = req.headers.origin;
  if (!origin || !allowedOrigins.includes(origin)) {
    return res.status(403).json({ error: 'Forbidden origin' });
  }
  next();
}

app.use(validateOrigin);

2. Use a strict CORS policy

Configure CORS to allow only known origins and to reject requests that do not explicitly include credentials when required. Do not allow * for credentials-enabled routes.

const cors = require('cors');

const corsOptions = {
  origin: allowedOrigins,
  credentials: true,
  methods: ['GET', 'POST', 'PUT', 'DELETE'],
  allowedHeaders: ['Authorization', 'Content-Type']
};

app.use(cors(corsOptions));

3. Token validation with host context

After verifying the bearer token, ensure the request’s host is within an expected set. Reject requests where the host does not match your service’s expected domain(s).

const expectedHosts = ['api.example.com', 'app.example.com'];

function validateHost(req, res, next) {
  const host = req.headers.host?.split(':')[0];
  if (!host || !expectedHosts.includes(host)) {
    return res.status(403).json({ error: 'Forbidden host' });
  }
  next();
}

app.use(validateHost);

4. Secure bearer token usage pattern

Use the Authorization header consistently and avoid relying on cookies for bearer tokens unless they are marked HttpOnly, Secure, and accompanied by appropriate SameSite attributes.

app.get('/api/resource', (req, res) => {
  const authHeader = req.headers.authorization;
  if (!authHeader || !authHeader.startsWith('Bearer ')) {
    return res.status(401).json({ error: 'Unauthorized' });
  }
  const token = authHeader.slice(7);
  // Validate token via your auth provider (e.g., verify signature, scope, issuer)
  if (!isValidToken(token, req.headers.host)) {
    return res.status(403).json({ error: 'Invalid token' });
  }
  res.json({ data: 'secure data' });
});

function isValidToken(token, host) {
  // Implement signature verification, scope checks, issuer validation, and host context
  const allowedHosts = ['api.example.com'];
  return allowedHosts.includes(host) && verifyJwt(token);
}

5. Avoid internal host resolution in client-side JavaScript

Do not expose internal hostnames or endpoints to browser JavaScript. If internal endpoints are required, proxy them through your Express app so that DNS resolution stays server-side and is not subject to rebinding.

app.post('/api/proxy', (req, res) => {
  const target = 'http://internal-service/action';
  // Perform server-side request with validated context
  fetch(target, {
    method: req.method,
    headers: { Authorization: `Bearer ${process.env.INTERNAL_TOKEN}` },
    body: req.body
  })
    .then(response => response.json())
    .then(data => res.json(data))
    .catch(err => res.status(500).json({ error: 'Proxy error' }));
});

Frequently Asked Questions

How does middleBrick help detect DNS rebinding risks with bearer tokens in Express?
middleBrick scans unauthenticated attack surfaces and checks for missing host-based restrictions and insecure token usage patterns. By correlating OpenAPI specs with runtime behavior, it can highlight endpoints where bearer token validation occurs without origin or host checks, which are relevant to DNS rebinding scenarios.
Can DNS rebinding bypass CORS if bearer tokens are stored in cookies?
Yes. If bearer tokens are stored in cookies without SameSite and Secure attributes, and CORS is misconfigured, a rebinding attack can cause the browser to send cookies and tokens to a malicious rebinded host. Always use strict CORS, validate Origin, set appropriate cookie attributes, and validate host context server-side.