Tip: MVC - Text input - Validate Xss
Pretty sure you came across this one: "A potentially dangerous Request.Form value was detected from the client", when you tried to add html tags in a blog post, for example.
To avoid this error in ASP.NET, you just had to add ValidateRequest="false" to the page directive, or in MVC add the ValidateInput(false) attribute to the controller method
Fairly easy to avoid the error, but now you're page is no longer secured for XSS attacks. One way to avoid this is filtering the user input, for example by using HtmlAgilityPack, as illustrated in the code below
Major advantage of this approach: it also removes encoded script tags. Actually, you can remove just about anything, like images if you want to.
using HtmlAgilityPack;
namespace iFrameWorx.Core.Utilities.Extensions.String
{
public static class ValidateXssExtension
{
public static string ValidateXss(this string input)
{
try
{
var html = new HtmlDocument { OptionFixNestedTags = true, OptionAutoCloseOnEnd = true };
html.LoadHtml(input);
// remove all scripts
var scripts = html.DocumentNode.SelectNodes("//script");
if (scripts != null)
foreach (var script in scripts)
script.Remove();
return html.DocumentNode.OuterHtml;
}
catch
{
// ignore error, return input
}
return input;
}
}
}
using iFrameWorx.Core.Utilities.Extensions.String;
using NUnit.Framework;
namespace iFrameWorx.Core.UnitTests.Extensions
{
[TestFixture]
public class ValidateXssUnitTest
{
[Test]
public void ValidateXss()
{
var s = "<script>alert('Hello!');</script>";
s = s.ValidateXss();
Assert.IsNullOrEmpty(s);
}
[Test]
public void ValidateXssEncoded()
{
var s = "\x3cscript\x3e%20alert(\x27Hello!\x27)%20\x3c/script\x3e";
s = s.ValidateXss();
Assert.IsNullOrEmpty(s);
}
}
}
Tags:



