This post is part of the series 'Vulnerabilities'. Be sure to check out the rest of the blog posts of the series!
- Impersonation and security
- SQL injections
- How to prevent CSRF attacks
- ASP MVC and XSRF
- Cross-site scripting (XSS) (this post)
- ASP MVC: Mass Assignment
- Regex - Deny of Service (ReDoS)
- Deserialization can be dangerous
- Prevent Zip bombs in .NET
- Prevent Zip Slip in .NET
- How to protect against XML vulnerabilities in .NET
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
>. 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.
iframe(potentially containing malicious code)
<iframe src="https://sitepirate.com" />
Show an annoying popup
<script>alert('Mon site est codé avec les pieds')</script>
The user will be redirected to the page
https://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 (Percent-encoding).
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!