Description
Using a query parameter, fragment or DOM value directly in location.assign, location.replace or location.href lets that value control where the browser navigates.
Potential impact
A trusted link can lead users to enter passwords or MFA codes on another site. OAuth codes or tokens may also be exposed if the flow trusts the return destination.
Remediation
- Map an allowed key such as
to=hometo an internal path and use a default for unknown keys. Apply the same allow-list if the server performs the final redirect. - If you accept paths directly, reject full URLs and paths starting with
//. Parse withnew URL(value, location.origin), then verify that the resultingoriginmatches the current site and thepathnamestarts with/.
Examples
Before
javascript
// Use the fragment directly as an external redirect destination
function unsafeRedirect() {
// URL: https://trusted.example/app#to=https://evil.example
const raw = location.hash.replace(/^#to=/, '');
if (raw) {
// A user-controlled absolute URL can navigate outside the site
top.location = decodeURIComponent(raw);
}
}
After
javascript
// Map allow-listed keys only to internal redirect paths
const ROUTE_MAP = Object.freeze({
home: '/home',
dashboard: '/dashboard',
help: '/help'
});
function safeRedirect() {
const params = new URLSearchParams(window.location.search);
const key = params.get('to');
const path = Object.hasOwn(ROUTE_MAP, key) ? ROUTE_MAP[key] : undefined;
if (path) {
// Navigate only to an internal path, without a supplied scheme or host
window.location.assign(path);
} else {
// Use the default path for unsupported values
window.location.replace('/home');
}
}
The new handler reads a query such as ?to=home and uses Object.hasOwn to select a key defined directly on ROUTE_MAP. Links using only the old #to= fragment and unknown keys lead to /home.