/// <summary>
        /// Loads a file into an XmlDocument. If the loading or the signature check fails, the method will retry using another encoding.
        /// </summary>
        /// <param name="filename">The filename.</param>
        /// <returns>The XML document.</returns>
        private static XmlDocument LoadAsXmlDocument(IEnumerable <Encoding> encodings, Action <XmlDocument> docLoad, Action <XmlDocument, Encoding> quirksModeDocLoad)
        {
            var doc = new XmlDocument {
                PreserveWhitespace = true
            };

            try
            {
                // First attempt a standard load, where the XML document is expected to declare its encoding by itself.
                docLoad(doc);
                try
                {
                    if (XmlSignatureUtils.IsSigned(doc) && !XmlSignatureUtils.CheckSignature(doc))
                    {
                        // Bad, bad, bad... never use exceptions for control flow! Who wrote this?
                        // Throw an exception to get into quirksmode.
                        throw new InvalidOperationException("Invalid file signature");
                    }
                }
                catch (CryptographicException)
                {
                    // Ignore cryptographic exception caused by Geneva server's inability to generate a
                    // .NET compliant xml signature
                    return(ParseGenevaServerMetadata(doc));
                }

                return(doc);
            }
            catch (XmlException)
            {
                // Enter quirksmode
                foreach (var encoding in encodings)
                {
                    StreamReader reader = null;
                    try
                    {
                        quirksModeDocLoad(doc, encoding);
                        if (XmlSignatureUtils.IsSigned(doc) && !XmlSignatureUtils.CheckSignature(doc))
                        {
                            continue;
                        }
                    }
                    catch (XmlException)
                    {
                        continue;
                    }
                    finally
                    {
                        if (reader != null)
                        {
                            reader.Close();
                        }
                    }

                    return(doc);
                }
            }

            return(null);
        }
        public void TestCertificateExtraction_01()
        {
            XmlDocument doc = new XmlDocument();

            doc.PreserveWhitespace = true;
            doc.Load(@"Saml20\Protocol\MetadataDocs\metadata-ADLER.xml");

            Saml20MetadataDocument metadata = new Saml20MetadataDocument(doc);
            List <KeyDescriptor>   keys     = metadata.Keys;

            Assert.That(keys[0].use == KeyTypes.signing);
            Assert.That(keys[1].use == KeyTypes.encryption);

            Assert.That(metadata.GetKeys(KeyTypes.signing).Count == 1);
            Assert.That(metadata.GetKeys(KeyTypes.encryption).Count == 1);

            // The two certs in the metadata document happen to be identical, and are also
            // used for signing the entire document.
            // Extract the certificate and verify the document.

            KeyInfo keyinfo = (KeyInfo)keys[0].KeyInfo;

            Assert.That(XmlSignatureUtils.CheckSignature(doc, keyinfo));
            Assert.AreEqual("ADLER_SAML20_ID", metadata.EntityId);
        }
Example #3
0
            public void CanExtractCertificates()
            {
                // Arrange
                var doc = new XmlDocument {
                    PreserveWhitespace = true
                };

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

                // Act
                var metadata = new Saml20MetadataDocument(doc);
                var certificateCheckResult = XmlSignatureUtils.CheckSignature(doc, (KeyInfo)metadata.Keys[0].KeyInfo);

                // Assert
                Assert.That(metadata.GetKeys(KeyTypes.Signing).Count == 1);
                Assert.That(metadata.GetKeys(KeyTypes.Encryption).Count == 1);
                Assert.That(metadata.Keys[0].Use == KeyTypes.Signing);
                Assert.That(metadata.Keys[1].Use == KeyTypes.Encryption);

                // The two certs in the metadata document happen to be identical, and are also
                // used for signing the entire document.
                // Extract the certificate and verify the document.
                Assert.That(certificateCheckResult);
                Assert.AreEqual("ADLER_SAML20_ID", metadata.EntityId);
            }
        /// <summary>
        /// Checks the signature.
        /// </summary>
        /// <param name="key">The key to check against.</param>
        /// <returns></returns>
        private bool CheckSignature(AsymmetricAlgorithm key)
        {
            XmlDocument doc = new XmlDocument();

            doc.PreserveWhitespace = true;
            doc.LoadXml(SamlMessage.OuterXml);
            return(XmlSignatureUtils.CheckSignature(doc, key));
        }
Example #5
0
        /// <summary>
        /// Loads a file into an XmlDocument. If the loading or the signature check fails, the method will retry using another encoding.
        /// </summary>
        private XmlDocument LoadFileAsXmlDocument(string filename)
        {
            XmlDocument doc = new XmlDocument();

            doc.XmlResolver        = null;
            doc.PreserveWhitespace = true;

            try
            {
                // First attempt a standard load, where the XML document is expected to declare its encoding by itself.
                doc.Load(filename);
                try
                {
                    if (XmlSignatureUtils.IsSigned(doc) && !XmlSignatureUtils.CheckSignature(doc))
                    {
                        throw new InvalidOperationException("Invalid file signature");
                    }
                    // Throw an exception to get into quirksmode.
                }
                catch (CryptographicException)
                {
                    //Ignore cryptographic exception caused by Geneva server's inability to generate a
                    //.net compliant xml signature
                    return(ParseGenevaServerMetadata(doc));
                }
                return(doc);
            }
            catch (XmlException)
            {
                // Enter quirksmode
                List <Encoding> encs = _getEncodings();
                foreach (Encoding encoding in encs)
                {
                    StreamReader reader = null;
                    try
                    {
                        reader = new StreamReader(filename, encoding);
                        doc.Load(reader);
                        if (XmlSignatureUtils.IsSigned(doc) && !XmlSignatureUtils.CheckSignature(doc))
                        {
                            continue;
                        }
                    }
                    catch (XmlException)
                    { continue; }
                    finally
                    {
                        if (reader != null)
                        {
                            reader.Close();
                        }
                    }

                    return(doc);
                }
            }
            return(null);
        }
Example #6
0
 private bool CheckSignature(AsymmetricAlgorithm key)
 {
     if (XmlSignatureUtils.CheckSignature(_samlAssertion, key))
     {
         SigningKey = key;
         return(true);
     }
     return(false);
 }
Example #7
0
        public void TestSHA256Signature()
        {
            var xmlDocument = new XmlDocument {
                PreserveWhitespace = true
            };

            xmlDocument.Load(@"Saml20\Assertions\SHA256Signedtest.xml");
            Assert.IsTrue(XmlSignatureUtils.CheckSignature(xmlDocument));
        }
            public void CanCheckDSAValidSignatures()
            {
                // Arrange
                var doc = LoadDocument(Path.Combine("Assertions", "Saml2Assertion_01"));

                // Act
                var result = XmlSignatureUtils.CheckSignature(doc);

                // Assert
                Assert.True(result);
            }
        /// <summary>
        ///     Checks the signature.
        /// </summary>
        /// <param name="key">The key to check against.</param>
        /// <returns></returns>
        private bool CheckSignature(AsymmetricAlgorithm key)
        {
            var doc = new XmlDocument
            {
                XmlResolver        = null,
                PreserveWhitespace = true
            };

            doc.LoadXml(SamlMessage.OuterXml);
            return(XmlSignatureUtils.CheckSignature(doc, key));
        }
Example #10
0
            public void CanCheckValidSignatures()
            {
                // Arrange
                var doc = LoadDocument(TestContext.CurrentContext.TestDirectory + @"\Assertions\Saml2Assertion_01");

                // Act
                var result = XmlSignatureUtils.CheckSignature(doc);

                // Assert
                Assert.That(result);
            }
            public void CanCheckValidSignatures()
            {
                // Arrange
                var doc = LoadDocument(@"Assertions\Saml2Assertion_01");

                // Act
                var result = XmlSignatureUtils.CheckSignature(doc);

                // Assert
                Assert.That(result);
            }
Example #12
0
        private void Initialize(XmlDocument entityDescriptor)
        {
            if (XmlSignatureUtils.IsSigned(entityDescriptor))
            {
                Signed         = true;
                ValidSignature = XmlSignatureUtils.CheckSignature(entityDescriptor);
            }

            ExtractKeyDescriptors(entityDescriptor);
            Entity = Serialization.DeserializeFromXmlString <EntityDescriptor>(entityDescriptor.OuterXml);
            ExtractEndpoints();
        }
        private static XmlDocument LoadBytesAsXmlDocument(byte[] xmlMetadataBytes)
        {
            XmlDocument doc = new XmlDocument();

            doc.XmlResolver        = null;
            doc.PreserveWhitespace = true;

            //try
            //{
            // First attempt a standard load, where the XML document is expected to declare its encoding by itself.
            doc.Load(new StreamReader(new MemoryStream(xmlMetadataBytes)));
            try
            {
                if (XmlSignatureUtils.IsSigned(doc) && !XmlSignatureUtils.CheckSignature(doc))
                {
                    throw new InvalidOperationException("Invalid file signature");
                }
                // Throw an exception to get into quirksmode.
            }catch (CryptographicException)
            {
                //Ignore cryptographic exception caused by Geneva server's inability to generate a
                //.net compliant xml signature
                return(ParseGenevaServerMetadata(doc));
            }
            return(doc);

            //}
            //catch (XmlException)
            //{
            //    // Enter quirksmode
            //    List<Encoding> encs = _getEncodings();
            //    foreach (Encoding encoding in encs)
            //    {
            //        StreamReader reader = null;
            //        try
            //        {
            //            doc.Load(new StreamReader(new MemoryStream(xmlMetadataBytes), encoding));
            //            if (XmlSignatureUtils.IsSigned(doc) && !XmlSignatureUtils.CheckSignature(doc))
            //                continue;
            //        }
            //        catch (XmlException)
            //        { continue; }
            //        finally
            //        {
            //            if (reader != null)
            //                reader.Close();
            //        }

            //        return doc;
            //    }
            //}
            return(null);
        }
Example #14
0
        /// <summary>
        /// Deserializes an assertion, verifies its signature and logs in the user if the assertion is valid.
        /// </summary>
        /// <param name="context">The context.</param>
        /// <param name="elem">The elem.</param>
        public static Saml20Assertion HandleAssertion(XmlElement elem, Saml2Configuration config, Func <string, object> getFromCache, Action <string, object, DateTime> setInCache)
        {
            logger.DebugFormat(TraceMessages.AssertionProcessing, elem.OuterXml);

            var issuer = GetIssuer(elem);
            var endp   = IdpSelectionUtil.RetrieveIDPConfiguration(issuer, config);

            PreHandleAssertion(elem, endp);

            if (endp == null || endp.Metadata == null)
            {
                logger.Error(ErrorMessages.AssertionIdentityProviderUnknown);
                throw new Saml20Exception(ErrorMessages.AssertionIdentityProviderUnknown);
            }

            var quirksMode = endp.QuirksMode;
            var assertion  = new Saml20Assertion(elem, null, quirksMode, config);

            // Check signatures
            if (!endp.OmitAssertionSignatureCheck)
            {
                var document = elem.OwnerDocument;

                if (!XmlSignatureUtils.CheckSignature(document))
                {
                    logger.Error(ErrorMessages.AssertionSignatureInvalid);
                    throw new Saml20Exception(ErrorMessages.AssertionSignatureInvalid);
                }
            }

            // Check expiration
            if (assertion.IsExpired)
            {
                logger.Error(ErrorMessages.AssertionExpired);
                throw new Saml20Exception(ErrorMessages.AssertionExpired);
            }

            // Check one time use
            if (assertion.IsOneTimeUse)
            {
                if (getFromCache(assertion.Id) != null)
                {
                    logger.Error(ErrorMessages.AssertionOneTimeUseExceeded);
                    throw new Saml20Exception(ErrorMessages.AssertionOneTimeUseExceeded);
                }

                setInCache(assertion.Id, string.Empty, assertion.NotOnOrAfter);
            }

            logger.DebugFormat(TraceMessages.AssertionParsed, assertion.Id);
            return(assertion);
        }
        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);
        }
            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        = "";
            }
Example #17
0
        /// <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>True of the signature is valid, else false.</returns>
        public bool CheckSignature(IEnumerable <KeyDescriptor> keys)
        {
            foreach (var keyDescriptor in keys)
            {
                foreach (KeyInfoClause clause in (KeyInfo)keyDescriptor.KeyInfo)
                {
                    var key = XmlSignatureUtils.ExtractKey(clause);
                    if (key != null && XmlSignatureUtils.CheckSignature(Document, 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>
        /// 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 (KeyDescriptor keyDescriptor in keys)
            {
                KeyInfo ki = (KeyInfo)keyDescriptor.KeyInfo;

                foreach (KeyInfoClause clause in ki)
                {
                    AsymmetricAlgorithm 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);
            }
Example #21
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);
            }
Example #22
0
        public void CheckSignature_02()
        {
            XmlDocument doc = LoadDocument(@"Saml20\Assertions\Saml2Assertion_01");

            Assert.That(XmlSignatureUtils.CheckSignature(doc));
        }
Example #23
0
        public void CheckSignature_01()
        {
            XmlDocument doc = LoadDocument(@"Saml20\Assertions\EncryptedAssertion_01");

            XmlSignatureUtils.CheckSignature(doc);
        }
        /// <summary>
        /// Loads a file into an XmlDocument. If the loading or the signature check fails, the method will retry using another encoding.
        /// </summary>
        /// <param name="filename">The filename.</param>
        /// <returns>The XML document.</returns>
        private static XmlDocument LoadAsXmlDocument(IEnumerable <Encoding> encodings, Action <XmlDocument> docLoad, Action <XmlDocument, Encoding> quirksModeDocLoad)
        {
            var doc = new XmlDocument {
                PreserveWhitespace = true
            };

            try {
                // First attempt a standard load, where the XML document is expected to declare its encoding by itself.
                docLoad(doc);

                //Remove MS markup that breals the SAML2 metadata format
                var nodes = doc.GetElementsByTagName("Signature", SAML2.Saml20Constants.Xmldsig);
                if (nodes.Count > 0)
                {
                    nodes[0].ParentNode.RemoveChild(nodes[0]);
                }
                doc.GetElementsByTagName("RoleDescriptor").Cast <XmlNode>().ToList().ForEach(node =>
                {
                    var attr = node.Attributes.GetNamedItem("xsi:type");
                    if (attr?.Value == "fed:ApplicationServiceType" || attr?.Value == "fed:SecurityTokenServiceType")
                    {
                        node.ParentNode.RemoveChild(node);
                    }
                });



                try {
                    if (XmlSignatureUtils.IsSigned(doc) && !XmlSignatureUtils.CheckSignature(doc))
                    {
                        // Bad, bad, bad... never use exceptions for control flow! Who wrote this?
                        // Throw an exception to get into quirksmode.
                        throw new InvalidOperationException("Invalid file signature");
                    }
                }
                catch (CryptographicException) {
                    // Ignore cryptographic exception caused by Geneva server's inability to generate a
                    // .NET compliant xml signature
                    return(ParseGenevaServerMetadata(doc));
                }

                return(doc);
            }
            catch (XmlException) {
                // Enter quirksmode
                foreach (var encoding in encodings)
                {
                    StreamReader reader = null;
                    try {
                        quirksModeDocLoad(doc, encoding);
                        if (XmlSignatureUtils.IsSigned(doc) && !XmlSignatureUtils.CheckSignature(doc))
                        {
                            continue;
                        }
                    }
                    catch (XmlException) {
                        continue;
                    }
                    finally {
                        if (reader != null)
                        {
                            reader.Close();
                        }
                    }

                    return(doc);
                }
            }

            return(null);
        }
Example #25
0
 /// <summary>
 /// Checks the signature of the message.
 /// </summary>
 /// <returns></returns>
 public bool CheckSignature()
 {
     return(XmlSignatureUtils.CheckSignature(_document));
 }