Skip to content

Commit

Permalink
Fix #483
Browse files Browse the repository at this point in the history
  • Loading branch information
mganss committed Oct 23, 2023
1 parent 13b2e1a commit fe337df
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 3 deletions.
7 changes: 5 additions & 2 deletions src/HtmlSanitizer/HtmlSanitizer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -468,7 +468,10 @@ private void RemoveComments(INode context)
private void DoSanitize(IHtmlDocument dom, IParentNode context, string baseUrl = "")
{
// always encode text in raw data content
foreach (var tag in context.QuerySelectorAll("*").Where(t => t.Flags.HasFlag(NodeFlags.LiteralText) && !string.IsNullOrWhiteSpace(t.InnerHtml)))
foreach (var tag in context.QuerySelectorAll("*")
.Where(t => t is not IHtmlStyleElement
&& t.Flags.HasFlag(NodeFlags.LiteralText)
&& !string.IsNullOrWhiteSpace(t.InnerHtml)))
{
var escapedHtml = tag.InnerHtml.Replace("<", "&lt;").Replace(">", "&gt;");
if (escapedHtml != tag.InnerHtml)
Expand Down Expand Up @@ -560,7 +563,7 @@ private void SanitizeStyleSheets(IHtmlDocument dom, string baseUrl)
else i++;
}

styleTag.InnerHtml = styleSheet.ToCss(StyleFormatter).Replace("<", "\\3c");
styleTag.InnerHtml = styleSheet.ToCss(StyleFormatter).Replace("<", "\\3c ").Replace(">", "\\3e ");
}
}

Expand Down
14 changes: 13 additions & 1 deletion test/HtmlSanitizer.Tests/Tests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3248,7 +3248,7 @@ public void StyleByPassTest()
var sanitized = sanitizer.Sanitize(html, "http://www.example.com");

// Assert
Assert.Equal("aaabc<style>x[x=\"\\3c/style&gt;\\3cimg src onerror=alert(1)&gt;\"] { }</style>", sanitized);
Assert.Equal("aaabc<style>x[x=\"\\3c /style\\3e \\3c img src onerror=alert(1)\\3e \"] { }</style>", sanitized);
}

[Fact]
Expand Down Expand Up @@ -3552,4 +3552,16 @@ public void Bypass4Test()
var expected = "<svg><p></p><style><!--&lt;/style&gt;&lt;img src=x onerror=alert(1)&gt;--></style></svg>";
Assert.Equal(expected, sanitized);
}

[Fact]
public void InlineCssTest()
{
// see https://github.com/mganss/HtmlSanitizer/issues/483

var input = "<style>span>p { font-size: 2em }</style><span><p>I am safe</p></span>";
var sanitizer = new HtmlSanitizer();
sanitizer.RemovingTag += (sender, args) => args.Cancel = true;
var output = sanitizer.Sanitize(input);
Assert.Equal(@"<style>span\3e p { font-size: 2em }</style><span><p>I am safe</p></span>", output);
}
}

0 comments on commit fe337df

Please sign in to comment.