防止使用innerHTML注入脚本 [英] Prevent script injection with innerHTML

查看:125
本文介绍了防止使用innerHTML注入脚本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经编写了一个微型模板实用程序,该实用程序可以根据用户输入(纯文本字符串或html字符串)使用innerHTML在网页中注入html片段.

I have written a micro-templating utility that uses innerHTML to inject html fragments in a Web page, based on user input (either plain text strings or html strings).

我主要担心的是恶意脚本注入的风险.可以通过脚本标签或在嵌入式事件(例如img onload,div onmouseover)中插入脚本.

My main concern is the risk of malicious script injection. The script could be injected via a script tag, or in an inline event (img onload, div onmouseover for example).

有没有办法清理html字符串以防止此类注入?另外,还有其他我应该注意的脚本注入方法吗?

Is there a way to sanitize the html string to prevent such injections? Also, are there other script injection methods I should be aware of?

推荐答案

如果您想安全起见,可以在客户端和服务器上清理模板.不要编写自己的反XSS库,因为恶意用户一定会知道您尚未考虑的漏洞;太多细微差别,除非您是XSS专家,否则您一定会错过的.

If you want to be safe, you'll sanitize your templates both on the client and the server. Don't write your own anti-XSS library as malicious users are bound to know an exploit that you haven't accounted for; there are just too many nuances and unless you're an XSS expert, you're bound to miss one.

在客户端, Google Caja HTML清理实用工具,它将对HTML字符串执行强大的清理,清除恶意属性或其他区域讨厌的用户可以在其中做讨厌的事情,例如通过注入 script 标签来进行XSS攻击.它们还清理属性和所有其他XSS注入点(例如, object applet 标记),因此您可以放心使用.

On the client side, Google Caja has a pretty nice HTML sanitization utility that will perform robust sanitization on HTML strings, cleaning up malicious attributes or other areas where nasty users can do nasty things, like XSS attacks via injecting script tags. They also scrub attributes and all kinds of other XSS injection points (object and applet tags, for instance), so you can feel fairly safe.

虽然您应该在服务器上进行清理以防止恶意用户简单地禁用javascript或覆盖Caja的清理器,但是您可以使用Caja清理输入和输出,以尽最大可能地捕获.

While you should sanitize on the server to prevent malicious users from simply disabling javascript or overwriting Caja's sanitizer, you can use Caja to sanitize both input and output to try to catch as much as you can.

这篇关于防止使用innerHTML注入脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆