public void XmlHelpers_IsSignedBy_ChecksDigestAlgorithmStrength()
        {
            var xml = "<xml ID=\"MyXml\" />";

            var xmlDoc = XmlHelpers.FromString(xml);
            var sx     = new SignedXml(xmlDoc);

            var reference = new Reference
            {
                Uri          = "#MyXml",
                DigestMethod = SignedXml.XmlDsigSHA1Url
            };

            reference.AddTransform(new XmlDsigExcC14NTransform());
            reference.AddTransform(new XmlDsigEnvelopedSignatureTransform());
            sx.AddReference(reference);
            sx.SigningKey = ((RSACryptoServiceProvider)SignedXmlHelper.TestCert.PrivateKey)
                            .GetSha256EnabledRSACryptoServiceProvider();

            sx.SignedInfo.SignatureMethod = SignedXml.XmlDsigRSASHA256Url;
            sx.ComputeSignature();
            xmlDoc.DocumentElement.AppendChild(sx.GetXml());

            var keyClause = new X509RawDataKeyIdentifierClause(SignedXmlHelper.TestCert);

            xmlDoc.DocumentElement.Invoking(x =>
                                            x.IsSignedByAny(Enumerable.Repeat(keyClause, 1), false, SignedXml.XmlDsigRSASHA256Url))
            .ShouldThrow <InvalidSignatureException>()
            .WithMessage("*digest*weak*");
        }
    /// <summary>
    /// Returns the collection of certificates that the STS uses to sign tokens.
    /// </summary>
    /// <returns>The collection of certificates.</returns>
    private IEnumerable <X509Certificate2> ReadStsSigningCertificates(SecurityTokenServiceDescriptor stsDescriptor)
    {
        List <X509Certificate2> stsCertificates = new List <X509Certificate2>();

        if (stsDescriptor != null && stsDescriptor.Keys != null)
        {
            Collection <KeyDescriptor> keyDescriptors = (Collection <KeyDescriptor>)stsDescriptor.Keys;

            if (keyDescriptors != null && keyDescriptors.Count > 0)
            {
                foreach (KeyDescriptor keyDescriptor in keyDescriptors)
                {
                    if (keyDescriptor.KeyInfo != null && (keyDescriptor.Use == KeyType.Signing || keyDescriptor.Use == KeyType.Unspecified))
                    {
                        SecurityKeyIdentifier          kid    = keyDescriptor.KeyInfo;
                        X509RawDataKeyIdentifierClause clause = null;

                        kid.TryFind <X509RawDataKeyIdentifierClause>(out clause);

                        if (clause != null)
                        {
                            X509Certificate2 certificate = new X509Certificate2(clause.GetX509RawData());
                            stsCertificates.Add(certificate);
                        }
                    }
                }
            }
        }

        return(stsCertificates);
    }
Example #3
0
            public override SecurityKeyIdentifierClause ReadKeyIdentifierClauseCore(XmlDictionaryReader reader)
            {
                SecurityKeyIdentifierClause clause = null;

                reader.ReadStartElement(XD.XmlSignatureDictionary.X509Data, this.NamespaceUri);
                while (reader.IsStartElement())
                {
                    if ((clause == null) && reader.IsStartElement(XD.XmlSignatureDictionary.X509Certificate, this.NamespaceUri))
                    {
                        X509Certificate2 certificate = null;
                        if (!System.ServiceModel.Security.SecurityUtils.TryCreateX509CertificateFromRawData(reader.ReadElementContentAsBase64(), out certificate))
                        {
                            throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MessageSecurityException(System.ServiceModel.SR.GetString("InvalidX509RawData")));
                        }
                        clause = new X509RawDataKeyIdentifierClause(certificate);
                    }
                    else if ((clause == null) && reader.IsStartElement("X509SKI", this.NamespaceUri.ToString()))
                    {
                        clause = new X509SubjectKeyIdentifierClause(reader.ReadElementContentAsBase64());
                    }
                    else
                    {
                        reader.Skip();
                    }
                }
                reader.ReadEndElement();
                return(clause);
            }
Example #4
0
 public static byte[] signingCertificate(string metadataURI)
 {
     if (metadataURI == null)
     {
         throw new ArgumentNullException(metadataURI);
     }
     using (XmlReader metadataReader = XmlReader.Create(metadataURI)) {
         MetadataSerializer serializer = new MetadataSerializer()
         {
             CertificateValidationMode = X509CertificateValidationMode.None
         };
         EntityDescriptor entityDescriptor = serializer.ReadMetadata(metadataReader) as EntityDescriptor;
         if (entityDescriptor != null)
         {
             SecurityTokenServiceDescriptor stsd = entityDescriptor.RoleDescriptors.OfType <SecurityTokenServiceDescriptor>().First();
             if (stsd != null)
             {
                 X509RawDataKeyIdentifierClause clause = stsd.Keys.First().KeyInfo.OfType <X509RawDataKeyIdentifierClause>().First();
                 if (clause != null)
                 {
                     return(clause.GetX509RawData());
                 }
                 throw new Exception("The SecurityTokenServiceDescriptor in the metadata does not contain a RawData signing certificate");
             }
             throw new Exception("The Federation Metadata document does not contain a SecurityTokenServiceDescriptor");
         }
         throw new Exception("Invalid Federation Metadata document");
     }
 }
Example #5
0
        private static SecurityKeyIdentifierClause ReadX509Certificate(XmlReader reader)
        {
            reader.ReadStartElement("X509Certificate", SignedXml.XmlDsigNamespaceUrl);
            var clause = new X509RawDataKeyIdentifierClause(
                ((XmlDictionaryReader)reader).ReadContentAsBase64());

            reader.ReadEndElement();

            return(clause);
        }
Example #6
0
        /// <summary>
        /// Retrieves a populated <see cref="WsFederationConfiguration"/> given an address and an <see cref="IDocumentRetriever"/>.
        /// </summary>
        /// <param name="address">address of the metadata document.</param>
        /// <param name="retriever">the <see cref="IDocumentRetriever"/> to use to read the metadata document</param>
        /// <param name="cancel"><see cref="CancellationToken"/>.</param>
        /// <returns>A populated <see cref="WsFederationConfiguration"/> instance.</returns>
        public static async Task <WsFederationConfiguration> GetAsync(string address, IDocumentRetriever retriever, CancellationToken cancel)
        {
            if (string.IsNullOrWhiteSpace(address))
            {
                LogHelper.Throw(string.Format(CultureInfo.InvariantCulture, LogMessages.IDX10000, GetType() + ": address"), typeof(ArgumentNullException), EventLevel.Verbose);
            }

            if (retriever == null)
            {
                LogHelper.Throw(string.Format(CultureInfo.InvariantCulture, LogMessages.IDX10000, GetType() + ": retriever"), typeof(ArgumentNullException), EventLevel.Verbose);
            }

            WsFederationConfiguration configuration = new WsFederationConfiguration();

            string document = await retriever.GetDocumentAsync(address, cancel);

            using (XmlReader metaDataReader = XmlReader.Create(new StringReader(document), SafeSettings))
            {
                var serializer = new MetadataSerializer {
                    CertificateValidationMode = X509CertificateValidationMode.None
                };

                MetadataBase metadataBase     = serializer.ReadMetadata(metaDataReader);
                var          entityDescriptor = (EntityDescriptor)metadataBase;

                if (!string.IsNullOrWhiteSpace(entityDescriptor.EntityId.Id))
                {
                    configuration.Issuer = entityDescriptor.EntityId.Id;
                }

                SecurityTokenServiceDescriptor stsd = entityDescriptor.RoleDescriptors.OfType <SecurityTokenServiceDescriptor>().First();
                if (stsd != null)
                {
                    configuration.TokenEndpoint = stsd.PassiveRequestorEndpoints.First().Uri.AbsoluteUri;
                    foreach (KeyDescriptor keyDescriptor in stsd.Keys)
                    {
                        if (keyDescriptor.KeyInfo != null && (keyDescriptor.Use == KeyType.Signing || keyDescriptor.Use == KeyType.Unspecified))
                        {
                            IdentityModelEventSource.Logger.WriteVerbose(LogMessages.IDX10807);
                            foreach (SecurityKeyIdentifierClause clause in keyDescriptor.KeyInfo)
                            {
                                X509RawDataKeyIdentifierClause x509Clause = clause as X509RawDataKeyIdentifierClause;
                                if (x509Clause != null)
                                {
                                    var key = new X509SecurityKey(new X509Certificate2(x509Clause.GetX509RawData()));
                                    configuration.SigningKeys.Add(key);
                                }
                            }
                        }
                    }
                }
            }

            return(configuration);
        }
Example #7
0
            public override void WriteKeyIdentifierClauseCore(XmlDictionaryWriter writer, SecurityKeyIdentifierClause keyIdentifierClause)
            {
                X509RawDataKeyIdentifierClause clause = keyIdentifierClause as X509RawDataKeyIdentifierClause;

                writer.WriteStartElement(XD.XmlSignatureDictionary.Prefix.Value, XD.XmlSignatureDictionary.X509Data, this.NamespaceUri);
                writer.WriteStartElement(XD.XmlSignatureDictionary.Prefix.Value, XD.XmlSignatureDictionary.X509Certificate, this.NamespaceUri);
                byte[] buffer = clause.GetX509RawData();
                writer.WriteBase64(buffer, 0, buffer.Length);
                writer.WriteEndElement();
                writer.WriteEndElement();
            }
    /// <summary>
    /// Generate a sample MetadataBase.
    /// </summary>
    /// <remarks>
    /// In a production system this would be generated from the STS configuration.
    /// </remarks>
    public static MetadataBase GetFederationMetadata()
    {
        string           endpointId = "http://localhost/stsservice/service.svc";
        EntityDescriptor metadata   = new EntityDescriptor();

        metadata.EntityId = new EntityId(endpointId);

        // Define the signing key
        string           signingCertificateName = WebConfigurationManager.AppSettings["SigningCertificateName"];
        X509Certificate2 cert = CertificateUtil.GetCertificate(StoreName.My, StoreLocation.LocalMachine, signingCertificateName);

        metadata.SigningCredentials = new X509SigningCredentials(cert);

        // Create role descriptor for security token service
        SecurityTokenServiceDescriptor stsRole = new SecurityTokenServiceDescriptor();

        stsRole.ProtocolsSupported.Add(new Uri(WSFederationMetadataConstants.Namespace));
        metadata.RoleDescriptors.Add(stsRole);

        // Add a contact name
        ContactPerson person = new ContactPerson(ContactType.Administrative);

        person.GivenName = "contactName";
        stsRole.Contacts.Add(person);

        // Include key identifier for signing key in metadata
        SecurityKeyIdentifierClause clause = new X509RawDataKeyIdentifierClause(cert);
        SecurityKeyIdentifier       ski    = new SecurityKeyIdentifier(clause);
        KeyDescriptor signingKey           = new KeyDescriptor(ski);

        signingKey.Use = KeyType.Signing;
        stsRole.Keys.Add(signingKey);

        // Add endpoints
        string          activeSTSUrl    = "https://localhost/stsservice/service.svc";
        EndpointAddress endpointAddress = new EndpointAddress(new Uri(activeSTSUrl),
                                                              null,
                                                              null, GetMetadataReader(activeSTSUrl), null);

        stsRole.SecurityTokenServiceEndpoints.Add(endpointAddress);

        // Add a collection of offered claims
        // NOTE: In this sample, these claims must match the claims actually generated in CustomSecurityTokenService.GetOutputClaimsIdentity.
        //       In a production system, there would be some common data store that both use
        stsRole.ClaimTypesOffered.Add(new DisplayClaim(ClaimTypes.Name, "Name", "The name of the subject."));
        stsRole.ClaimTypesOffered.Add(new DisplayClaim(ClaimTypes.Role, "Role", "The role of the subject."));
        // Add a special claim for the QuoteService
        stsRole.ClaimTypesOffered.Add(new DisplayClaim(QuotationClassClaimType, "QuotationClass", "Class of quotation desired."));

        return(metadata);
    }
Example #9
0
        internal static XmlDocument GetPlainAsertion(SecurityTokenResolver securityTokenResolver, XmlElement el)
        {
            var encryptedDataElement = GetElement(HttpRedirectBindingConstants.EncryptedData, Saml20Constants.Xenc, el);

            var encryptedData = new System.Security.Cryptography.Xml.EncryptedData();

            encryptedData.LoadXml(encryptedDataElement);
            var encryptedKey        = new System.Security.Cryptography.Xml.EncryptedKey();
            var encryptedKeyElement = GetElement(HttpRedirectBindingConstants.EncryptedKey, Saml20Constants.Xenc, el);

            encryptedKey.LoadXml(encryptedKeyElement);
            var securityKeyIdentifier = new SecurityKeyIdentifier();

            foreach (KeyInfoX509Data v in encryptedKey.KeyInfo)
            {
                foreach (X509Certificate2 cert in v.Certificates)
                {
                    var cl = new X509RawDataKeyIdentifierClause(cert);
                    securityKeyIdentifier.Add(cl);
                }
            }

            var         clause = new EncryptedKeyIdentifierClause(encryptedKey.CipherData.CipherValue, encryptedKey.EncryptionMethod.KeyAlgorithm, securityKeyIdentifier);
            SecurityKey key;
            var         success = securityTokenResolver.TryResolveSecurityKey(clause, out key);

            if (!success)
            {
                throw new InvalidOperationException("Cannot locate security key");
            }

            SymmetricSecurityKey symmetricSecurityKey = key as SymmetricSecurityKey;

            if (symmetricSecurityKey == null)
            {
                throw new InvalidOperationException("Key must be symmentric key");
            }

            SymmetricAlgorithm symmetricAlgorithm = symmetricSecurityKey.GetSymmetricAlgorithm(encryptedData.EncryptionMethod.KeyAlgorithm);
            var encryptedXml = new System.Security.Cryptography.Xml.EncryptedXml();

            var plaintext = encryptedXml.DecryptData(encryptedData, symmetricAlgorithm);
            var assertion = new XmlDocument {
                PreserveWhitespace = true
            };

            assertion.Load(new StringReader(Encoding.UTF8.GetString(plaintext)));
            return(assertion);
        }
        //[Authorize]
        public ActionResult FederationMetadata()
        {
            var endpoint         = Request.Url.Scheme + "://" + Request.Url.Host + ":" + Request.Url.Port;
            var entityDescriptor = new EntityDescriptor(
                new EntityId(ConfigurationManager.AppSettings["stsName"]))
            {
                SigningCredentials = CertificateFactory.GetSigningCredentials()
            };

            var roleDescriptor = new SecurityTokenServiceDescriptor();

            roleDescriptor.Contacts.Add(new ContactPerson(ContactType.Administrative));

            var clause = new X509RawDataKeyIdentifierClause(CertificateFactory.GetCertificate());
            var securityKeyIdentifier = new SecurityKeyIdentifier(clause);
            var signingKey            = new KeyDescriptor(securityKeyIdentifier)
            {
                Use = KeyType.Signing
            };

            roleDescriptor.Keys.Add(signingKey);

            var endpointAddress =
                new System.IdentityModel.Protocols.WSTrust.EndpointReference(endpoint + "/Security/Authorize");

            roleDescriptor.PassiveRequestorEndpoints.Add(endpointAddress);
            roleDescriptor.SecurityTokenServiceEndpoints.Add(endpointAddress);

            roleDescriptor.ProtocolsSupported.Add(new Uri("http://docs.oasis-open.org/wsfed/federation/200706"));

            entityDescriptor.RoleDescriptors.Add(roleDescriptor);

            var serializer = new MetadataSerializer();
            var settings   = new XmlWriterSettings {
                Encoding = Encoding.UTF8
            };

            var memoryStream = new MemoryStream();
            var writer       = XmlWriter.Create(memoryStream, settings);

            serializer.WriteMetadata(writer, entityDescriptor);
            writer.Flush();

            var content = Content(Encoding.UTF8.GetString(memoryStream.GetBuffer()), "text/xml");

            writer.Dispose();

            return(content);
        }
Example #11
0
        static ClaimsPrincipal ValidateTokenWithX509SecurityToken(X509RawDataKeyIdentifierClause x509DataClause, string token)
        {
            var validatingCertificate = new X509Certificate2(x509DataClause.GetX509RawData());
            var tokenHandler          = new JwtSecurityTokenHandler();
            var x509SecurityToken     = new X509SecurityToken(validatingCertificate);
            var validationParameters  = new TokenValidationParameters()
            {
                AllowedAudience = "http://www.example.com",
                SigningToken    = x509SecurityToken,
                ValidIssuer     = "self",
            };

            ClaimsPrincipal claimsPrincipal = tokenHandler.ValidateToken(new JwtSecurityToken(token), validationParameters);

            return(claimsPrincipal);
        }
        /// <summary>
        /// Build a new RequestSecurityToken structure without actually sending it.
        /// </summary>
        /// <param name="bootstrapSecurityToken">The token to include in ActAs</param>
        /// <param name="clientCertificate">The instance certificate. Must have a private key.</param>
        /// <param name="RelyingPartyAdress">Address/uri of the provider service which is going to receive the token in the end</param>
        /// <param name="requestClaims">Any additional claims to add to the request</param>
        /// <returns></returns>
        public static RequestSecurityToken RequestSecurityToken(SecurityToken bootstrapSecurityToken, X509Certificate2 clientCertificate, Uri RelyingPartyAdress, IEnumerable <RequestClaim> requestClaims)
        {
            var requestSecurityToken = new RequestSecurityToken(WSTrust13Constants.RequestTypes.Issue);

            requestSecurityToken.AppliesTo = new EndpointAddress(RelyingPartyAdress);
            requestSecurityToken.TokenType = "http://docs.oasis-open.org/wss/oasis-wss-saml-token-profile-1.1#SAMLV2.0";
            requestSecurityToken.KeyType   = "http://docs.oasis-open.org/ws-sx/ws-trust/200512/PublicKey";
            requestSecurityToken.ActAs     = new SecurityTokenElement(bootstrapSecurityToken);
            SecurityKeyIdentifierClause clause = new X509RawDataKeyIdentifierClause(clientCertificate);

            requestSecurityToken.UseKey = new UseKey(new SecurityKeyIdentifier(clause), new X509SecurityToken(clientCertificate));

            foreach (RequestClaim claim in requestClaims)
            {
                requestSecurityToken.Claims.Add(claim);
            }

            return(requestSecurityToken);
        }
Example #13
0
    /// <summary>
    /// Resolves the given SecurityKeyIdentifierClause to a SecurityToken.
    /// </summary>
    /// <param name="keyIdentifierClause">SecurityKeyIdentifierClause to resolve.</param>
    /// <param name="token">The resolved SecurityToken.</param>
    /// <returns>True if successfully resolved.</returns>
    /// <exception cref="ArgumentNullException">The input argument 'keyIdentifierClause' is null.</exception>
    protected override bool TryResolveTokenCore(SecurityKeyIdentifierClause keyIdentifierClause, out SecurityToken token)
    {
        if (keyIdentifierClause == null)
        {
            throw new ArgumentNullException("keyIdentifierClause");
        }

        token = null;

        foreach (X509Certificate2 cert in trustedIssuerCertificates)
        {
            X509ThumbprintKeyIdentifierClause thumbprintKeyIdentifierClause = keyIdentifierClause as X509ThumbprintKeyIdentifierClause;
            if ((thumbprintKeyIdentifierClause != null) && (thumbprintKeyIdentifierClause.Matches(cert)))
            {
                token = new X509SecurityToken(cert);
                return(true);
            }

            X509IssuerSerialKeyIdentifierClause issuerSerialKeyIdentifierClause = keyIdentifierClause as X509IssuerSerialKeyIdentifierClause;
            if ((issuerSerialKeyIdentifierClause != null) && (issuerSerialKeyIdentifierClause.Matches(cert)))
            {
                token = new X509SecurityToken(cert);
                return(true);
            }

            X509SubjectKeyIdentifierClause subjectKeyIdentifierClause = keyIdentifierClause as X509SubjectKeyIdentifierClause;
            if ((subjectKeyIdentifierClause != null) && (subjectKeyIdentifierClause.Matches(cert)))
            {
                token = new X509SecurityToken(cert);
                return(true);
            }

            X509RawDataKeyIdentifierClause rawDataKeyIdentifierClause = keyIdentifierClause as X509RawDataKeyIdentifierClause;
            if ((rawDataKeyIdentifierClause != null) && (rawDataKeyIdentifierClause.Matches(cert)))
            {
                token = new X509SecurityToken(cert);
                return(true);
            }
        }

        return(false);
    }
        protected override bool TryResolveSecurityKeyCore(SecurityKeyIdentifierClause keyIdentifierClause, out SecurityKey key)
        {
            key = (SecurityKey)null;
            var identifierClause = keyIdentifierClause as EncryptedKeyIdentifierClause;

            if (identifierClause != null)
            {
                var encryptingKeyIdentifier = identifierClause.EncryptingKeyIdentifier;

                if (encryptingKeyIdentifier != null && encryptingKeyIdentifier.Count == 0)
                {
                    var certificate = this._certificateManager.GetCertificateFromContext(this._x509CertificateContext);
                    var kic         = new X509RawDataKeyIdentifierClause(certificate);
                    encryptingKeyIdentifier.Add(kic);
                    var result = base.TryResolveSecurityKeyCore(keyIdentifierClause, out key);
                    return(result);
                }
            }
            return(base.TryResolveSecurityKeyCore(keyIdentifierClause, out key));
        }
        protected override bool TryResolveTokenCore(SecurityKeyIdentifierClause keyIdentifierClause, out SecurityToken token)
        {
            token = null;
            X509Certificate2 matched = null;
            X509ThumbprintKeyIdentifierClause clause = keyIdentifierClause as X509ThumbprintKeyIdentifierClause;

            if ((clause != null) && this.TryMatchCertificates(clause.Matches, out matched))
            {
                token = new X509SecurityToken(matched);
                return(true);
            }
            X509IssuerSerialKeyIdentifierClause clause2 = keyIdentifierClause as X509IssuerSerialKeyIdentifierClause;

            if ((clause2 != null) && TryMatchCertificates(clause2.Matches, out matched))
            {
                token = new X509SecurityToken(matched);
                return(true);
            }
            X509SubjectKeyIdentifierClause clause3 = keyIdentifierClause as X509SubjectKeyIdentifierClause;

            if ((clause3 != null) && TryMatchCertificates(clause3.Matches, out matched))
            {
                token = new X509SecurityToken(matched);
                return(true);
            }
            X509RawDataKeyIdentifierClause clause4 = keyIdentifierClause as X509RawDataKeyIdentifierClause;

            if ((clause4 != null) && TryMatchCertificates(clause4.Matches, out matched))
            {
                token = new X509SecurityToken(matched);
                return(true);
            }

            if (this.innerResolver != null)
            {
                return(this.innerResolver.TryResolveToken(keyIdentifierClause, out token));
            }

            return(false);
        }
        /// <summary>
        /// Converts a SKI into one or more certificates for further processing.
        /// </summary>
        /// <param name="ski">SecurityKeyIdentifier to convert.</param>
        /// <returns>List of X509Certificate2 objects converted from the SKI.</returns>
        static List <X509Certificate2> GetCertificatesFromKeyInfo(SecurityKeyIdentifier ski)
        {
            List <X509Certificate2> certificates = new List <X509Certificate2>();

            foreach (SecurityKeyIdentifierClause keyClause in ski)
            {
                //
                // Only X509RawData clauses are supported. If any other clause is present, custom code
                // would be required to resolve the clause against some certificate store, such as the Windows
                // certificate store or a database. WIF exposes security token resolver classes which can
                // help with this resolution if needed.
                //
                X509RawDataKeyIdentifierClause x509KeyClause = keyClause as X509RawDataKeyIdentifierClause;
                if (x509KeyClause != null)
                {
                    byte[] certificateBytes = x509KeyClause.GetX509RawData();
                    certificates.Add(new X509Certificate2(certificateBytes));
                }
            }

            return(certificates);
        }
Example #17
0
        public void MatchesKeyIdentifierClause()
        {
            UniqueId                   id = new UniqueId();
            X509SecurityToken          t  = new X509SecurityToken(cert, id.ToString());
            LocalIdKeyIdentifierClause l  =
                new LocalIdKeyIdentifierClause(id.ToString());

            Assert.IsTrue(t.MatchesKeyIdentifierClause(l), "#1-1");

            l = new LocalIdKeyIdentifierClause("#" + id.ToString());
            Assert.IsFalse(t.MatchesKeyIdentifierClause(l), "#1-2");

            X509ThumbprintKeyIdentifierClause h =
                new X509ThumbprintKeyIdentifierClause(cert);

            Assert.IsTrue(t.MatchesKeyIdentifierClause(h), "#2-1");

            h = new X509ThumbprintKeyIdentifierClause(cert2);
            Assert.IsFalse(t.MatchesKeyIdentifierClause(h), "#2-2");

            X509IssuerSerialKeyIdentifierClause i =
                new X509IssuerSerialKeyIdentifierClause(cert);

            Assert.IsTrue(t.MatchesKeyIdentifierClause(i), "#3-1");

            i = new X509IssuerSerialKeyIdentifierClause(cert2);
            Assert.IsFalse(t.MatchesKeyIdentifierClause(i), "#3-2");

            X509RawDataKeyIdentifierClause s =
                new X509RawDataKeyIdentifierClause(cert);

            Assert.IsTrue(t.MatchesKeyIdentifierClause(s), "#4-1");

            s = new X509RawDataKeyIdentifierClause(cert2);
            Assert.IsFalse(t.MatchesKeyIdentifierClause(s), "#4-2");
        }
        public static AuthMetadata GetWSFederationMetadata(string content)
        {
            AuthMetadata result;

            try
            {
                using (TextReader textReader = new StringReader(content))
                {
                    using (XmlReader xmlReader = XmlReader.Create(textReader))
                    {
                        MetadataSerializer metadataSerializer = new MetadataSerializer
                        {
                            CertificateValidationMode = X509CertificateValidationMode.None
                        };
                        EntityDescriptor entityDescriptor = metadataSerializer.ReadMetadata(xmlReader) as EntityDescriptor;
                        SecurityTokenServiceDescriptor securityTokenServiceDescriptor = entityDescriptor.RoleDescriptors.OfType <SecurityTokenServiceDescriptor>().First <SecurityTokenServiceDescriptor>();
                        List <string> list = new List <string>();
                        foreach (KeyDescriptor keyDescriptor in from k in securityTokenServiceDescriptor.Keys
                                 where k.Use == KeyType.Signing
                                 select k)
                        {
                            foreach (SecurityKeyIdentifierClause securityKeyIdentifierClause in keyDescriptor.KeyInfo)
                            {
                                X509RawDataKeyIdentifierClause x509RawDataKeyIdentifierClause = securityKeyIdentifierClause as X509RawDataKeyIdentifierClause;
                                if (x509RawDataKeyIdentifierClause != null)
                                {
                                    list.Add(Convert.ToBase64String(x509RawDataKeyIdentifierClause.GetX509RawData()));
                                }
                            }
                        }
                        AuthMetadata authMetadata = new AuthMetadata();
                        authMetadata.CertificateStrings = list.ToArray();
                        string serviceName;
                        string realm;
                        if (AuthMetadataParser.TryExtractUrlFormatServiceNameAndRealm(entityDescriptor.EntityId.Id, out serviceName, out realm))
                        {
                            authMetadata.ServiceName = serviceName;
                            authMetadata.Realm       = realm;
                        }
                        else
                        {
                            authMetadata.ServiceName = entityDescriptor.EntityId.Id;
                            authMetadata.Realm       = null;
                        }
                        if (string.IsNullOrEmpty(authMetadata.ServiceName))
                        {
                            throw new AuthMetadataParserException(DirectoryStrings.ErrorAuthMetadataCannotResolveServiceName);
                        }
                        result = authMetadata;
                    }
                }
            }
            catch (XmlException innerException)
            {
                throw new AuthMetadataParserException(DirectoryStrings.ErrorCannotParseAuthMetadata, innerException);
            }
            catch (IOException innerException2)
            {
                throw new AuthMetadataParserException(DirectoryStrings.ErrorCannotParseAuthMetadata, innerException2);
            }
            catch (SecurityException innerException3)
            {
                throw new AuthMetadataParserException(DirectoryStrings.ErrorCannotParseAuthMetadata, innerException3);
            }
            catch (SystemException innerException4)
            {
                throw new AuthMetadataParserException(DirectoryStrings.ErrorCannotParseAuthMetadata, innerException4);
            }
            return(result);
        }
        private bool ResolvesToSigningToken(SecurityKeyIdentifierClause keyIdentifierClause, out SecurityKey key, out SecurityToken token)
        {
            token = null;
            key   = null;
            CertMatcher certMatcher = null;

            // for SAML tokens the highest probability are certs, with RawData first
            X509RawDataKeyIdentifierClause rawCertKeyIdentifierClause = keyIdentifierClause as X509RawDataKeyIdentifierClause;

            if (rawCertKeyIdentifierClause != null)
            {
                certMatcher = rawCertKeyIdentifierClause.Matches;
            }
            else
            {
                X509SubjectKeyIdentifierClause subjectKeyIdentifierClause = keyIdentifierClause as X509SubjectKeyIdentifierClause;
                if (subjectKeyIdentifierClause != null)
                {
                    certMatcher = subjectKeyIdentifierClause.Matches;
                }
                else
                {
                    X509ThumbprintKeyIdentifierClause thumbprintKeyIdentifierClause = keyIdentifierClause as X509ThumbprintKeyIdentifierClause;
                    if (thumbprintKeyIdentifierClause != null)
                    {
                        certMatcher = thumbprintKeyIdentifierClause.Matches;
                    }
                    else
                    {
                        X509IssuerSerialKeyIdentifierClause issuerKeyIdentifierClause = keyIdentifierClause as X509IssuerSerialKeyIdentifierClause;
                        if (issuerKeyIdentifierClause != null)
                        {
                            certMatcher = issuerKeyIdentifierClause.Matches;
                        }
                    }
                }
            }

            if (_validationParameters.IssuerSigningKeyResolver != null)
            {
                key = _validationParameters.IssuerSigningKeyResolver(token: _securityToken, securityToken: null, keyIdentifier: new SecurityKeyIdentifier(keyIdentifierClause), validationParameters: _validationParameters);
                if (key != null)
                {
                    this.IsKeyMatched = true;
                }
            }

            if (_validationParameters.IssuerSigningKey != null)
            {
                if (Matches(keyIdentifierClause, _validationParameters.IssuerSigningKey, certMatcher, out token))
                {
                    key = _validationParameters.IssuerSigningKey;
                    this.IsKeyMatched = true;
                }
            }

            if (_validationParameters.IssuerSigningKeys != null)
            {
                foreach (SecurityKey securityKey in _validationParameters.IssuerSigningKeys)
                {
                    if (Matches(keyIdentifierClause, securityKey, certMatcher, out token))
                    {
                        key = securityKey;
                        this.IsKeyMatched = true;
                        break;
                    }
                }
            }

            if (_validationParameters.IssuerSigningToken != null)
            {
                if (_validationParameters.IssuerSigningToken.MatchesKeyIdentifierClause(keyIdentifierClause))
                {
                    token             = _validationParameters.IssuerSigningToken;
                    key               = token.SecurityKeys[0];
                    this.IsKeyMatched = true;
                }
            }

            if (_validationParameters.IssuerSigningTokens != null)
            {
                foreach (SecurityToken issuerToken in _validationParameters.IssuerSigningTokens)
                {
                    if (_validationParameters.IssuerSigningToken.MatchesKeyIdentifierClause(keyIdentifierClause))
                    {
                        token             = issuerToken;
                        key               = token.SecurityKeys[0];
                        this.IsKeyMatched = true;
                        break;
                    }
                }
            }

            return(this.IsKeyMatched);
        }