views:

62

answers:

3

I need to start worrying about user input. I notice the htmlhelper class doesnt do a great job of this. Can anyone suggest a nice framework for input sanitization? I'm using asp.net mvc2.

+3  A: 

The HtmlHelper class is for HTML output and not input, so I don't understand what do you mean by not doing a great job for user input sanitation. There are different ways of doing input validation like data annotations or using some third party framework like FluentValidation. If you are using a SQL database you should also make sure to avoid SQL injection by using prepared statements and parametrized queries. Also when you need to show user input on the page you should always make sure to properly HTML encode it using <%= Html.Encode("some user input") %> or the newer syntax <%: "some user input" %>.

Darin Dimitrov
I'm using NHibernate which I'm sure parametrizes queries when the Criteria class is used to interact with the DB.
Am
+1 @AM that + HTML encoding the output goes a long way, care to share more on why do you say it doesn't do a great job? Maybe you mean validation ...
eglasius
+1  A: 

DataAnnotations are a good start for model validation. See this link for details on how to set up data annotations. They may be used in conjunction with the Microsoft MVC javascript libraries or jQuery to perform client side validation, and additionally may be used server-side to validate whether the model, once bound, is valid. See the ModelState.IsValid property.

While Annotations may help prevent and catch bad user input, they will not "sanitize" the input for you. If you are willing to accept bad input and want to handle its sanitization, a custom model binder would be a good place to start. Scott provides a good scenario of how to implement one here. . In a custom binder, you could pass text input thorough a series of string cleansing methods to strip out unwanted characters or standardize formatting, etc.

The combination of both of these approaches should equip you with the ability to handle almost any sanitization you may need.

Ben Elder
I like your answer, I'll look into your suggestion and see how I go
Am
A: 

I recommend you don't sanitize the input, rather, sanitize the output.

This avoids possible improper sanitation or corrupting the actual user input.

Let the user submit HTML, just make sure that when it's displayed, it's always encoded.

As Darin stated, use <%: %> syntax or <%= Html.Encode() %> to take care of this

Baddie