Wednesday, January 08, 2014

C# : Cross site scripting and quotes

Busy developing a web site (ASP.NET, C#, Windows Forms, .NET Framework 4) and I got some security gurus to help do some security / penetration testing.

The site has some forms where you enter user details into text boxes. This is stored in a DB. You can search for users and the results are displayed in a grid e.g. first name, last name, email, roles etc.

So if you entered some Javascript into the last name text box e.g.

script Alert ('XSS error'); /script

(insert your own angle brackets!)

this would be written to the DB and when the grid displayed the next tine, you would see the Alert - the dreaded XSS syndrome.

Microsoft has a library to handle this - the somewhat maligned AntiXSS.

This has methods for HTML encoding, CSS encoding, URL encoding, injection etc.

So e.g. you can use:

AntiXssEncoder.HtmlEncode(lastname, true);

If someone types:

 script Alert ('XSS error'); /script

as a last name, this is encoded as:
<script>Alert (‘XSS Error’);</script>

which is harmless.

Now that's all well and good but you will note from the above that the single quote "'" is also encoded.

So what happens when you have someone with a name of O'Reilly?

Bad stuff happens - that's what!

What is saved is:


There are many Google hits around the fact that the library is actually too strict etc. etc.

What I do is after the encoding, is:

lastname.Replace("& # 3 9 ;''", "'");     // Remove the spaces

So it's back to the single quote.

 You could also use something like:

Sanitizer.GetSafeHtmlFragment (lastname);

which removes a few HTML elements like script - so in this case there's just an empty string.

And for injection e.g. LDAP, you can use:



No comments: