消毒粘贴输入

tjh*_*nce 5 javascript copy-paste contenteditable

假设我复制了一些“恶意”输入,例如带有事件处理程序或其他 JavaScript 的 DOM 节点

<img src="bunny.jpg" onload="alert('hi');">
Run Code Online (Sandbox Code Playgroud)

如果我将其复制到剪贴板并将其粘贴到contenteditablediv 中,则事件处理程序将被干净地删除。

<img src="/Users/tjhance/Desktop/bunny.jpg">
Run Code Online (Sandbox Code Playgroud)

我现在可以随心所欲地操纵这个 DOM 节点了。到目前为止还不错。

另一方面,假设我想挂钩浏览器的粘贴事件并以我自己的方式处理粘贴。我可以轻松获取剪贴板数据:

<div contenteditable="true" id="myContentEditableDiv"></div>

<script>

$('#myContentEditableDiv').on('paste', function(event) {
    console.log(event);
    var pastedHtml = event.originalEvent.clipboardData.getData('text/html');
    console.log(pastedHtml);
});

</script>
Run Code Online (Sandbox Code Playgroud)

当我粘贴时,我得到了 HTML

<meta charset='utf-8'><img src="/Users/tjhance/Desktop/bunny.jpg" onload="alert('hi');" style="color: rgb(0, 0, 0); font-family: Times; font-size: medium; font-style: normal; font-variant: normal; font-weight: normal; letter-spacing: normal; line-height: normal; orphans: auto; text-align: start; text-indent: 0px; text-transform: none; white-space: normal; widows: 1; word-spacing: 0px; -webkit-text-stroke-width: 0px;">
Run Code Online (Sandbox Code Playgroud)

它未经消毒,并且仍然具有事件侦听器。据我所知,我无法用这个字符串做任何事情。我无法使用浏览器将其解析为 HTML,因为它会运行 JavaScript,这是一个巨大的安全漏洞。

很明显,浏览器具有一定的清理 HTML 的功能,因为它是在粘贴时执行的。因此,如果我想要干净的 HTML,我可以等待事件完成并将 HTML 添加到 DOM。当然,如果我同意这样做,我就不会在这里发帖......

所以我的问题是,有什么方法可以获取潜在的脏 HTML 并获得干净、安全的 DOM 节点来使用浏览器 DOM api 进行操作,而无需浏览器将 HTML 实际粘贴到 contenteditable div(用户可以看到)中?我在这里有什么选择?

Tim*_*own 1

在所有浏览器都支持获取剪贴板数据之前,您可以使用这种古老的技巧,尽管它不是很好。最大的缺点是它只适合通过键盘粘贴。

另一种选择是自己清理 HTML 字符串。作为起点我想到的选项是DOMParserdocument.implementation.createHTMLDocument。我不确定它们有多安全;快速搜索发现了这个:

https://security.stackexchange.com/questions/50970/is-it-safe-to-use-createhtmldocument-to-sanitize-html


归档时间:

查看次数:

3353 次

最近记录:

10 年,3 月 前