Friday, July 27, 2012

Programming WCF Security – Three


So in Programming WCF Security - One, we discussed core security features that WCF addresses & Transport Level Security, & in Programming WCF Security - Two, Lets move to next I’ll discuss more about Authentication , Authorization & Impersonation ...
Although it might seems like it should be a simple process to determine who someone is? The reality is that it’s not. Problems are well understood, who confirms the credentials? Which encryption is used? Describing how WCF provides answers to these questions is purpose of this discussion. Here I will discuss more about Authentication, Authorization & little bit about Impersonation too.
Authentication
Basically, authentication is process of one party verifying that the claims regarding the identity of second party are correct. Typically that would be client needing to be verified by the service; however this is possible for the service to also authenticate itself with the client. WCF offers a variety of authentication mechanisms:
  1. No Authentication (Anonymous Authentication)
  2. Windows Authentication
  3. User name & password
  4. X.509 certificate
  5. Issued tokens Authentication
  6. Custom Authentication
Issued tokens Authentication
 
The main idea behind the issued token credentials is to allow a third-party token granting authority to perform the authentication process. The client requests a token and then includes that token in the request to the WCF service. The WCF service then hands that token to the token granting authority to retrieve information about the requester. With following sample of service configuration file:
 
<services>
<service name=”Samples.Service” behaviorConfiguration=”ServiceBehavior”>
<!– Use the base address provided by the host. –>
<endpoint address=”" binding=”wsHttpBinding”
bindingConfiguration=”requireInfocard″
contract=”Samples.IService” >
<identity>
<certificateReference findValue=”” X509FindType=”” storelocation=”” storename=””
</identity>
</endpoint>
</service>
</services>
<bindings>
 <wsHttpBinding>
   <binding name=” requireInfocard”>
     <security mode=”message”>
       <message clientCredentialType=”IssuedToken”
     </security>
    </binding>
 </wsHttpBinding>
</bindings>
<behaviors>
 <serviceBehaviors>
<behavior name=”ServiceCredentials”>
        <serviceCredentials>
         <serviceCertificate =”” X509FindType=”” storelocation=”” storename=”” />
         <issuedTokenAuthentication allowUntrustedRsaIssuers=”True” />
        </serviceCredentials>
</behavior>
 <serviceBehaviors>
</behaviors>
Above settings provide details of which authentication facility to use. 
Authorization & Impersonation
Being able to identify the client it just half the process, Authorization determines the access that is allowed to various resources. You can control access in several ways with Windows Communication Foundation (WCF)
  1. PrincipalPermissionAttribute
  2. Identity Model
We will only discuss how Restrict Access with the PrincipalPermissionAttribute Class here, for Identity Model Please visit MSDN.
Controlling the access to resources on a Windows-domain computer is a basic security task. For example, only certain users should be able to view sensitive data, such as payroll information. The task consists of two separate procedures. 
The first creates the group and populates it with users. The second applies the PrincipalPermissionAttribute class to specify the group.
To create a Windows group
  1.  Open the Computer Management console. In the left panel, click Local Users and Groups.
  2.  Right-click Groups, and click New Group.
  3.  In the Group Name box, type a name for the new group.
  4. In the Description box, type a description of the new group.
  5.  Click the Add button to add new members to the group.
  6. If you have added yourself to the group and want to test the following code, you must log off the computer and log back on to be included in the group. 
To demand user membership

1. Open the Windows Communication Foundation (WCF) code file that contains the implemented service contract code.

2. Apply the PrincipalPermissionAttribute attribute to each method that must be restricted to a specific group. Set the Action property to Demand and the Role property to the name of the group. For example:

[PrincipalPermission(SecurityAction.Demand,
  Role = "CalculatorClients")]
public double Add(double a, double b)
{    return a + b; }

Using a Certificate to Control Access to a Method
[PrincipalPermission(SecurityAction.Demand,
  Name = "CN=ReplaceWithSubjectName;
  123456712345677E8E230FDE624F841B1CE9D41E
")]
public double Add(double a, double b)
{    return a + b; } 
Impersonation Basics
Windows Communication Foundation (WCF) supports impersonation for a variety of client credentials by following two approaches
  1. Cached Token Impersonation
  2.  S4U-Based Impersonation
The extent to which the service can impersonate the client depends on the privileges the service account holds when it attempts impersonation, the type of impersonation used, and possibly the extent of impersonation the client permits. To enable impersonation, set the Impersonation property to one of the Impersonation Option enumeration values as follows
  [OperationBehavior(Impersonation = ImpersonationOption.Required)]
    public string Hello(string message)
    {return "hello";}

This is all about Windows Communication Foundation Security Infrastructure.

Tuesday, July 24, 2012

Programming WCF Security - Two

So in Programming WCF Security - One,we discussed core security features that WCF addresses & Transport Level Security, Let's move to next...

Message Level Security...
The main difference between transport & message security is that the message security includes required credentials & claims along with message. Contrast this with transport security, use handshaking or external resources such as active directory to verify credentials associated with message… 
The Biggest reason for choosing message level security over transport level is that message is self-contained because it allows number of scenarios that are not possible using transport security e.g. When using transport security, it secures message from endpoint to endpoint  over channel . After message has been received, it’s not encrypted... while Message level security provides end to end encryption... Even after a message has been received it’s still encrypted....A second reason for consideration is different parts of message can be secured using different encryption mechanisms.
Let’s see how to implement Message level security in WCF with certificates at both Server and Client end.
Step 1:  As we are dealing with Sample programs, we don't need “VeriSign” approved certificates. So let's generate our own. We need to create both Server and Client certificates.

 makecert.exe -sr CurrentUser -ss My -a sha1 -n CN=WCfMsgTestServer -sky exchange -pe

makecert.exe -sr CurrentUser -ss My -a sha1 -n CN=WcfMsgTestClient -sky exchange -pe
In order to do so, we need to install SDK tools from Microsoft. If you install, you may find makecert.exe in "C:\Program Files\Microsoft SDKs\Windows\v7.1\Bin" else download from here. Now traverse to the path mentioned above in command prompt. Execute above code snippet.

Step 2: Both the certificates are created but they are not still under trusted category. For that Open Microsoft Management Console. Go to Run --> execute "MMC"
Now console is opened, go to File --> Click on "Add/Remove Snap-in" --> now select Certificates on left pane and click "Add" button.
 Now certificates are registered, we have to made configuration settings at both Server and Client end.

Step 3: Insert below code snippets in you server configuration file.

Binding Behavior:
<bindings> 
    <wsHttpBinding>
             <binding name="wsHttpEndpointBinding">
                   <security>
                        <message clientCredentialType="Certificate" />
                  </security>
           </binding> 
     </wsHttpBinding> 
  </bindings>


<serviceCredentials>
      <clientCertificate>
         <authentication certificateValidationMode="PeerTrust"/>
      </clientCertificate>
      <serviceCertificate findValue="WCfMsgTestServer"
         storeLocation="CurrentUser"
         storeName="My"
         x509FindType="FindBySubjectName" />
</serviceCredentials>
 
 
Step 4:  Create client application, add service reference & Configure client certificate credentials in client code.

<behaviors>
      <endpointBehaviors>
        <behavior name="CustomBehavior">
          <clientCredentials>
            <clientCertificate findValue="WcfMsgTestClient" x509FindType="FindBySubjectName" storeLocation="CurrentUser" storeName="My" />
            <serviceCertificate>
              <authentication certificateValidationMode="PeerTrust"/>
            </serviceCertificate>
          </clientCredentials>
        </behavior>
      </endpointBehaviors>
</behaviors>

Change the endpoint definition by associating the behavior to end point and pointing the identity of end point to server certificate.

<client>
      <endpoint address="http://localhost:39487/Service1.svc" binding="wsHttpBinding"
        bindingConfiguration="WSEndpoint" contract="WCFMsgSecService.IService1"
        name="WSEndpoint" behaviorConfiguration="CustomBehavior">
        <identity>
          <dns value="WcfMsgTestServer"/>
        </identity>
      </endpoint>
    </client>


By These changes client will be able to communicate with service using message level security.

Courtesy: Random Web Images, MSDN, Microsoft .NET 3.5 WCF Book, Several online resources