This post is part of the serie 'Vulnerabilities'. Be sure to check out the rest of the blog posts of the serie!
- Impersonation and security
- SQL injections
- How to prevent CSRF attacks
- ASP MVC and XSRF
- Cross-site scripting (XSS) (this post)
- ASP MVC: Mass Assignment
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
>. 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
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
", etc.), whereas in the last one it will be necessary to encode the URL (http://www.W3schools.com/tags/ref_urlencode.asp).
For more information about how to prevent XSS attacks, I'll let you read the OWASP guidelines.