Javascript – How to prevent XSS (Cross Site Scripting) whilst allowing HTML input

asp.netchtmljavascriptxss

I have a website that allows to enter HTML through a TinyMCE rich editor control. It's purpose is to allow users to format text using HTML.

This user entered content is then outputted to other users of the system.

However this means someone could insert JavaScript into the HTML in order to perform a XSS attack on other users of the system.

What is the best way to filter out JavaScript code from a HTML string?

If I perform a Regular Expression check for <SCRIPT> tags it's a good start, but an evil doer could still attach JavaScript to the onclick attribute of a tag.

Is there a fool-proof way to script out all JavaScript code, whilst leaving the rest of the HTML untouched?

For my particular implementation, I'm using C#

Best Answer

Microsoft have produced their own anti-XSS library, Microsoft Anti-Cross Site Scripting Library V4.0:

The Microsoft Anti-Cross Site Scripting Library V4.0 (AntiXSS V4.0) is an encoding library designed to help developers protect their ASP.NET web-based applications from XSS attacks. It differs from most encoding libraries in that it uses the white-listing technique -- sometimes referred to as the principle of inclusions -- to provide protection against XSS attacks. This approach works by first defining a valid or allowable set of characters, and encodes anything outside this set (invalid characters or potential attacks). The white-listing approach provides several advantages over other encoding schemes. New features in this version of the Microsoft Anti-Cross Site Scripting Library include:- A customizable safe list for HTML and XML encoding- Performance improvements- Support for Medium Trust ASP.NET applications- HTML Named Entity Support- Invalid Unicode detection- Improved Surrogate Character Support for HTML and XML encoding- LDAP Encoding Improvements- application/x-www-form-urlencoded encoding support

It uses a whitelist approach to strip out potential XSS content.

Here are some relevant links related to AntiXSS:

Related Topic