xss 攻击 - 正则表达式或 htmlspecialchars
为了防止 xss 攻击,如果我使用 php 正则表达式来阻止像 '>
或 ;
这样的奇怪字符,我仍然需要使用 htmlspecialchars
和htmlentities
?
To prevent an xss attack, if I use a php regex to block strange characters like '>
or ;
do I still need to use htmlspecialchars
and htmlentities
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
![扫码二维码加入Web技术交流群](/public/img/jiaqun_03.jpg)
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
htmlspecialchars()
或htmlentities()
作为针对 XSS 攻击的保护手工制作的正则表达式。 但是,您必须考虑上下文。例如,htmlspecialchars()
将保护标记内的动态内容,但不在
标记或事件处理程序(例如
onclick
)内。在 html 注释中,编码不提供任何保护。编写不易受到 XSS 攻击的代码的关键是了解所有不同的攻击向量。有关 XSS 预防的完整详细信息,我推荐 OWASP XSS 备忘单。
htmlspecialchars()
orhtmlentities()
are recommended as protection from XSS attacks over a hand-crafted regex. But, you must take into account context. For example,htmlspecialchars()
will protect dynamic content inside a<div>
tag but not inside a<script>
tag or an event handler such asonclick
. Within html comments, no protection is offered by encoding. The key to writing code that is not vulnerable to XSS attacks is understanding all the different attack vectors.For the complete details on XSS prevention, I recommend the OWASP XSS cheatsheet.
也尝试使用:
html_entity_decode()
try use also:
html_entity_decode()
PDO 在保护您的查询免受 XSS 攻击方面非常有效。无需担心您是否记得保护您的查询,因为它是自动的。其他几个框架也支持此功能。
如果由于客户要求等原因我不使用 PDO,我至少会在我的连接类中构建一个自动 htmlspecialchars 函数,这样我就永远不会忘记这样做(尽管这是我最不喜欢的选项
) UI 人员,我总是首先从前端开始解决安全问题。正确且设计良好的前端验证可以阻止无意的问题,甚至可以从一开始就阻止查询,并且它们是向用户报告问题的最有效的 UI 模式。诸如
<
或;
之类的阻塞元素在大多数字段中都是有意义的,因为它们根本不适合。不过,您不能仅仅依赖前端,因为人们可以通过关闭 javascript 来绕过它。但是,这是一个很好的第一步,也是限制流量大的网站上的不当查询的好方法。我选择的快速有效的前端字段验证方法是 这里。PDO does a very effective job of protecting your queries from XSS attacks. No need to worry about whether or not you remembered to protect your queries, because it is automatic. Several other frameworks support this feature as well.
If I'm not using PDO because of a client requirement or the like, I will at the very least build into my connection class an automatic htmlspecialchars function so that I never forget to do it (though this is my least favorite option)
As a UI guy, I always attack my security issues starting on the --front-- end first. Proper and well-designed front-end validation can stop unintentional issues from even getting to the query in the first place, and they're the most effective UI pattern for reporting problems to the user. Blocking elements such as
<
or;
makes sense in most fields, because they just don't fit. You can't rely on the front end solely, though, because a person could bypass it by turning off javascript. But, it's a good first step and a great way to limit improper queries on heavily traffic-ed sites. My validation of choice for quick and effective front-end validation of fields is here.