Monday, January 28, 2013

Claims-Based Identity and Authorization

As a follow-up to the previous post about security, I am examining a claims-based security model within WCF using the Windows Identity Foundation (WIF). In a claims-based application, a user is represented by a set of claims. The basic idea is that an external service is configured to give you any relevant information about the user as part of each request. This also includes some assurance that the identity data you receive comes from a trusted source by using some flavor of cryptography. This really flows into a good SOA design because you are basically decoupling your application from the logic of authentication, the storage and protection of user names, passwords and emails, and forced integration with in-house identity systems. In a claims-based paradigm, your application is making decisions for access and security using information from the authenticating system.

Claims

Claims are really just pieces of data associated with the currently authenticated user. These 'claims' from the authenticating service can consist of items such as the user name, email, security group membership, etc. When your application receives these claims, it enables you to cater the availability of content to the authenticated user. A very important point on which to be clear is that the claims made from the issuing service are only as trustworthy as that service itself. For example, you trust a claim made by your company’s domain controller more than you trust a claim made by, for example, Facebook. In that regard, WIF represents claims with a Claim type, which has an Issuer property that allows you to find out who issued the claim.

Tokens

The user delivers a set of claims to your application along with a request. In a web service, these claims are carried in the security header of the SOAP envelope. In a browser-based web application, the claims arrive through the HTTP request from the browser. The claims, regardless of the arrival method, are serialized, which is where why we need security tokens. A security token is really just a serialized set of claims that is digitally signed by the issuing authority. The signature is needed because it guarantees the issuing authority has generated the attached claims, which validates their authenticity. In other scenarios where that kind of security isn’t needed, you can use unsigned tokens. One of the core features in WIF is the ability to create and read security tokens. WIF and the .NET Framework handle all of the cryptographic work, and present your application with a set of claims that you can read.

Relying Party

When you build an application that relies on claims, you are building a relying party (RP) application. Synonyms for an RP include “claims-aware application” and “claims-based application.” Both web applications and web services can be RPs. An RP is nothing more than a consumer of tokens issued by an STS who reads the claims from tokens for use in security or access as it relates to the identity of the user. WIF offers inherent functionality to help you build RP applications.

Issuing Authority

It seems there are endless types of issuing authorities, but we really want to focus on security tokens that contain claims. This issuing authority is another application or service that is tasked with the issuance security tokens. This logic is responsible for having the insight needed to be able to issue the proper claims given the specific application and the user making the request, and might ultimately just be a pass-through to other services to receive claims and authenticate users.

Security Token Service (STS)

A security token service (STS) is the service that creates, signs, and issues any security tokens based on the WS-Trust and WS-Federation protocols. These protocols are really difficult to implement on a stand-alone basis, but WIF seems to handle the vast majority of this work. It appears that it is much easier to get STS up and running by leveraging WIF. You can use a pre-built STS such as Active Directory® Federation Services (AD FS) 2.0, a cloud STS such as a Windows Azure Access Control Service (ACS), or, if you want to issue custom tokens or provide custom authentication or authorization, you can build your own custom STS using WIF. The following is an example from Microsoft of a claims-based system.

Relying Partner Authentication Flow
This diagram shows a Web site (the relying party application, RP) that has been configured to use WIF for authentication and a client, a web browser, that wants to use that site.
  1. When an unauthenticated user requests a page their browser is redirected to the identity provider (IP) pages.
  2. The IP requires the user to present their credentials, e.g. username/password.
  3. The IP issues a token back to that is returned to the browser.
  4. The browser is now redirected back to the originally requested page where WIF determines if the token satisfies the requirements to access the page. If so a cookie is issued to establish a session so the authentication only needs to occur once, and control is passed to the application.
It seems that leveraging WIF as an STS provider is an easily achievable way to use a secure and standardized methodology of application security.

Tuesday, January 22, 2013

SOA and Security

We have talked about WCF at great length, but have focused mainly on the scalability and dependability of the Service-Oriented Architecture (SOA) itself.  One of the topics we haven't gotten into at a sufficient depth is security and service access management as an integral part of the SOA design.  I'd like to explore some of the options available for securing your services while adhering to the good design principles of SOA.  But first, I would like to discuss what it means to have security built in to your SOA.  We know that a well-designed SOA should be an architecture of loosely coupled components that can be distributed across platform, technology, and physical environments. Service components can be abstracted, grouped and presented to provide a single process, or to provide more complex user stories for a consuming application. Services are the preferred communication technique across application boundaries, including platform, deployment, and trust boundaries.  The key attributes of SOA are:
  • Interoperable. Components can be interoperable across platform and technology boundaries.  In fact, a well designed service should be totally agnostic to the technologies interacting with it.
  • Autonomous. Services are exposed as autonomous components that can be versioned and managed independently.  As with all good platform design, think of each service as a black box.
  • Abstracted. Services should be abstracted at a granular enough level so they can be grouped by another service or application to perform more complex operations as a single method.  This is what I often call a user story service layer.  Business logic can be abstracted and presented as specific component-like stories for targeted consumption.
  • Interface based. Interfaces are defined by message contracts and schemas. Operation calls and parameters are passed in XML message envelopes.  Stick to agreed upon standards here for maximum scalability and interoperability.
  • Location agnostic. Service components can be consumed from the same machine or distributed to remote machines. The service interface and logic is independent of the transport and protocol used to access the service.  This gives you many points to scale and inject redundancy for performance and dependability.
  • Discoverable. Services publish their interface in such a way that client applications can discover them and generate a proxy mechanism for consumption.

I try to adhere to the agreed upon four tenets of SOA from Microsoft architect Don Box:
  • Boundaries are explicit. Services are black-boxed and will never allow direct internal visibility.  All interaction comes from agreed upon messaging and interaction methods.
  • Services are autonomous. Each service is viewed autonomously with a complete disregard for any client activities or accompanying services.  While interaction is allowed and obviously required, see the first tenet.  These services should not be intimately aware of each other.
  • Services share schemas and contracts, not class. Services share contracts and schemas to communicate.  This is analogous to a menu in a restaurant.  All of the inner workings are abstracted to a set of choices and communicated with an agreed upon contract. 
  • Compatibility is based upon policy. Policy in this case means definition of transport, protocol, security, etc.  This is primarily where we are focusing today.
To focus in on the compatibility tenet, let's delve into security at a deeper level. Security is fundamentally about protecting assets. Assets may be physical items such as code sets, methods or a database, but also can be more nebulous, such as your brand.  It is important to recognize that security is a commitment, not a software feature, as it is a never-ending process. As you design services and applications, you need to identify potential threats and understand that each threat presents a degree of risk. Security is basically about mitigating those risks via restrictions and/or counter measures. When done effectively,  security is a combination of people, process, and technology.

Security is comprised primarily of the following ideals:
  • Authentication. Authentication is, at its base, the ability for a system to know who the user is.  It is the process of uniquely identifying the users of applications and services. Keep in mind that users of applications and services may be people, other services, processes, or computers. When reading security documentation or writing code, these 'users' are called Principles.
  • Authorization. Authorization is the equivalent of a key card.  Just as a key card gives its holder permission to enter certain rooms in a building, authorization manages the resources and operations that the authenticated client is permitted to access. These resources can include operations, physical storage (as granular as tables and rows), registry keys and other  configuration data. Operations are basically equivalent to the methods at any given layer of the SOA.
  • Auditing. Effective auditing and logging is the key to non-repudiation. Non-repudiation at its base is evidence.  If you have implementing effective auditing, a user or process will be unable to deny its activities. For example, in a medical system, auditing is required to make sure that a user cannot deny changing information in a specific patient chart.
  • Confidentiality. Confidentiality, or privacy, is the process of making sure that all data is private and confidential and cannot be viewed by unauthorized users who attempt to monitor the traffic across a network. Encryption is the most used method of confidentiality.  Primarily, you must ensure that the only users and processes who can view specific data, are the ones for whom it is intended.
  • Integrity. Integrity is the guarantee that data is protected from modification, be it accidental or malicious. Like privacy, integrity is a huge deal, particularly when there is sensitive data being passed across networks. Integrity for data in transit is typically provided by using hashing and message authentication codes.
  • Availability. From a security perspective, availability means that systems remain available for legitimate users.  There are some malicious individuals who will attempt to bring down your services and thus cause your real users to be unable to leverage the system.  The denial of service attack (DoS) is aimed at simply over-running your system and bringing it down. 
Some keys to building secure services include the following:
  • Identify the targets for security. You should think through all of the objectives you have for security. User stories are a good tool for gaining insight into the natural roles and levels of security that come from usage of your system.  Identify all assets that need security as well as the granularity to which security is applied.
  • Understand the possible threats. Try to identify the threats which are relevant for your scenarios and context. This is called 'Threat Modeling' and is a good practice which helps you identify the realistic  threats to your system. Your security targets will help you prioritize your threats and vulnerabilities. Using the threat model, architects and developers should address vulnerabilities, and QA should ensure that the developers have addressed the vulnerability.
  • Stay away from 'roll your own' security. Proven principles, patterns, and practices are the best place to start building a security model.  By using time-tested, proven principles, patterns, and practices, you can eliminate entire groups of security problems without needing to discover the specific vulnerability in your identification process. You should take advantage of the experience of others when it comes to security.  That being said, proven principles, patterns, and practices are a great starting point.  But like all other architectural paradigms, security is fact dependent and you should not just implement something off-the-shelf without going through the identification and threat processes.
  • Commit to security as an eternal process.  Security should be of paramount consideration at every stage of a service, application or software development life cycle. At every stage, targets should be defined, threats should be modeled and mitigating actions should be taken.  Security is not and will never be a 'set it and forget it' item.
I am going to dig deeper into some of the possible mechanisms for securing WCF services in a web environment in the near future.  As part of a current project, I am spending a lot of mental energy looking into the options.  I will post some of the opportunities and how to leverage them in the coming days and weeks.

Thursday, January 17, 2013

Javascript is a Free-For-All....

As part of a boot camp I am teaching this week, we decided to see how much insanity we could inject into Javascript before it would fail.  The group is made up of experienced C# programmers and we decided to experiment with blowing up the sort of structure and type restrictions we have all grown accustomed to in a structured language.  We created the following code block just to see how far we could push the 'undefined ' functionality, along with the variable typing being a basic free-for-all.


var arr = function()
{
  alert(arr['testB']);
}

arr['testA'] = true;
arr['testB'] = false;
arr['testC'] = true;
arr[arr[0]] = arr;

document.write(arr[arr[0]]);
document.write("<br/>");

document.write(arr['testC']);
document.write("<br/>");

document.write(arr[0]);
document.write("<br/>");

arr[arr[0]]();
document.write("<br/>");

document.write("foreach...<br/>");

for (var i in arr)
{
  document.write(arr[i]);
  document.write("<br/>");
}


This is not only viable syntax, but this code will run and output values consistent with the index resolution of the array (when it is an array and not a function, that is).  Interestingly, it appears to be a valid strategy to have an undefined value as a key in a key value pair.  My favorite aspect of this is declaring a function, array and key/value list as a single variable and have it act accordingly depending on how you reference it.  Even when you make one of the values within the key/value array the array itself.

Go home Javascript, you are drunk.

Friday, January 11, 2013

WebSockets

The web is based on the request/response paradigm of HTTP.  This pattern comes with inherent latency in communication by forcing a consumer of data to request all data to be consumed.  AJAX has really helped in making web application communication more dynamic than it had been historically; however, all HTTP communication is still completely driven by the client side of the equation.  This forces a developer to engage in user interaction or long-polling to create applications that, while they look and feel dynamic, are really still request/response in some fashion.  Push communication is loosely defined as the ability for a server to send data to its client without requiring the client to ask for it.  People have historically falsified a push application by engaging in long polling solutions.  A long polling solution requires that a client open a connection to the server so the server can keep it open until something is sent to the client.  At that point, the client deals with the data and then opens another long polling connection.  While enabling some dynamism, at the end of the day, it is a hack.  The new WebSocket technology defines an API for creating connections between a web browser and a server.  This allows the web client application to be notified from the server when and if the server has pertinent information for the client.

Walk-through

Following is a sample block of code using Javascript.  This will hit a WebSocket server and handle notifications based on listening to the events from the socket itself.  This sample was stolen verbatim from WebSocket.org and is a great example of a simple creation, connection and consumption mechanism.


var wsUri = "ws://echo.websocket.org/";
  var output;

  function init()
  {
    output = document.getElementById("output");
    testWebSocket();
  }

  function testWebSocket()
  {
    websocket = new WebSocket(wsUri);
    websocket.onopen = function(evt) { onOpen(evt) };
    websocket.onclose = function(evt) { onClose(evt) };
    websocket.onmessage = function(evt) { onMessage(evt) };
    websocket.onerror = function(evt) { onError(evt) };
  }

  function onOpen(evt)
  {
    writeToScreen("CONNECTED");
    doSend("WebSocket rocks");
  }

  function onClose(evt)
  {
    writeToScreen("DISCONNECTED");
  }

  function onMessage(evt)
  {
    writeToScreen('<span style="color: blue;">RESPONSE: ' + evt.data+'</span>');
    websocket.close();
  }

  function onError(evt)
  {
    writeToScreen('<span style="color: red;">ERROR:</span> ' + evt.data);
  }

  function doSend(message)
  {
    writeToScreen("SENT: " + message); 
    websocket.send(message);
  }

  function writeToScreen(message)
  {
    var pre = document.createElement("p");
    pre.style.wordWrap = "break-word";
    pre.innerHTML = message;
    output.appendChild(pre);
  }

  window.addEventListener("load", init, false);
 
You should try to use a WebSocket when you need low latency, real-time connections between the client and the server.  This technology can reduce your application chattiness and provide a truly dynamic experience for all of your users.  As more browsers move to support the WebSocket, this will push the envelope again on developing web based applications.  We will be able to provide the same kind of functionality we have grown used to in a net.tcp environment to distributed users of a web application.

Thursday, January 3, 2013

ASP.NET Web Tools 2012.2 Release Candidate

 Last Month, Microsoft released the ASP.NET and Web Tools 2012.2 update.  This release will extend the ASP.NET runtime a little bit and adds new tools to Visual Studio 2012. This update adds some new features and tools for all the flavors of ASP.NET (Web Forms, MVC, Web API, etc.).  I copied some of the highlights from the release marketing below.  It sounds pretty cool.

ASP.NET Enhancements
This update adds new ASP.NET templates and features, including:
  • New ASP.NET MVC templates.
    • Creating Facebook applications just became easier using the new Facebook Application template. In just a few easy steps you can create a Facebook application that gets data from logged in users and integrates with their friends.
    • A new Single Page Application template allows developers to build interactive client-side web apps using Knockout, jQuery, and ASP.NET Web API.
  • Real-time communication support with ASP.NET SignalR.  This enables you to easily take advantage of the new WebSocket support in .NET 4.5, while also automatically degrading to long-polling and other protocols for older clients.  If you haven’t tried SignalR yet you should – it is awesome.
  • New ASP.NET Web API functionality, including support for OData, integrated tracing, and automatically generating help page documentation for your API.
  • New ASP.NET Friendly URL functionality. This new feature makes it very easy for Web Forms developers to generate cleaner looking URLs (without the .aspx extension). The Friendly URLs feature also makes it easier for developers to add mobile support to their applications with support for mobile .ASPX pages and  supporting switching between desktop and mobile views.  It can be used with existing ASP.NET v4.0 applications.
  • Visual Studio 2012 Web publishing enhancements. Web site projects now have the same publish experience as web application projects (including to Windows Azure Web Sites), and you can selectively publish files, see the differences between local and remote files, and update local to remote files or vice versa.
  • Visual Studio 2012 Page Inspector enhancements. JavaScript selection mapping is now supported, and you can CSS updates in real-time.
  • Visual Studio 2012 editor support for Knockout IntelliSense and pasting JSON as a .NET class (which makes it even easier to consume Web APIs from others).
  • Visual Studio 2012 Project Template updates, including the latest versions of jQuery, jQuery UI, jQuery Validation, Modernirz, Knockout and more…
How it is delivered
You can download and install an integrated setup that contains the above enhancements today from http://www.asp.net/vnext.  The new runtime functionality is delivered to ASP.NET via additional NuGet packages. This means that installing this update does not make any changes to the existing ASP.NET binaries, and thus does not cause any compatibility issues with existing projects. New projects will contain the new functionality and existing projects can be updated with the new NuGet packages.

Summary
Web development is changing, and ASP.NET is rapidly delivering new capabilities to developers that help them take full advantage of new capabilities.  The ASP.NET and Web Tools 2012.2 update installs in minutes without altering the current ASP.NET run time components.  For a complete description see the Release Notes.

You can download and install the RC today: http://www.asp.net/vnext.

Wednesday, December 26, 2012

Javascript Extension Via Constructor

When using Javascript, there are a few ways to inherit or extend object definitions.  Depending on the choices you have made for your prototype declaration, some options make more sense than others.  For this discussion, let's focus on using a function to declare your prototype. This is a pretty common practice and does dictate some other direction if this is where you started.  Let's look at the following declaration:


function Vehicle(numWheels, motor)
{
     this.NumberOfWheels = numWheels;
     this.MotorType = motor;    
};


This is a pretty straightforward object.  We are simply creating a definition for a vehicle based on its number of wheels and the type of motor included.  If we want to extend this prototype and add a function allowing the vehicle to be driven, we would have two possible choices.  We could extend the prototype or simply update the original definition.  It may be best to extend the prototype in order to adhere to good design (e.g. the open/closed principle).  So, we will extend the prototype as follows:

Vehicle.prototype.Drive = function(){document.write("driving from the prototype!<br/>");}


Now our vehicle has the ability to drive via its extended prototype.  Our next step would be to extend the Vehicle object into another object based upon the definition of a Vehicle.  Again, assuming the use of constructor functions for object definitions, we would  start like this.

function MotorCycle(make, model)
{  
     Vehicle.call(this, 2,"V-Twin");
     this.Make = make;
     this.Model = model;
}


The line of code that is giving us the copy of properties is Vehicle.call(this, 2, "V-Twin"); This line is basically grabbing the properties from the Vehicle definition and extending them into the Motorcycle class.  If I were to create a new MotorCycle and output its definition to the document, it would look like this: {"NumberOfWheels":2,"MotorType":"V-Twin","Make":"Honda","Model":"VTX"}".  But, if I were to try to Drive() my new MotorCycle, what would happen?  Nothing.  The Motorcycle doesn't know how to drive since the definition from the prototype has not been applied to the MotorCycle.  In order to have the prototype functions attached to the new object, you have to explicitly set the MotorCycle prototype by default as follows:

MotorCycle.prototype = new Vehicle("2","V-Twin");
MotorCycle.prototype.constructor = MotorCycle;


This gives us access to the functions defined in the prototype of the Vehicle.  The second line appears to have no bearing upon the output or operation of the MotorCycle class.  While this is true at a glance, you have to focus on good design principles ensuring that behavior is what would be expected at every layer of inheritance, a.k.a., the Liskov Substitution Principle.  In Javascript, many people will do type-checking by performing a check against the constructor.  So, in the following statements, the MotorCycle.prototype.constructor = MotorCycle; statement would be the difference between a type check failing or passing.  Without getting into other ways to perform that check, let's just focus on the fact that people will do this:


if( cycle.constructor == Vehicle)
{
   document.write("type check says I am a vehicle");
}
else if( cycle.constructor == MotorCycle)
{
   document.write("type check says I am a motorcycle");
}


Many of the decisions made during the design of the prototype of an object will dictate direction when using the object itself.  In the following code, I have commented out all of the lines that have to do with possible methods of prototyping and extension.  As an exercise, it is interesting to choose varying methods and interact with the prototype by removing the comment from different lines and see how they interact.

function Vehicle(numWheels, motor)
{
     this.NumberOfWheels = numWheels;
     this.MotorType = motor;
//     this.Drive = function(){document.write("driving from the base<br/>");}
};

//Vehicle.prototype.Drive = function(){document.write("driving!<br/>");}


function MotorCycle(make, model)
{  
  //   Vehicle.call(this, 2,"V-Twin");
     this.Make = make;
     this.Model = model;
}


//MotorCycle.prototype = new Vehicle("2","V-Twin");
//MotorCycle.prototype.constructor = MotorCycle;

var cycle=new MotorCycle("Honda","VTX");
document.write(JSON.stringify(cycle)+"<br/>");
cycle.Drive();

if( cycle.constructor == Vehicle)
{
   document.write("old school type check says I am a vehicle");
}
else if( cycle.constructor == MotorCycle)
{
   document.write("old school type check says I am a motorcycle");
}


I have been an object-oriented developer for over 15 years on structured languages such as C++ and C#.  As I spend more time with Javascript, I keep flashing back to a certain meme that sums up my initial reaction to Javascript. 


That is until you really dig in and just spend time trying to break and fix things.  Then, it becomes at least a little bit more clear and can be related back to the knowledge you may already have.