【问题标题】:jquery.min.js violates CSP for inline-stylejquery.min.js 违反了内联样式的 CSP
【发布时间】:2021-11-11 19:00:25
【问题描述】:

我想将 CSP 标头添加到网络服务器。我不想添加“不安全内联”。我已使用“nonce”将所需的内联脚本和样式列入白名单,这似乎工作正常。但是,本地 jquery.min.js 似乎存在一些问题,因为它显示了许多内联样式的 CSP 违规错误。在 Chrome 调试器窗口中检查错误后,它指向 jquery.min.js 的以下行:

a.innerHTML = u[1] + S.htmlPrefilter(o) + u[2],

我不确定这有什么关系。有没有办法在不添加“unsafe-inline”的情况下消除 jquery.min.js 的这些 CSP 违规错误?

详情:

jquery.min.js 版本 => v3.5.1

CSP 政策 => default-src 'self' 'nonce-XXXX'; frame-ancestors 'self'; form-action 'self';

【问题讨论】:

    标签: jquery http-headers content-security-policy


    【解决方案1】:

    Jquery 与它无关。 a.innerHTML = u[1] + S.htmlPrefilter(o) + u[2] 构造用于调用 .html() / .append() / .prepend() 方法将 HTML 代码插入 DOM。

    由于这会导致 CSP 违规,这意味着您插入的 HTML 代码包含内联样式:<tag style='...'<style>...</style>。您有 2 个选择:

    • 重构 JS 代码以摆脱这种内联样式插入。
    • 使用this hackstyle=<style>...</style> 替换为与CSP 兼容的等效项。
      hack 的想法是覆盖 htmlPrefilter() 方法,默认情况下它是 empty,旨在根据您的需要重新定义。

    如果 style= 导致 CSP 违规,您可以使用类似:

    $.htmlPrefilter = function( html ) {
      // Really it have to be more complicated for replacing a tag's attributes only,
      // not just plain text replacement:
      return ( html + '' ).replace( / style=/gi, ' data-style=' );
      };
    

    那么当使用.html()/.append()/.prepend()方法时,所有style=inline_styles_here属性将被data-style='inline_styles_here'替换。

    为了 CSP 安全,将真正的 CSS 样式应用于您可以使用这样的脚本的标签:

    $(function() {   // On page loads
      var tags = document.querySelectorAll('[data-style]');
      for (var tag of tags) {
        var attr = tag.getAttribute('data-style')
        var arr = attr.split(';').map( (el, index) => el.trim() );
        for (var i=0, tmp; i < arr.length; ++i) {
          if (! /:/.test(arr[i]) ) continue;        // Empty or wrong style
          tmp = arr[i].split(':').map( (el, index) => el.trim() );
          tag.style[ camelize(tmp[0]) ] = tmp[1];
          }
        }
    
      function camelize(str) {
        return str
          .split('-')
          .map( (word, index) => index == 0 ? word : word[0].toUpperCase() + word.slice(1) )
          .join('');
        }
    
    )}
    

    Javascript 不是我的强项,重写上面的脚本以使用原生 jquery 调用。

    如果 &lt;style&gt;...&lt;/style&gt; 导致 CSP 违规,您可以重新定义 htmlPrefilter() 以将 &lt;style&gt; 替换为 &lt;style nonce='value'&gt;,但您必须以某种方式将“nonce”传递给脚本。

    【讨论】:

    • 非常感谢您!!!我已经替换了 javascript 中的所有 style="..." 内联样式。我认为问题在于您在 js 代码中指出了 .html() 和 .append() 调用。还有 .css() 调用。那么像 element.css("width", "10px") 这样的东西会导致内联样式吗?
    • element.css("width", "10px")CSP-compatible,不被视为内联样式。
    猜你喜欢
    • 1970-01-01
    • 2016-07-19
    • 1970-01-01
    • 1970-01-01
    • 2020-12-21
    • 2017-07-15
    • 2020-01-12
    • 2017-04-12
    • 2013-07-19
    相关资源
    最近更新 更多