6

在我的 javascript 函数中,我使用 location.href 如下 location.href = "../Floder1/result.jsp";,它工作正常,但是当我使用强化工具时,它显示跨站点脚本which can result in the browser executing malicious code. 如何保护它免受跨站点脚本的影响。非常感谢,您的回答将不胜感激。

4

2 回答 2

1

此代码应仅在 firefox 中有效,因为并非在所有浏览器中都实现了代理

您可以做的是将原始location对象替换为代理对象,在其中向代理添加一些逻辑以检查位置的允许值。这不会防止直接修改原始对象(location),但如果您在代码中仅使用代理对象,您应该没问题。

// 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
于 2021-01-16T23:56:21.573 回答
0

例如,当用户可以将数据放入网页或获取会话数据时,就会发生跨站点脚本。

如何保护

永远不允许在您的网页中注入代码。因此,如果您有一个表单,请在服务器中检查它并在打印到您的页面之前对其进行解析。

您不应该允许页面内容被href. 你总是escape之前的数据!

阅读有关以下内容的答案location.hrefhttps ://stackoverflow.com/a/24089350/2389232

样品

您有一个 iframe,它随着 GET 变量的变化而变化:

sample.tld/index.jsp?iframe=none.jsp

我可以将 a 注入script您的 iframe,因此您应该使用转义字符保护它:

// Escape the characters in the server and send it to the client.
// So the variable GET iframe will be valid
于 2014-08-22T06:47:20.410 回答