Showing posts with label ADFS. Show all posts
Showing posts with label ADFS. Show all posts

Monday, September 17, 2018

Parsing SAML 1.1 (WS-Federation) tokens without the WSFam module

Ocassionally there's a scenario where a SAML token must be parsed without the WSFederationAuthentication module. Note that when the WSFam can be used, parsing is straightforward.

For us, it was one of our old applications that still can't be upgraded to .NET 4.5, because of reasons ;), and we wanted to drop the old WIF runtime (the one that targets older .NET versions). For someone else it can be another scenario, e.g. you have the SAML token as string and just want the IPrincipal out of the token.

The solution is to think of the token as it was the regular XMLDsig signed XML - the assertion node is signed and the signature's reference points back to it:

<?xml version="1.0"?>
<t:RequestSecurityTokenResponse xmlns:t="http://schemas.xmlsoap.org/ws/2005/02/trust">
  <t:Lifetime>
    <wsu:Created xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd">2018-09-18</wsu:Created>
    <wsu:Expires xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd">2018-09-18</wsu:Expires>
  </t:Lifetime>
  <wsp:AppliesTo xmlns:wsp="http://schemas.xmlsoap.org/ws/2004/09/policy">
    <wsa:EndpointReference xmlns:wsa="http://www.w3.org/2005/08/addressing">
      <wsa:Address>https://foo.bar/</wsa:Address>
    </wsa:EndpointReference>
  </wsp:AppliesTo>
  <t:RequestedSecurityToken>
    <saml:Assertion xmlns:saml="urn:oasis:names:tc:SAML:1.0:assertion" MajorVersion="1" MinorVersion="1" AssertionID="_assertionID" 
        Issuer="http://issuer" IssueInstant="2018-09-18">
      <saml:AttributeStatement>
        <saml:Subject>
          <saml:SubjectConfirmation>
            <saml:ConfirmationMethod>urn:oasis:names:tc:SAML:1.0:cm:bearer</saml:ConfirmationMethod>
          </saml:SubjectConfirmation>
        </saml:Subject>
        <saml:Attribute AttributeName="windowsaccountname" AttributeNamespace="http://schemas.microsoft.com/ws/2008/06/identity/claims">
          <saml:AttributeValue>username</saml:AttributeValue>
        </saml:Attribute>
      </saml:AttributeStatement>
      <ds:Signature xmlns:ds="http://www.w3.org/2000/09/xmldsig#">
        <ds:SignedInfo>
          <ds:CanonicalizationMethod Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#"/>
          <ds:SignatureMethod Algorithm="http://www.w3.org/2001/04/xmldsig-more#rsa-sha256"/>
          <ds:Reference URI="#_assertionID">
            <ds:Transforms>
              <ds:Transform Algorithm="http://www.w3.org/2000/09/xmldsig#enveloped-signature"/>
              <ds:Transform Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#"/>
            </ds:Transforms>
            <ds:DigestMethod Algorithm="http://www.w3.org/2001/04/xmlenc#sha256"/>
            <ds:DigestValue>digest</ds:DigestValue>
          </ds:Reference>
        </ds:SignedInfo>
        <ds:SignatureValue>signature</ds:SignatureValue>
        <KeyInfo xmlns="http://www.w3.org/2000/09/xmldsig#">
          <X509Data>
            <X509Certificate>certificate</X509Certificate>
          </X509Data>
        </KeyInfo>
      </ds:Signature>
    </saml:Assertion>
  </t:RequestedSecurityToken>
  <t:TokenType>urn:oasis:names:tc:SAML:1.0:assertion</t:TokenType>
</t:RequestSecurityTokenResponse>
What you should do is to
  1. validate the signature
  2. accept or reject the signature's certificate
  3. parse the token to retrieve claims required to create the IPrincipal
The code is rather simple, what's interesting however is that the SignedXml class has to be inherited to have the signature validator that follows the AssertionID attribute (the default convention is that the signed node's id attribute is called just ID and the default validator just won't find the node that has the id attribute called differently):
    public class SamlSignedXml : SignedXml
    {
        public SamlSignedXml(XmlElement e) : base(e) { }

        public override XmlElement GetIdElement(XmlDocument document, string idValue)
        {
            XmlNamespaceManager mgr = new XmlNamespaceManager(document.NameTable);
            mgr.AddNamespace("trust", "http://docs.oasis-open.org/ws-sx/ws-trust/200512");
            mgr.AddNamespace("wsu", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd");
            mgr.AddNamespace("saml", "urn:oasis:names:tc:SAML:1.0:assertion");

            XmlElement assertionNode = 
                   (XmlElement)document.SelectSingleNode("//trust:RequestSecurityTokenResponseCollection/trust:RequestSecurityTokenResponse/"+
                                                         "trust:RequestedSecurityToken/saml:Assertion", mgr);

            if (assertionNode.Attributes["AssertionID"] != null &&
                string.Equals(assertionNode.Attributes["AssertionID"].Value, idValue, StringComparison.InvariantCultureIgnoreCase)
                )
                return assertionNode;

            return null;
        }
    }
Note that the XPath assumes the token has the RequestSecurityTokenResponseCollection in the root, make sure your tokens follow this convention (in case of a single token, the collection node can be missing and the token's root could be just RequestSecurityTokenResponse, update the code accordingly).

The validation code is then

// token is the string representation of the SAML1 token
// expectedCertThumb is the expected certificate's thumbprint
protected bool ValidateToken( string token, string expectedCertThumb, out string userName )
{
 userName = string.Empty;

 if (string.IsNullOrEmpty(token)) return false;

 var xd = new XmlDocument();
 xd.PreserveWhitespace = true;
 xd.LoadXml(token);

 XmlNamespaceManager mgr = new XmlNamespaceManager(xd.NameTable);
 mgr.AddNamespace("trust", "http://docs.oasis-open.org/ws-sx/ws-trust/200512");
 mgr.AddNamespace("wsu", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd");
 mgr.AddNamespace("saml", "urn:oasis:names:tc:SAML:1.0:assertion");

 // assertion
 XmlElement assertionNode = (XmlElement)xd.SelectSingleNode("//trust:RequestSecurityTokenResponseCollection/trust:RequestSecurityTokenResponse/trust:RequestedSecurityToken/saml:Assertion", mgr);

 // signature
 XmlElement signatureNode = (XmlElement)xd.GetElementsByTagName("Signature")[0];

 var signedXml = new SamlSignedXml( assertionNode );
 signedXml.LoadXml(signatureNode);

 X509Certificate2 certificate = null;
 foreach (KeyInfoClause clause in signedXml.KeyInfo)
 {
  if (clause is KeyInfoX509Data)
  {
   if (((KeyInfoX509Data)clause).Certificates.Count > 0)
   {
    certificate =
    (X509Certificate2)((KeyInfoX509Data)clause).Certificates[0];
   }
  }
 }

 // cert node missing
 if (certificate == null) return false;

 // check the signature and return the result.
 var signatureValidationResult = signedXml.CheckSignature(certificate, true);

 if (signatureValidationResult == false) return false;

 // validate cert thumb
 if ( !string.IsNullOrEmpty( expectedCertThumb ) )
 {
  if ( !string.Equals( expectedCertThumb, certificate.Thumbprint ) )
   return false;
 }

 // retrieve username

 // expires = 
 var expNode = xd.SelectSingleNode("//trust:RequestSecurityTokenResponseCollection/trust:RequestSecurityTokenResponse/trust:Lifetime/wsu:Expires", mgr );

 DateTime expireDate;

 if (!DateTime.TryParse(expNode.InnerText, out expireDate)) return false; // wrong date

 if (DateTime.UtcNow > expireDate) return false; // token too old

 // claims
 var claimNodes =                 
   xd.SelectNodes("//trust:RequestSecurityTokenResponseCollection/trust:RequestSecurityTokenResponse/trust:RequestedSecurityToken/"+
                  "saml:Assertion/saml:AttributeStatement/saml:Attribute", mgr );
 foreach ( XmlNode claimNode in claimNodes )
 {
  if ( claimNode.Attributes["AttributeName"] != null && 
              claimNode.Attributes["AttributeNamespace"] != null &&
       string.Equals( claimNode.Attributes["AttributeName"].Value, "name", StringComparison.InvariantCultureIgnoreCase ) &&   
                     string.Equals( claimNode.Attributes["AttributeNamespace"].Value, "http://schemas.xmlsoap.org/ws/2005/05/identity/claims", StringComparison.InvariantCultureIgnoreCase ) &&
         claimNode.ChildNodes.Count == 1 
      )
  {
   userName = claimNode.ChildNodes[0].InnerText;
   return true;
  }
 }

 return false;
}
A couple of comments here.

First, the XPath could possibly be shortened to reflect the possibility of a missing collection node.

Then, the code assumes there's the name claim that contains the username but it could be the windowsaccountname or maybe yet another claim type.

Monday, September 11, 2017

ADFS and the SAML2 Artifact Binding woes

We've been using the WS-Fed for ages, I myself wrote a couple of tutorials and was often emailed by people asking for some details. As time passes, the Ws-Fed is pushed away in favor of the SAML2 protocol. And yes, SAML2 has some significant advantages over Ws-Fed, namely it supports multiple bindings.

The idea behind bindings is to allow both the token request and the actual token response be transmitted in various ways. Specifically, if you have ever worked with the WS-Fed, you are aware that the request from the Relying Party to the Identity Provider is passed over the browser's query string

https://idp.com?wa=wsignin1.0&wtrealm=https://rp.com
and the response is always passed in a HTML form that is POSTed to the Relying Party. On the other hand, the OAuth2/OpenID Connect have a different way of passing messages - while the request is also passed over the browser's query string
https://idp.com?wa=response_type=code&client_id=foobar&redirect_uri=https://rp.com&scope=profile
it is the RP that creates a direct HTTPs request to the IdP's profile endpoint to retrieve the user token.

This subtle difference has substantial consequences. In particular:

  • since the WS-Fed SAML1.1 token is passed from the IdP to the RP using the client's browser, it has to be signed to prevent it from being tampered. Also, large tokens could possibly introduce unwanted lag issues as it unfortunately takes some time to POST large data from a browser to a webserver
  • the OAuth2 tokens don't have to be signed as the trust is established by direct requests from the RP to the IdP, which, on the other hand could possibly be one of attack vectors (suppose the DNS can be poisoned at the RP's side and direct requests from the RP to the IdP target an attacker's site instead of the IdP

These two examples show that there are three different ways of passing the data between the RP and the IdP and this is exactly what three most important SAML2 binding are about

  1. the HTTP-Redirect binding consists in a 302 redirect and passing data in the query string
  2. the HTTP-POST binding consists of a HTTP POSTed form where the data is included in the form's inputs
  3. the Artifact binding consists in a redirect (302 or POST) where only a single artifact is returned, the receiver creates a HTTPs request passing the artifact as an argument and gets the data as the response
Note that any binding can be used to initiate the flow from the RP to the IdP and any other binding can be used to pass the SAML2 response token from the IdP to the RP.

For example, the RP can use the HTTP-Redirect binding to initiate the flow and then the IdP can use the HTTP-POST binding to send the token back (this particular combination of bindings would make such SAML2 negotiation very similar to WS-Fed):

Or, the RP can use the HTTP-Redirect binding to send the request to the IdP but can get the response back with the Artifact binding (which would make it look similar to OAuth2):

What this blog entry is about is how difficult it was to implement the SAML2's Artifact binding in a scenario where the ADFS is the actual Identity Provider.

First, why would you implement the SAML2 for yourself? Well, few reasons:

  • practical - the SAML2 is not supported by the base class library, although SAML1.1 (Ws-Fed) is. There are some classes in the base class library (the SAML2 token, the token handler) but the SAML2 protocol classes (handling different bindings) are missing. It's just like somebody has started the work but was interrupted in the middle of it and was never allowed to return and finish the job. There are some free and paid implementations (look here, or here, or here and google paid libraries on your own)
  • practical - although some SAML2 implementations can be found, it looks like this particular binding, the Artifact binding is not always supported, even though the other two bindings usually are supported
  • theoretical - to better understand all the details and have a full control over what happends under the hood of the Artifact binding

The implementation turned out to be more or less straightforward as long as HTTP-Redirect and HTTP-POST bindings are considered. It turned out, however, that the Artifact binding is a malicious strain and just doesn't want to cooperate that easily. Problems started when the ADFS was expected to return the artifact that the Artifact Resolve endpoint at the ADFS's side was about to be queried so the artifact could be exchanged for a SAML2 token. A following list enumerates some possible issues and could be used as a checklist not only by implementors but also by administrators who configure a channel between a Relying Party and the ADFS based on the Artifact binding.

  1. make sure you read the SAML 2.0 ADFS guide from Microsoft
  2. make sure the Artifact Resolve endpoint is turned on in the ADFS configuration
  3. make sure the signing certificate is imported in the Relying Party Trust Properties on the Signing tab - the ArtifactResolve request has to be signed by the RP's certificate, otherwise ADFS will reject the request (actually, ADFS tends to return an empty ArtifactResponse, with StatusCode equal to urn:oasis:names:tc:SAML:2.0:status:Success but no token included
  4. make sure you set correct signature algorithm in the Properties on the Advanced tab - by default ADFS expects the ArtifactResolve will be signed using SHA256RSA, however, your certificate can be SHA1RSA one
  5. make sure you consult the Event Log entries (under Applications and Services Logs/AD FS 2.0/Admin) to find detailed information on request processing. What you will get at the RP's side from sending invalid request is just urn:oasis:names:tc:SAML:2.0:status:Requester (which means that your request is incorrect for some reason) or urn:oasis:names:tc:SAML:2.0:status:Responder (which means ADFS is misconfigured). On the other hand, peeking into the system log can sometimes reveal additional details, e.g.
  6. make sure you sign the ArtifactResolve request and then you put it into a SOAP Envelope. Make sure you don't sign the whole envelope. This is how a correct request should look like
    <s:Envelope xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\">
      <s:Body>
        <samlp:ArtifactResolve
          xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol"
          xmlns:saml="urn:oasis:names:tc:SAML:2.0:assertion"
          ID="_cce4ee769ed970b501d680f697989d14"
          Version="2.0"
          IssueInstant="current-date-here e.g. 2017-09-11T12:00:00">
        <saml:Issuer>the ID of the RP from ADFS config e.g. https://rp.com</saml:Issuer>
        <ds:Signature xmlns:ds="http://www.w3.org/2000/09/xmldsig#">...</ds:Signature>
        <samlp:Artifact>the artifact goes here</samlp:Artifact>
      </samlp:ArtifactResolve>    
      </s:Body>
    </s:Envelope>
    
  7. (this one was tricky)make sure the Signature goes between the Issuer and Artifact nodes. By taking a look into ADFS sources (the Microsoft.IdentityServer.dll) you could learn that ADFS has its own exclusive, hand-written algorithm of signature validation which doesn't use the .NET's SignedXml class at all. This manually coded algorithm expects this particular order of nodes and logs 'Element' is an invalid XmlNodeType (as shown at the screenshot above, not too helpful) if you put your signature as the very last node. Frankly, I don't see any sense in this limitation at all.
  8. make sure you set SignedInfo's CanonicalizationMethod to SignedXml.XmlDsigExcC14NTransformUrl (which resolves to http://www.w3.org/2001/10/xml-exc-c14n#) (for some reason the ADFS just doesn't accept the default SignedXml.XmlDsigC14NTransformUrl aka http://www.w3.org/TR/2001/REC-xml-c14n-20010315)
  9. (this was even tricker) make sure you add XmlDsigExcC14NTransform to the Reference element of the signature. The relevant part of the ArtifactResolve code is presented below. It expects the ArtifactResolve XML in a string form, the signing certificate and the id of the ArtifactResolve (to put it into the signature)
            public string SignArtifactResolve(string artifactResolveBody, X509Certificate2 certificate, string id)
            {
                if (artifactResolveBody == null || certificate == null || string.IsNullOrEmpty( id ))
                    throw new ArgumentNullException();
    
                XmlDocument doc = new XmlDocument();
                doc.LoadXml(artifactResolveBody);
    
                SignedXml signedXml  = new SignedXml(doc);
                signedXml.SigningKey = certificate.PrivateKey;
                signedXml.SignedInfo.CanonicalizationMethod = SignedXml.XmlDsigExcC14NTransformUrl; //"http://www.w3.org/2001/10/xml-exc-c14n#";
    
                // Create a reference to be signed.
                Reference reference = new Reference();
                reference.Uri       = id;
    
                // Add an enveloped transformation to the reference.            
                XmlDsigEnvelopedSignatureTransform env =
                   new XmlDsigEnvelopedSignatureTransform(true);
                reference.AddTransform(env);
    
                XmlDsigExcC14NTransform c14n = new XmlDsigExcC14NTransform();
                c14n.Algorithm = SignedXml.XmlDsigExcC14NTransformUrl;
                reference.AddTransform(c14n);
    
                // Add the reference to the SignedXml object.
                signedXml.AddReference(reference);
    
                // Compute the signature.
                signedXml.ComputeSignature();
    
                // Get the XML representation of the signature and save 
                // it to an XmlElement object.
                XmlElement xmlDigitalSignature = signedXml.GetXml();
    
                // the signature does directly between Issuer and Artifact
                doc.DocumentElement.AppendChild(doc.ImportNode(xmlDigitalSignature, true));
    
                //var artifactChild = doc.DocumentElement.ChildNodes[doc.DocumentElement.ChildNodes.Count-1];
                //doc.DocumentElement.InsertBefore(doc.ImportNode(xmlDigitalSignature, true), artifactChild);
    
                // soap enveloped
                return CreateSoapEnvelope( doc.OuterXml );
            }
    
            private string CreateSoapEnvelope( string soapBodyContent )
            {
                if (string.IsNullOrEmpty(soapBodyContent)) throw new ArgumentNullException();
                return string.Format("<?xml version=\"1.0\" encoding=\"utf-8\"?><s:Envelope xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\"><s:Body>{0}</s:Body></s:Envelope>", 
                       soapBodyContent );
            }
    
  10. (this was slightly tricky) when sending the SOAP Envelope with the ArtifactResolve to ADFS, make sure you add the SOAPAction header set to http://www.oasis-open.org/committees/security. Also make sure you set the Content-Type to text/xml

A correct ArtifactResolve request makes ADFS return the ArtifactResponse document which looks more or less like

<s:Envelope xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\">
 <s:Body>
  <samlp:ArtifactResponse ID=\"_d9f59a16-8189-4095-9f57-1033439cb1f3\" Version=\"2.0\" IssueInstant=\"2017-09-11T10:20:49.527Z\" 
                        Consent=\"urn:oasis:names:tc:SAML:2.0:consent:unspecified\" InResponseTo=\"_id\" xmlns:samlp=\"urn:oasis:names:tc:SAML:2.0:protocol\">
   <Issuer xmlns=\"urn:oasis:names:tc:SAML:2.0:assertion\">http://adfs.local/adfs/services/trust</Issuer>
   <samlp:Status>
    <samlp:StatusCode Value=\"urn:oasis:names:tc:SAML:2.0:status:Success\" />
   </samlp:Status>
   <samlp:Response ID=\"_e0d8b313-ba58-4325-a9af-39a406a73bc8\" Version=\"2.0\" IssueInstant=\"2017-09-11T10:20:49.277Z\" Destination=\"https://rp.com\" 
       Consent=\"urn:oasis:names:tc:SAML:2.0:consent:unspecified\" InResponseTo=\"guid_2e0575b5-37b5-4546-a209-1bbc725c6532\">
    <Issuer xmlns=\"urn:oasis:names:tc:SAML:2.0:assertion\">http://adfs.local/adfs/services/trust</Issuer>
    <samlp:Status>
     <samlp:StatusCode Value=\"urn:oasis:names:tc:SAML:2.0:status:Success\" />
    </samlp:Status>
    <Assertion ID=\"_04f54457-70ce-4850-a639-c068a0f801db\" IssueInstant=\"2017-09-11T10:20:49.277Z\" ...>
     <Issuer>http://adfs.local/adfs/services/trust</Issuer>
     <ds:Signature xmlns:ds=\"http://www.w3.org/2000/09/xmldsig#\">...</ds:Signature>
     <Subject>...</Subject>
     <Conditions">...</Conditions>
     <AttributeStatement>
      <Attribute Name=\"http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name\">
       <AttributeValue>foo
      </Attribute>
      <Attribute Name=\"http://schemas.xmlsoap.org/ws/2005/05/identity/claims/surname\">
       <AttributeValue>Foo
      </Attribute>
      <Attribute Name=\"http://schemas.xmlsoap.org/ws/2005/05/identity/claims/givenname\">
       <AttributeValue>Bar
      </Attribute>
     </AttributeStatement>
     <AuthnStatement AuthnInstant=\"2017-09-11T10:20:49.199Z\">
      <AuthnContext>
       <AuthnContextClassRef>urn:oasis:names:tc:SAML:2.0:ac:classes:PasswordProtectedTransport</AuthnContextClassRef>
      </AuthnContext>
     </AuthnStatement>
    </Assertion>
   </samlp:Response>
  </samlp:ArtifactResponse>
 </s:Body>
</s:Envelope>
The response has to be extracted from the SOAP Envelope and verified (assertions are signed). Then, it can be passed down the pipeline as if it comes from any other binding.

Monday, January 27, 2014

ADFS2.0 and the maximum number of groups

Another subtle issue with ADFS2.0. This time it turned out that the maximum allowed token size is set rather low to 8192 bytes. This means that ADFS is fixed to issue at most two federation cookies to persist its internal user session.

What if the token should be larger, for example user belongs to many security groups?

Well, ADFS just doesn’t issue its own cookies. As a result, user inputs her correct credentials and instead being redirected to a RP application, the ADFS login page is rendered (as there are no cookies indicating a correct authentication) again. The RP is even not hit at all.

In one of our environments, it turned out that somewhere around 100 security groups was the limit. For users with more groups, the login page is rendered forever, accepting credentials but returing to the very same page.

Fortunately, the limit can be changed. Unfortunately, it is stored in a internal class. To raise the limit, reflection has to be used. Put this in ADFS’s global.asax or even in the static constructor of the login page (FormsSignIn.aspx.cs):

public partial class FormsSignIn : FormsLoginPage
{
    // Static constructor, added to the existing class
    static FormsSignIn()
    {
            // raise the limit of the internal cookie size 
            Type federationPassiveAuthentication =
                typeof( FormsLoginPage ).Assembly.GetType( 
                    "Microsoft.IdentityServer.Web.FederationPassiveAuthentication" );
 
            federationPassiveAuthentication.InvokeMember( "SsoMaxSize",
                System.Reflection.BindingFlags.SetProperty |
                System.Reflection.BindingFlags.Public |
                System.Reflection.BindingFlags.Static,
                null,
                federationPassiveAuthentication,
                new object [] { 100000u } // new limit
                );           
    }
    
    // The untouched code
    protected void Page_Load( object sender, EventArgs e )
    {
    }
 
    ... untouched code follows
 

Looks ugly but works. With this technique, we are able to get ADFS to issue the maximum allowed number of cookies until ultimately the “Request Headers too long” exception is raised by IIS indicating that there are too many cookies to be handled.

(and unfortunately, I was not able to work this around)

In our scenario, this change allows users to have up to 300 security groups.

Friday, May 25, 2012

An unfortunate issue in the ADFS2 sign out page

In one of my last entries, I’ve described an inconsistent behavior of different web browsers which occurs when users click the Back button in their browsers.

This subtle issue causes a deadful issue in an environment built around the ADFS2.

The problem is as follows: you have your applications federated with the ADFS2, tons of them. Each application has the “SignOff” button which takes users to ADFS2. ADFS2 renders the signoff page (containing iframes with urls with wsignoutcleanup1.0) which uses a jscript to redirect to the login page (if the wreply parameter is included).

One of our clients alarmed us that signing off from applications still allows users to see the last visited page. Upon closer inspection, it turned out that because of the way Opera, Firefox and Chrome treat “redirect” pages (please consult the mentioned blog entry), clicking Back on the login page (after succesful sign off) takes users back to the last page they visited (the one they clicked “sign off” on). And because most pages are read from a disc cache, the page is rendered even though a user hasjust signed off from the application!

A disaster.

A general solution was proposed in the last blog entry. It involves a modified javascript where the redirect is not done in an explicit way but rather with a setTimeout which prevents the unintended browser behavior.

Luckily, when ADFS2 is deployed, web pages have both *.aspx and *.cs available for modifications. There is a chance then to change the way the script is generated in the SignOut.aspx page.

The offensive javascript, generated in the SignOut.aspx is as follows:

<script>
   window.onload = function() 
   { 
      document.location = decodeURIComponent('return_url_herex') 
   }
</script>

What you have to find out is to find a way to replace this script with the modified one.

When you open the SignOut.aspx.cs however, you will find out that there’s nothing much to do there:

//------------------------------------------------------------
// Copyright (c) Microsoft Corporation.  All rights reserved.
//------------------------------------------------------------
 
using System;
 
using Microsoft.IdentityServer.Web.UI;
 
/// <summary>
/// This page sends WS-Federation SignOutCleanup messages to all the relying parties
/// that the user has signed in to during this session.
/// </summary>
public partial class SignOut : SignOutPage
{
    protected void Page_Load( object sender, EventArgs e )
    {
        CleanupUrisRepeater.DataSource = SignOutMessages;
        CleanupUrisRepeater.DataBind();
    }
}

There does not seem to be an explicit way to change the way the unfortunate javascript is generated. The base class, SignOutPage, is one of the ADFS2 core classes, it comes from Microsoft.IdentityServer.Web.UI library. If you decompile the class, it seems that it registers the startup script in the constructor.

The critical detail to change is then to replace the javascript with a new one which would use the setTimeout. Since you cannot modify the SignOutPage class and its constructor (would have to decompile, modify, recompile and resign the DLL!), my approach is as follows – I introduce a new class, CustomSignOutPage, which inherits from SignOutPage. The SignOut page class will then inherit from the newly introduced one.

Since I cannot replace the base class’ constructor – my new class will always call it. That’s unfortunate as the script is registered in the constructor, using ClientScript.RegisterStartupScript. But the ClientScriptManager class lacks a way to unregister scripts! Another unfortunate issue!

What I can do however, is to generate a new window.onload handler which will replace the one created by the script registered with an existing, base class code. The intention is to have the following structure of scripts in the SignOut page:

<!-- this one cannot be replaced because of the design! unfortunate! !-->
<script>
   1:  
   2:    window.onload = function() 
   3:    { 
   4:       document.location = decodeURIComponent('return_url_here') 
   5:    }
</script>
<!-- these must be injected !-->
<script>
   1:  
   2:    window.onload = function() 
   3:    { 
   4:       setTimeout( "location.href = decodeURIComponent('return_url_here')", 10 ) 
   5:    }
</script>
<script>
   1:  
   2:    window.onunload = function(){};
   3:    window.history.navigationMode = "compatible";
   4:    window.history.go(1);
</script>

My proposal is then to change the SignOut.aspx.cs to:

//------------------------------------------------------------
// Copyright (c) Microsoft Corporation.  All rights reserved.
//------------------------------------------------------------
 
using System;
 
using Microsoft.IdentityServer.Web.UI;
 
/// <summary>
/// This page sends WS-Federation SignOutCleanup messages to all the relying parties
/// that the user has signed in to during this session.
/// </summary>
public partial class SignOut : CustomSignOutPage
{
    protected void Page_Load( object sender, EventArgs e )
    {
        CleanupUrisRepeater.DataSource = SignOutMessages;
        CleanupUrisRepeater.DataBind();
    }
}
 
public class CustomSignOutPage : SignOutPage
{
    protected override void OnPreRender( EventArgs e )
    {
        base.OnPreRender( e );
 
        if ( this.ClientScript.IsStartupScriptRegistered( this.GetType(), "SignoutPage" ) )
        {
            Type FederationPassiveAuth = 
                 typeof( SignOutPage )
                      .Assembly
                      .GetType( "Microsoft.IdentityServer.Web.FederationPassiveAuthentication" );
            string signOutReplyUrlFromRequest = 
                 (string)FederationPassiveAuth
                      .GetMethod( "GetSignOutReplyUrlFromRequest" )
                      .Invoke( FederationPassiveAuth, null ); 
            
             this.ClientScript.RegisterStartupScript( 
                typeof( SignOutPage ), 
               "SignoutPageFix", 
                string.Format( 
                    System.Globalization.CultureInfo.InvariantCulture, 
  "<script>window.onload = function() {{ " +
  "setTimeout( \"location.href = decodeURIComponent('{0}')\", 10 ) }}</script>", 
                        new object[]
                    {
                        JSEncode(signOutReplyUrlFromRequest)
                    }));
        }
 
        this.ClientScript.RegisterStartupScript( 
            this.GetType(), 
            "RedirectBackFix", 
              "<script>window.onunload = function(){};" +
              "window.history.navigationMode = \"compatible\";" +
              "window.history.go(1);</script>" );
 
    }
 
    public static string JSEncode(string originalValue)
    {
      if (string.IsNullOrEmpty(originalValue))
      {
          return string.Empty;
      }
      return System.Web.HttpUtility
            .UrlEncode(originalValue)
            .Replace("+", "%20").Replace("'", "%27");
    }
}

There are few things to explain.

First as you can see, I introduce a new class between the core SignOutPage class and the actual SignOut page class. The introduced class creates two scripts and injects them to the generated web page. The first script is rendered using a reflection on the FederationPassiveAuthentication type – this is because the type is internal in the ADFS2 core libraries. The second script uses the JSEncode method which is rewritten to mimic the way ADFS2 implements it.

And this is it. This does the trick and solves the unfortunate issue. Newly introduced scripts prevents the application page to be seen when users press the Back button in their browsers.

Once again – for this to work, you have to copy the above SignOut.aspx.cs and replace the original one. Remember to save a backup copy of the original file. Also, altough the solution was tested in a development environment, I can’t be 100% sure that there are no unexpected side effects of this change.