
ARanjan261637 (Community Member) asked a question.
I have code in my application user i have written code for redirection
function redirect(url){
window.location=url
}
this code is failed in veracode scan stating CWE-601: URL Redirection to Untrusted Site ('Open Redirect')
i have tried with below code as well, same result
window.location= encodeURI(url)
and also wrote code for custom validation still its not working
function sameOrigin(url) {
const { host } = window.document.location; // host + port
const { protocol } = window.document.location;
const srOrigin = `//${host}`;
const origin = protocol + srOrigin;
// Allow absolute or scheme relative URLs to same origin
const isvalidPath =
url === origin ||
url.slice(0, origin.length + 1) === `${origin} /` ||
url === srOrigin ||
url.slice(0, srOrigin.length + 1) === `${origin} /` ||
// or any other URL that isn't scheme relative or absolute i.e relative.
!/^(\/\/|http:|https:).*/.test(url);
return isvalidPath ? url : '/';
}
in my scenario i cant manage all valid urls and cross check with it
.png)
Your code uses window.location = url to redirect users based on a provided URL (url).
Veracode flags this as a vulnerability because url could potentially be manipulated by an attacker to redirect users to malicious websites (Open Redirect).
Encoding the URL with encodeURI doesn't address the core issue.
While your sameOrigin function attempts to validate URLs for the same origin, it might be challenging to manage all valid URLs in your scenario.
If you have a limited set of valid URLs for redirection, create a whitelist and only allow redirection to those URLs. You can achieve this with an array of allowed origins or regular expressions matching valid URL patterns.
Implement redirection logic on the server-side. This way, user-provided input (url) is validated on the server before redirection occurs. The server can check if the URL originates from a trusted source or adheres to specific criteria.
Some web development frameworks provide built-in functions for secure redirection. These functions often handle URL validation and prevent Open Redirects. Explore your framework's documentation for such functionalities.