Welcome to MSDN Blogs Sign in | Join | Help

Patterns and Practices: WCF Security Guidance available online

The Microsoft Patterns and Practices team has created a guide for WCF security.

http://blogs.msdn.com/jmeier/archive/2008/03/27/patterns-and-practices-wcf-security-guidance-now-available.aspx

You can find more information at the root site

http://www.codeplex.com/WCFSecurity/

Posted by govindr | 0 Comments
Filed under: ,

503 Server Unavailable failure with IIS 7.0

When working with IIS 7.0 in Vista if you are seeing this failure trying to access the webserver, there are couple of things to look for.

 1. Check if the Application Pool is running. You can click on the Application Pools option on the Left Pane of IIS 7.0 and check all running App pools.

2. You might have the URL http://+:80 reserved. Run netsh http show urlacl from a command window. If this shows an output similar to

     Reserved URL            : http://+:80/
        User: BUILTIN\IIS_IUSRS
            Listen: Yes
            Delegate: Yes
        User: BUILTIN\Administrators
            Listen: Yes
            Delegate: Yes
        User: NT AUTHORITY\NETWORK SERVICE
            Listen: Yes
            Delegate: Yes
            SDDL: D:(A;;GA;;;IS)(A;;GA;;;BA)(A;;GA;;;NS)

Then you have this port reserved which takes precedence over your http://localhost calls. Go ahead and remove this URL reservation by running the following command,

netsh http delete urlacl url=http://+:80/

Posted by govindr | 2 Comments
Filed under: , ,

Reliable Messaging and SecurityToken validation

One of the things that have come up many times is how the service could stop a client from retrying a request for a valid security validation error while Reliable Messaging is enabled. If you are not familiar with the situation the essence of the problem is this,

Binding on the Service has Reliable Messaging (RM) enabled. You can do this using WsHttpBinding and setting the ReliableSession.Enabled property to true. What this would mean is that the client will re-try the request when the service responds with any random failure, after a session has been established. By random failure I mean failures that does not close the RM session while sending back the response. A fault sent back with proper RM headers to close the message would not result in a retry of the failed request. Unfortunately all SecurityToken validation and SecurityHeader validation exceptions are treated random exceptions as the response does not contain any required header or is the response secured.

One of the most common cases when this happens is when RM is enabled and a Username/Password validation fails. WCF provides extensibility points to  plug in your Custom Username/Password validator, but any exception from the validator does not close the RM session and hence the client keep retrying the request until it finally times out. The post discusses a work around to close the RM session when such failures occur.

Write a Custom Username/Password Authenticator and plug this into the service using a Custom ServiceCredentials. The Custom Authenticator should add a specific failure claim to the AuthorizationContext.  A sample code for the Custom Username/Password Authenticator is shown below.

        class CustomUsernamePasswordAuthenticator : UserNameSecurityTokenAuthenticator

        {

            protected override ReadOnlyCollection<IAuthorizationPolicy> ValidateUserNamePasswordCore(string userName, string password)

            {

                Claim claim = null;

                if (String.CompareOrdinal(userName, password) == 0)

                {

                    claim = Claim.CreateNameClaim(userName);

                }

                else

                {

                    claim = new Claim("http://contoso.com/InvalidUsernameClaim", true, Rights.PossessProperty);

                }

 

                List<IAuthorizationPolicy> policies = new List<IAuthorizationPolicy>();

                List<ClaimSet> claimsets = new List<ClaimSet>();

                claimsets.Add(new DefaultClaimSet(claim));

                policies.Add(new ClaimFactoryPolicy(claimsets.AsReadOnly()));

                return policies.AsReadOnly();

            }

      }

As you can see the above code is adding a specific claim of type http://contoso.com/InvalidUsernameClaim to the AuthorizationContext. For more information on how to plug custom authenticators in WCF you can take a look at http://msdn2.microsoft.com/en-us/library/ms730079.aspx.

The next we would do is to write a Custom Service Authorization Manager (SAM). The SAM gets called when the request has finally passed through all the binding elements so the RM header on the Request has been consumed. When an Access Denied result is returned by the SAM the failure response returned will be returned as Access Denied fault with the RM header enabled in the response that closes the RM session. Our Custom SAML will look for the specific Claim of type http://contoso.com/InvalidUsernameClaim to check whether to Authorize the user or not.

        class CustomServiceAuthorizationManager : ServiceAuthorizationManager

        {

            public override bool CheckAccess(OperationContext operationContext)

            {

                ReadOnlyCollection<ClaimSet> claimsets = operationContext.ServiceSecurityContext.AuthorizationContext.ClaimSets;

                foreach (ClaimSet claimSet in claimsets)

                {

                    if (claimSet.ContainsClaim(new Claim("http://contoso.com/InvalidUsernameClaim", true, Rights.PossessProperty)))

                    {

                        return false;

                    }

                }

 

                return true;

            }

        }

Custom SAM can be plugged into the ServiceCredentials as shown below,

service.Authorization.ServiceAuthorizationManager = new CustomServiceAuthorizationManager();

The fault returned by the Custom SAM will stop the client from retrying when a token validation failure happens on the Service end.

 

Handling Mismatched Trust Versions on the Client

Federation Clients might have scenarios where it is talking to a Service and STS that don't have the same trust version. The Service WSDL can contain a RequestSecurityTokenTemplate with Trust elements that are in different version than the STS. In these cases a WCF client will convert the Trust elements received from the Service's RequestSecurityTokenTemplate to match the STS Trust version. WCF will handle mismatched Trust version only for Standard Binding. All algorithm parameters that we recognize as standard are part of the Standard Binding. Below is our behavior under various Trust settings between the Service and the STS.

 

In the below description RP refers to "Relying Party" or the "Service" and STS refers to "Security Token Service".

RP Feb 2005 & STS Feb 2005

 

RP's WSDL contains the following elements in the RequestSecurityTokenTemplate.

  • 1. CanonicalizationAlgorithm
  • 2. EncryptionAlgorithm
  • 3. EncryptWith
  • 4. SignWith
  • 5. KeySize
  • 6. KeyType

Client Config contains a list of parameters.

 

WCF cannot differentiate between client and service parameters. We just add all the parameters and send them over the RST.

RP Trust 1.3 & STS Trust 1.3

 

RP's WSDL contains the following elements in the RequestSecurityTokenTemplate.

  • 1. CanonicalizationAlgorithm
  • 2. EncryptionAlgorithm
  • 3. EncryptWith
  • 4. SignWith
  • 5. KeySize
  • 6. KeyType
  • 7. KeyWrapAlgorithm

Client config contains a "secondaryParamters" element that wraps the RP specified parameters.

 

WCF removes the EncryptionAlgorithm, CanonicalizationAlgorithm and KeyWrapAlgorithm from the top-level element under the RST if these are present inside the SecondaryParameters. We append the SecondaryParamters element as is to the outgoing RST.

 

RP Trust Feb 2005 & STS Trust 1.3

 

RP's WSDL contains the following elements in the RequestSecurityTokenTemplate.

  • 1. CanonicalizationAlgorithm
  • 2. EncryptionAlgorithm
  • 3. EncryptWith
  • 4. SignWith
  • 5. KeySize
  • 6. KeyType

Client Config contains a list of parameters.

 

WCF cannot differentiate between the Service and Client parameters in this case from config on the client side. So we convert all the parameters to Trust 1.3 namespace.

 

Our handling of KeyType, KeySize and TokenType elements in this case is as follows,

 

  • We download WSDL and create the binding and assign KeyType, KeySize and TokenType from RP's parameters and the client config is generated.
  • Client can now change any parameter in the config.
  • During Runtime WCF will copy all parameters specified inside the AdditionalTokenParameters section of the client config except KeyType, KeySize and TokenType as they were accounted for during config generation.

RP Trust 1.3 & STS Trust Feb 2005

 

RP's WSDL contains the following elements in the RequestSecurityTokenTemplate.

  • 1. CanonicalizationAlgorithm
  • 2. EncryptionAlgorithm
  • 3. EncryptWith
  • 4. SignWith
  • 5. KeySize
  • 6. KeyType
  • 7. KeyWrapAlgorithm

Client config contains a "secondaryParamters" element that wraps the RP specified parameters.

 

WCF converts only EncryptionAlgorithm and CanonicalizationAlgorithm specified inside the "SecondaryParameters" and move them as top-level under the RST and replace the client specified values.  The "SecondaryParameters" element is dropped from the AdditionalRequestParameters.

Posted by govindr | 0 Comments

Security element and "actor" attribute.

SOAP 1.1 defines the attribute "actor" that can be on any SOAP header which will indicate who the ultimate processor of the header is going to be. It also defines a standard URI value for this actor attribute that is "http://schemas.xmlsoap.org/soap/actor/next" which implies that the header is intended for the very first SOAP application that processes the message. The absence of the actor attribute would mean the same as well.

SOAP 1.2 renamed this attribute to "role". But the semantics remanis the same as SOAP 1.1.

WCF Security does not recognize this attribute. WCF will not emit this attribute in the Security header element in any messages it emits. If a received message contains a actor attribute in the Security header the header will not be recognized even if the value is set to http://schemas.xmlsoap.org/soap/actor/next. You will see an exception that says "No Security header present in the message.". To work around this do not emit this attribute in the Security header in your messages to WCF.

Updated Re-Serialize SAML token

There has been a lot of interest around this and hence I have attached some code listing to this post. Check it out!
Posted by govindr | 0 Comments
Filed under: ,

WSE VS addin fails to generate WSE proxy in 64-bit machine

If you are using WSE and are a VS developer, you would be familar with the WSE Visual Studio Addin that automatically generates WSE Proxy when a Web Reference is added to the project. But if you are a developer in 64-bit machine you will not have this experience due to a bug in WSE setup. It fails to add the necessary entry in devenv.exe.config to enable this automatic generation of proxy. To work around this you can add the following XML to the devenv.exe.config which can be found at %Program Files(x86)%\Microsoft Visual Studio 8\Common7\IDE\devenv.exe.config

<configuration>

  <system.web>

    <webServices>

      <soapExtensionImporterTypes>

        <add type="Microsoft.Web.Services3.Description.WseExtensionImporter, Microsoft.Web.Services3, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />

      </soapExtensionImporterTypes>

    </webServices>

  </system.web>

</configuration>

Save the config and restart VS. You will have the same experience as in x86 machines.

Posted by govindr | 0 Comments
Filed under: , , ,

Using Visual Studio Intellisense to Edit WCF Configuration files.

If you are using Visual Studio 2005 below is how you can enable intellisense to edit your WCF config files. 

Copy the Attached WCF Configuration schema file to your VS installation folder at %Program Files%\Visual Studio 8\Xml\Schemas. You will find DotNetConfig.xsd in the same directory. Open this file in notepad and  following right after the xs:schema element add the below line,

<xs:include schemaLocation="WCFConfig.xsd" /> 

You will now have intellisense support for your WCF configuration files in VS!

Posted by govindr | 6 Comments
Filed under: ,

Attachment(s): WCFConfig.xsd

Trouble Installing .NET 2.0....

If you had a Beta version of Framework 2.0 installed on your machine and are moving to a the RTM version, then you might have some trouble with getting the correct version of mscoree.dll in place. The reason is Microsoft Installer's resilence feature will restore the old version of mscoree.dll in your system directory even if you delete it. To fix this follow the belwo support article from Microsoft.

http://support.microsoft.com/kb/908077

Posted by govindr | 0 Comments
Filed under: , , ,

Daylight savings changes and WCF Security Processing

I had a question today from a customer who was concerned that his WCF application might start to behave erratically due to the new Daylight savings schedule. Then I realized that there has been quite some noise around this area and people are predicting systems to stop responding when the new Daylight savings goes into effect. It reminded me of the Y2K days which was hyped as the doomsday of the Millennium.

In actual fact you don't have to worry about anything. WCF security has been tested for daylight savings time changes and the fact that the change happens earlier is not of concern. To be specific, WCF is using UTC time in all its code that the local time really doesn't affect us. As long as you have the Windows patch to adjust your clock at the correct time you should be fine. So, Enjoy! Keep coding with WCF!

Posted by govindr | 0 Comments
Filed under: , ,

WS-Federation Passive

I have discussed about Federation before. This post discusses Federation from the active context. "Active" means that the client is a smart client capable of doing encryption and signing and can actively participate in the Federation protocol. There are cases where the client is simply a Web Browser that is not capable of creating a secure message. In these cases the client is said to be "Passive". Federation in this case can be regulated through a series of HTTP 302 web redirects. The profile is described as the WS-Federation Passive profile.

ADFS Version 1 uses this profile to enable Federation of Identity. Moving forward ADFS will have support for Active and Passive profiles from version 2 onwards.

Posted by govindr | 0 Comments

Asymmetric tokens and Mixed-Mode Security

When you are using a X.509 Certificate as the client authentication token in Mixed-Mode Security - apart from signing the Timestamp WCF will sign the 'To' header as well. This is to prevent a client spoofing attack by a rougue service. Consider the situation where the client does not sign the 'To' header and sends the message to a rogue service. As long as the Timestamp is valid the rogue service can just forward the message to another service that trusts the client's certificate. The receiving service would validate the signature on the Timestamp and will accept the message and will respond back to the rogue service as if it is the client.

To prevent this WCF will sign the 'To' header as well when the client token used with Mixed-Mode security is an Asymmetric token. It will enforce the check on the receiving side as well. Now the rogue service cannot forward the message as the 'To' header needs to change for the called service and hence forces the service to create a new signature.

WCF Security Modes

WCF supports three types of Security. They are,

  • Transport Security
  • Mixed-Mode Security
  • Message Security

Let's discuss the various Security Modes below. 

Transport Security is applied at the transport byte stream below the message layer. The message does not have a Security header and the message does not carry any user authentication data. It is the least flexible in terms of WS-Security usage and it is highly dependent on the transport. It is the fastest in terms of performance.

Message Security is applied at the message layer and it is transport independent. It is a point to point security model with 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 provides the maximum flexibility in terms of that as well. Message Security is slowest in terms of performance.

Mixed-Mode Security is a hybrid between Transport and Message Security. The transport is encrypted and the message contains some user authentication tokens. If the token can provide a key (i.e., it is not a username/password token) then it will sign the timestamp in the security header. If the client token is a Asymmetric token then the 'To' header will be signed as well. It is faster than Message Security.

Configure SSL in IIS 7.0

If you are confused looking at the IIS 7.0 UI, you are not alone. I recently had to configure SSL on a IIS 7.0 and had quite some guessing work before I could get it to work. Below documents the procedure required to do this,

  1. Open IIS Manager and click on the Web Server on the Connection Pane on the left.
  2. On the middle Pane under the IIS section you will see a bunch of options. Select the "Server Certificates".
  3. On the resulting page the certs in your LocalMachine->My store should be automatically listed in the Middle Pane. If your server cert is something else, that you have exported then use the "Import..." option on the right pane to get your certificate.
  4. Now click on the Web Site on the Connection Pane on the left. On the right pane select bindings and click "Add". Select "https" for the Type, the default port is 443 which you can change and select your Certificate in the SSL Certificate list. Click OK.

You now have SSL enabled using IIS 7.0

Posted by govindr | 1 Comments
Filed under: ,

Security Header Layout

There are four different security header layout that can be specified in WCF. The values are defined in WS-SecurityPolicy. They are,

  • Strict - All security tokens are defined in the security header before its first use. The primary signature should be specified before any endorsing signatures.
  • Lax - All elements inside the security header can appear in any order.
  • LaxWithTimestampFirst - Timestamp element should be the first element that appears inside the security header. All other elements can appear in any order.
  • LaxWithTimestampLast - Timestamp element should be the last element inside the security header.

WCF provides a way to specify the security header layout using a switch on the security binding element called securityHeaderLayout.

Strict is the default mode in WCF. Lax mode can be slower in rejecting invalid messages as most of the validations are done after the security header is consumed. LaxWithTimestampLast serves the least purpose among the different header layouts but is defined for Interop reasons.

So what should you use? Lax is predominantly used when incoming message can be generated by different stacks. If all your messages are from WCF then using the default of Strict gives the maximum benefit.

More Posts Next page »
 
Page view tracker