
AngleSharp을 사용하여 HTML 조각과 문서를 정화하고, 태그, 속성, CSS 속성 및 URI 스킴에 대한 구성 가능한 허용 목록을 통해 XSS 벡터를 제거하는 .NET 라이브러리입니다.
HtmlSanitizer는 XSS 공격으로 이어질 수 있는 구성 요소로부터 HTML 프래그먼트와 문서를 정리하기 위한 .NET 라이브러리입니다. HTML과 CSS를 파싱, 조작, 렌더링하기 위해 AngleSharp를 사용합니다.
HtmlSanitizer는 견고한 HTML 파서를 기반으로 하기 때문에, 한 프래그먼트의 잘못된 HTML이 전체 문서를 손상시켜 레이아웃이나 스타일이 깨지는 의도적이거나 우발적인 "태그 오염(tag poisoning)"으로부터도 보호해 줄 수 있습니다.
다양한 사용 사례를 지원하기 위해 HtmlSanitizer는 여러 수준에서 사용자 정의할 수 있습니다:
AllowedTags 속성을 통해 허용되는 HTML 태그를 구성합니다. 그 외의 모든 태그는 제거됩니다.AllowedAttributes 속성을 통해 허용되는 HTML 속성을 구성합니다. 그 외의 모든 속성은 제거됩니다.AllowedCssProperties 속성을 통해 허용되는 CSS 속성 이름을 구성합니다. 그 외의 모든 스타일은 제거됩니다.AllowedAtRules 속성을 통해 허용되는 CSS at-규칙을 구성합니다. 그 외의 모든 at-규칙은 제거됩니다.AllowedSchemes 속성을 통해 허용되는 URI 스킴을 구성합니다. 그 외의 모든 URI는 제거됩니다.UriAttributes 속성을 통해 URI를 포함하는 HTML 속성(예: "src", "href" 등)을 구성합니다.UriListAttributes 속성을 통해 URI의 목록을 포함하는 HTML 속성(예: "srcset", "ping")을 구성합니다. 각 항목은 개별적으로 검사됩니다.SanitizeFragment()를 통해 <body>가 아닌, 삽입될 요소에 맞게 프래그먼트를 정리합니다. 이렇게 하면 트리 더 깊은 곳에서만 유효한 단독 <th> 같은 마크업이 유지됩니다.HtmlSanitizerOptions 객체를 전달하여 한 번에 설정할 수 있습니다. new HtmlSanitizerOptions()는 new HtmlSanitizer()와 동일한 기본값으로 미리 채워져 시작하므로 변경하려는 항목만 설정하면 됩니다. 빈 상태에서 시작하려면 대신 HtmlSanitizerOptions.Empty()를 사용하세요. 자세한 내용은 Configuring with 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);