Dns Rebinding in Express with Hmac Signatures
Dns Rebinding in Express with Hmac Signatures — how this specific combination creates or exposes the vulnerability
DNS Rebinding is a client-side network attack that manipulates DNS responses to make a browser believe a malicious host is the same origin as a trusted one. In an Express backend that uses Hmac Signatures to protect webhook or API endpoints, this combination can bypass signature validation when the server trusts the request hostname or IP without additional constraints.
Consider an Express endpoint that verifies an Hmac Signature header but does not independently validate the request origin. The server may compute the expected Hmac using a shared secret and a canonical string that includes the request method, URL path, and a timestamp. If the server also uses hostname-based routing or conditional logic that depends on req.hostname or req.ip, an attacker can control the DNS resolution of a benign domain and rebind it to an internal or attacker-controlled IP between requests.
In a typical vulnerable flow, a victim’s browser sends a request to api.example.com with a valid Hmac signature computed over POST /webhook. The server validates the signature, checks that the host matches an allowlist, and proceeds. An attacker registers evil.com and uses DNS rebinding so that api.example.com resolves first to the expected IP and then to an internal IP such as 127.0.0.1. Because the signature was valid and the hostname check initially passes, the server may still process the request. If internal routing or service discovery relies on req.hostname without strict validation, the server might route to an internal service or accept a modified path that the signature did not originally cover.
The risk is amplified when the Hmac signature does not cover the full target URI, including hostname-sensitive parameters or when the server uses a per-request nonce derived from host-dependent data. An attacker can rebind to an internal IP and attempt path-based or header-based injection that the signature validation does not detect, leading to unauthorized actions or information exposure. This pattern violates the principle that signature verification must be based on immutable, attacker-independent values such as a canonical request string and strict origin checks rather than mutable network properties.
middleBrick can detect such misconfigurations by scanning the unauthenticated attack surface and correlating endpoint behavior with signature validation logic, highlighting findings related to Input Validation and Unsafe Consumption. The tool maps these findings to frameworks such as OWASP API Top 10 and provides remediation guidance without claiming to fix or block traffic.
Hmac Signatures-Specific Remediation in Express — concrete code fixes
To mitigate DNS Rebinding when using Hmac Signatures in Express, ensure that signature validation is independent of mutable request properties and that host or IP-based routing does not affect security decisions. Use strict allowlists, canonical request construction, and avoid relying on req.hostname or req.ip for signature computation or routing.
Secure Express Hmac Signature Verification Example
The following example shows a hardened Express route that verifies an Hmac signature using a canonical string that excludes hostname-dependent values and uses a constant-time comparison. It also enforces an explicit allowlist of permitted hostnames at the application layer, ignoring any host-derived routing logic for security decisions.
const crypto = require('crypto');
const express = require('express');
const app = express();
const SHARED_SECRET = process.env.WEBHOOK_SECRET; // store securely
const ALLOWED_HOSTS = new Set(['api.example.com', 'webhook.example.com']);
function verifyHmac(req, res, next) {
const signature = req.get('X-Hub-Signature-256');
if (!signature || !signature.startsWith('sha256=')) {
return res.status(401).send('Missing or invalid signature header');
}
const expected = signature.split('=')[1];
// Canonical string excludes hostname and is stable across proxies
const canonical = [
req.method,
req.path,
req.query ? new URLSearchParams(req.query).toString() : '',
typeof req.body === 'string' ? req.body : JSON.stringify(req.body || {}),
req.get('X-Timestamp') || '',
].join('\n');
const hmac = crypto.createHmac('sha256', SHARED_SECRET);
const computed = hmac.update(canonical).digest('hex');
// Constant-time comparison
const isValid = crypto.timingSafeEqual(Buffer.from(computed), Buffer.from(expected));
if (!isValid) {
return res.status(401).send('Invalid signature');
}
// Enforce hostname allowlist independently
if (!ALLOWED_HOSTS.has(req.get('host')?.split(':')[0])) {
return res.status(403).send('Host not allowed');
}
// Attach verified metadata for downstream use
req.verified = { host: req.get('host'), timestamp: req.get('X-Timestamp') };
next();
}
app.post('/webhook', express.json({ type: '*/*' }), verifyHmac, (req, res) => {
// Safe to process verified webhook
res.status(200).send('ok');
});
app.listen(3000, () => console.log('Server running on port 3000'));
Additional hardening steps include:
- Always include a timestamp and nonce in the canonical string and reject requests with timestamps outside a narrow window to prevent replay.
- Use
req.pathandreq.querydirectly rather than reconstructing URLs from host-dependent sources. - Avoid using
req.hostnameorreq.ipin security-sensitive routing or signature logic; treat them as network metadata only. - Deploy behind a proxy that normalizes hosts and paths before requests reach Express, and ensure the proxy enforces host header validation.
By combining strict Hmac verification with explicit allowlists and canonical request normalization, you reduce the attack surface exposed by DNS rebinding. middleBrick’s scans can validate these controls by checking Authentication, Input Validation, and BOLA/IDOR findings, helping teams confirm secure configuration.
For teams seeking automated oversight, the middleBrick CLI (middlebrick scan <url>) and GitHub Action can integrate checks into CI/CD, while the Pro plan enables continuous monitoring and alerts when deviations are detected.