XSS exploit protection?

I am new to PHP, but I heard that XSS exploits are bad. I know what it is, but how to protect my sites?

+7
source share
4 answers

To prevent XSS attacks, you just need to check and correctly verify all user input that you plan to use, and not allow html or javascript code to be inserted from this form. Or you can use htmlspecialchars () to convert HTML characters to HTML objects. Thus, characters like <> that mark the start / end of a tag are converted to html objects, and you can use strip_tags () to only allow tags, since the function does not highlight harmful attributes such as onclick or onload.

+10
source

Delete all user data (data in the database from the user) using the htmlentities () function .

For HTML data (for example, from WYSIWYG editors), use the HTML Cleaner to clear the data before storing it in the database.

+4
source

strip_tags() if you do not want to have any tags at all. Value of something like <somthinghere>
htmlspecialchars() will hide them until html, so the browser will show and not run.
If you want to allow good html, I would use something like htmLawed or htmlpurifier

0
source

Bad news

Unfortunately, preventing XSS in PHP is a nontrivial undertaking.

Unlike SQL injection , which you can soften using prepared statements and carefully selected white lists, there is no reliable way to separate the information you are trying to transfer your HTML document from the rest of the document structure.

Good news

However, you can mitigate known attack vectors, especially for fear of your shielding ( and updating your software up to date ).

The most important rule to keep in mind: Always exit at the exit, never at the entrance. You can safely cache your shielded output if you are concerned about performance, but always save and manage unescaped data.

XSS Reduction Strategies

In order of preference:

  • If you use a template engine (e.g. Twig, Smarty, Blade), make sure it offers context-sensitive escaping. I know from experience what Twig does. {{ var|e('html_attr') }}
  • If you want to enable HTML, use the HTML Cleaner . Even if you think that you accept only Markdown or ReStructuredText, you still want to clear HTML these markup languages.
  • Otherwise, use htmlentities($var, ENT_QUOTES | ENT_HTML5, $charset) and make sure that the rest of the document uses the same character set as $charset . In most cases, 'UTF-8' is the desired character set.

Why shouldn't I filter the input?

Attempting to filter XSS in the input for premature optimization , which can lead to unexpected vulnerabilities in other places.

For example, a recent WordPress XSS vulnerability used MySQL column truncation to break their escaping strategy and allow insecurely to prevent premature payload leakage. Do not repeat your mistake.

0
source

All Articles