/// <summary> /// Sanitizes the specified HTML, removing scripts, styles, and tags /// which might pose a security concern /// </summary> /// <param name="html">The HTML content to minify. A <see cref="string"/> or <see cref="Stream"/> can also be used.</param> /// <param name="writer">Writer to which the sanitized HTML is written</param> /// <param name="settings">Settings controlling what CSS and HTML is permitted in the result</param> /// <remarks> /// The goal of sanitization is to prevent XSS patterns /// described on <a href="https://www.owasp.org/index.php/XSS_Filter_Evasion_Cheat_Sheet">XSS Filter Evasion Cheat Sheet</a> /// </remarks> public static void Sanitize(TextSource html, XmlWriter writer, HtmlSanitizeSettings settings = null) { using (var reader = new HtmlReader(html, false)) { reader.Sanitize(settings).ToHtml(writer); } }
private void TestSanitize(string input, string expected, HtmlSanitizeSettings settings = null, HtmlWriterSettings writerSettings = null) { using (var reader = new HtmlReader(input)) { var rendered = reader.Sanitize(settings ?? HtmlSanitizeSettings.Default()).ToHtml(writerSettings); Assert.Equal(expected, rendered); } }
/// <summary> /// Sanitizes the specified HTML, removing scripts, styles, and tags /// which might pose a security concern /// </summary> /// <param name="html">The HTML content to minify. A <see cref="string"/> or <see cref="Stream"/> can also be used.</param> /// <param name="settings">Settings controlling what CSS and HTML is permitted in the result</param> /// <returns>An <see cref="HtmlString"/> containing only the permitted elements</returns> /// <remarks> /// The goal of sanitization is to prevent XSS patterns /// described on <a href="https://www.owasp.org/index.php/XSS_Filter_Evasion_Cheat_Sheet">XSS Filter Evasion Cheat Sheet</a> /// </remarks> public static HtmlString Sanitize(TextSource html, HtmlSanitizeSettings settings = null) { var sb = new StringBuilder(html.Length); using (var reader = new HtmlReader(html, false)) using (var sw = new StringWriter(sb)) { reader.Sanitize(settings).ToHtml(sw, new HtmlWriterSettings()); return(new HtmlString(sw.ToString())); } }
public void Example_KitchenSink() { var html = @"<div> <script>alert('xss');</script> <a href=""http://www.google.com/"">Google</a> <a href=""http://www.yahoo.com/"">Yahoo</a> </div>"; using (var reader = new HtmlReader(html)) { var result = (string)reader.Sanitize().Minify().ToHtml(); Assert.Equal(@"<div><a href=""http://www.google.com/"">Google</a> <a href=""http://www.yahoo.com/"">Yahoo</a></div>" , result); } }