Cross site scripting attack is one of the high-rated web attacks.
In this blog, we will focus on the root cause of this attack in ASP.NET based applications. And why some existing controls fail to prevent this attack?
To understand the subject we will take the case of a search feature. Here the application accepts search keywords from the user and displays the results on the screen. If there are no matches for the text entered, it displays back an error message to the user saying, there are no results for the given keyword, as shown below:
Are you wondering what might have caused this issue?
Let’s try to find this out from its code. The code reveals that the keyword entered by the user is retrieved from the text box control and is used to look up the database. If the matching results are not found, its value is displayed back to the user. The “Response.Write” method is used in this case to display the output.
Same is the case with use of scriplets <%, <%# that are used to display un-validated data back to the users in views.
This is the main reason why applications are vulnerable to XSS attack. The user inputs are processed by the application and displayed back to the user without any validation.
So, are Response.Write and scriplets the only vulnerable instances?
What if the data is rendered through web controls?
Web Controls perform HTML encoding of the values that they render on the screen. Hence, they are safe to use, except for Labels and Literals.
If the untrusted inputs are displayed back using Label and Literal controls, as the one shown below, then they would still be vulnerable to XSS attack.
Implement the following controls to prevent against this attack:
- Encode the content before displaying it to the user – This can be done using available HTML encode functions/APIs.
- Do not assume that all web controls perform HTML encoding. Encode the data being displayed using web controls.
- Use Safer version of Scriplets to display data – The scriplets with a colon “<#: and <%: ” provide inbuilt HTML encoding, so all the variable displayed using them are encoded by default.
- Don’t turn off ValidateRequest – Validate Request is an inbuilt protection available with ASP.Net framework. It looks for html injection syntax in the user requests and prevents it from getting executed on the server.
- Whitelist validations using RegexValidators – In addition to HTML encoding, also perform input validation to allow only valid characters from the user. This will prevent the possibility of user carrying out any web attack using special characters.