Security in WCF

Pratikshagzb
Posted by in WCF category on for Beginner level | Views : 128522 red flag

WCF is distributed programming platform . Using WCF, you can create applications that function as both services and service clients.Security in WCF provides Authentication,Authorization,Integrity,Confidentiality.

Here in this article I have discussed security in WCF.


 Download source code for Security in WCF

Topics Covered


1.    Is security needed in WCF.
2.    Choices in WCF

·         Transport Security

·         Message Security

.         Mixed Mode

·         Credentials

3.    Default Security in Standard Bindings

·         basicHttpBinding

·         wsHttpBinding

·         netTcpBinding

4.    Implement Transport Security
5.    Implement Message Security




1. Is Security needed in WCF at all?


In distributed application, in the intermediate nodes or in the network there are malicious user, hackers always on the prowl to transfer funds, obtain sensitive information, phishing, alteration of messages etc. This gives way to a variety of message security threats.

I have quoted some examples where WCF security helps us in moderating security threats.

·         Phishing Attack

In this malicious user acts as online service and obtains user name, password etc. Then this malicious user transfers funds into his account. This is known as Phishing attack which is very common now a days. Daily you must have received emails asking for username, password or you have won a lottery and asks for your Account number to credit the amount in your  account .If you provide the information the malicious user transfers funds into his account .This is known as Phishing .

  •  Stealing sensitive information from Network Traffic

The spy of other country intercept Network Traffic to obtain sensitive defence related information and use it to their advantage or  in online–banking client transfers funds from one account to another. A malicious user intercepts the message and having account number and password  transfers  funds into his account.

·         Alteration of messages to transfer funds in malicious user Account

Intercept messages sent through network and altering the account number to which deposit is made to transfer fund in malicious user Account.

  • Malicious user or Hacker replays the purchase order

Eg. Onlline shopping website receives hundreds of orders and sends items to Customers who have not even ordered them.

  • Authentication

The Service cannot assure that authorized person indeed performed the Transaction.

So after all this security is needed.

Windows Communication Foundation provides the basic security features that most distributed systems need. The big three protections— confidentiality, integrity, and authentication (or CIA as I like to think of them) are provided by most standard Windows® Communication Foundation bindings. If you don't want these protections, you'll have to turn them off, because they are on by default.

When you hear people say, "Windows Communication Foundation is secure by default," understand that they are probably talking about CIA.

 


 

2. Security Choices in Windows Communication Foundation


First step to secure WCF is to define security policy. When you expose a service endpoint you also select a binding for proper communication protocol and message encoding format.

Example-For intranet communications or systems behind the firewall, TCP protocol with binary message encoding is  preferred. For Internet access, HTTP protocol is a typical choice using text or MTOM encoding (depending on the message size).

You don’t need to make just one choice. You can expose contract over many bindings.

A standard set of bindings satisfy these protocol and encoding choices. 

·         NetTcpBinding is the right choice for binary TCP communications that cross machine boundaries.

·         BasicHttpBinding is the right choice for HTTP communications that must support legacy Web service        protocols.

·         WSHttpBinding orWSFederationHttpBinding are the right choice for Web services that can leverage a richer set of standards including those for secure communications.
Beyond bindings, behaviors also provide information about client and service credentials, and affect how authorization is handled.

You can configure bindings and behaviors declaratively or through the runtime object model.

 Each binding provides default security settings. The two important knobs in security settings are security mode( transport versus message security) and Client Credential.


Transport Security



In Transport security  transports available for use are HTTP, TCP, IP and MSMQ. All  communication that takes place across the channel must be encrypted.


Advantage of using Transport security:

Less chances of Message Alteration, Sniffing network, Phishing and replay of message attack.

 Transport level security provides

Authentication of the senderservice, Message integrity, Confidentiality and Replay of message detection.

When you configure security for WCF  binding,  you'll need to decide  whether you want CIA to be provided at the transport level or at the message level.

 

If you configure wsHttpBinding for transport security, WCF will not supply CIA for your messages. You need to run URI  over HTTPS . If you're hosting inside IIS, you'll need to install an SSL certificate for the Web site. On the other hand, if you're hosting in your own process and using HTTP.SYS directly, you'll need to register a certificate with HTTP.SYS, either programmatically or via the command-line tool, HTTPCFG.EXE.

For Intranet where both client and service use WCF, netTcpBinding with transport security might be a better choice. It  performs  better due to its  binary encoding.

Message Security

Message Security is applied at the message layer which is transport independent. It has maximum flexibility in terms of having the message routed over different transports. WS-Security defines different ways to secure a message and the tokens that can be used. Message Security is slowest in terms of performance.

 

You can provide CIA at the transport level, you can choose to push these details down into the SOAP messages themselves by using message security.

 

Eg wsHttpBinding  By default it uses message-level security, assuming the service and the client will identify and authenticate themselves using Windows credentials. Body and most headers are signed to maintain the integrity of the message and the body is encrypted. An attacker looking at a message trace would see the SOAP envelope in the clear, but the SOAP body would contain an EncryptedData element full of base64-encoded ciphertext.

 

Mixed Mode

WCF also allows you to mix transport and message security. At Transport level confidentiality, integrity and authentication are provided  (therefore the entire bytestream is encrypted, not just the message body).Client authentication is performed at the message level. The client can then use WS-Security to send any shape of credential that she wants.

 

Credentials

After deciding  whether to use either transport or message security (or mixed mode), and assuming you've not chosen a security mode of None, the next major decision is the shape of credential that the client and service will use.

Credential is used to provide verification of identity.

WCF GIVES  client credential type. There are at least five options for client credentials, although some options may not be available in certain contexts

 

                  

3. Default Security in Standard Bindings


The three most popular standard bindings are basicHttpBinding, wsHttpBinding, and netTcpBinding. The simplest is basicHttpBinding.This doesn't provide CIA by default. This type of  binding is secured  by running over HTTPS. For this you'll need to change  the binding to let WCF know you'll be using transport security:


i).   basicHttpBinding


<bindings>

  <basicHttpBinding>

    <binding name="MyBindingChanged">

      <security mode="Transport">

        <transport clientCredentialType="None"/>

      </security>

    </binding>

  </basicHttpBinding>

</bindings>

Now  deploy this  in IIS and turn on SSL support for your virtual directory.Install a certificate for the Web site.  If you're deploying in IIS and plan to require client certificates, change the clientCredentialType to Certificate.

 

ii).   wsHttpBinding


The next binding, wsHttpBinding, uses message security by default The default client credential type is Windows. You can use  this binding to switch it to use TransportWithMessageCredential. Here you'll use an HTTPS endpoint to provide authentication, integrity, and confidentiality, while the client credential remains in the SOAP Security header for flexibility.SOAP envelope with header is encrypted by the transport. There are some disadvantages, however, such as the lack of end-to-end security at the message level.

<binding name="MyBindingChanged">

  <security mode="TransportWithMessageCredential">

    <transport clientCredentialType="None"/>

    <message clientCredentialType="IssuedToken"/>

  </security>

</binding>

 

iii). netTcpBinding


If you want raw speed for Web services intranet use netTcpBinding .This binding uses transport security with Windows credentials.  The default binding uses transport security.

<client>

  <endpoint name="MyEndpointChanged" address="net.tcp://..."

    binding="netTcpBinding" contract="IFoo" >

    <identity>

      <servicePrincipalName value='MyArticleService/MyArticleMachine' />

    </identity>

  </endpoint>

</client>

 

iv).   Implement Transport security


SAMPLE WCF SERVICE

Step 1:

Click on new project and select WCF service project.

public class Service1 : IService1

{

public string GetData(int value)

{

return string.Format("The Value entered: {0}", value);

}

public CompositeType GetDataUsingDataContract(CompositeType composite)

{

if (composite.BoolValue)

{

composite.StringValue += "Add";

}

return composite;

}

}

Step 2:

To enable transport security in WsHttp binding. This is done using the ‘Security’ XML tag as shown in the below code snippet.

<bindings>

<wsHttpBinding>

<binding name="TransportSecurity">

<security mode="Transport">

<transport clientCredentialType="None"/>

</security>

</binding>

</wsHttpBinding>

</bindings>

Step 3: Tie up the Binding and specify HTTPS Configuration

Now use the ‘bindingConfiguration’ tag to specify the binding name. We also need to specify the address where the service is hosted. HTTS in the address tag.

Change ‘mexHttpBinding’ to ‘mexHttpsBinding’ in the second end point

<service name="WCFWSHttps.Service1" behaviorConfiguration="WCFWSHttps.Service1Behavior">

<!-- Service Endpoints -->

<endpoint address="https://localhost/WCFWSHttps/Service1.svc" binding="wsHttpBinding" bindingConfiguration="TransportSecurity" contract="WCFWSHttps.IService1"/>

<endpoint address="mex" binding="mexHttpsBinding" contract="IMetadataExchange"/>

</service>

 

In the ‘serviceMetadata’ we also need to change ‘httpGetEnabled’ to ‘httpsGetEnabled’.

<serviceBehaviors>

........

.........

<serviceMetadata httpsGetEnabled="true"/>

.........

.........

</serviceBehaviors>

Step 4: Make the Application HTTPS enabled

Compile the WCF service project and host the same in IIS application with HTTPS enabled
.

Code for consuming Service-

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.UI;

using System.Web.UI.WebControls;

using WebApplicationConsumer.ServiceReference1;

using System.Net;

using System.Net.Security;

using System.Security.Cryptography.X509Certificates;

 

namespace WebApplicationConsumer

{

public partial class _Default : System.Web.UI.Page

{

 

protected void Page_Load(object sender, EventArgs e)

{

ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(IgnoreCertificateErrorHandler);

Service1Client obj = new Service1Client();

Response.Write(obj.GetData(007));

}

public static bool IgnoreCertificateErrorHandler(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)

{

return true;

}

}

}

Step 5: Now compile the Application.


v). Implement Message Level Security

Step 1: Create Client and Server Certificates using makecert.

Step 2:

In the web.config file of the WCF service.

<serviceCredentials>

<clientCertificate>

<authentication certificateValidationMode="PeerTrust"/>

</clientCertificate>

<serviceCertificate findValue="WCfServer"

storeLocation="CurrentUser"

storeName="MyArticle"

x509FindType="FindBySubjectName" />

</serviceCredentials>

Step 3. Define Bindings

I  have defined the ‘WsHttpBinding’ with message attribute specifying that the WCF client needs to send a certificate for validation.
 

<bindings>

<wsHttpBinding>

<binding name="wsHttpEndpointBinding">

<security>     

<message clientCredentialType="Certificate" />

</security>

</binding>

</wsHttpBinding>

</bindings>

Step 4 :Tie the Bindings with the End point

Use ‘bindingConfiguration’ tag as shown in the below code snippet.

<endpoint address="" binding="wsHttpBinding" "BACKGROUND-COLOR: #ffff00">bindingConfiguration"BACKGROUND-COLOR: #ffff00">="wsHttpEndpointBinding" contract="WCFServiceCertificate.IService1">

Step 5  Make Application to Consume the Web Service

Compile the WCF service and reference the same in the ASP.NET web application using ‘Service reference’. Below is the code snippet where we have referenced the service and called the ‘GetData’ function of the service.

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.UI;

using System.Web.UI.WebControls;

"BACKGROUND-COLOR: #ffff00">using WebConsumer.ServiceReference1;

namespace WebConsumer

{

public partial class _Default : System.Web.UI.Page

{

protected void Page_Load(object sender, EventArgs e)

{

"BACKGROUND-COLOR: #ffff00">Service1Client obj = new Service1Client();

"BACKGROUND-COLOR: #ffff00">Response.Write(obj.GetData(12));

}

}

}

Step 6 : Define Certificates in WCF Client

I have set  authentication mode as ‘peertrust’ and we have specified the client certificate name as ‘WcfClient’.

<behaviors>

<endpointBehaviors>

<behavior name="CustomBehavior">

<clientCredentials>

<clientCertificate findValue="WcfClient" x509FindType="FindBySubjectName" storeLocation="CurrentUser" storeName="MyArticle" />

<serviceCertificate>

<authentication certificateValidationMode="PeerTrust"/>

</serviceCertificate>

</clientCredentials>

</behavior>

</endpointBehaviors>

</behaviors>

Step7 : Tie up the behavior with end point on WCF client

Now  bound the behavior using ‘behaviorConfiguration’ property. We also need to specify that the DNS value .

<client>

<endpoint address="http://localhost:1387/Service1.svc" binding="wsHttpBinding"

bindingConfiguration="WSHttpBinding_IService1" contract="ServiceReference1.IService1"

name="WSHttpBinding_IService1"

"BACKGROUND-COLOR: #ffff00">behaviorConfiguration="CustomBehavior">

<identity>

"BACKGROUND-COLOR: #ffff00"><dns value="WcfServer" />

</identity>

</endpoint>

</client>

Step 8 : Now run the Application.

 

I think I have covered security aspects of WCF in an easy way.

As always your suggestions are welcome.

Reference:  

Msdn,Code reference from Shivprasad Koirala Code Project Article.

Page copy protected against web site content infringement by Copyscape

About the Author

Pratikshagzb
Full Name: Pratiksha Saxena
Member Level: Starter
Member Status: Member
Member Since: 3/26/2010 12:52:14 AM
Country: India



Login to vote for this post.

Comments or Responses

Posted by: Brajesh.mahor on: 4/22/2011 | Points: 25
how to authenticate using username and password

Login to post response

Comment using Facebook(Author doesn't get notification)