How to prevent XSS in attributes

so I have a website where users can register using the username of their choice and can send large blocks of text and add comments. Currently, to prevent XSS, I use strip_tags for data entering the database, and I only output data in the body, not the attribute. I am currently making changes to the site, one of which is to create a custom page that loads when someone clicks on the username (link). It will look like this:

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

I'm worried that for the $ username variable, someone might insert

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

I read a bunch of other SO posts about this, but no one gave a black and white answer. If I use the following in all the text in the output, in addition to strip_tags in the input:

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

- will this be enough to stop all XSS attacks, including those that use inline javascript: syntax:?

Also, is there a way to remove the current html tags without removing things like "Me> you"?

Thanks!

+6
source share
2 answers

Shielding is context sensitive. If this is a URL, use the URL encoding (% xx), but also make sure the full URL does not start with "javascript:". Your onclick attribute syntax is not required. Onclick is a javascript event handler, so any javascript inside it will work.

Refer to the OWASP XSS Prevention winding sheet for how to escape for different contexts.

+1
source

According to the PHP5 testing guide, there are two golden safety rules:

  • Filter input
  • Escape Escape

You are currently looking at only one side of the problem.

But I would prefer htmlentities.

+3
source

Source: https://habr.com/ru/post/895037/


All Articles