最佳实践:用户生成的 HTML 清理
我正在 iframe 上编写一个 WYSIWYG 编辑器宽度 designMode="on" 。编辑器工作正常,我将代码按原样存储在数据库中。
在输出 html 之前,我需要在服务器端使用 php 进行“清理”,以避免跨站点脚本和其他可怕的事情。是否有某种关于如何做到这一点的最佳实践?哪些标签可能是危险的?
更新:错字已修复,所见即所得。没什么新意:)
I'm coding a WYSIWYG editor width designMode="on" on a iframe. The editor works fine and i store the code as is in the database.
Before outputing the html i need to "clean" with php on the server-side to avoid cross-site-scripting and other scary things. Is there some sort of best practice on how to do this? What tags can be dangerous?
UPDATE: Typo fixed, it's What You See Is What You Get. Nothing new :)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
最佳实践是只允许某些您知道不危险的事情,并删除/逃避所有其余的事情。请参阅论文自动恶意攻击Web 上的代码检测和删除 (OWASP AntiSamy) 对此进行了讨论(该库适用于 Java,但原则适用于任何语言)。
The best practice is to allow only certain things you know aren't dangerous, and remove/escape all the rest. See the paper Automated Malicious Code Detection and Removal on the Web (OWASP AntiSamy) for a discussion on this (the library is for Java, but the principles apply for any language).
如果您确实愿意允许这样做,则应该使用白名单方法。
最好的方法可能是禁止 HTML 并使用简化的标记格式;如果性能是一个问题,您可以预渲染为 HTML 并将其存储在数据库中。避免此类问题是使用 Markdown、纺织品,reStructuredText 等
注意:我链接到 GitHub 风格的 Markdown (GFM),而不是标准 Markdown (SM)。 GFM 解决了最终用户使用 SM 时遇到的一些常见问题。
If you're really bent on allowing this, you should use a white list approach.
The best approach is probably to disallow HTML and use a simplified markup format instead; you can pre-render to HTML and store that in the database if performance is a concern. Avoiding these sorts of problems is one of the big reasons for using Markdown, Textile, reStructuredText, etc.
NOTE: I linked to GitHub-Flavored Markdown (GFM), not Standard Markdown (SM). GFM addresses some common problems that end-users have with SM.
我最近用 Perl 作为服务器端语言研究了同样的问题。
在这样做的过程中,我遇到了 HTML Purifier 这可能就是你想要的。但显然,由于它是用 PHP 而不是 Perl 编写的,所以我没有实际测试它。
另外,在我的研究中,我得出的结论是,这是一项非常棘手的业务,并考虑是否可能使用简化的标记语言,如 Hank Gay 所建议的 Markdown。
I looked into the same question recently with Perl as the server-side language.
While doing so I ran into HTML Purifier which may be what you want. But obviously as it's in PHP and not Perl, I didn't actually test it out.
Also, in my research I came to the conclusion that this is a very tricky business and consider if possible using a simplified markup language like Markdown, as suggested by Hank Gay.
如果您熟悉 ASP .NET,只需执行 Server.htmlencode() 即可转换特殊字符,例如 < >到“>” “<”
在 php 中,您可以使用 htmlspecialchars() 函数。
一旦对特殊字符进行编码,就可以防止跨站点脚本编写。
If you are familiar with ASP .NET, just perform a Server.htmlencode() to convert special characters like < > to "& g t;" "&l t ;"
In php, you can use htmlspecialchars() functions.
Once the special characters are encoded, cross-site-scripting can be prevented.