Javascript – Preventing Javascript and XSS attacks

asp.netjavascriptxss

I'm xss-proofing my web site for javascript and xss attacks. It's written in ASP.NET Webforms.

The main part I'd like to test is a user control that has a textbox (tinyMCE attached to it).

Users can submit stories to site by writing in this textbox. I had to set validateRequest to false since I want to get users' stories in HMTL (tinyMCE).

How should I prevent javascript-xss attacks? Since users' stories are HMTL texts, I cannot use Server.HtmlEncode on their stories. In general, what's the safe way to receive HTML content from user, save and then display it to users?

If one user puts malicious code in the textbox and submits it, is there a chance that this could harm other people who view that text?
Thanks.

Best Answer

If you don't clean what the user puts in the textbox and submits, then yes, there is a chance for harm to be done.

You might want to check out the Microsoft Anti-Cross Site Scripting Library, as it is designed to help developers prevent just such attacks.

Also worth taking a look at is OWASP's Cross-site Scripting (XSS)

You might want to look into HttpUtility.HtmlEncode and HttpUtility.HtmlDecode as well. I just wrote a quick test, and it looks like it might address your concern in the comment below (about how to display the data to other users in the right format):

string htmlString = "<b>This is a test string</b><script>alert(\"alert!\")</script> and some other text with markup <ol><li>1234235</li></ol>";

string encodedString = HttpUtility.HtmlEncode(htmlString);
// result = &lt;b&gt;This is a test string&lt;/b&gt;&lt;script&gt;alert(&quot;alert!&quot;)&lt;/script&gt; and some other text with markup &lt;ol&gt;&lt;li&gt;1234235&lt;/li&gt;&lt;/ol&gt;

string decodedString = HttpUtility.HtmlDecode(encodedString);
// result = <b>This is a test string</b><script>alert("alert!")</script> and some other text with markup <ol><li>1234235</li></ol>

ASP.NET Controls and HTMLEncode I was going to post the information I had from my class, but I found a link that lists the exact same thing (for 1.1 and 2.0), so I'll post the link for easier reference. You can probably get more information on a specific control not listed (or 3.0/3.5/4.0 versions if they've changed) by looking on MSDN, but this should serve as a quick start guide for you, at least. Let me know if you need more information and I'll see what I can find.

ASP.NET Controls Default HTML Encoding

Here's a more comprehensive list from one of the MSDN blogs: Which ASP.NET Controls Automatically Encodes?