Varad, The .NET Guy!

Exploring the excitement of Microsoft .NET and much more..

Prevent Cross-site Scripting

Cross-site scripting vulnerabilities are Web-specific issues and can compromise a client's data through a flaw in a single Web page.  Imagine the following ASP.NET code fragment:

 <script language=c#>

     Response.Write("Hello, " + Request.QueryString("name"));

 </script>

 How many of us have written or seen code like this? You may be surprised to learn that its buggy!

 Normally, a user would access this code using a URL that looks like this:

 http://MyWeb.com/welcome.aspx?name=Varad

 The C# code assumes that the data is always well formed and contains nothing more than a name.  Attackers, however, abuse this code and provide script and HTML as the name. If you typed the following URL

 alert('hi!');http://MyWeb.com/welcome.aspx?name=<script>alert('hi!');</script>

 You’d get a Web page that displays a dialog box, saying "hi!"

 "So what?" you say. Well, imagine that the attacker convinces a user to click on a link like this, but the querystring contains some really nasty script and HTML to  get  your  cookie and post it to a site that the attacker owns; the attacker now has your private cookie information or worse.

There are two ways to avoid Cross-site scripting.

The first is not to trust the input and be strict about what comprises a user's name.  For example, you could use regular expressions to check that the name contains only a common subset of characters and is not too big. The following C# code snippet shows the way that you can accomplish this
 

      //please include this namespace to run this code snippet

      //using System.Text.RegularExpressions;


      Regex rg = new Regex(@"^[\w]{1,40}$");

 

      if (rg.Match(vpuCode).Success)

      {

            // Cool! The string is ok

      }

      else

      {

            // Not cool! Invalid string

      }


This code uses a regular expression to verify that a string contains between 1 and 40 alphanumeric characters and nothing else. This is the only safe way to determine whether a value is correct.

Don’t use a regular expression to look for invalid characters and reject the request if such characters are found because there is always a case that will slip by you.

The second defense is to HTML-encode all input when it is used as output. This will reduce dangerous HTML tags to more secure escape characters. You can escape any  strings that might be a problem in ASP.NET with HttpServerUtility.HtmlEncode, or in ASP with Server.HTMLEncode.

 

Posted: Feb 16 2005, 08:36 PM by Varad | with 2 comment(s)
Filed under:

Comments

TrackBack said:

^_^,Pretty Good!
# April 10, 2005 8:18 AM

Is Your Web Site or App Secure? Preventing Cross-Site Scripting Attacks said:

Pingback from  Is Your Web Site or App Secure? Preventing Cross-Site Scripting Attacks

# April 27, 2011 3:36 PM