javascript - 如何防止javascript中的Client DOM XSS漏洞?

标签 javascript jquery

checkmarx 扫描我的代码后,我收到以下消息。

Method execute at line 23 of ...\action\searchFun.js gets user input for the form element.

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. This may enable a DOM XSS attack.

有人可以帮助我如何清理上述场景以满足 Checkmarx 的要求吗? 脚本如下:

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);
    });
  },
}

最佳答案

您可以使用DOMPurify库。 https://github.com/cure53/DOMPurify

这应该通过保留安全的 HTML 标记来防止 XSS 注入(inject)。

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));
    });
  },
}

关于javascript - 如何防止javascript中的Client DOM XSS漏洞?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46300267/

相关文章:

javascript - 文件上传事件绑定(bind)

javascript - 此 JavaScript 文件在一个页面上运行,但在其他页面上不运行,这是为什么?

jQuery Bootstrap 动态选项卡(添加和删除)

javascript - 字符数据没有从 php 传递到 jquery

javascript - 模块模式中的私有(private)方法 : TypeError: undefined is not a function

javascript - 在 DOM 元素上强制执行更改事件而不实际更改它

javascript - 从 getElementsByTagName() 获取属性的最佳方法?

javascript - 需要函数等待事件处理程序完成后再执行下一个函数

javascript - ES6 更改对象值简写

jquery - 等待使用 JQuery 加载图像