简体   繁体   English

如何防止属性中的 XSS

[英]How to prevent XSS in attributes

so I have a site where users can register using a username of their choosing and can submit large blocks of text and add comments.所以我有一个网站,用户可以使用他们选择的用户名进行注册,并且可以提交大量文本并添加评论。 Currently, to avert XSS, I use strip_tags on the data on input to the database and I only output the data in the body, rather than in an attribute.目前,为了避免 XSS,我在输入到数据库的数据上使用 strip_tags,并且我只在正文中使用 output 数据,而不是在属性中。 I'm currently making changes to the site, one of which is to make a user page which is loaded when someone clicks on the username (a link).我目前正在对该站点进行更改,其中之一是创建一个用户页面,当有人单击用户名(链接)时加载该页面。 This would look like:这看起来像:

<a href="example.com/user/<?php echo $username; ?>">...</a>

I'm worried that for the $username variable, someone could insert我担心对于 $username 变量,有人可能会插入

<a href="example.com/user/user" onClick="javascript:alert('XSS');">...</a>

I've read a bunch of the other SO posts on this, but none gave a black-and-white answer.我已经阅读了很多关于此的其他 SO 帖子,但没有一个给出黑白答案。 If I use the following on all text on output, in addition to strip_tags on input:如果我在 output 上的所有文本上使用以下内容,除了输入上的 strip_tags:

echo htmlspecialchars($string, ENT_QUOTES, 'UTF-8');

is that going to be enough to stop all XSS attacks, including those using the inline javascript: syntax?这是否足以阻止所有 XSS 攻击,包括那些使用内联javascript:语法的攻击?

Also, is there any way to remove actual html tags without removing things like "Me > you"?另外,有什么方法可以删除实际的 html 标签而不删除“我>你”之类的东西?

Thanks!谢谢!

According to the PHP5 Certification Study guide, there are two golden rules about security:根据 PHP5 认证学习指南,关于安全性有两条黄金法则:

  1. Filter input过滤器输入
  2. Escape output逃生 output

At the moment you are only looking at one side of the problem.目前,您只关注问题的一方面。

But I would prefer htmlentities.但我更喜欢htmlentities。

Escaping depends on the context. Escaping 取决于上下文。 If it's a URL, use URL encoding (%xx), but also check that the full URL does not start with "javascript:".如果是 URL,请使用 URL 编码 (%xx),但还要检查完整的 URL 是否以“javascript:”开头。 Your syntax for the onclick-attribute is not required.您的 onclick-attribute 语法不是必需的。 Onclick is a javascript event handler, so any javascript inside it will run. Onclick 是一个 javascript 事件处理程序,因此其中的任何 javascript 都将运行。

See the OWASP XSS Prevention Cheat sheet to see how to escape for different contexts.请参阅 OWASP XSS 预防备忘单,了解如何针对不同的上下文进行转义。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM