June 5th, 2006
HOWTO: Anti-XSS w/ ASP.NET and C#C#, by jay.
This HOWTO was a specific requirement of my job so I can't go into to great detail nor-can I give you all of the source code. What I am going to cover is building an XSS filter to use in your ASP.NET app.
Trying to stop every kind of XSS can be and is a full-time job. It's like trying to stop the rain from falling on your lawn. Sure you can get a huge tent to cover the whole lawn but then the wind will start blowing it in side-ways.
One of the most important things you can do is validate and scrutinize every price of information a user enters into you web app. Everything.
The list of things you need to do secure app is nearly endless. I am not going to go into detail on what to do because if you've gotten this far then you certainly know how to use google.
The XSS Filter
Like I said before I cannot give you all of the source code but I can give some.
Build this filter requires very good knowledge of RegEx for instance take the following line of code:
It looks like a bunch of crap but what it is doing is creating a RegEx that will look for a string like:
<j a v a s c r i p t
causes a RegEx Exception.
Now that you've got a RegEx defined that you need to use it in a RegEx function:
RegexOptions options = RegexOptions.IgnoreCase;
Regex regex = new Regex(regX, options);
string result = regex.Replace(strIn.ToLower(), replacement);
This function has 2 parameters: 1) the string that needs to be checked for exploits and 2) the string you want to replace the charters with.
The real work in all of this is creating the RegEx to filter out the XSS. If you know what you are doing you will build your self a class that has a private function Then you'll create a public function that takes a string to be filtered, an enum of filter types and the replacement string which has a switch statement that get the RegEx filter using the enum value. Once you've got the RegEx filter pass it to another function takes a string to be filtered, the RegEx filter and the replacement string.
One for the Road
This last RegEx filter will find tags in the text:
private string unwantedTags = "</*(table|drop|delete|applet|meta|xml|blink|link|style|script|embed|object|iframe|frame|frameset|ilayer|layer|bgsound|title|base)[^>]*>";
- This site has a nice list of XSS Attacks
- Foiling Cross-Site Attacks - Good Info
- The Cross Site Scripting FAQ - Must read
- Wikipedia: Cross-site scripting
- ASP.NET Security stuff I did not talk about.
- Good source of RegEx's