AdSense

網頁

2018/2/12

處理弱點掃描XSS問題jQuery append() 的做法

jQuery append()有潛在XSS攻擊(跨網站指令碼攻擊)的風險,例如下面append()的參數會被執行。

<div id="test">
</div>
<script>
$(document).ready(function(){
  var script = "<script>console.log('hello');"
  $('#test').append(script); // 會在console印出 hello
});
</script>

但如果使用JavaScript的原生DOM方法替代則不會被執行,因為<script>會被忽略,例如

<div id="test">
</div>
<script>
$(document).ready(function(){
  var script = "<script>console.log('hello');"
  $('#test')[0].innerHTML = script ; // 不會印出 hello
});
</script>

除了append()外,其他jQuery的操作function如html()before()after()prepend()appendTo()prependTo()都有同樣的問題。

解決方法是改用JavaScript DOM原生方法來操作,不過使用JavaScript的方法來操作DOM實在是很痛苦。或是仍然使用以上的方法,但在傳入參數前要先把html的特殊符號(e.g.&<>"')取代成html代碼,例如

<div id="test">
</div>
<script>
$(document).ready(function(){
  var script = "<script>console.log('hello');"
  $('#test').append(htmlEncode(script)); // 不會印出 hello
   
  function htmlEncode(value){
    // 建立一個暫存的div元素,並使用text()將內容存成html編碼文字後再用html()取出
    return $('<div/>').text(value).html();
  }
});
</script>

在jQuery的API文件中的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, ). 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.

不要使用append()來插入來源不明的url參數, cookies或使用者輸入的form表單的input資料,或是插入內容前先進行特殊字元的escape處理。


參考:

沒有留言:

AdSense