Home » XSS Vulnerability (Cross-site Scripting)

Categorised in: Better Web Experience

Cross-site scripting (XSS) is a web application vulnerability caused by insufficient output escaping. It allows attacker to inject JavaScript code into your site pages.

For example, if your website has comments, an attacker may add the following text as a comment:

alert('Hello from a hacker');

If there’s no filtering and comment is published as is, every user who visits the page will get “Hello from hacker” alert box which means JavaScript is executed. With JavaScript attackers can do virtually anything.

To avoid that, it is recommended to properly encode the output.

Output escaping

In Yii2 (our favorite framework), it is quite easy to do that.

If you’re sure you’ll have just text in your data, you can escape it in the view with Html::encode() while outputting it:

php echo Html::encode($post);

If you need to output HTML anyway

In case you need to output HTML entered by user it’s getting a bit more complicated. Yii has a built in HtmlPurifier helper which cleans up everything dangerous from HTML. In a view you may use it as the following:

echo HtmlPurifier::process($post);

Note: HtmlPurifier isn’t fast so consider caching what’s produced by HtmlPurifier not to call it too often.

Leave a reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.