Wednesday, August 24, 2011

IIS7 and easy configuration of SSL host headers

If you ever tried to configure SSL host headers for your IIS7 sites, you already know that this can be done from the IIS management console only for the very first site. If you try to add the SSL binding for another site, the console will prevent you from doing so.

How people usually solve this problem is they use the appcmd commandline tool to add the SSL binding manually for other sites. First, you map add SSL to the very first of your sites manually and then use a script to map another site:

appcmd set site /site.name:"thesitename" /+bindings.[protocol='https',bindingInformation='*:443:host.header.value.com']

However, there’s actually much simpler way to add the SSL binding. It involves manually editing the IIS configuration file, which is C:\Windows\System32\intersrv\config\applicationHost.config. The IIS uses this file to store its configuration.

Edit this file, find a <site> node which refers to your site, it should look like this:

<site name="thesitename" id="3" serverAutoStart="true">
      <application path="/" applicationPool="thepoolname">
          <virtualDirectory path="/" physicalPath="C:\inetpub\somepath" />
      </application>
      <bindings>
          <binding protocol="http" bindingInformation="*:80:host.header.value.com" />
      </bindings>
</site>

Just modify this to:

<site name="thesitename" id="3" serverAutoStart="true">
      <application path="/" applicationPool="thepoolname">
          <virtualDirectory path="/" physicalPath="C:\inetpub\somepath" />
      </application>
      <bindings>
          <binding protocol="http" bindingInformation="*:80:host.header.value.com" />
          <binding protocol="https" bindingInformation="*:443:host.header.value.com" />
      </bindings>
</site>

You can quickly and easily modify all of your sites this way. Then, restart IIS and you are done.

Tuesday, August 23, 2011

ADFS 2.0 – MSIS7012/MSIS3127 when accepting claims from a custom claims provider

The scenario is as follows. You provide a custom claims provider for ADFS2.0 so that when user logs-in to the application, the ADFS should offer a list of possible authentication providers. When the custom provider is selected, ADFS redirects the browser to it. Then, ADFS should accept incoming claims and pass them through to the relying party application.

There are plenty of useful scenarios when this could be handy and people blog about it, for example take a look at this article. In one of our projects we go this route, trying to provide a custom STS to support ADFS with various login options (username/password, email/password, uniqueid/password, name.surname/password etc).

What people seem to have problems with is the number of different issues which arise when the ADFS is up to accept and transform incoming claims. One of such common issues show as MSIS7012/MSIS3127 in the event log:

Microsoft.IdentityServer.Web.RequestFailedException: MSIS7012: Wystąpił błąd podczas przetwarzania żądania. Aby uzyskać szczegółowe informacje, skontaktuj się z administratorem. ---> System.ServiceModel.FaultException: MSIS3127: Określone żądanie nie powiodło się.
   w Microsoft.IdentityServer.Protocols.WSTrust.WSTrustClientManager.Issue(Message request, WCFResponseData responseData)
   w Microsoft.IdentityServer.Protocols.WSTrust.WSTrustClient.Issue(RequestSecurityToken rst, WCFResponseData responseData)
   w Microsoft.IdentityServer.Web.FederationPassiveAuthentication.SubmitRequest(MSISRequestSecurityToken request)
   --- Koniec śladu stosu wyjątków wewnętrznych ---
   w Microsoft.IdentityServer.Web.FederationPassiveAuthentication.SubmitRequest(MSISRequestSecurityToken request)
   w Microsoft.IdentityServer.Web.FederationPassiveAuthentication.RequestBearerToken(MSISSignInRequestMessage signInRequest, SecurityTokenElement onBehalfOf, SecurityToken primaryAuthToken, String desiredTokenType, Uri& replyTo)
   w Microsoft.IdentityServer.Web.FederationPassiveAuthentication.RequestBearerToken(MSISSignInRequestMessage signInRequest, SecurityTokenElement onBehalfOf, SecurityToken primaryAuthToken, String desiredTokenType, MSISSession& session)
   w Microsoft.IdentityServer.Web.FederationPassiveAuthentication.BuildSignInResponseCoreWithSerializedToken(String signOnToken, WSFederationMessage incomingMessage)
   w Microsoft.IdentityServer.Web.FederationPassiveAuthentication.BuildSignInResponseForProtocolResponse(FederationPassiveContext federationPassiveContext)
   w Microsoft.IdentityServer.Web.FederationPassiveAuthentication.BuildSignInResponse(SecurityToken securityToken)

System.ServiceModel.FaultException: MSIS3127: Określone żądanie nie powiodło się.
   w Microsoft.IdentityServer.Protocols.WSTrust.WSTrustClientManager.Issue(Message request, WCFResponseData responseData)
   w Microsoft.IdentityServer.Protocols.WSTrust.WSTrustClient.Issue(RequestSecurityToken rst, WCFResponseData responseData)
   w Microsoft.IdentityServer.Web.FederationPassiveAuthentication.SubmitRequest(MSISRequestSecurityToken request)

If you take a look at the accompanying event log entry you will learn that:

A token was received from a claims provider identified by the key somekeyhere, but the token could not be validated because the key does not identify any known claims provider trust. Key: somekeyhere. This request failed. User Action If this key represents the certificate thumbprint of a claims provider trust, verify that it matches the signing certificate of the claims provider trust in the AD FS configuration database.

It took like 3 hours to finally find the problem. And the problem is the mismatch between the issuer name provided in the provider’s metadata and the issuer name provided in the ADFS configuration.

First one of these two names is set programmatically somewhere in the configuration of the claims provider, in the SecurityTokenServiceConfiguration class:

public class CustomSecurityTokenServiceConfiguration : SecurityTokenServiceConfiguration
{
    ...
 
    /// <summary>
    /// CustomSecurityTokenServiceConfiguration constructor.
    /// </summary>
    public CustomSecurityTokenServiceConfiguration()
        : base( "ADFS Stub",
                new X509SigningCredentials( the certificate here )
               )
    {
        this.SecurityTokenService = typeof( CustomSecurityTokenService );
    }
}

Note the “ADFS Stub” here – the name is invisible in an explicit form in the metadata because it’s base64’ed somewhere in the certificate description.

The second one of these two names is visible in the explicit form in the ADFS claims trust configuration:

Note that the value of the “Claims provider identifier” attribute (the lower textbox) matches the name provided as the issuer name in the C# code snippet above. If the two do not match you get the exception in the ADFS log.

Monday, July 18, 2011

WIF and custom UserData in authentication cookies

The UserData is a common and yet handy mechanism of authentication frameworks and it consist in injecting a portion of arbitrary data to the authentication information upon logon so that the data is available later during the session.

For example, FormsAuthenticationModule allows to inject userdata to the Forms cookie by manually creating the FormsAuthenticationTicket:

FormsAuthenticationTicket ticket = 
    new FormsAuthenticationTicket(
        1,
        UserName,
        DateTime.Now, DateTime.Now.AddMinutes( 20 ),
        false, "userdata here" );
string cookieValue = FormsAuthentication.Encrypt( ticket );

The similar mechanism in WIF is more “WS-Federation oriented” – you just create a new claim (one or many) of type ClaimTypes.UserData with arbitrary value. How exactly you create such claim? Well, there are two alternatives.

First, you can inject a custom claims authentication manager into the WIF’s pipeline. The manager fires at the beginning of every request and this is where you can inject “per-request” claims.

public class FederatedClaimsAuthenticationManager : ClaimsAuthenticationManager
{
    public override IClaimsPrincipal Authenticate( 
        string resourceName, 
        IClaimsPrincipal incomingPrincipal )
    {
        // If not authenticated - redirect
        if ( !incomingPrincipal.Identity.IsAuthenticated )
            return incomingPrincipal;
 
        // else - inject local claims
        IClaimsIdentity identity = incomingPrincipal.Identity as IClaimsIdentity;
        if ( identity != null && identity.IsAuthenticated )
        {
            identity.Claims.Add( new Claim( ClaimTypes.UserData, 
               "local per-request userdata", ClaimValueTypes.String, "(local)" ) );
        }
 
        return incomingPrincipal;
    }
}

Remember to register the manager in web.config in WIF’s <claimsAuthenticationManager /> section.

But injecting claims at every request is not a choice if you wish to inject userdata once, when user logs in and then be able to read it back at every request.

This is where the second possibility comes in. It consist in injecting the claim during the SessionSecurityTokenCreated event of the WIF’s SessionAuthenticationModule. Since I prefer the FederatedPassiveSignIn user control than direct fedutil.exe approach, I just provide a handler for the user control:

WSFederationLogin.SessionSecurityTokenCreated +=
     ( s, ev ) =>
     {
         ev.SessionToken
            .ClaimsPrincipal.Identities[0]
            .Claims.Add( 
                new Claim( ClaimTypes.UserData, 
                          "local per-session userdata (injected once)", 
                           ClaimValueTypes.String, "(local)" ) );
     };

In both approaches, the UserData claim is present among all other user claims.

Friday, May 27, 2011

Builtin Base64 Streaming

Months ago I’ve blogged on how to implement base64 streaming reader and writer. Just for the record – the same can be achieved using built-in classes:

class Program
{
    static void Main( string[] args )
    {
        string Original = "foo bar, this is an example";
        byte[] ToBase64;
        string Decoded;
 
        using ( MemoryStream ms = new MemoryStream() )
        using ( CryptoStream cs = new CryptoStream( ms, new ToBase64Transform(),
                                                        CryptoStreamMode.Write ) )
        using ( StreamWriter st = new StreamWriter( cs ) )
        {
            st.Write( Original );
            st.Flush();
 
            ToBase64 = ms.ToArray();
        }
 
        using ( MemoryStream ms = new MemoryStream( ToBase64 ) )
        using ( CryptoStream cs = new CryptoStream( ms, new FromBase64Transform(), 
                                                        CryptoStreamMode.Read ) )
        using ( StreamReader sr = new StreamReader( cs ) )
            Decoded = sr.ReadToEnd();
 
        Console.WriteLine( Original );
        Console.WriteLine( Encoding.Default.GetString( ToBase64 ) );
        Console.WriteLine( Decoded );
 
        Console.ReadLine();
    }
}

The output of above snippet is:

foo bar, this is an example
Zm9vIGJhciwgdGhpcyBpcyBhbiBleGFtcGxl
foo bar, this is an example

WIF, WS-Federation and Single sign-out for RP – R-STS – IP-STS scenario

There seems to be no strict specification on how Single sign-out should be implemented for WS-Federation. Not so long ago I’ve blogged about a simple scenario involving an IP-STS and a group of RPs.

A simple scenario

In such simple scenario, when the IP-STS receives a wsignout1.0 request from one of RPs (which is basically a request to sign out the whole party from current session), it returns a page to the browser which contains a list of images pointing back to all RPs that have signed using the IP-STS. Each single url to the image is of the form:

<img src="http://the.relyingparty.com/default.aspx?wa=wsignoutcleanup1.0" />

Thus, it’s not the IP-STS who signs out everyone but rather it’s the responsibility of the browser to tell everyone to log off.

Imagine that the browser is an office-boy who passes messages between the boss (IP-STS) and his workers (RPs). When one of workers says “I want everyone to log off”, the boy delivers the request to the boss and in return the boss gives a list of workers to the boy saying “go, tell everyone from this list to log off”.

What works like a charm in a simple scenario, seems to be problematic in a more complicated one.

A complicated hierarchy

Suppose that this time there are not only RPs and the IP-STS but also R-STSes in the middle (Relaying Security Token Services which pass sign in requests upwards). Each of such R-STSes acts just like a lower-level manager who’s now collecting requests from his workers and passes them to the boss.

Note that such hierarchy can be arbitrarily complicated, with a single IP-STS at the top, possibly multiple layers of R-STSes in the middle and RPs at the bottom.

Suppose now that, as previously, the office-boy (one of RPs) asks his manager (one of R-STSes) to log-off. This time however the manager would be torn between two conflicting needs:

  • he has to inform all his workers (RPs that are directly under him) to sign off (by sending links with wa=wsignoutcleanup1.0)
  • he has to ask his boss (the IP-STS) to log off everyone (all other possible R-STSes)

The office-boy (the browser) can unfortunately perform only one of above requests at a time. Either the R-STS will return images to log off all his child RPs or it will push the log-off request to the IP-STS.

The former is a bad choice – as the log off request should not be restricted to a subtree of such complicated hierarchy. The latter however raises a new issue – yes, the log-off request can be pushed to the IP-STS but if the IP-STS returns a list of images to log off is direct descendants (R-STSes), it will log off only R-STSes! None of RPs will log off, as the IP-STS has no idea of what happens two levels above him!

And just for the record: the difference in handling a sign-out request between an IP-STS and a R-STS is presented below:

...
else if ( action == WSFederationConstants.Actions.SignOut )
{
    // Process signout request.
    SignOutRequestMessage requestMessage = 
        (SignOutRequestMessage)WSFederationMessage.CreateFromUri( Request.Url );
 
    // IP-STS: answer to the signout request
    FederatedPassiveSecurityTokenServiceOperations.ProcessSignOutRequest( 
        requestMessage, 
        User, 
        requestMessage.Reply, 
        Response );
    
    // R-STS: push signout request upwards
    WSFederationAuthenticationModule.FederatedSignOut( 
        null, 
        new Uri( requestMessage.Reply ) );
}
Frames to the rescue

A solution to this issue can be easily inferred from the way ADFS 2.0 handles sign-out requests.

It seems that instead of returning a list of images containing signout requests to his direct descendants, a STS should return a list of invisible iframes of a form:

<iframe src="the.relyingparty.com/default.aspx?wa=wsignoutcleanup1.0" class="MakeItInvisible" />

This way, the browser deilvering such request to each of R-STSes expects a web page in a return.

But, in contrast “imaging approach”, a web page can contain further references which will make the browser go after them.

Each of R-STSes should then return a page containing a list of iframes containing links to log off his descendants and so on.

Note, that the structure of dependency tree in such approach can be arbitrarily complicated as each parent node returns iframes pointing to its descendants.

The only drawback of such approach is that if you’d like to have some visual feedback from consecutive STSes then you have to implement it on your own (embed some images inside returned iframes).

Saturday, May 21, 2011

Implementing a HeartLight clone in XNA, continued (3)

Download Torq314Dash 0.2 (binary and source)

My implementation of the HeartLight clone improves. Profile of the new version

  • implemented LEVELS.HL file reader which makes it possible to play all 70 levels from the original implementation (the file is included in the distribution, all credits go to Janusz Pelc, Maciej Miąsik and others from the team who brought HeartLight to life
  • implemented balloons and tunnels
  • bomb timing is slightly improved
  • new texture set

Most of 70 levels are playable now, with 13, 21 or 37 as exceptions which reveal further issues in timing (bombs/balloons).

Ballons were easy to implement. They fall down when two movable blocks are above them and an empty square below. They move up when none or a single movable block is above them and an empty square yet above.

Tunnels were tricky. In fact, I’ve implemented them in such way that the player block is marked to be processed by the physics engine and then it moves along the tunnel, eating a block ahead and leaving a new block behind. During the tunnel travel, the player block returns a different texture so that the effect of moving along the tunnel is clearly visible.

Feel free to comment. Please also take a look at the implementation of a BoulderDash clone by Fingus. It’s been a mutual challenge between us to first implement a tetris clone and then a BoulderDash clone. A possible next challenge would be a Super Mario clone.

Sunday, May 15, 2011

Implementing a HeartLight clone in XNA, continued (2)

One if the issues with my implementation I’ve been trying to resolve is the way HeartLight implements falling blocks. There are at least few levels to test this, my favourite is the level 20 which starts with several stones and hearts falling from the top to the bottom. The way they fall and interact during falling determines the way the board looks like when all the blocks finally fall and do not move anymore (and this is when player can start the level).

The level in HeartLight, after blocks finally fall down looks like this:

If you try this level in my original implementation you’ll however end up with following:

 

Most blocks completely miss their destination and although the physics I’ve implemented feels ok, it surely gives different output.

Unfortunately, I do not have the source code of HeartLight. The only way to “debug” the implementation was then to slow down both versions (mine and the original) and stone-by-stone, heart-by-heart try to find the difference in the way objects fall. I also tried to validate each single observation by slight changes in the implementation. It was then “reimplement – rethink – reimplement -rethink” cycle.

The first big difference I’ve found concerns the way blocks “bounce” when they fall down. I’ve mentioned this last time but when there’s an empty space to the left/right of the block, the block is supposed to move there (bounce). It turned out however that there’s a one frame delay in this move. This has a huge impact on the way blocks interact when they fall, as a free square not occupied by an object because of the delay can be occupied by another object.

Another very subtle difference I have found (and this was quite tricky) is the way HeartLight implements per-frame loops for X axis and Y axis. My first approach was to analyze rows from the lowest in the outer loop and then columns in the inner loop. HeartLight however has this inverted – the outer loop is for columns and the inner – for rows.

What’s important is that the final output of a fixed physics routine is now correct (below). Compare it with the first screenshot taken from the original version.

Next issue to fix is the way bombs explode. There’s also a great testing ground (below). In my implementation this level is currently completely unplayable.

Expect then to hear more on that in the future.