I am tying to make comments in a blog engine XSS-safe. Tried a lot of different approaches but find it very difficult.
When I am displaying the comments I am first using Microsoft AntiXss 3.0 to html encode the whole thing. Then I am trying to html decode the safe tags using a whitelist approach.
Been looking at Steve Downing's example in Atwood's "Sanitize HTML" thread at refactormycode.
My problem is that the AntiXss library encodes the values to &#DECIMAL; notation and I don't know how to rewrite Steve's example, since my regex knowledge is limited.
I tried the following code where I simply replaced entities to decimal form but it does not work properly.
< with <
> with >
My rewrite:
class HtmlSanitizer
{
/// <summary>
/// A regex that matches things that look like a HTML tag after HtmlEncoding. Splits the input so we can get discrete
/// chunks that start with < and ends with either end of line or >
/// </summary>
private static Regex _tags = new Regex("<(?!>).+?(>|$)", RegexOptions.Singleline | RegexOptions.ExplicitCapture | RegexOptions.Compiled);
/// <summary>
/// A regex that will match tags on the whitelist, so we can run them through
/// HttpUtility.HtmlDecode
/// FIXME - Could be improved, since this might decode > etc in the middle of
/// an a/link tag (i.e. in the text in between the opening and closing tag)
/// </summary>
private static Regex _whitelist = new Regex(@"
^</?(a|b(lockquote)?|code|em|h(1|2|3)|i|li|ol|p(re)?|s(ub|up|trong|trike)?|ul)>$
|^<(b|h)r\s?/?>$
|^<a(?!>).+?>$
|^<img(?!>).+?/?>$",
RegexOptions.Singleline | RegexOptions.IgnorePatternWhitespace |
RegexOptions.ExplicitCapture | RegexOptions.Compiled);
/// <summary>
/// HtmlDecode any potentially safe HTML tags from the provided HtmlEncoded HTML input using
/// a whitelist based approach, leaving the dangerous tags Encoded HTML tags
/// </summary>
public static string Sanitize(string html)
{
string tagname = "";
Match tag;
MatchCollection tags = _tags.Matches(html);
string safeHtml = "";
// iterate through all HTML tags in the input
for (int i = tags.Count - 1; i > -1; i--)
{
tag = tags[i];
tagname = tag.Value.ToLowerInvariant();
if (_whitelist.IsMatch(tagname))
{
// If we find a tag on the whitelist, run it through
// HtmlDecode, and re-insert it into the text
safeHtml = HttpUtility.HtmlDecode(tag.Value);
html = html.Remove(tag.Index, tag.Length);
html = html.Insert(tag.Index, safeHtml);
}
}
return html;
}
}
My input testing html is:
<p><script language="javascript">alert('XSS')</script><b>bold should work</b></p>
After AntiXss it turns into:
<p><script language="javascript">alert('XSS')</script><b>bold should work</b></p>
When I run the version of Sanitize(string html) above it gives me:
<p><script language="javascript">alert('XSS')</script><b>bold should work</b></p>
The regex is matching script from the whitelist which I don't want. Any help with this would be highly appreciated.