Cleans HTML to avoid XSS attacks
HtmlSanitizer is a .NET library for cleaning HTML fragments and documents from constructs that can lead to XSS attacks. It uses AngleSharp to parse, manipulate, and render HTML and CSS.
Because HtmlSanitizer is based on a robust HTML parser it can also shield you from deliberate or accidental "tag poisoning" where invalid HTML in one fragment can corrupt the whole document leading to broken layout or style.
In order to facilitate different use cases, HtmlSanitizer can be customized at several levels:
AllowedTags. All other tags will be stripped.AllowedAttributes. All other attributes will be stripped.AllowedCssProperties. All other styles will be stripped.AllowedAtRules. All other at-rules will be stripped.AllowedSchemes. All other URIs will be stripped.UriAttributes.UriListAttributes. Every entry is checked separately.<body>, through SanitizeFragment(). This keeps markup such as a lone <th> that is only valid deeper in the tree.HtmlSanitizerOptions object to the constructor. new HtmlSanitizerOptions() starts pre-populated with the same defaults as new HtmlSanitizer(), so you only need to set what you want to change; use HtmlSanitizerOptions.Empty() instead if you want a blank slate, see Configuring with HtmlSanitizerOptions.Install the HtmlSanitizer NuGet package. Then:
using Ganss.Xss;
var sanitizer = new HtmlSanitizer();
var html = @"<script>alert('xss')</script>
";
var sanitized = sanitizer.Sanitize(html, "https://www.example.com");
var expected = @"
";
Assert.Equal(expected, sanitized);There's an online demo, plus there's also a .NET Fiddle you can play with.
More example code and a description of possible options can be found in the Wiki.
HtmlSanitizerOptionsA sanitizer can also be configured in one go by passing an HtmlSanitizerOptions object to the constructor. Every collection on HtmlSanitizerOptions starts out pre-populated from HtmlSanitizerDefaults, the same defaults new HtmlSanitizer() uses, so you only need to set what you want to change:
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);Reassigning a collection outright, rather than mutating the pre-populated one, still replaces the default for that property alone - the other properties are unaffected:
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
});If you want a blank slate instead - nothing allowed until you add it - start from 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-isUriAttributes is a screening list rather than an allow list: an attribute not in it is not treated as carrying a URI at all, so its value is never checked against AllowedSchemes. This matters most when building an allowlist from Empty(), where it's easy to allow href without also adding it to UriAttributes. And UriAttributes and AllowedSchemes need to be set together - screening an attribute against an empty scheme set drops every absolute URI, valid https ones included:
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,
contenteditable,
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
Note: to prevent classjacking and interference with classes where the sanitized fragment is to be integrated, the class attribute is disallowed by default.
It can be added as follows:
var sanitizer = new HtmlSanitizer();
sanitizer.AllowedAttributes.Add("class");
var sanitized = sanitizer.Sanitize(html);align-content,
align-items,
align-self,
all,
animation,
animation-delay,
animation-direction,
animation-duration,
animation-fill-mode,
animation-iteration-count,
animation-name,
animation-play-state,
animation-timing-function,
backface-visibility,
background,
background-attachment,
background-blend-mode,
background-clip,
background-color,
background-image,
background-origin,
background-position,
background-position-x,
background-position-y,
background-repeat,
background-repeat-x,
background-repeat-y,
background-size,
border,
border-bottom,
border-bottom-color,
border-bottom-left-radius,
border-bottom-right-radius,
border-bottom-style,
border-bottom-width,
border-collapse,
border-color,
border-image,
border-image-outset,
border-image-repeat,
border-image-slice,
border-image-source,
border-image-width,
border-left,
border-left-color,
border-left-style,
border-left-width,
border-radius,
border-right,
border-right-color,
border-right-style,
border-right-width,
border-spacing,
border-style,
border-top,
border-top-color,
border-top-left-radius,
border-top-right-radius,
border-top-style,
border-top-width,
border-width,
bottom,
box-decoration-break,
box-shadow,
box-sizing,
break-after,
break-before,
break-inside,
caption-side,
caret-color,
clear,
clip,
color,
column-count,
column-fill,
column-gap,
column-rule,
column-rule-color,
column-rule-style,
column-rule-width,
column-span,
column-width,
columns,
content,
counter-increment,
counter-reset,
cursor,
direction,
display,
empty-cells,
filter,
flex,
flex-basis,
flex-direction,
flex-flow,
flex-grow,
flex-shrink,
flex-wrap,
float,
font,
font-family,
font-feature-settings,
font-kerning,
font-language-override,
font-size,
font-size-adjust,
font-stretch,
font-style,
font-synthesis,
font-variant,
font-variant-alternates,
font-variant-caps,
font-variant-east-asian,
font-variant-ligatures,
font-variant-numeric,
font-variant-position,
font-weight,
gap,
grid,
grid-area,
grid-auto-columns,
grid-auto-flow,
grid-auto-rows,
grid-column,
grid-column-end,
grid-column-gap,
grid-column-start,
grid-gap,
grid-row,
grid-row-end,
grid-row-gap,
grid-row-start,
grid-template,
grid-template-areas,
grid-template-columns,
grid-template-rows,
hanging-punctuation,
height,
hyphens,
image-rendering,
isolation,
justify-content,
left,
letter-spacing,
line-break,
line-height,
list-style,
list-style-image,
list-style-position,
list-style-type,
margin,
margin-bottom,
margin-left,
margin-right,
margin-top,
mask,
mask-clip,
mask-composite,
mask-image,
mask-mode,
mask-origin,
mask-position,
mask-repeat,
mask-size,
mask-type,
max-height,
max-width,
min-height,
min-width,
mix-blend-mode,
object-fit,
object-position,
opacity,
order,
orphans,
outline,
outline-color,
outline-offset,
outline-style,
outline-width,
overflow,
overflow-wrap,
overflow-x,
overflow-y,
padding,
padding-bottom,
padding-left,
padding-right,
padding-top,
page-break-after,
page-break-before,
page-break-inside,
perspective,
perspective-origin,
pointer-events,
position,
quotes,
resize,
right,
row-gap,
scroll-behavior,
tab-size,
table-layout,
text-align,
text-align-last,
text-combine-upright,
text-decoration,
text-decoration-color,
text-decoration-line,
text-decoration-skip,
text-decoration-style,
text-indent,
text-justify,
text-orientation,
text-overflow,
text-shadow,
text-transform,
text-underline-position,
top,
transform,
transform-origin,
transform-style,
transition,
transition-delay,
transition-duration,
transition-property,
transition-timing-function,
unicode-bidi,
unicode-range,
user-select,
vertical-align,
visibility,
white-space,
widows,
width,
word-break,
word-spacing,
word-wrap,
writing-mode,
z-index
namespace, style
style refers to style declarations within other at-rules such as @media. Disallowing @namespace while allowing other types of at-rules can lead to errors.
Property declarations in @font-face and @viewport are not sanitized.
Note: the style tag is disallowed by default.
http, https
Note: [Protocol-relative URLs](https://e
No open issues yet, or sync has not completed.