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

    一、原生dom方式

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

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

  

修改方案

<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的方式处理。

代码如下

<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 2022-08-11 21:14  GirlsBoy  阅读(2178)  评论(0编辑  收藏  举报

java\web应用开发&研究

梦想程序改变生活

成为一个了不起的人