简体   繁体   English

正确使用 appendChild 避免 XSS

[英]Use appendChild correctly to avoid XSS

After doing an XXS site check, one error that pops up in the console is the inline use of the scripts needed for Google Analytics Tag Manager.在进行 XXS 站点检查后,控制台中弹出的一个错误是内联使用了 Google Analytics(分析)跟踪代码管理器所需的脚本。 I have now created an external analytics.js file, which I load in the header and created an IIFE to load the script, then checked that it works in GA (it does):我现在创建了一个外部 analytics.js 文件,我将其加载到 header 并创建了一个 IIFE 来加载脚本,然后检查它是否在 GA 中工作(确实如此):

var load_google_tag_manager = function(){
    var script = document.createElement("script");
    var head = document.getElementsByTagName('head')[0];
    script.async = true;
    script.type = "text/javascript";
    script.src = "https://www.googletagmanager.com/gtag/js?id=UA-XXXXXX-1";
    head.appendChild(script);
}();

window.dataLayer = window.dataLayer || [];

function gtag() {
    dataLayer.push(arguments);
}
gtag('js', new Date());
gtag('config', 'UA-XXXXXX-1', {
    "anonymize_ip": true,
    "allow_display_features": false,
    "link_attribution": false
});

I then checked the console again for error warnings and got one, this was the use of the function appendChild .然后我再次检查控制台的错误警告并得到一个,这是 function appendChild的使用。 After reading some OWASP documentation , I understand that using this can be potentially dangerous, and some good examples of how to make it safer are given, such as: how to use the setAttribute method.在阅读了一些OWASP 文档后,我了解到使用它可能会有潜在的危险,并且给出了一些如何使其更安全的好例子,例如:如何使用setAttribute方法。 eg:例如:

SAFE and FUNCTIONALLY CORRECT example

 var x = document.createElement("input");
 x.setAttribute("name", "company_name");
 x.setAttribute("value", '<%=Encoder.encodeForJS(companyName)%>');
 var form1 = document.forms[0];
 form1.appendChild(x);

But it does not say how to do this when you are eg not using this method.但它没有说明当您不使用这种方法时如何执行此操作。 How would I eg set the src value safely?我将如何安全地设置src值? Ultimately, I want to make my IIFE safe from XXS.最终,我想让我的 IIFE 远离 XXS。

The encoding is needed in the example because of the mixing of server-side templating with client-side code.由于服务器端模板与客户端代码混合在一起,因此示例中需要编码。 The quotes need to be escaped to prevent the string literal from being closed, and more code added after it.引号需要转义以防止字符串文字被关闭,并在其后添加更多代码。

So if companyName were '); alert(1);//所以如果companyName'); alert(1);// '); alert(1);// , then: '); alert(1);// ,然后:

x.setAttribute("value", '<%=companyName%>');

would become:会成为:

x.setAttribute("value", ''); alert(1);//');

Your URL looks like a fixed constant, so there is no possibility of something like this, so your code should be fine as it is.您的 URL 看起来像一个固定常量,所以不可能出现这样的情况,所以您的代码应该没问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM