…
processingalert('test');
Figure 10.4 XSS is similar to SQL injection, but the code is inserted in the markup and isn’t executed in a database query With identity theft, for example, an attacker could gain access to a website by simply cloning its identity cookie For this reason, you have to avoid XSS in your applications TECHNIQUE 62 Handling and displaying user input As we’ve stated previously, not trust user input This mantra applies to both SQL injection and XSS In our next scenario, the countermeasures might vary, depending on how you need to treat (and store) user input PROBLEM We want to avoid XSS and we want to let a user send different kinds of content: plain text and markup We need a method to sanitize the user input before saving it in a database SOLUTION ASP.NET, starting with version 1.1, is protected by default to malicious user input If you try to insert some markup or JavaScript code via a GET or POST field, the runtime intercepts the input and produces an error similar to the one shown in figure 10.5 272 CHAPTER 10 ASP.NET security Figure 10.5 ASP.NET has a default validation mechanism that can intercept potentially dangerous values and display a specific error page If you need basic protection against common kinds of attacks, this default behavior is what will help you first If you store your code to display it later in a page, it’s better to encode it properly in the first place Remember: not trust user input! You can implement this solution by using the HtmlEncode method from the HttpServerUtility or HttpUtility class in the System.Web namespace You can also access it directly via the Server property on both HttpContext and Page You need to write the following code in your markup: C#: string text = HttpUtility.HtmlEncode (SomeText.Text); VB: Dim text as String = HttUtility.HtmlEncode(SomeText.Text) New in version 4.0, this protection is applied to all requests (not just aspx pages) because it’s fired in the BeginRequest event of HttpApplication If you need to revert to the old behavior, you can change it via web.config: In version 4.0, you can tweak the default validation mechanism by writing a new class that inherits from System.Web.Util.RequestValidator and specifying its name in web.config: TECHNIQUE 62 273 Handling and displaying user input Figure 10.6 Without (on the left), and with (on the right) input encoding In the first example, the markup is processed by the browser because it’s not escaped Another way to allow blocked characters (like < or >, for example) is to set the ValidateRequest property on the @Page directive to false, which will help us in testing our new solution: Figure 10.6 shows you the result of using the encoding and of not using it Beginning in ASP.NET version 4.0, you can also use a handy shortcut and simply embed a value in the markup This same syntax is available with ASP.NET MVC 2.0, shipped with ASP.NET 4.0 C#: VB: The syntax