
基于 AngleSharp 的 .NET 库,用于净化 HTML 片段和文档,通过可配置的标签、属性、CSS 属性和 URI 方案允许列表来剥离 XSS 向量。
HtmlSanitizer 是一个 .NET 库,用于清理 HTML 片段和文档中可能导致 XSS 攻击的构造。 它使用 AngleSharp 来解析、操作和渲染 HTML 与 CSS。
由于 HtmlSanitizer 基于健壮的 HTML 解析器,它还能保护你免受有意或无意的 “标签污染”(tag poisoning)之害——即某个片段中的无效 HTML 可能破坏整个文档,导致布局或样式错乱。
为了便于适应不同的使用场景,HtmlSanitizer 可以在多个层面进行自定义:
AllowedTags 配置允许的 HTML 标签。所有其他标签都将被移除。AllowedAttributes 配置允许的 HTML 属性。所有其他属性都将被移除。AllowedCssProperties 配置允许的 CSS 属性名。所有其他样式都将被移除。AllowedAtRules 配置允许的 CSS at-rules。所有其他 at-rules 都将被移除。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 需要一起设置——用空的 scheme 集合筛查属性会丢弃所有绝对 URI,包括有效的 https:
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);