Wednesday, July 02, 2008

Prevent XSS in ASP.net (Regular expression)

I've been working on the security of a web application to prevent the XSS (cross site scripting). I read many articles about how to handle this issue. There are two ways that I found is easy to implement and will prevent most of the XSS attack.

The first is to use HttpUtility.HtmlEncode in the code behind page. It will encode specially characters in the script code, so the script will not run when the page is rendered.

The second is to use the Regular Expression validator on the client side (I think custom validaor calling the System.Text.RegularExpressions.Regex.IsMatch(string input, string pattern) is most secure).

Here are some frequently use regular expressions I found on the web:

1. Name
"^([A-Za-z']|-|\s)+$"

2. Address (allow number, text only, ., -, and space. no special characters are allowed)
"^([a-zA-Z0-9.]|-|\s)+$"

3. Email
"^([\w\-\.]+)@((\[([0-9]{1,3}\.){3}[0-9]{1,3}\])|(([\w\-]+\.)+)([a-zA-Z]{2,4}))$"

4. Social Security #:
"\d{9}"

5. Date:
"^(([1-9])|(0[1-9])|(1[0-2]))\/(([0-9])|([0-2][0-9])|(3[0-1]))\/(([0-9][0-9])|([1-2][0,9][0-9][0-9]))$"

Regular Express Library

No comments: