Validating Input in ASP.NET MVC - asp.net-mvc

Any suggestions for best practice on validating/cleaning user input in ASP.NET MVC. It seems ValidateInput will almost always need to be set to False since it cant be handled from within the MVC framework (the error is thrown even before the Action Method is fired).
So how should the input be validated for malicious input. Do we have to manually screen each input and check it for characters such as <, >, " etc
How about if we only wish to allow some types of input such as tags but forbid and other inputs? This must be a pretty common requirement of a web app now, but I can't see much in ASP.NET MVC to automate this.

So how should the input be validated for malicious input. \
It depends on what your application is doing with this input. If you are storing it in a relational database for example, well, as long as you use parametrized queries and properly encode the user request, relational database don't care about storing for example alert('foo'); in a given column. When you might get into trouble is when you try to fetch the result stored in this database and show it on some view. It is at that moment that you must ensure that the result is properly HTML encoded.
So for example let's suppose that you have stored some hyper dangerous string in your data store and you want to display it on your view. If you were using the Razor view engine you would simply:
#Html.DisplayFor(x => x.SomeProperty)
which will take care of properly HTML encoding the value of SomeProperty so that you don;t have to worry about.
And if you were using the WebForms view engine:
<%= Html.DisplayFor(x => x.SomeProperty) %>
So, as you can see there are two critical moments where you should be careful with the user input:
always use parametrized queries if you are storing this user input into a relational database
always HTML encode the value you have stored when time comes to render it on some view

Related

spring security native xss filter

Why Spring Security doesn't provide any XSS filter to clean the form input values?
Accordingly to this ticket, such XSS filter is a low priority:
https://jira.spring.io/browse/SEC-2167?jql=text%20~%20%22xss%22
(although the ticket speaks only about URL querystring. Sanitizing POST params would be also required)
In my opinion it would be really useful that spring would provide such a filter instead of building your own. This filter it's a recurrent problem.
XSS is best handled at output stage via the use of encoding. That is, store everything in your database as is, and yes storing <script> is fine, however once output, encode correctly for the context it is output in. For HTML this would be <script>, however if your output context was plain text you would just output as is <script> (assuming the same character set encoding is used). Side note: Use parameterised queries or equivalent for storing in your database to avoid SQL injection, however the text stored should exactly match what was entered.
Microsoft attempts to block inputs that look like XSS via their request validation feature in ASP.NET. However, this isn't very effective and flaws are found quite often. Similar approaches from other frameworks are doomed to fail.
The reason that this is much better is that it makes things much more simple. Imagine if StackOverflow didn't allow HTML or script tags - the site would not be functional as a place for people to post code snippets.
You can use input validation as second line of defence. For example, if you are asking the user to enter their car registration you would only want to allow alphanumerics and space to be entered. However, for more complex fields it is often difficult to restrict input to a safe set as output context is unknown at this stage.
Say your language filtered < and > characters. However you were outputting user input into the following context.
<img src="foo.jpg" alt="USER-INPUT" />
An XSS attack is possible by entering " onmouseover="alert('xss') because it would be rendered as
<img src="foo.jpg" alt="" onmouseover="alert('xss')" />
Similar problems would ensue if you were outputting to JavaScript server-side. This is why it should be up to the developer to select the correct encoding type when using user controlled values.

is it good practice to encode user input to database?

I am wondering if it is consider good practice to encode user input to database.
Or is it ok to not encode to user input instead.
Currently my way of doing it is to encode it when entering database and use Html.DisplayFor to display it.
No. You want to keep the input in its original form until you need it and know what the output type is. It might be HTML for now, but later if you want to change it to json, text file, xml, etc the encoding might make it look different then you want.
So, first you want to make sure you are securely validating your input. It is a good idea to know what are the requirements for each of your inputs and validate that they are withing the correct length, range, character set, etc. It will be to your interest to limit the type of characters that are allowed as valid characters of an input type. (If using Regular Expressions to validate input ensure you do not use a regular expressions that is susceptible to a Regular Expression Denial of Service.
When moving the data around in your code ensure that you are properly handling the data in a manner that it will not turn into an Injection Attack.
Since you are talking about a database, the best practice is to use paramaterized statements. Check out the prevention methods in the above link.
Then when it comes outputting using MVC, if you are not using RAW or MvcHtmlString functions/calls, then the output is automatically encoded. With the automatic encoding, you want to make sure you are using the AntiXss encoder and not the default (whitelist approach vs. blacklist). Link
If you are using Raw or MvcHtmlString, you want to make sure you COMPLETE TRUST the values (you hard coded them in) or you manually encode them using the AntiXss Encoder class.
No it is not necessary to encode all the user inputs, rather if you want to avoid the script injection either you my try to validate the fields for special characters like '<', '>', '/', etc. else your Html helper method itself will do the needful.

Struts 2 - is there any way to escape HTML in input fields?

When I allow a user to enter text using s:textfield, he can enter something like <b>Name</b> or something like \Me/. I want that these should be escaped before I am saving them to the database. When we retrieve them, the escaping is done automatically, but I want it to happen also when we are saving it.
I was trying to return a json output from my action class, but due to a name \a/ stored in my database, wrong json was being formed. This would have been avoided if the name had been escaped before being saved into the database.
You can use StringEscapeUtils. You can call escapeJavascript(textfield) in your action and then store it into the database.
#Daud, The problem you explained is called Cross site scripting or XSS.
And I think you should use Filters to clean the request parameters. This is the most sophisticated way. You can call these filters for the actions which are posting some parameters via request.
Visit my blog to see how to avoid XSS threat using Filter approach.
I also faced this issue when our project was tested by well known firm specializing in security testing and they suggested this filter approach.
You can give it a try.

Simple string templating in ASP.NET MVC

I have a bunch of database log messages containing references like Invoice 45 or Case 123 which I want to parse to output links to the appropriate invoice or case when displaying to the user.
These are fairly simple to parse with RegEx and replace with an action link using an ASCX display template, but is there a right way to do this? I imagine this means writing a parser to tokenise the string and prevent any potential circular references.
An HTML helper is probably a better fit - the parsing / display doesn't do anything that you could put in the ascx that isn't better handled in code.

Alternative to ValidateInput("false") when passing HTML to a controller

I have a pretty simple ASP.NET MVC page and am using TinyMCE to allow users to enter comments. However, when I pass the data to a controller I receive the following error message:
A potentially dangerous Request.Form
value was detected from the client
The consensus is that ValidateInput("false") should be set on the Action method but somehow that does not sit well with me. I have tried to intercept this by ordering my action methods and sanitizing the data through my ActionExecitomgContext ActionParameters however this error keeps occurring time and again. Does anyone know of a way to allow this content through (or properly intercept it) without disabling ValidateInput
Do you have specifics on why it doesn't sit well? ValidateInput("false") on the one action that accepts HTML is the proper way to go. The input validation is an old ASP.NET feature that is on by default for security in depth, but is like a sledge hammer. It doesn't understand the nuances of allowed HTML.
For that one action method, you could write your own ValidateSafeHtmlAttribute action filter and put that on the method instead. Maybe that one internally encapsulates a ValidateInput set to false and then does its own validation specific to your scenario. That'd be my recommendation.

Resources