GirlsBoy
回首向来萧瑟处,归去,也无风雨也无晴。
posts - 36,comments - 1,views - 12万
做安全红线使用Fortify工具进行扫描时,jquery append会报Cross Site Scripting DOM风险。解决该问题有两种办法。

    一、原生dom方式

    使用JavaScript原生dom替换append方法,原生dom会忽略<script>标签。比如,下列代码就会报Cross Site Scripting DOM攻击的问题

1
2
3
4
5
6
7
8
<div id="jqueryid">
</div>
<script>
    $(document).ready(function(){ 
        var val = "<script>console.log('cross site');" 
        $('#jqueryid').append(val); // console会打印出 cross site
    });
</script>       

  

修改方案

1
2
3
4
5
6
7
8
<div id="jqueryid">
</div>
<script>
$(document).ready(function(){
  var val = "<script>console.log('cross site');"
  $('#jqueryid')[0].innerHTML = val; // console不再会打印出cross site
});
</script>

在jQuery方法中,初append之外,html、before、after等方法同样存在此跨站点攻击的问题。

二、传入参数特殊处理

    我们也可以将传入的参数进行特殊符号转化成html的方式处理。

代码如下

1
2
3
4
5
6
7
8
9
10
11
12
<div id="jqueryid">
</div>
<script>
$(document).ready(function(){
  var script = "<script>console.log('cross site');"
  $('#jqueryid').append(encodeHtml(script)); // console不会打印出cross site
    
  function encodeHtml(value){
    return $('<div/>').text(value).html();
  }
});
</script>

  

其实在jQuery的官方文档中,存在如下说明。正是解决跨站点攻击的方法所在。

This method uses the browser's innerHTML property. Some browsers may not return HTML that exactly replicates the HTML source in an original document. For example, Internet Explorer sometimes leaves off the quotes around attribute values if they contain only alphanumeric characters.

Additional Notes: By design, any jQuery constructor or method that accepts an HTML string — jQuery(), .append(), .after(), etc. — can potentially execute code. This can occur by injection of script tags or use of HTML attributes that execute code (for example, <img onload="">). Do not use these methods to insert strings obtained from untrusted sources such as URL query parameters, cookies, or form inputs. Doing so can introduce cross-site-scripting (XSS) vulnerabilities. Remove or escape any user input before adding content to the document. 

 

 
posted on   GirlsBoy  阅读(2645)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

java\web应用开发&研究

梦想程序改变生活

成为一个了不起的人

点击右上角即可分享
微信分享提示