title: How to prevent Javascript injection attacks within user-generated HTML
body: <p>I am saving user-submitted HTML (in a database). I must prevent JavaScript injection attacks.  The most pernicious I have seen is JavaScript in a <code>style=&quot;expression(...)&quot;</code>.</p>
  <p>In addition to this, a fair amount of valid user content will include special characters and XML constructs, so I'd like to avoid a white-list approach if possible. (Listing every allowable HTML element and attribute).</p>
  <p>Examples of JavaScript attack strings:</p>
  <p>1.</p>
  <pre><code>&quot;Hello, I have a
  &amp;lt;script&amp;gt;alert(&quot;bad!&quot;)&amp;lt;/script&amp;gt;
  problem with the &amp;lt;dog&amp;gt;
  element...&quot;
  </code></pre>
  <ol start="2">
  <li></li>
  </ol>
  <pre><code>&quot;Hi, this &amp;lt;b
  style=&quot;width:expression(alert('bad!'))&quot;&amp;gt;dog&amp;lt;/b&amp;gt;
  is black.&quot;
  </code></pre>
  <p>Is there a way to prevent such JavaScript, and leave the rest intact?</p>
  <p>The only solution I have so far is to use a regular expression to remove certain patterns. It solves case 1, but not case 2.</p>
  <p>The environment is essentially the Microsoft stack:</p>
  <ul>
  <li>SQL Server 2005</li>
  <li>C# 3.5  (ASP.NET)</li>
  <li>JavaScript and jQuery.</li>
  </ul>
  <p>I would like the chokepoint to be the ASP.NET layer - anyone can craft a bad HTTP request.</p>
  <h3>Edit</h3>
  <p>Thanks for the links, everyone. Assuming that I can define my list (the content will include many mathematical and programming constructs, so a whitelist is going to be very annoying), I still have a question:</p>
  <p>What kind of parser will allow me to just remove the &quot;bad&quot; parts?  The bad part could be an entire element, but then what about those scripts that reside in the attributes? I can't remove <code>&lt; a hrefs &gt;</code> willy-nilly.</p>