ASP.NET MVC XSS Validation
We are using ASP.NET MVC 5.0 to build a website. If I enter a textbox, some javascript, when I save, I get a page with potentially dangerous inputs, which is great.
However a few of our screens use ajax submit to pass json directly to the controller, this seems to skip the validation above.
Is there a way to call the standard model check (or every textbox in the model) in the controller to throw the error above. that is, something like
public override ActionResult Create(MyModel myModel)
{
/* Any dubious input this should throw an error*/
AntiXSS.ValidateInput(myModel);
...
source to share
I ran into a similar issue, and as noted in the comments on another answer, we had JQuery using $.ajax
to post JSON for an MVC action. The standard binder does not validate posted JSON allowing unsafe XSS to be hosted against our action.
To solve this problem, I found I had RequestValidator
a static method InvokeIsValidRequestString
that allowed
public class ValidateJsonXssAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
var request = filterContext.HttpContext?.Request;
if (request != null && "application/json".Equals(request.ContentType, StringComparison.OrdinalIgnoreCase))
{
if (request.ContentLength > 0 && request.Form.Count == 0) //
{
if (request.InputStream.Position > 0)
request.InputStream.Position = 0; // InputStream has already been read once from "ProcessRequest"
using (var reader = new StreamReader(request.InputStream))
{
var postedContent = reader.ReadToEnd(); // Get posted JSON content
var isValid = RequestValidator.Current.InvokeIsValidRequestString(HttpContext.Current, postedContent,
RequestValidationSource.Form, "postedJson", out var failureIndex); // Invoke XSS validation
if (!isValid) // Not valid, so throw request validation exception
throw new HttpRequestValidationException("Potentially unsafe input detected");
}
}
}
}
}
Then you can simply decorate the appropriate MVC actions, waiting for the posted JSON data, which can bypass the standard XSS prevention:
[HttpPost]
[ValidateJsonXss]
public ActionResult PublishRecord(RecordViewModel vm) { ... }
You can see other options for customizing request validation using OWASP.NET best practices by extending the RequestValidator object, which provides string validation done by ValidateInput
MVC automatically for other query string, form collection and cookie value scenarios.
For more information: https://www.owasp.org/index.php/ASP.NET_Request_Validation
source to share
The [ValidateInput] attribute can be bound to each method. http://www.c-sharpcorner.com/UploadFile/dacca2/validateinput-attribute-to-prevent-css-attack-in-mvc/
source to share