Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to protect location.href from cross site scripting in javascript?

Here in my javascript function im using location.href as follows location.href = "../Floder1/result.jsp"; it is working fine but when i used fortify tool it is showing Cross-site Scripting which can result in the browser executing malicious code. how to protect this from cross site scripting. Thank you very much,your answer will be very much appreciated.

like image 595
tajMahal Avatar asked Nov 23 '22 14:11

tajMahal


1 Answers

This code should work only in firefox since Proxy isn't implemented in all browsers

What you can do is to replace the original location object with a proxied one where you add some logic to your proxy to check for allowed value for location. this will not protect against the direct modification of the original object (location) but if you use only the proxied object in your code you should be fine.

// suppose we are in example.com
let validator = {
   set: function(obj, prop, val) {
     if (prop === 'href') {
       if(typeof val != 'string'){
         throw new TypeError('href must be string.');
       }
       if (!val.startsWith("https://example.com/")) {
         throw new Error('XSS');
       }
     }
    obj[prop] = val;
    return true;
   },
   get: function(obj, prop){
    return prop in obj?
        obj[prop] :
        null;
   }
};
let proxiedLocation = new Proxy(location, validator);
console.log(proxiedLocation.href);// work same as location.href
proxiedLocation.href = "https://example.com/page1";// work fine
proxiedLocation.href = "https://example.net/page1";// cause exception
like image 152
phoenixstudio Avatar answered Dec 28 '22 06:12

phoenixstudio