简体   繁体   English

如何防止javascript中的客户端DOM XSS漏洞?

[英]How to prevent Client DOM XSS vulnerability in javascript?

After checkmarx scan on my code,I am getting the below message.对我的代码进行 checkmarx 扫描后,我收到以下消息。

Method execute at line 23 of ...\action\searchFun.js gets user input for the form element.在 ...\action\searchFun.js 的第 23 行执行的方法获取表单元素的用户输入。

This element's value then flows through the code without being properly sanitized or validated and is eventually displayed to the user in function at line 28 of ../action/searchFun.js.然后,该元素的值在未经过适当清理或验证的情况下流经代码,并最终在 ../action/searchFun.js 的第 28 行的函数中显示给用户。 This may enable a DOM XSS attack.这可能会启用 DOM XSS 攻击。

Could some help me how to sanitize the above scenario to satisfy Checkmarx?有人可以帮助我如何清理上述场景以满足 Checkmarx 的要求吗? Script as follows:脚本如下:

function searchAnnouncements(){
  $('#loadingAnnouncements').html('Loading...');
  var formData = $('form').serialize();

  jQuery.ajax({
    type: "post",
    url:  "bat.ajax",
    data: formData,
    cache: false,
    dataType: "json",
    cache: false,
    success: function(json) {
      $('div.block').unblock();
      $('#loadingAnnouncements').html('');
      if (json.resultSize > 0)
        $('#searchResults').html(json.searchResult);
    });
  },
}

You can use DOMPurify library.您可以使用DOMPurify库。 https://github.com/cure53/DOMPurify https://github.com/cure53/DOMPurify

This should prevent XSS injection by keeping safe HTML tags.这应该通过保持安全的 HTML 标签来防止 XSS 注入。

function searchAnnouncements(){
  $('#loadingAnnouncements').html('Loading...');
  var formData = $('form').serialize();

  jQuery.ajax({
    type: "post",
    url:  "bat.ajax",
    data: formData,
    cache: false,
    dataType: "json",
    cache: false,
    success: function(json) {
      $('div.block').unblock();
      $('#loadingAnnouncements').html('');
      if (json.resultSize > 0)
        $('#searchResults').html(DOMPurify.sanitize(json.searchResult));
    });
  },
}

Try modifying your code to be similar to the following:尝试将您的代码修改为类似于以下内容:

function searchAnnouncements(){  
    $("#loadingAnnouncements").html("Loading...");
    var formData = $("#form").serialize();

    jQuery.ajax({
        type: "post",
        url:  "bat.ajax",
        data: formData,
        cache: false,
        dataType: "json",
        cache: false,
        success: function(json) {
            $("#div.block").unblock();
            $("#loadingAnnouncements").html('');
            if (json.resultSize > 0)
              $("#searchResults").html(DOMPurify.sanitize(json.searchResult));
        });   
    }, 
}

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

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