当前位置: 首页 > news >正文

Vue: v-html安全性问题

一、问题描述

在这里插入图片描述

可能都知道使用v-html插入富文本,存在安全隐患,比如 cross-site scripting attack(xss)。但具体什么情况下v-html会引发安全问题呢?是否内容中含有<scrpit>标签就会触发执行脚本呢?

二、问题探究

写个简单的代码来看看:

<template><div v-html="content" />
</template>
<script setup lang="ts">
const content = `<script>alert('XSS Attack')<\/script>`
</script>

在这里插入图片描述

可以看到script节点成功的插入文档,但页面并没有出现相应的弹框。通过文档可以看到v-html是通过修改innerHtml来实现的,当然也可以从源码里看到:

在这里插入图片描述

那么换成innerHTML的方式动态插入试试:

在chrome DevTools中的元素面板下选中目标节点,在控制台中输入:

const name = "<script>alert('XSS Attack')</script>";
$0.innerHTML = name; 

可以发现依然没有任何作用,那是因为在HTML标准中规定使用innerHtml插入script标签时不会执行里面的任何代码:

Although this may look like a cross-site scripting attack, the result is harmless. HTML specifies that a <script> tag inserted with innerHTML should not execute.

但这并不代表这种动态插入的方式没有安全问题:

<template><div v-html="content" />
</template>
<script setup lang="ts">
const content = `<img src=x οnerrοr="alert('XSS Attack')">`
</script>

可以看到终于出现了:
在这里插入图片描述

三、解决方案

为了避免v-html潜在的安全隐患,可以使用dompurify(先安装dompurify):

DOMPurify sanitizes HTML and prevents XSS attacks. You can feed DOMPurify with string full of dirty HTML and it will return a string (unless configured otherwise) with clean HTML. DOMPurify will strip out everything that contains dangerous HTML and thereby prevent XSS attacks and other nastiness. It’s also damn bloody fast. We use the technologies the browser provides and turn them into an XSS filter. The faster your browser, the faster DOMPurify will be.

使用方法:

<template><div v-html="content" />
</template>
<script setup lang="ts">
import DOMPurify from 'dompurify';
const content = DOMPurify.sanitize(`<img src=x οnerrοr="alert('XSS Attack')">`)
</script>

http://www.mrgr.cn/news/4549.html

相关文章:

  • Go语言基础--嵌套循环(多重循环)
  • 论文翻译:Universal and Transferable Adversarial Attacks on Aligned Language Models
  • [数据集][目标检测]街灯路灯检测数据集VOC+YOLO格式1893张1类别
  • LCP9回文数[leetcode-9-easy]
  • vue面试题十七
  • 【原创】java+swing+mysql学生请假管理系统设计与实现
  • 小米便签——ui包详细解读
  • Unity3D URP 后处理如何作用于 UI 控件 Image 的详解
  • 大型语言模型(LLM)——直接偏好优化完整指南
  • 【Python爬虫】教你追剧看电影不求人!python爬虫代码教你爬取各平台视频,小白也能学会!附源码
  • 【Electron】桌面应用开发快速入门到打包Windows应用程序
  • hostapd生成beacon_ie
  • C语言破墙镐对称飞迷宫
  • 索引的数据结构
  • 《Cloud Native Data Center Networking》(云原生数据中心网络设计)读书笔记 -- 07数据中心的边缘
  • XSS game复现(DOM型)
  • Golang | Leetcode Golang题解之第354题俄罗斯套娃信封问题
  • 黑神话:悟空游戏用的什么服务器?
  • 构建艺术:Ruby中RESTful API的精粹实践
  • 【数据分析】时间滞后相干性分析