views:

293

answers:

2

What security protection does HTML.Encode() afford me when I'm dealing with user input, specifically scripting problems?

+5  A: 

Please see Server.HTMLEncode:

The HTMLEncode method applies HTML encoding to a specified string. This is useful as a quick method of encoding form data and other client request data before using it in your Web application. Encoding data converts potentially unsafe characters to their HTML-encoded equivalent.

If the string to be encoded is not DBCS, HTMLEncode converts characters as follows:

  • The less-than character (<) is converted to &lt;.
  • The greater-than character (>) is converted to &gt;.
  • The ampersand character (&) is converted to &amp;.
  • The double-quote character (") is converted to &quot;.
  • Any ASCII code character whose code is greater-than or equal to 0x80 is converted to &#<number>, where is the ASCII character value.

This means that if you are going to dump some data to the request stream and that data was saved to the database from a user-entered field it will prevent users from being able to say that their first name is:

<script type="text/javascript">
    function doSomethingEvil() { /* ... */ }
</script>

In this example, Server.HTMLEncode would encode the <, >, and " characters leaving this:

&lt;script type=&quot;text/javascript&quot;&gt;
    function doSomethingEvil() { /* ... */ }
&lt;/script&gt;

which, if rendered in the browser will look like this:

<script type="text/javascript"> function doSomethingEvil() { /* ... */ } </script>

rather than actually executing.

Andrew Hare
That's a great explanation! I'm putting that to use ASAP!
Achilles
+1  A: 

it prevents XSS (cross site scripting) attacks, since if it prevents users input to turn into scripts that can be used to perform this type of attack

BlackTigerX