内容安全策略拒绝v-html中的XSS攻击

问题描述

我希望我的Nuxt.js .vue文件中包含一个响应头Content-Security-Policy-Report-Only: script-src 'self' 'unsafe-inline'。下面是我的代码

<template>
  <div>
    <span v-html="xss"></span>
  </div>
</template>

<script>
export default {
  data() {
    return { xss: '<b onmouSEOver=alert("Wufff!")>click me!</b>' }
  }
}
</script>

我期望浏览器在span上悬停不会导致alert,但是尽管有Content-Security-Policy-Report-Only

解决方法

我无法发表评论,所以我发布了答案,因为我完全不理解这个问题(我听说过xhtml存在,从未听说过vhtml)。 <span>无法抵御XSS攻击。这会触发xss。

<html>
    <head>
        <title></title></head>
    <body>
        <span ><img src=x onerror=alert(1)></img></span>
</html>

请勿使用<span>作为缓解措施。您应该阅读unsafe-inline政策的内容。顾名思义,它允许攻击者在该页面上的任何脚本。因此,永远不要使用unsafe-inline来减轻XSS攻击。仅使用self或您信任的其他来源。简而言之,unsafe-inline是黑客的福气。顾名思义,这是不安全的政策

此主题更适用于security.stackexchange.com alert(1)

,

螺母头盔模块帮了我大忙。只需在 nuxt.config.js

中的以下代码段中添加
   helmet: {
     contentSecurityPolicy: {
       directives: {
         defaultSrc: ["'self'"],scriptSrc: ["'self'","'unsafe-eval'"]
       }
     }
   }