
AngleSharp を使用して HTML フラグメントやドキュメントをサニタイズし、タグ、属性、CSS プロパティ、URI スキームの設定可能な許可リストによって XSS ベクターを除去する .NET ライブラリです。
HtmlSanitizer は、XSS 攻撃につながる可能性のある構文から HTML フラグメントやドキュメントをクリーンアップするための .NET ライブラリです。 HTML と CSS の解析、操作、レンダリングには AngleSharp を使用します。
HtmlSanitizer は堅牢な HTML パーサーに基づいているため、あるフラグメント内の不正な HTML がドキュメント全体を破損させ、レイアウトやスタイルの崩れを引き起こすような、意図的または偶発的な 「タグポイズニング」からも保護できます。
さまざまなユースケースに対応するため、HtmlSanitizer は複数のレベルでカスタマイズできます:
AllowedTags を通じて、許可する HTML タグを設定します。それ以外のタグはすべて除去されます。AllowedAttributes を通じて、許可する HTML 属性を設定します。それ以外の属性はすべて除去されます。AllowedCssProperties を通じて、許可する CSS プロパティ名を設定します。それ以外のスタイルはすべて除去されます。AllowedAtRules を通じて、許可する CSS at-rule を設定します。それ以外の at-rule はすべて除去されます。AllowedSchemes を通じて、許可する URI スキームを設定します。それ以外の URI はすべて除去されます。UriAttributes を通じて、URI を含む HTML 属性 ("src"、"href" など) を設定します。UriListAttributes を通じて、URI のリストを含む HTML 属性 ("srcset"、"ping" など) を設定します。各エントリは個別にチェックされます。SanitizeFragment() を通じて、<body> ではなく、挿入先の要素に合わせてフラグメントをサニタイズします。これにより、ツリーのより深い位置でのみ有効な単独の <th> などのマークアップが保持されます。HtmlSanitizerOptions オブジェクトをコンストラクタに渡すことで一度に設定できます。new HtmlSanitizerOptions() は new HtmlSanitizer() と同じデフォルト値で事前に設定されているため、変更したい項目だけを設定すれば済みます。まっさらな状態から始めたい場合は代わりに HtmlSanitizerOptions.Empty() を使用してください。詳細は HtmlSanitizerOptions による設定を参照してください。HtmlSanitizer NuGet パッケージをインストールします。次に:
using Ganss.Xss;
var sanitizer = new HtmlSanitizer();
var html = @"<script>alert('xss')</script><div onload=""alert('xss')"""
+ @"style=""background-color: rgba(0, 0, 0, 1)"">Test<img src=""test.png"""
+ @"style=""background-image: url(javascript:alert('xss')); margin: 10px""></div>";
var sanitized = sanitizer.Sanitize(html, "https://www.example.com");
var expected = @"<div style=""background-color: rgba(0, 0, 0, 1)"">"
+ @"Test<img src=""https://www.example.com/test.png"" style=""margin: 10px""></div>";
Assert.Equal(expected, sanitized);
オンラインデモがあり、さらに遊べる.NET Fiddleもあります。
より多くのサンプルコードと利用可能なオプションの説明はWikiにあります。
HtmlSanitizerOptions による設定サニタイザーは、HtmlSanitizerOptions オブジェクトをコンストラクターに渡すことで一度に設定することもできます。HtmlSanitizerOptions の各コレクションは HtmlSanitizerDefaults から事前に設定されており、これは new HtmlSanitizer() が使用するのと同じデフォルト値であるため、変更したい項目だけを設定すれば済みます:
var options = new HtmlSanitizerOptions();
options.AllowedTags.Clear();
options.AllowedTags.Add("a");
options.AllowedTags.Add("img");
// AllowedAttributes, UriAttributes, AllowedSchemes, etc. remain at their defaults
var sanitizer = new HtmlSanitizer(options);
事前に用意されたコレクションを変更するのではなく、コレクションを丸ごと再代入した場合でも、そのプロパティだけがデフォルトを置き換えます。他のプロパティには影響しません:
var sanitizer = new HtmlSanitizer(new HtmlSanitizerOptions
{
AllowedTags = new HashSet<string> { "a", "img" },
AllowedAttributes = new HashSet<string> { "href", "src" },
// UriAttributes and AllowedSchemes are not reassigned here, so they keep their defaults
});
代わりにまっさらな状態から始めたい場合 — 追加するまで何も許可されない状態 — は、HtmlSanitizerOptions.Empty() から始めてください:
var options = HtmlSanitizerOptions.Empty();
options.AllowedTags.Add("a");
options.AllowedAttributes.Add("href");
var sanitizer = new HtmlSanitizer(options);
// UriAttributes is empty, so href is *not* screened against AllowedSchemes
// <a href="javascript:alert(1)">click</a> is preserved as-is
UriAttributes は許可リストではなく スクリーニング リストです。そこに含まれない属性は URI を持つものとして扱われないため、その値が AllowedSchemes に対してチェックされることはありません。これは Empty() から許可リストを構築する際に最も重要です。href を許可しつつ、それを UriAttributes に追加し忘れるのは容易だからです。また、UriAttributes と AllowedSchemes は一緒に設定する必要があります。空のスキームセットに対して属性をスクリーニングすると、有効な https のものを含め、すべての絶対 URI が除外されてしまいます:
var options = HtmlSanitizerOptions.Empty();
options.AllowedTags.Add("a");
options.AllowedAttributes.Add("href");
options.UriAttributes.Add("href");
// AllowedSchemes left empty - every absolute URI is dropped
var sanitizer = new HtmlSanitizer(options);
// <a href="https://example.com">ok</a> becomes <a>ok</a>
a,
abbr,
acronym,
address,
area,
article,
aside,
b,
bdi,
big,
blockquote,
body,
br,
button,
caption,
center,
cite,
code,
col,
colgroup,
data,
datalist,
dd,
del,
details,
dfn,
dir,
div,
dl,
dt,
em,
fieldset,
figcaption,
figure,
font,
footer,
form,
h1,
h2,
h3,
h4,
h5,
h6,
head,
header,
hr,
html,
i,
img,
input,
ins,
kbd,
keygen,
label,
legend,
li,
main,
map,
mark,
menu,
menuitem,
meter,
nav,
ol,
optgroup,
option,
output,
p,
pre,
progress,
q,
rp,
rt,
ruby,
s,
samp,
section,
select,
small,
span,
strike,
strong,
sub,
summary,
sup,
table,
tbody,
td,
textarea,
tfoot,
th,
thead,
time,
tr,
tt,
u,
ul,
var,
wbr
abbr,
accept-charset,
accept,
accesskey,
action,
align,
alt,
autocomplete,
autosave,
axis,
bgcolor,
border,
cellpadding,
cellspacing,
challenge,
char,
charoff,
charset,
checked,
cite,
clear,
color,
cols,
colspan,
compact,
coords,
datetime,
dir,
disabled,
draggable,
dropzone,
enctype,
for,
frame,
headers,
height,
high,
href,
hreflang,
hspace,
ismap,
keytype,
label,
lang,
list,
longdesc,
low,
max,
maxlength,
media,
method,
min,
multiple,
name,
nohref,
noshade,
novalidate,
nowrap,
open,
optimum,
pattern,
placeholder,
prompt,
pubdate,
radiogroup,
readonly,
rel,
required,
rev,
reversed,
rows,
rowspan,
rules,
scope,
selected,
shape,
size,
span,
spellcheck,
src,
start,
step,
style,
summary,
tabindex,
target,
title,
type,
usemap,
valign,
value,
vspace,
width,
wrap
注: classjacking や、サニタイズされたフラグメントを統合するクラスへの干渉を防ぐため、class 属性はデフォルトでは許可されていません。
次のように追加できます:
var sanitizer = new HtmlSanitizer();
sanitizer.AllowedAttributes.Add("class");
var sanitized = sanitizer.Sanitize(html);