An open redirection vulnerability occurs when an application accepts a user-supplied URL and reidrects the user to it without proper validation. This commonly happens when using window.location.href or similar client-side redirection mechanisms, potentially allowing attackers to craft malicious links that appear trustworthy.
To address this issue, two primary mitigation strategies are typically employed:
Approach 1: Validate Redirect URLs Against Allowed Hostnames
This method ensures that any redirect target belongs to the same origin as the current application. Below is a JavaScript implementation that parses and validates the destination URL:
function isValidRedirect(targetUrl) {
try {
const parsed = new URL(targetUrl, window.location.origin);
return parsed.hostname.toLowerCase() === window.location.hostname.toLowerCase();
} catch (e) {
return false;
}
}
// Usage example:
// if (isValidRedirect(userProvidedUrl)) {
// window.location.href = userProvidedUrl;
// }
This approach leverages the built-in URL constructor for robust parsing and avoids manual string manipulation, reducing the risk of bypasses due to malformed URLs.
Approach 2: Sanitize and Encode Redirect URLs Before Navigation
A alternative solution involves sanitizing the URL—particularly its query parameters—and then triggering navigation via a dynamically created anchor element. This not only helps pass static analysis tools like Fortify but also enforces safer handling of user input:
function safeRedirect(destination) {
try {
const url = new URL(destination, window.location.href);
// Rebuild search parameters with proper encoding
const sanitizedParams = new URLSearchParams();
for (const [key, value] of new URLSearchParams(url.search).entries()) {
sanitizedParams.set(encodeURIComponent(key), encodeURIComponent(value));
}
url.search = sanitizedParams.toString();
// Create and trigger a synthetic click on an <a> element
const link = document.createElement('a');
link.href = url.href;
link.target = '_self';
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
} catch (error) {
console.warn('Invalid redirect URL:', destination);
}
}
This technique combines URL normalization, parameter encoding, and DOM-based navigation to mitigate open redirection risks while satisfying security scanning requirements such as those from Fortify.