public void FailsOnDocumentWithoutPreserveWhitespace()
            {
                // Arrange
                var doc = LoadDocument(@"Assertions\EncryptedAssertion_01");

                doc.PreserveWhitespace = false;

                // Act
                XmlSignatureUtils.IsSigned(doc);

                // Assert
                Assert.Fail("Signed documents that do not have PreserveWhitespace set should fail to be processed.");
            }
        public bool CheckSamlMessageSignature(KeyInfo keyInfo)
        {
            foreach (KeyInfoClause clause in keyInfo)
            {
                var key = XmlSignatureUtils.ExtractKey(clause);
                if (key != null && CheckSignature(key))
                {
                    return(true);
                }
            }

            return(false);
        }
Esempio n. 3
0
        public void SignatureResponseTest()
        {
            // Arrange
            var rtsrSoapMessageSigned = XDocument.Load(@"Resources\Response25022015.xml");

            var cert = new X509Certificate2(Convert.FromBase64String("MIIGRTCCBS2gAwIBAgIEUw8DszANBgkqhkiG9w0BAQsFADBHMQswCQYDVQQGEwJESzESMBAGA1UECgwJVFJVU1QyNDA4MSQwIgYDVQQDDBtUUlVTVDI0MDggU3lzdGVtdGVzdCBYSVggQ0EwHhcNMTQwNTA1MTMzNTU4WhcNMTcwNTA1MTMzNTEyWjCBljELMAkGA1UEBhMCREsxMTAvBgNVBAoMKERpZ2l0YWxpc2VyaW5nc3N0eXJlbHNlbiAvLyBDVlI6MzQwNTExNzgxVDAgBgNVBAUTGUNWUjozNDA1MTE3OC1VSUQ6ODMzODQ5NzAwMAYDVQQDDClEaWdpdGFsaXNlcmluZ3NzdHlyZWxzZW4gLSBOZW1Mb2ctaW4gVGVzdDCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBALnCmDRMztjDckSupQBLcEzrRRJnAFxzEFdB7Cj6ApMQ/YxqKzfL/TSIr3v2mdgQNnsJGz91YbAteDPRHR/K1W3kqoIX/qH2uXDzHK+qi4YD9D8s4MnHAt02x6t0TgKQGjn1XO6lgLQ563DjtgD2fdPm9USV2Lkxe5ofNRG7yvWowBWjXKia8D64k6zSzoHKdPz6GCy9S0NmwIyJE0sJavcfwxT3/ia0g63/xD77SteT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Ujh/oDAdBgNVHQ4EFgQUwm9c3oUHE/zZ/43g4RUhswnMVAowCQYDVR0TBAIwADANBgkqhkiG9w0BAQsFAAOCAQEACLh3Ovvljv4b/Ywf/8WxoB2y50Oqt8rpwXZp+no4d5tLqIMTSAlQxL0lAf4Qm4e6tF5m/55+dLwxw5/Dqwa0bQXHt98vJjSBYLQH6rwfDzNmVGimO1n84k4MMYY449ykjqRNDfCS3+5+zV/An4CH9eUhvB0AHHWbD6eALw39sPGxc5kHADTOdJ5SboSm9DHYdLLt9k8HyxrHIkcJApLWPgyFmkE0+8jtuQQluN62F5+j5d53oTKinHEd7adM0ea537vNf5uBGu6h9OTXlhZwM9tlnrsTYQTTAIzdxGPlpD9Zvo5nmJHwILdRonm8rZf3vAm59/U6+Cht4+X2l5zxyg=="));

            // Act
            var verified = XmlSignatureUtils.VerifySignature(rtsrSoapMessageSigned, cert);

            // Assert
            Assert.IsTrue(verified);
        }
Esempio n. 4
0
        public void SignatureTest()
        {
            // Arrange
            var rtsSoapMessageNotSigned = XDocument.Load(@"Resources\RST_Not_Signed.xml");
            var ids  = new[] { "action", "msgid", "to", "sec-ts", "sec-binsectoken", "body" };
            var cert = CertificateUtil.GetCertificate("0E6DBCC6EFAAFF72E3F3D824E536381B26DEECF5");

            // Act
            var rtsSoapMessageSigned = XmlSignatureUtils.SignDocument(rtsSoapMessageNotSigned, ids, cert);

            // Assert
            Assert.IsTrue(XmlSignatureUtils.VerifySignature(rtsSoapMessageSigned, cert));
        }
        private void Initialize(XmlDocument entityDescriptor)
        {
            if (XmlSignatureUtils.IsSigned(entityDescriptor))
            {
                if (!XmlSignatureUtils.CheckSignature(entityDescriptor))
                {
                    throw new Saml20Exception("Metadata signature could not be verified.");
                }
            }

            ExtractKeyDescriptors(entityDescriptor);
            Entity = Serialization.DeserializeFromXmlString <EntityDescriptor>(entityDescriptor.OuterXml);
        }
Esempio n. 6
0
        /// <summary>
        /// Signs the document.
        /// </summary>
        /// <param name="doc">The doc.</param>
        private static void SignDocument(XmlDocument doc, X509Certificate2 certificate, AlgorithmType signatureAlgorithm)
        {
            if (!certificate.HasPrivateKey)
            {
                throw new InvalidOperationException("Private key access to the signing certificate is required.");
            }

            XmlSignatureUtils.GenericSign(doc, doc.DocumentElement.GetAttribute("ID"), certificate, (appDoc, xmlElm) =>
            {
                // Append the computed signature. The signature must be placed as the sibling of the Issuer element.
                appDoc.DocumentElement.InsertBefore(appDoc.ImportNode(xmlElm, true), appDoc.DocumentElement.FirstChild);
            }, signatureAlgorithm);
        }
            public void TestMetadataloadWithNoUseTypeSigning()
            {
                var doc = new XmlDocument {
                    PreserveWhitespace = true
                };

                doc.Load(@"Protocol\MetadataDocs\rmit-metadata.xml");

                // Act
                var metadata = new Saml20MetadataDocument(doc);
                var l        = XmlSignatureUtils.CheckSignature(doc);
                var a        = "";
            }
Esempio n. 8
0
        public void SignatureFinalRequestTest()
        {
            // Arrange
            var rtsSoapMessageSigned = XDocument.Load(@"Resources\Request25022015.xml");

            var cert = new X509Certificate2(Convert.FromBase64String("MIIGLjCCBRagAwIBAgIEUw9wBzANBgkqhkiG9w0BAQsFADBHMQswCQYDVQQGEwJESzESMBAGA1UECgwJVFJVU1QyNDA4MSQwIgYDVQQDDBtUUlVTVDI0MDggU3lzdGVtdGVzdCBYSVggQ0EwHhcNMTQxMTEwMTQwMTQxWhcNMTcxMTEwMTQwMTMxWjB2MQswCQYDVQQGEwJESzEqMCgGA1UECgwhw5hrb25vbWlzdHlyZWxzZW4gLy8gQ1ZSOjEwMjEzMjMxMTswFwYDVQQDDBBNb3J0ZW4gTW9ydGVuc2VuMCAGA1UEBRMZQ1ZSOjEwMjEzMjMxLVJJRDo5Mzk0NzU1MjCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBALDVoVZz4QT+WP43mTl28pM9+Jy4JtBFV4R/LP2d2xLrAUGnDXn8dkAnTn4xcDll7t1kzCceI4/0ngN/CGwMpxynBbWRhoYWk4DesR34G2XehPiAf4E8Wsup2ad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UUlVTVDI0MDgxJDAiBgNVBAMMG1RSVVNUMjQwOCBTeXN0ZW10ZXN0IFhJWCBDQTEOMAwGA1UEAwwFQ1JMMTYwHwYDVR0jBBgwFoAUzAJVDOSBdK8gVNURFFeckVI4f6AwHQYDVR0OBBYEFKuH3e+mCu7y3/brN7zXSkvo6MwKMAkGA1UdEwQCMAAwDQYJKoZIhvcNAQELBQADggEBAESudYwnM/vbo5cMrUvgnpSgJUZhsQnSzLMwJTsT45OS3O+yct1ci9vPI1ExFZeAisC0bROV3tlsPuDiAVgmErgrHbrz1CmNqIxNcQvkqeL1sQtsrMSRicyILvU7Ve0N0gryR/axG+7D3U488X3oxXtJlS/9WZd33FVDnTIo7Asb+c1clqlUa/DSeBBdZ19L4DbfEkamLA96trEkH1hUTZfRXLFvYW5w8w+muaBu7eL84zzTxpGZxYM14ap+cQHuq+uczDsGDDUKc/BHUmN1UuQ0QCCxHegMHUDD8KXVsosj5wUXOLzd8WwKjPyUTxKPAI5xv9/Bim4mAA7eYc+3lXs="));

            // Act
            var verified = XmlSignatureUtils.VerifySignature(rtsSoapMessageSigned, cert);

            // Assert
            Assert.IsTrue(verified);
        }
Esempio n. 9
0
            public void CanDetectIfDocumentIsSigned()
            {
                // Arrange
                var badDocument  = LoadDocument(TestContext.CurrentContext.TestDirectory + @"\Assertions\EncryptedAssertion_01");
                var goodDocument = LoadDocument(TestContext.CurrentContext.TestDirectory + @"\Assertions\Saml2Assertion_01");

                // Act
                var badResult  = XmlSignatureUtils.IsSigned(badDocument);
                var goodResult = XmlSignatureUtils.IsSigned(goodDocument);

                // Assert
                Assert.IsFalse(badResult);
                Assert.IsTrue(goodResult);
            }
Esempio n. 10
0
            public void CanDetectIfDocumentIsSigned()
            {
                // Arrange
                var badDocument  = LoadDocument(Path.Combine("Assertions", "EncryptedAssertion_01"));
                var goodDocument = LoadDocument(Path.Combine("Assertions", "Saml2Assertion_01"));

                // Act
                var badResult  = XmlSignatureUtils.IsSigned(badDocument);
                var goodResult = XmlSignatureUtils.IsSigned(goodDocument);

                // Assert
                Assert.False(badResult);
                Assert.True(goodResult);
            }
Esempio n. 11
0
        private static AsymmetricAlgorithm GetTrustedSigner(KeyInfoClause clause, IdentityProvider identityProvider)
        {
            // Check certificate specifications
            if (clause is KeyInfoX509Data)
            {
                var cert = XmlSignatureUtils.GetCertificateFromKeyInfo((KeyInfoX509Data)clause);

                if (!CertificateSatisfiesSpecifications(identityProvider, cert))
                {
                    return(null);
                }
            }

            return(XmlSignatureUtils.ExtractKey(clause));
        }
        /// <summary>
        /// Check the signature of a HTTP-Redirect message using the list of keys.
        /// </summary>
        /// <param name="keys">A list of KeyDescriptor elements. Probably extracted from the metadata describing the IDP that sent the message.</param>
        /// <returns>True, if one of the given keys was able to verify the signature. False in all other cases.</returns>
        public bool VerifySignature(IEnumerable <KeyDescriptor> keys)
        {
            foreach (var keyDescriptor in keys)
            {
                foreach (KeyInfoClause clause in (KeyInfo)keyDescriptor.KeyInfo)
                {
                    var key = XmlSignatureUtils.ExtractKey(clause);
                    if (key != null && CheckSignature(key))
                    {
                        return(true);
                    }
                }
            }

            return(false);
        }
Esempio n. 13
0
        /// <summary>
        /// Checks the SAML message signature.
        /// </summary>
        /// <param name="keys">The keys to check the signature against.</param>
        /// <returns>True if the signature is valid, else false.</returns>
        public bool CheckSamlMessageSignature(List <KeyDescriptor> keys)
        {
            foreach (var keyDescriptor in keys)
            {
                foreach (KeyInfoClause clause in (KeyInfo)keyDescriptor.KeyInfo)
                {
                    var key = XmlSignatureUtils.ExtractKey(clause);
                    if (key != null && CheckSignature(key))
                    {
                        return(true);
                    }
                }
            }

            return(false);
        }
Esempio n. 14
0
            public void FailsOnDocumentWithoutPreserveWhitespace()
            {
                // Arrange
                var doc = LoadDocument(Path.Combine("Assertions", "EncryptedAssertion_01"));

                doc.PreserveWhitespace = false;

                // Act
                Assert.Throws(typeof(InvalidOperationException), () =>
                {
                    XmlSignatureUtils.IsSigned(doc);

                    // Assert
                    //Assert.Fail("Signed documents that do not have PreserveWhitespace set should fail to be processed.");
                });
            }
        /// <summary>
        /// Check the signature of a HTTP-Redirect message using the list of keys.
        /// </summary>
        /// <param name="keys">A list of KeyDescriptor elements. Probably extracted from the metadata describing the IDP that sent the message.</param>
        /// <returns>True, if one of the given keys was able to verify the signature. False in all other cases.</returns>
        public bool VerifySignature(IEnumerable <KeyDescriptor> keys)
        {
            foreach (KeyDescriptor keyDescriptor in keys)
            {
                KeyInfo ki = (KeyInfo)keyDescriptor.KeyInfo;
                foreach (KeyInfoClause clause in ki)
                {
                    AsymmetricAlgorithm key = XmlSignatureUtils.ExtractKey(clause);
                    if (key != null && CheckSignature(key))
                    {
                        return(true);
                    }
                }
            }

            return(false);
        }
        public void TestSHA256Signature()
        {
            var xmlDocument = new XmlDocument();

            xmlDocument.PreserveWhitespace = true;
            xmlDocument.Load(@"Saml20\Assertions\SHA256Signedtest.xml");
            var result = "";

            if (XmlSignatureUtils.CheckSignature(xmlDocument))
            {
                result = "Works, must be using .NET 4.0 or greater.";
            }
            else
            {
                result = "Doesn't work, must be using .NET 3.5 or something... (default for this project)";
            }
        }
        /// <summary>
        ///     Loads an assertion from XML.
        /// </summary>
        /// <param name="element">The element.</param>
        /// <param name="trustedSigners">The trusted signers.</param>
        private void LoadXml(XmlElement element, IEnumerable <AsymmetricAlgorithm> trustedSigners)
        {
            _samlAssertion = element;
            if (trustedSigners != null && XmlSignatureUtils.IsSigned(element))
            {
                if (!CheckSignature(trustedSigners))
                {
                    throw new Saml2Exception("Assertion signature could not be verified.");
                }
            }

            // Validate the saml20Assertion.
            if (_autoValidate)
            {
                AssertionValidator.ValidateAssertion(Assertion);
            }
        }
Esempio n. 18
0
        private void CreateAssertionResponse(User user)
        {
            string entityId = request.Issuer.Value;
            Saml20MetadataDocument metadataDocument = IDPConfig.GetServiceProviderMetadata(entityId);
            IDPEndPointElement     endpoint         =
                metadataDocument.AssertionConsumerServiceEndpoints().Find(delegate(IDPEndPointElement e) { return(e.Binding == SAMLBinding.POST); });

            if (endpoint == null)
            {
                Context.Response.Write(string.Format("'{0}' does not have a SSO endpoint that supports the POST binding.", entityId));
                Context.Response.End();
                return;
            }

            UserSessionsHandler.AddLoggedInSession(entityId);

            Response response = new Response();

            response.Destination             = endpoint.Url;
            response.InResponseTo            = request.ID;
            response.Status                  = new Status();
            response.Status.StatusCode       = new StatusCode();
            response.Status.StatusCode.Value = Saml20Constants.StatusCodes.Success;

            Assertion assertion = CreateAssertion(user, entityId);

            response.Items = new object[] { assertion };

            // Serialize the response.
            XmlDocument assertionDoc = new XmlDocument();

            assertionDoc.XmlResolver        = null;
            assertionDoc.PreserveWhitespace = true;
            assertionDoc.LoadXml(Serialization.SerializeToXmlString(response));

            // Sign the assertion inside the response message.
            XmlSignatureUtils.SignDocument(assertionDoc, assertion.ID, IDPConfig.IDPCertificate);

            HttpPostBindingBuilder builder = new HttpPostBindingBuilder(endpoint);

            builder.Action   = SAMLAction.SAMLResponse;
            builder.Response = assertionDoc.OuterXml;

            builder.GetPage().ProcessRequest(Context);
            Context.Response.End();
        }
Esempio n. 19
0
        /// <summary>
        /// Adds the signature.
        /// </summary>
        /// <param name="assertionDocument">The assertion document.</param>
        /// <param name="cert">The cert.</param>
        private static void AddSignature(XmlDocument assertionDocument, X509Certificate2 cert, AlgorithmType algorithmType)
        {
            var list = assertionDocument.GetElementsByTagName(Assertion.ElementName, Saml20Constants.Assertion);
            var el   = (XmlElement)list[0];

            XmlSignatureUtils.GenericSign(assertionDocument, el.GetAttribute("ID"), cert, (doc, signedXml) =>
            {
                // Append the computed signature. The signature must be placed as the sibling of the Issuer element.
                var nodes = doc.DocumentElement.GetElementsByTagName("Issuer", Saml20Constants.Assertion);
                if (nodes.Count != 1)
                {
                    throw new Saml20Exception("Assertion MUST contain one <Issuer> element.");
                }

                doc.DocumentElement.InsertAfter(assertionDocument.ImportNode(signedXml, true), nodes[0]);
            }, algorithmType);
        }
Esempio n. 20
0
        /// <summary>
        /// Checks the signature of a message received using the redirect binding using the keys found in the
        /// metadata of the federation partner that sent the request.
        /// </summary>
        protected static bool CheckRedirectSignature(HttpRedirectBindingParser parser, Saml20MetadataDocument metadata)
        {
            List <KeyDescriptor> keys = metadata.GetKeys(KeyTypes.signing);

            // Go through the list of signing keys (usually only one) and use it to verify the REDIRECT request.
            foreach (KeyDescriptor key in keys)
            {
                KeyInfo keyinfo = (KeyInfo)key.KeyInfo;
                foreach (KeyInfoClause keyInfoClause in keyinfo)
                {
                    AsymmetricAlgorithm signatureKey = XmlSignatureUtils.ExtractKey(keyInfoClause);
                    if (signatureKey != null && parser.CheckSignature(signatureKey))
                    {
                        return(true);
                    }
                }
            }
            return(false);
        }
Esempio n. 21
0
        /// <summary>
        /// Gets the trusted signers.
        /// </summary>
        /// <param name="keys">The keys.</param>
        /// <param name="identityProvider">The identity provider.</param>
        /// <returns>List of trusted certificate signers.</returns>
        public static IEnumerable<AsymmetricAlgorithm> GetTrustedSigners(ICollection<KeyDescriptor> keys, IdentityProvider identityProvider)
        {
            if (keys == null) {
                throw new ArgumentNullException("keys");
            }

            foreach (var clause in keys.SelectMany(k => k.KeyInfo.Items.AsEnumerable().Cast<KeyInfoClause>())) {
                // Check certificate specifications
                if (clause is KeyInfoX509Data) {
                    var cert = XmlSignatureUtils.GetCertificateFromKeyInfo((KeyInfoX509Data)clause);
                    if (!CertificateSatisfiesSpecifications(identityProvider, cert)) {
                        continue;
                    }
                }

                var key = XmlSignatureUtils.ExtractKey(clause);
                yield return key;
            }
        }
        /// <summary>
        ///     Checks the signature of the message, using a specific set of keys
        /// </summary>
        /// <param name="keys">The set of keys to check the signature against</param>
        /// <returns></returns>
        public bool CheckSignature(IEnumerable <KeyDescriptor> keys)
        {
            foreach (var keyDescriptor in keys)
            {
                var ki = (KeyInfo)keyDescriptor.KeyInfo;

                foreach (KeyInfoClause clause in ki)
                {
                    var key = XmlSignatureUtils.ExtractKey(clause);

                    if (key != null && XmlSignatureUtils.CheckSignature(_samlMessage, key))
                    {
                        return(true);
                    }
                }
            }

            return(false);
        }
            public void SignsXml()
            {
                // Arrange
                var doc    = new Saml20MetadataDocument(true);
                var entity = doc.CreateDefaultEntity();

                entity.ValidUntil = DateTime.Now.AddDays(14);

                // Act
                var metadata = doc.ToXml();
                var document = new XmlDocument {
                    PreserveWhitespace = true
                };

                document.LoadXml(metadata);
                var result = XmlSignatureUtils.CheckSignature(document);

                // Assert
                Assert.That(result);
            }
Esempio n. 24
0
        /// <summary>
        /// Loads an assertion, deserializes it using the <code>Assertion</code> class and returns the
        /// resulting <code>Assertion</code> instance.
        /// </summary>
        /// <param name="assertionFile">The assertion file.</param>
        /// <param name="verify">if set to <c>true</c> [verify].</param>
        /// <returns>The <see cref="Saml20Assertion"/>.</returns>
        public static Saml20Assertion DeserializeToken(string assertionFile, bool verify)
        {
            var document = LoadXmlDocument(assertionFile);

            var assertion = new Saml20Assertion(document.DocumentElement, null, false, TestConfiguration.Configuration);

            if (verify)
            {
                var result = new List <AsymmetricAlgorithm>(1);
                foreach (KeyInfoClause clause in assertion.GetSignatureKeys())
                {
                    var key = XmlSignatureUtils.ExtractKey(clause);
                    result.Add(key);
                }

                assertion.CheckValid(result);
            }

            return(assertion);
        }
Esempio n. 25
0
        public static IEnumerable <AsymmetricAlgorithm> GetTrustedSigners(string issuer)
        {
            if (issuer == null)
            {
                throw new ArgumentNullException("issuer");
            }

            SAML20FederationConfig config = ConfigurationReader.GetConfig <SAML20FederationConfig>();

            config.Endpoints.Refresh();
            IDPEndPoint idpEndpoint = config.FindEndPoint(issuer);

            if (idpEndpoint == null)
            {
                throw new InvalidOperationException(String.Format("No idp endpoint found for issuer {0}", issuer));
            }

            if (idpEndpoint.metadata == null)
            {
                throw new InvalidOperationException(String.Format("No metadata found for issuer {0}", issuer));
            }

            if (idpEndpoint.metadata.Keys == null)
            {
                throw new InvalidOperationException(String.Format("No key descriptors found in metadata found for issuer {0}", issuer));
            }

            List <AsymmetricAlgorithm> result = new List <AsymmetricAlgorithm>(1);

            foreach (KeyDescriptor key in idpEndpoint.metadata.Keys)
            {
                KeyInfo ki = (KeyInfo)key.KeyInfo;
                foreach (KeyInfoClause clause in ki)
                {
                    AsymmetricAlgorithm aa = XmlSignatureUtils.ExtractKey(clause);
                    result.Add(aa);
                }
            }

            return(result);
        }
Esempio n. 26
0
        /// <summary>
        /// Gets the trusted signers.
        /// </summary>
        /// <param name="issuer">The issuer.</param>
        /// <returns>A list of trusted signing certificates.</returns>
        public static IEnumerable <AsymmetricAlgorithm> GetTrustedSigners(string issuer)
        {
            if (issuer == null)
            {
                throw new ArgumentNullException("issuer");
            }

            var config = Saml2Config.GetConfig();

            config.IdentityProviders.Refresh();

            var idpEndpoint = config.IdentityProviders.FirstOrDefault(x => x.Id == issuer);

            if (idpEndpoint == null)
            {
                throw new InvalidOperationException(string.Format("No idp endpoint found for issuer {0}", issuer));
            }

            if (idpEndpoint.Metadata == null)
            {
                throw new InvalidOperationException(string.Format("No metadata found for issuer {0}", issuer));
            }

            if (idpEndpoint.Metadata.Keys == null)
            {
                throw new InvalidOperationException(string.Format("No key descriptors found in metadata found for issuer {0}", issuer));
            }

            var result = new List <AsymmetricAlgorithm>(1);

            foreach (var key in idpEndpoint.Metadata.Keys)
            {
                foreach (KeyInfoClause clause in (KeyInfo)key.KeyInfo)
                {
                    var aa = XmlSignatureUtils.ExtractKey(clause);
                    result.Add(aa);
                }
            }

            return(result);
        }
Esempio n. 27
0
            public void SignsXml()
            {
                // Arrange
                var doc    = new Saml20MetadataDocument(true);
                var entity = doc.CreateDefaultEntity();

                entity.ValidUntil = DateTime.Now.AddDays(14);

                var certificate = new X509Certificate2(FileEmbeddedResource("SAML2.Tests.Certificates.sts_dev_certificate.pfx"), "test1234");
                // Act
                var metadata = doc.ToXml(null, certificate);
                var document = new XmlDocument {
                    PreserveWhitespace = true
                };

                document.LoadXml(metadata);
                var result = XmlSignatureUtils.CheckSignature(document);

                // Assert
                Assert.That(result);
            }
Esempio n. 28
0
        /// <summary>
        /// Handles responses to an artifact resolve message.
        /// </summary>
        /// <param name="artifactResolve">The artifact resolve message.</param>
        public void RespondToArtifactResolve(ArtifactResolve artifactResolve, XmlElement samlDoc)
        {
            var response = Saml20ArtifactResponse.GetDefault(config.ServiceProvider.Id);

            response.StatusCode   = Saml20Constants.StatusCodes.Success;
            response.InResponseTo = artifactResolve.Id;
            response.SamlElement  = samlDoc; //samlDoc.DocumentElement;

            var responseDoc = response.GetXml();

            if (responseDoc.FirstChild is XmlDeclaration)
            {
                responseDoc.RemoveChild(responseDoc.FirstChild);
            }

            XmlSignatureUtils.SignDocument(responseDoc, response.Id, config);

            _logger.LogDebug(TraceMessages.ArtifactResolveResponseSent, artifactResolve.Artifact, responseDoc.OuterXml);

            sendResponseMessage(responseDoc.OuterXml);
        }
Esempio n. 29
0
        /// <summary>
        /// Gets the trusted signers.
        /// </summary>
        /// <param name="issuer">The issuer.</param>
        /// <returns>A list of trusted signing certificates.</returns>
        public static IEnumerable <AsymmetricAlgorithm> GetTrustedSigners(string issuer)
        {
            if (issuer == null)
            {
                throw new ArgumentNullException(nameof(issuer));
            }

            // TODO: Mock out a config for this test
            SAML2.Config.Saml2Configuration config = TestConfiguration.Configuration; // Saml2Config.GetConfig();

            var idpEndpoint = config.IdentityProvidersSource.GetById(issuer);

            if (idpEndpoint == null)
            {
                throw new InvalidOperationException(string.Format("No idp endpoint found for issuer {0}", issuer));
            }

            if (idpEndpoint.Metadata == null)
            {
                throw new InvalidOperationException(string.Format("No metadata found for issuer {0}", issuer));
            }

            if (idpEndpoint.Metadata.Keys == null)
            {
                throw new InvalidOperationException(string.Format("No key descriptors found in metadata found for issuer {0}", issuer));
            }

            var result = new List <AsymmetricAlgorithm>(1);

            foreach (var key in idpEndpoint.Metadata.Keys)
            {
                foreach (KeyInfoClause clause in (KeyInfo)key.KeyInfo)
                {
                    var aa = XmlSignatureUtils.ExtractKey(clause);
                    result.Add(aa);
                }
            }

            return(result);
        }
Esempio n. 30
0
        /// <summary>
        /// Resolves an artifact.
        /// </summary>
        /// <returns>A stream containing the artifact response from the IdP</returns>
        public Stream ResolveArtifact()
        {
            Trace.TraceMethodCalled(GetType(), "ResolveArtifact()");

            string artifact = _context.Request.Params["SAMLart"];

            IDPEndPoint idpEndPoint = DetermineIdp(artifact);

            if (idpEndPoint == null)
            {
                throw new InvalidOperationException("Received artifact from unknown IDP.");
            }

            ushort endpointIndex = ArtifactUtil.GetEndpointIndex(artifact);

            string endpointUrl = idpEndPoint.metadata.GetARSEndpoint(endpointIndex);

            Saml20ArtifactResolve resolve = Saml20ArtifactResolve.GetDefault();

            resolve.Artifact = artifact;

            XmlDocument doc = resolve.GetXml();

            if (doc.FirstChild is XmlDeclaration)
            {
                doc.RemoveChild(doc.FirstChild);
            }

            XmlSignatureUtils.SignDocument(doc, resolve.ID);

            string artifactResolveString = doc.OuterXml;

            if (Trace.ShouldTrace(TraceEventType.Information))
            {
                Trace.TraceData(TraceEventType.Information, string.Format(Tracing.ResolveArtifact, artifact, idpEndPoint.Id, endpointIndex, endpointUrl, artifactResolveString));
            }

            return(GetResponse(endpointUrl, artifactResolveString, idpEndPoint.ArtifactResolution));
        }