Cross Site Scripting (XSS) is an attack where attackers inject code into a website which is then executed. XSS is on place seven of the OWASP Top 10 list of 2017 but could be easily avoided. In this post, I will talk about the concepts of cross site scripting and how you can protect your application against these attacks.
What is Cross Site Scripting
Consequences of XSS Attacks
There are many possible consequences for your users if your website got attacked by cross site scripting:
- Attackers could read your cookies and therefore gain access to your private accounts like social media or bank
- Users may be redirected to malicious sites
- Attackers could modify the layout of the website to lure users into unintentional actions
- Users could be annoyed which will lead to damage to your reputation and probably a loss of revenue
- Often used in combination with other attacks like cross site request forgery (CSRF)
Best Practices against Cross Site Scripting Attacks
Preventing XSS attacks is pretty simple if you follow these best practices:
- Validate every user input, either reject or sanitize unknown character, for example, < or > which can be used to create
- Test every input from an external source
- Use markdown instead of HTML editors
Cross Site Scripting in ASP .NET Core
ASP .NET Core Is already pretty safe out of the box due to automatically encoding HTML, for example < gets encoded into <. Let’s have a look at two examples where XSS attacks can happen and how to prevent them. You can find the code for the demo on Github.
ASP .NET Core 3.1 Demo
XSS can occur when you display text which a user entered. ASP .NET Core automatically encodes text when you use @Model, but displays the code as it if if you use @Html.Raw.
Preventing XSS Attacks in forms
The following code creates a form where the user can enter his user name. The input is displayed once in a safe way and once in an unsafe way.
tag. When you enter the following code as your name:
and click submit, an alert windows will be displayed.
Preventing XSS Attacks in Query Parameters
In reality, an attacker wouldn’t display an alert box but try to access your cookies or redirect you to a malicious website.
This post showed what cross site scripting attacks are and how they can be executed. ASP .NET Core makes it very easy to prevent these attacks and to offer a great user experience to your users.
You can find the code for the demo on Github.