/// <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);
        }
Beispiel #2
0
        public void DetectSignature_02()
        {
            XmlDocument doc = LoadDocument(@"Saml20\Assertions\EncryptedAssertion_01");

            doc.PreserveWhitespace = false;
            XmlSignatureUtils.IsSigned(doc);
        }
Beispiel #3
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);
        }
Beispiel #4
0
        /// <summary>
        /// Returns the KeyInfo element of the signature of the token.
        /// </summary>
        /// <returns>Null if the token is not signed. The KeyInfo element otherwise.</returns>
        public KeyInfo GetSignatureKeys()
        {
            if (!XmlSignatureUtils.IsSigned(_samlAssertion))
            {
                return(null);
            }

            return(XmlSignatureUtils.ExtractSignatureKeys(_samlAssertion));
        }
            public void FailsOnDocumentWithoutPreserveWhitespace()
            {
                // Arrange
                var doc = LoadDocument(TestContext.CurrentContext.TestDirectory + @"\Assertions\EncryptedAssertion_01");

                doc.PreserveWhitespace = false;

                // Act
                Assert.Throws <InvalidOperationException>(() => XmlSignatureUtils.IsSigned(doc));
            }
Beispiel #6
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);
        }
        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 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 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);
            }
            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);
            }
            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>
        ///     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);
            }
        }
Beispiel #14
0
 public void DetectSignature_01()
 {
     Assert.IsFalse((XmlSignatureUtils.IsSigned(LoadDocument(@"Saml20\Assertions\EncryptedAssertion_01"))));
     Assert.IsTrue(((XmlSignatureUtils.IsSigned(LoadDocument(@"Saml20\Assertions\Saml2Assertion_01")))));
 }
 /// <summary>
 /// Returns the KeyInfo element of the signature of the token.
 /// </summary>
 /// <returns>Null if the token is not signed. The KeyInfo element otherwise.</returns>
 public KeyInfo GetSignatureKeys()
 {
     return(!XmlSignatureUtils.IsSigned(XmlAssertion) ? null : XmlSignatureUtils.ExtractSignatureKeys(XmlAssertion));
 }
        /// <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);
        }
 /// <summary>
 /// Determines whether the message is signed.
 /// </summary>
 /// <returns>
 ///     <c>true</c> if the message is signed; otherwise, <c>false</c>.
 /// </returns>
 public bool IsSigned()
 {
     return(XmlSignatureUtils.IsSigned(_samlMessage));
 }
 /// <summary>
 /// Determines whether the message is signed.
 /// </summary>
 /// <returns>
 ///     <c>true</c> if the message is signed; otherwise, <c>false</c>.
 /// </returns>
 public bool IsSigned()
 {
     return(XmlSignatureUtils.IsSigned(_document));
 }