How to: Protect Against Script Exploits in a Web Application by Applying HTML Encoding to Strings

Most scripting exploits occur when users can get executable code (or script) into your application. By default, ASP.NET provides request validation, which raises an error if a form post contains any HTML.

You can help protect against script exploits in the following ways:

  • Perform parameter validation on form variables, query-string variables, and cookie values. This validation should include two types of verification: verification that the variables can be converted to the expected type (for example, convert to an integer, convert to date-time, and so on), and verification of expected ranges or formatting. For example, a form post variable that is intended to be an integer should be checked with the Int32.TryParse method to verify the variable really is an integer. Furthermore, the resulting integer should be checked to verify the value falls within an expected range of values.

  • Apply HTML encoding to string output when writing values back out to the response. This helps ensure that any user-supplied string input will be rendered as static text in the browsers instead of executable script code or interpreted HTML elements.

HTML encoding converts HTML elements using HTML–reserved characters so that they are displayed rather than executed.

To apply HTML encoding to a string

  • Before displaying strings, call the HtmlEncode method. HTML elements are converted into string representations that the browser will display rather than interpret as HTML.

    The following example illustrates HTML encoding. In the first instance, the user input is encoded before being displayed. In the second instance, data from a database is encoded before being displayed.

    Note

    This example will only work if you disable request validation in the page by adding the @ Page attribute ValidateRequest="false". It is not recommended that you disable request validation in a production application, so make sure that you enable request validation again after viewing this example.

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e _
        As System.EventArgs) Handles Button1.Click
            Label1.Text = Server.HtmlEncode(TextBox1.Text)
            Label2.Text = _
                Server.HtmlEncode(dsCustomers.Customers(0).CompanyName)
    End Sub
    
    private void Button1_Click(object sender, System.EventArgs e)
    {
        Label1.Text = Server.HtmlEncode(TextBox1.Text);
        Label2.Text = 
            Server.HtmlEncode(dsCustomers1.Customers[0].CompanyName);
    }
    

See Also

Concepts

Script Exploits Overview

Overview of Web Application Security Threats

Basic Security Practices for Web Applications