我想在博客引擎 XSS 安全中发表评论。尝试了很多不同的方法,但发现非常困难。
当我显示评论时,我首先使用Microsoft AntiXss 3.0对整个内容进行 html 编码。然后我尝试使用白名单方法对安全标签进行 html 解码。
在 refactormycode 的 Atwood 的“Sanitize HTML”线程中查看Steve Downing 的示例。
我的问题是 AntiXss 库将值编码为 &#DECIMAL; 符号,我不知道如何重写史蒂夫的例子,因为我的正则表达式知识有限。
我尝试了以下代码,我只是将实体替换为十进制形式,但它不能正常工作。
< with <
> with >
我的重写:
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;
}
}
我的输入测试html是:
<p><script language="javascript">alert('XSS')</script><b>bold should work</b></p>
AntiXss 之后变成:
<p><script language="javascript">alert('XSS')</script><b>bold should work</b></p>
当我运行上面的 Sanitize(string html) 版本时,它给了我:
<p><script language="javascript">alert('XSS')</script><b>bold should work</b></p>
正则表达式匹配我不想要的白名单中的脚本。对此的任何帮助将不胜感激。