防止xss攻击的更好方法
这两种方法中哪一种是更好的防止 xss 攻击的方法?
- 时保存在 db
- HTMLEntities在显示/回显
HTMLEntities 中时我发现第一个更好,因为您可能会在显示时忘记添加它。
Which of the two is a better way to prevent an xss attack?
- HTMLEntities while saving in db
- HTMLEntities while displaying/echoing
I find the first one better because you may forget to add this while displaying.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
2 — 您应该在最后一刻转换为目标格式。例如,如果您决定在电子邮件、PDF 中使用相同的内容,作为文本返回给用户进行编辑等,这可以帮助您避免出现问题。
而在插入数据库时也可能会忘记。
此外,并非所有数据都会进入数据库。例如,由于错误而要插入的数据预览或放回到表单中的数据都是可能的 XSS 向量。您不想处理诸如“在放入数据库之前进行编码,或者如果文档不是来自数据库则在回显文档时进行编码”之类的事情。异常是让自己陷入忘记编码的情况的最好方法。
2 — you should convert to the target format at the last possible moment. This saves you from problems down the road should you, for example, decide you want to use the same content in an email, a PDF, as text back to the user for editing, etc, etc.
You might forget when inserting into the database too.
Also, not all data goes into the database. e.g. A preview of data about to be inserted or data put back into a form because of errors are both possible XSS vectors. You don't want to be dealing with things like "Encode before putting into the database, or when echoing back into the document if it didn't come from a database". Exceptions are the best way to get yourself into a situation where you forget to encode.
如果你问我,最好的方法(选项号 3..)是使用最新的 过滤器 扩展来为您处理过滤(PHP5)。我喜欢将 filter_input_array 放在我的 php 文件的顶部保护自己免受 POST XSS 攻击等攻击
您应该阅读过滤器文档(教程)并保护自己免受输入 XSS 攻击。
The best way(option number 3..) if you ask me is using the latest filter extension to handle filtering for you(PHP5). I like to put filter_input_array at the top of my php file to protect myself against for example POST XSS attacks
You should read the filter documentation(tutorials) and protect yourself against XSS for input.
在显示代码中进行编码的原因(即从数据库读取文本后):
我在写的时候想不出什么编码的理由。您提到人们可能会忘记在显示逻辑中对数据进行编码,但我认为您同样可能会在存储代码的数据库中忘记它。
Reasons for encoding in the display code (i.e. after reading text from the database):
I can't think of any reason for encoding when writing. You mention one may forget to encode data in the displaying logic, but I'd argue you're equally likely to forget it in the database storing code.
更好的方法是在保存到数据库之前使用
strip_tags()
和htmlentities()
(如果您不介意一些额外的数据位)。但是,请确保您还采取了其他预防措施,通过使用 mysql_real_escape_string() 或准备好的语句数据访问抽象层(例如 PDO)来防止 SQL 注入。
A better way would be
strip_tags()
andhtmlentities()
before saving to db (if you don't mind some extra bits of data).However, make sure you have taken other precautions as well to protect against SQL injection, by using
mysql_real_escape_string()
or a prepared statement data-access abstraction layer, such as PDO.