Thursday, May 28, 2015

Preventing XSS Attacks in ASP.NET MVC using ValidateInput and AllowHTML

Introduction
What is XSS?
How can we prevent the same in MVC?
What is the difference between “ValidateInput” and “AllowHTML” in MVC ?

Introduction

In this blog we will try to understand how we can prevent and fine tune XSS(Cross Site Security) security attacks in ASP.NET MVC.

What is XSS?

XSS(Cross Site Security) is a security attack where the attacker injects malicious code while doing data entry. This code can be a javascript, vbscript or any other scripting code. Once the code is injected in end user’s browser. This code can run and gain access to cookies,sessions, local files and so on.
For instance below is a simple product data entry form. You can see in the product description how the attacker has injected a javascript code.

Once we click submit you can see the JavaScript code actually running.

How can we prevent the same in MVC?

In MVC by default XSS attack is validated. So if any one tries to post javascript or HTML code he lands with the below error.

What is the difference between “ValidateInput” and “AllowHTML” in MVC?

As said in the previous question in ASP.NET MVC we are not allowed to post scripts and HTML code by default. But consider the below situation where we want HTML to be written and submitted.
The other scenario where we need HTML to be posted is HTML editors. So there is always a need now and then to post HTML to the server.

So for those kinds of scenarios where we want HTML to be posted we can decorate the action with “ValidateInput” set to false.This by passes the HTML and Script tag checks for that action.
You can see in the below code we have requested the MVC framework to NOT VALIDATE the input to the action.
[ValidateInput(false)]
public ActionResult PostProduct(Product obj)
{
return View(obj);
} 
But the above solution is not proper and neat. It opens a complete Pandora box of security issues. In this product screen scenario we just HTML in product description and not in product name.
But because we have now decorated validate false at the action level , you can also write HTML in product name field as well. We would love to have more finer control on the field level rather than making the complete action naked.

That’s where “AllowHTML” comes to help. You can see in the below code we have just decorated the “ProductDescription” property .
public class Product
{
        public string ProductName { get; set; }
        [AllowHtml]
        public string ProductDescription { get; set; }
}
And from the action we have removed “ValidateInput” attribute.
public ActionResult PostProduct(Product obj)
{
            return View(obj);
}
If you now try to post HTML in product name field you will get the below error saying you cannot post HTML tags in product name field.

So the difference between ValidateInput and AllowHTML is the granularity of preventing XSS attacks.
Hope you have enjoyed this blog.
Also the other dead attack which happens on a MVC website is CSRF, see the below facebook video which demonstrates how CSRF attack can be prevented.

Monday, May 25, 2015

What is CSRF attack and how can we prevent the same in MVC?

CSRF (Cross site request forgery) is a method of attacking a website where the attacker imitates a.k.a forges as a trusted source and sends data to the site. Genuine site processes the information innocently thinking that data is coming from a trusted source.

For example conside the below screen of a online bank. End user’s uses this screen to transfer money.

Below is a forged site created by an attacker which looks a game site from outside, but internally it hits the bank site for money transfer.

The internal HTML of the forged site has those hidden fields which have the account number and amount to do money transfer.

Now let’s say the user has logged in to the genuine bank site and the attacker sent this forged game link to his email. The end user thinking that it’s a game site clicks on the “Play the Ultimate Game” button and internally the malicious code does the money transfer process.

So a proper solution to this issue can be solved by using tokens: -

  • End user browses to the screen of the money transfer. Before the screen is served server injects a secret token inside the HTML screen in form a hidden field.
  • Now hence forth when the end user sends request back he has to always send the secret token. This token is validated on the server.

Implementing token is a two-step process in MVC: -

First apply “ValidateAntiForgeryToken” attribute on the action.

[ValidateAntiForgeryToken]
public ActionResult Transfer()
{
            // password sending logic will be here
            return Content(Request.Form["amount"] + 
                " has been transferred to account " 
                + Request.Form["account"]);
}

Second in the HTML UI screen call “@Html.AntiForgeryToken()” to generate the token.

So now henceforth when any untrusted source send a request to the server it would give the below forgery error.

If you do a view source of the HTML you would find the below verification token hidden field with the secret key.

Tuesday, May 19, 2015

How to handle multiple Submit button issues in ASP.NET MVC? (MVC Interview Questions)

How to handle multiple Submit button issues in ASP.NET MVC? (MVC Interview Questions)

Let us understand the above problem in more detail.

Take a scenario where you have a view with two submit buttons as shown in the below code.

In the above code when the end user clicks on any of the submit buttons it will make a HTTP POST to “Action1”.

The question from the interviewer is: -

“What if we have want that on “Submit1” button click it should invoke “Action1” and on the “Submit2” button click it should invoke “Action2”.”

There are three basic approaches to solve the above problem scenario.

HTML way: -

In the HTML way we need to create two forms and place the “Submit” button inside each of the forms. And every form’s action will point to different / respective actions. You can see the below code the first form is posting to “Action1” and the second form will post to “Action2” depending on which “Submit” button is clicked.

AJAX way: -

In case you are an AJAX lover this second option would excite you more. In the Ajax way we can create two different functions “Fun1” and “Fun1”, see the below code. These functions will make Ajax calls by using JQUERY or any other framework. Each of these functions is binded with the “Submit” button’s “OnClick” events. Each of these function make call to respective action names.

Using “ActionNameSelectorAttribute”: -

This is a great and a clean option. The “ActionNameSelectorAttribute” is a simple attribute class where we can write decision making logic which will decide which action can be executed.

So the first thing is in HTML we need to put proper name’s to the submit buttons for identifying them on the server.

You can see we have put “Save” and “Delete” to the button names. Also you can notice in the action we have just put controller name “Customer” and not a particular action name. We expect the action name will be decide by “ActionNameSelectorAttribute”.

So when the submit button is clicked, it first hits the “ActionNameSelector” attribute and then depending on which submit is fired it invokes the appropriate action.

So the first step is to create a class which inherits from “ActionNameSelectorAttribute” class. In this class we have created a simple property “Name”.

We also need to override the “IsValidName” function which returns true or flase. This function is where we write the logic whether an action has to be executed or not. So if this function returns true then the action is executed or else it is not.

public class SubmitButtonSelector : ActionNameSelectorAttribute
    {
        public string Name { get; set; }
        public override bool IsValidName(ControllerContext controllerContext, string actionName, System.Reflection.MethodInfo methodInfo)
        {
            // Try to find out if the name exists in the data sent from form
var value = controllerContext.Controller.ValueProvider.GetValue(Name);
            if (value != null)
            {
                return true;
            }
            return false;

        }
    }

The main heart of the above function is in the below code. The “ValueProvider” collection has all the data that has been posted from the form. So it first looks up the “Name” value and if its found in the HTTP request it returns true or else it returns false.

var value = controllerContext.Controller.ValueProvider.GetValue(Name);
if (value != null)
      {
 return true;
      }
      return false;

This attribute class can then decorated on the respective action and the respective “Name” value can be provided. So if the submit is hitting this action and if the name matches of the HTML submit button name it then executes the action further or else it does not.

public class CustomerController : Controller
{
        [SubmitButtonSelector(Name="Save")]
        public ActionResult Save()
        {
            return Content("Save Called");
        }
        [SubmitButtonSelector(Name = "Delete")]
        public ActionResult Delete()
        {
            return Content("Delete Called");
        }
}

Monday, May 11, 2015

Validation’s using C# “DataAnnotation”

Introduction
How to use “DataAnnotations” ?
Step 1:- Refer System.ComponentModel.DataAnnotations
Step 2:- Decorate the class with attributes
Step 3:- Call the “Validator” for validation.

Introduction

Validations are one of the most important aspects of any software application. Normally as a best practice we put these validation’s in the business class , model etc. So if you normally see the trend, developers end up writing these validations in the “set” method of the class property.

 
public class Customer
    {

        private string _CustomerName;
        public string CustomerName
        {
            get { return _CustomerName; }
            set 
            {
                if (value.Length == 0)
                {
                    throw new Exception("Customer Name is required");
                }
                _CustomerName = value; 
            }
        }    
    }

“DataAnnotation” gives you ready made attributes which you can decorate on the class properties and the validation will be applied accordingly.

[Required]
public string CustomerName
{
            get { return _CustomerName; }
            set {_CustomerName = value; }
}

How to use “DataAnnotations” ?


Step 1:- Refer System.ComponentModel.DataAnnotations

The first step is to add reference to “System.ComponentModel.DataAnnotations” assembly to your class library project.

Step 2:- Decorate the class with attributes

The next step is to decorate the class with validation attributes. For instance on the “CustomerName” property we have decorated the “Required” attribute.

public class Customer
{
        private string _CustomerName;

        [Required]
        public string CustomerName
        {
            get { return _CustomerName; }
            set {_CustomerName = value; }
        }
        
}

Step 3:- Call the “Validator” for validation.

Once the validation attributes are decorated we need to call the “Validator” class to do the validations. Create the customer object and set the “CustomerName” property to nothing , so validation errors fire up.

Customer obj = new Customer();
obj.CustomerName = "";

Use the above created object to create the “ValidationContext” object.

var context = new ValidationContext(obj,null,null);

Use “Validator” to call  “TryValidateObject” method to run the validations. The validation errors get collected in the “ValidationResult” collection.

var result = new List();
var isValid = Validator.TryValidateObject(obj, context, result,true);

If you wish to loop through the error results you can run a “foreach” on the “result” collection.

foreach (var str in result)
{
Console.WriteLine(str.ErrorMessage.ToString());
}

Below is a pictorial representation of the above code. In simple words the object to be validated is passed to the “validator” class with the context and the error results come out in “ValidationResult” collection.

FYI :- If you have multiple validation do not forget to make the last property true.

var isValid = Validator.TryValidateObject(obj, context, result,true);