XSS セーフのブログ エンジンでコメントを作成しようとしています。さまざまなアプローチを試しましたが、非常に難しいことがわかりました。
コメントを表示するときは、まずMicrosoft AntiXss 3.0を使用してすべてを html エンコードします。次に、ホワイトリスト アプローチを使用して安全なタグを html デコードしようとしています。
refactormycode の Atwood の「HTML のサニタイズ」スレッドで、 Steve Downing の例を見てきました。
私の問題は、AntiXss ライブラリが値を &#DECIMAL; にエンコードすることです。私の正規表現の知識が限られているため、スティーブの例を書き直す方法がわかりません。
エンティティを 10 進形式に単純に置き換えた次のコードを試しましたが、正しく動作しません。
< 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>
正規表現は、私が望まないホワイトリストのスクリプトと一致しています。これに関する任意の助けをいただければ幸いです。