示例#1
0
            //ExpectedMessage = "Type attribute of EncryptedData MUST have value " + Saml20Constants.Xenc + "Element" + " if it is present")]
            public void ThrowsExceptionWhenXmlAttributeStatementEncryptedAttributeWrongType()
            {
                // Arrange
                var saml20Assertion    = AssertionUtil.GetBasicAssertion();
                var statements         = new List <StatementAbstract>(saml20Assertion.Items);
                var attributeStatments = (AttributeStatement)statements.Find(x => x is AttributeStatement);

                var attributes = new List <object>(attributeStatments.Items);
                var ee         = new EncryptedElement
                {
                    EncryptedData = new EncryptedData
                    {
                        Type = "SomeWrongType"
                    }
                };

                attributes.Add(ee);
                attributeStatments.Items = attributes.ToArray();
                saml20Assertion.Items    = statements.ToArray();

                // Act
                Assert.Throws(typeof(Saml20FormatException), () =>
                {
                    var assertion = new Saml20Assertion(AssertionUtil.ConvertAssertionToXml(saml20Assertion).DocumentElement, null, false, TestConfiguration.Configuration);
                });
            }
示例#2
0
 //ExpectedMessage = "Signature could not be verified.")]
 public void TestSaml20TokenVerification04()
 {
     Assert.Throws(typeof(Saml20Exception), () =>
     {
         AssertionUtil.DeserializeToken(Path.Combine("Assertions", "EvilSaml2Assertion_03"));
     });
 }
示例#3
0
            public void AddAttribute()
            {
                // Arrange
                var assertion  = new Saml20Assertion(AssertionUtil.LoadXmlDocument(Path.Combine("Assertions", "Saml2Assertion_01")).DocumentElement, null, false, TestConfiguration.Configuration);
                var attributes = assertion.Attributes;

                // This needs to be addressed and is why the test is ignored. See the original Hg project
                attributes.Add(new SamlAttribute());

                var cert = _context.Sts_Dev_cetificate;

                assertion.Sign(cert, null);

                assertion.CheckValid(new[] { cert.PublicKey.Key });

                // Verify that the modified assertion can survive complete serialization and deserialization.
                var assertionString = assertion.GetXml().OuterXml;

                var deserializedAssertionDoc = new XmlDocument {
                    PreserveWhitespace = true
                };

                deserializedAssertionDoc.Load(new StringReader(assertionString));

                var deserializedAssertion = new Saml20Assertion(deserializedAssertionDoc.DocumentElement, null, false, TestConfiguration.Configuration);

                Assert.NotNull(deserializedAssertion.GetSignatureKeys()); // "Signing keys must be present");
                deserializedAssertion.CheckValid(new[] { cert.PublicKey.Key });
            }
示例#4
0
        /// <summary>
        /// Generates an encrypted assertion and writes it to disk.
        /// </summary>
        public static void GenerateEncryptedAssertion()
        {
            var cert      = Certificates.InMemoryResourceUtility.GetInMemoryCertificate("sts_dev_certificate.pfx", "test1234");
            var assertion = AssertionUtil.GetTestAssertion();

            // Create an EncryptedData instance to hold the results of the encryption.o
            var encryptedData = new EncryptedData
            {
                Type             = EncryptedXml.XmlEncElementUrl,
                EncryptionMethod = new EncryptionMethod(EncryptedXml.XmlEncAES256Url)
            };

            // Create a symmetric key.
            var aes = new RijndaelManaged {
                KeySize = 256
            };

            aes.GenerateKey();

            // Encrypt the assertion and add it to the encryptedData instance.
            var encryptedXml     = new EncryptedXml();
            var encryptedElement = encryptedXml.EncryptData(assertion.DocumentElement, aes, false);

            encryptedData.CipherData.CipherValue = encryptedElement;

            // Add an encrypted version of the key used.
            encryptedData.KeyInfo = new KeyInfo();

            var encryptedKey = new EncryptedKey();

            // Use this certificate to encrypt the key.
            var publicKeyRsa = cert.PublicKey.Key as RSA;

            Assert.True(publicKeyRsa != null, "Public key of certificate was not an RSA key. Modify test.");
            encryptedKey.EncryptionMethod = new EncryptionMethod(EncryptedXml.XmlEncRSA15Url);
            encryptedKey.CipherData       = new CipherData(EncryptedXml.EncryptKey(aes.Key, publicKeyRsa, false));

            encryptedData.KeyInfo.AddClause(new KeyInfoEncryptedKey(encryptedKey));

            // Create the resulting Xml-document to hook into.
            var encryptedAssertion = new EncryptedAssertion
            {
                EncryptedData = new Schema.XEnc.EncryptedData(),
                EncryptedKey  = new Schema.XEnc.EncryptedKey[1]
            };

            encryptedAssertion.EncryptedKey[0] = new Schema.XEnc.EncryptedKey();

            var result = Serialization.Serialize(encryptedAssertion);

            var encryptedDataElement = GetElement(Schema.XEnc.EncryptedData.ElementName, Saml20Constants.Xenc, result);

            EncryptedXml.ReplaceElement(encryptedDataElement, encryptedData, false);

            // At this point, result can be output to text
        }
        public void HasNoAssertionBeforeDecrypt()
        {
            // Arrange
            var doc = AssertionUtil.LoadXmlDocument(Path.Combine("Assertions", "EncryptedAssertion_01"));

            // Act
            var encryptedAssertion = new Saml20EncryptedAssertion((RSA)_context.Sts_Dev_cetificate.PrivateKey, doc);

            // Assert
            Assert.Null(encryptedAssertion.Assertion);
        }
示例#6
0
            //ExpectedMessage = "Document does not contain a signature to verify."
            public void VerifySignatureByDefault()
            {
                // Arrange
                // Any key-containing algorithm will do - the basic assertion is NOT signed anyway
                var cert = _context.Sts_Dev_cetificate;

                // Act
                Assert.Throws(typeof(InvalidOperationException), () =>
                {
                    var assertion = new Saml20Assertion(AssertionUtil.GetTestAssertion().DocumentElement, new[] { cert.PublicKey.Key }, false, TestConfiguration.Configuration);
                });
            }
            public void CanDecryptAssertionWithPeerIncludedKeysWithoutSpecifiedEncryptionMethod()
            {
                // Arrange
                var doc = AssertionUtil.LoadXmlDocument(Path.Combine("Assertions", "EncryptedAssertion_03"));
                var encryptedAssertion = new Saml20EncryptedAssertion((RSA)_context.Sts_Dev_cetificate.PrivateKey, doc);

                // Act
                encryptedAssertion.Decrypt();

                // Assert
                Assert.NotNull(encryptedAssertion.Assertion);
            }
            public void CanDecryptAssertion()
            {
                // Arrange
                var doc = AssertionUtil.LoadXmlDocument(Path.Combine("Assertions", "EncryptedAssertion_01"));
                var encryptedAssertion = new Saml20EncryptedAssertion((RSA)_context.Sts_Dev_cetificate.PrivateKey, doc);

                // Act
                encryptedAssertion.Decrypt();
                var assertion = new Saml20Assertion(encryptedAssertion.Assertion.DocumentElement, null, false, TestConfiguration.Configuration);

                // Assert
                Assert.NotNull(encryptedAssertion.Assertion);
            }
            public void CanDecryptAssertionWithPeerIncludedAesKeys()
            {
                // Arrange
                var doc = AssertionUtil.LoadXmlDocument(Path.Combine("Assertions", "EncryptedAssertion_05"));
                var encryptedAssertion = new Saml20EncryptedAssertion((RSA)_context.Sts_Dev_cetificate.PrivateKey, doc);

                // Act
                encryptedAssertion.Decrypt();

                // Assert
                Assert.NotNull(encryptedAssertion.Assertion);
                Assert.Equal(1, encryptedAssertion.Assertion.GetElementsByTagName(Assertion.ElementName, Saml20Constants.Assertion).Count);
            }
示例#10
0
        public void AssertionCanBeSignedAndVerified()
        {
            // Arrange
            var token = AssertionUtil.GetTestAssertion();

            SignDocument(token);

            // Act
            var verified = VerifySignature(token);

            // Assert
            Assert.True(verified);
        }
示例#11
0
            public void CanReadAttributes()
            {
                // Act
                var assertion = new Saml20Assertion(AssertionUtil.LoadXmlDocument(Path.Combine("Assertions", "Saml2Assertion_01")).DocumentElement, null, false, TestConfiguration.Configuration);

                // Assert
                Assert.True(assertion.Attributes.Any());
                Assert.Equal(4, assertion.Attributes.Count);
                foreach (var sa in assertion.Attributes)
                {
                    Assert.True(sa.AttributeValue.Length != 0, "Attribute should have a value");
                }
            }
示例#12
0
            //ExpectedMessage = "SubjectConfirmation element has Method attribute which is not a wellformed absolute uri."
            public void ThrowsWhenSubjectMethodIsNotWellFormedUri()
            {
                // Arrange
                var saml20Assertion     = AssertionUtil.GetBasicAssertion();
                var subjectConfirmation = (SubjectConfirmation)Array.Find(saml20Assertion.Subject.Items, item => item is SubjectConfirmation);

                subjectConfirmation.Method = "IllegalMethod";

                // Act
                Assert.Throws(typeof(Saml20FormatException), () =>
                {
                    var assertion = new Saml20Assertion(AssertionUtil.ConvertAssertionToXml(saml20Assertion).DocumentElement, null, false, TestConfiguration.Configuration);
                });
            }
示例#13
0
            //ExpectedMessage = "AttributeStatement MUST contain at least one Attribute or EncryptedAttribute"
            public void ThrowsExceptionWhenNoItemsArePresent()
            {
                // Arrange
                var saml20Assertion    = AssertionUtil.GetBasicAssertion();
                var attributeStatement = (AttributeStatement)Array.Find(saml20Assertion.Items, x => x is AttributeStatement);

                // Clear all the attributes.
                attributeStatement.Items = new object[0];

                // Act
                Assert.Throws(typeof(Saml20FormatException), () =>
                {
                    var assertion = new Saml20Assertion(AssertionUtil.ConvertAssertionToXml(saml20Assertion).DocumentElement, null, false, TestConfiguration.Configuration);
                });
            }
示例#14
0
            //ExpectedMessage = "AuthnContextClassRef has a value which is not a wellformed absolute uri")]
            public void ThrowsWhenAuthnContextClassRefIsNotWellFormedUri()
            {
                // Arrange
                var saml20Assertion = AssertionUtil.GetBasicAssertion();
                var authnStatement  = (AuthnStatement)Array.Find(saml20Assertion.Items, stmnt => stmnt is AuthnStatement);

                var index = Array.FindIndex(authnStatement.AuthnContext.Items, o => o is string && o.ToString() == "urn:oasis:names:tc:SAML:2.0:ac:classes:X509");

                authnStatement.AuthnContext.Items[index] = "Hallelujagobble!!";

                // Act
                Assert.Throws(typeof(Saml20FormatException), () =>
                {
                    var assertion = new Saml20Assertion(AssertionUtil.ConvertAssertionToXml(saml20Assertion).DocumentElement, null, false, TestConfiguration.Configuration);
                });
            }
示例#15
0
            //ExpectedMessage = "AuthnStatement, AuthzDecisionStatement and AttributeStatement require a subject."
            public void ThrowsWhenSubjectElementIsNotPresent()
            {
                // Arrange
                var saml20Assertion     = AssertionUtil.GetBasicAssertion();
                var subjectConfirmation = (SubjectConfirmation)Array.Find(saml20Assertion.Subject.Items, item => item is SubjectConfirmation);

                subjectConfirmation.SubjectConfirmationData.NotOnOrAfter = DateTime.UtcNow;
                subjectConfirmation.SubjectConfirmationData.NotBefore    = null;
                saml20Assertion.Subject = null;

                // Act
                Assert.Throws(typeof(Saml20FormatException), () =>
                {
                    var assertion = new Saml20Assertion(AssertionUtil.ConvertAssertionToXml(saml20Assertion).DocumentElement, null, false, TestConfiguration.Configuration);
                });
            }
            public void CanEncryptAssertion()
            {
                // Arrange
                var encryptedAssertion = new Saml20EncryptedAssertion {
                    Assertion = AssertionUtil.GetTestAssertion()
                };

                encryptedAssertion.TransportKey = (RSA)_context.Sts_Dev_cetificate.PublicKey.Key;

                // Act
                encryptedAssertion.Encrypt();
                var encryptedAssertionXml = encryptedAssertion.GetXml();

                // Assert
                Assert.NotNull(encryptedAssertionXml);
                Assert.Equal(1, encryptedAssertionXml.GetElementsByTagName(EncryptedAssertion.ElementName, Saml20Constants.Assertion).Count);
                Assert.Equal(1, encryptedAssertionXml.GetElementsByTagName(Schema.XEnc.EncryptedKey.ElementName, Saml20Constants.Xenc).Count);
            }
        public void CanEncryptAssertionFull()
        {
            // Arrange
            var encryptedAssertion = new Saml20EncryptedAssertion
            {
                SessionKeyAlgorithm = EncryptedXml.XmlEncAES128Url,
                Assertion           = AssertionUtil.GetTestAssertion()
            };

            encryptedAssertion.TransportKey = (RSA)_context.Sts_Dev_cetificate.PublicKey.Key;

            // Act
            encryptedAssertion.Encrypt();
            var encryptedAssertionXml = encryptedAssertion.GetXml();

            // Now decrypt the assertion, and verify that it recognizes the Algorithm used.
            var decrypter = new Saml20EncryptedAssertion((RSA)_context.Sts_Dev_cetificate.PrivateKey);

            decrypter.LoadXml(encryptedAssertionXml.DocumentElement);

            // Set a wrong algorithm and make sure that the class gets it algorithm info from the assertion itself.
            decrypter.SessionKeyAlgorithm = EncryptedXml.XmlEncTripleDESUrl;
            decrypter.Decrypt();

            // Assert
            // Go through the children and look for the EncryptionMethod element, and verify its algorithm attribute.
            var encryptionMethodFound = false;

            foreach (XmlNode node in encryptedAssertionXml.GetElementsByTagName(Schema.XEnc.EncryptedData.ElementName, Saml20Constants.Xenc)[0].ChildNodes)
            {
                if (node.LocalName == Schema.XEnc.EncryptionMethod.ElementName && node.NamespaceURI == Saml20Constants.Xenc)
                {
                    var element = (XmlElement)node;
                    Assert.Equal(EncryptedXml.XmlEncAES128Url, element.GetAttribute("Algorithm"));
                    encryptionMethodFound = true;
                }
            }

            Assert.True(encryptionMethodFound, "Unable to find EncryptionMethod element in EncryptedData.");

            // Verify that the class has discovered the correct algorithm and set the SessionKeyAlgorithm property accordingly.
            Assert.Equal(EncryptedXml.XmlEncAES128Url, decrypter.SessionKeyAlgorithm);
            Assert.NotNull(decrypter.Assertion);
        }
            //[ExpectedException(typeof(Saml20Exception), ExpectedMessage = "Assertion is no longer valid.")]
            public void CanDecryptFOBSAssertion()
            {
                // Arrange
                var doc           = AssertionUtil.LoadBase64EncodedXmlDocument(@"Assertions\fobs-assertion2");
                var encryptedList = doc.GetElementsByTagName(EncryptedAssertion.ElementName, Saml20Constants.Assertion);

                // Do some mock configuration.
                var config = new Saml2Configuration
                {
                    AllowedAudienceUris = new System.Collections.Generic.List <Uri>(),
                    IdentityProviders   = new IdentityProviders()
                };

                config.AllowedAudienceUris.Add(new Uri("https://saml.safewhere.net"));
                config.IdentityProviders.AddByMetadataDirectory(Path.Combine(Directory.GetCurrentDirectory(), @"Protocol\MetadataDocs\FOBS")); // Set it manually.

                var cert = _context.SafewhereTest_SFS;
                var encryptedAssertion = new Saml20EncryptedAssertion((RSA)cert.PrivateKey);

                encryptedAssertion.LoadXml((XmlElement)encryptedList[0]);

                // Act
                encryptedAssertion.Decrypt();

                // Retrieve metadata
                var assertion = new Saml20Assertion(encryptedAssertion.Assertion.DocumentElement, null, false, TestConfiguration.Configuration);
                var endp      = config.IdentityProviders.FirstOrDefault(x => x.Id == assertion.Issuer);

                // Assert
                Assert.True(encryptedList.Count == 1);
                Assert.NotNull(endp);          //, "Endpoint not found");
                Assert.NotNull(endp.Metadata); //, "Metadata not found");

                Assert.Throws(typeof(InvalidOperationException), () =>
                {
                    assertion.CheckValid(AssertionUtil.GetTrustedSigners(assertion.Issuer));
                    //Assert.Fail("Verification should fail. Token does not include its signing key.");
                });

                Assert.Null(assertion.SigningKey); //, "Signing key is already present on assertion. Modify test.");
                //Assert.IsTrue("We have tested this next test" == "");
                //Assert.True(assertion.CheckSignature(Saml20SignonHandler.GetTrustedSigners(endp.Metadata.GetKeys(KeyTypes.Signing), endp)));
                //Assert.IsNotNull(assertion.SigningKey, "Signing key was not set on assertion instance.");
            }
示例#19
0
        public void ManipulatingAssertionMakesSignatureInvalid()
        {
            // Arrange
            var token = AssertionUtil.GetTestAssertion();

            SignDocument(token);

            // Manipulate the #%!;er: Attempt to remove the <AudienceRestriction> from the list of conditions.
            var conditions          = (XmlElement)token.GetElementsByTagName("Conditions", "urn:oasis:names:tc:SAML:2.0:assertion")[0];
            var audienceRestriction = (XmlElement)conditions.GetElementsByTagName("AudienceRestriction", "urn:oasis:names:tc:SAML:2.0:assertion")[0];

            conditions.RemoveChild(audienceRestriction);

            // Act
            var verified = VerifySignature(token);

            // Assert
            Assert.False(verified);
        }
示例#20
0
            //ExpectedMessage = "Attribute extension xml attributes MUST BE namespace qualified"
            public void ThrowsExceptionWhenXmlAttributeStatementAttributeAnyAttrUnqualified()
            {
                // Arrange
                var saml20Assertion    = AssertionUtil.GetBasicAssertion();
                var statements         = new List <StatementAbstract>(saml20Assertion.Items);
                var attributeStatments = (AttributeStatement)statements.Find(x => x is AttributeStatement);
                var attribute          = (SamlAttribute)attributeStatments.Items[0];

                var doc = new XmlDocument();

                attribute.AnyAttr = new[] { doc.CreateAttribute(string.Empty, "Nonqualified", string.Empty) };

                saml20Assertion.Items = statements.ToArray();

                // Act
                Assert.Throws(typeof(Saml20FormatException), () =>
                {
                    new Saml20Assertion(AssertionUtil.ConvertAssertionToXml(saml20Assertion).DocumentElement, null, false, TestConfiguration.Configuration);
                });
            }
示例#21
0
            public void ThrowsExceptionWhenXmlAttributeStatementAttributeAnyAttrSamlQualified()
            {
                // Arrange
                var saml20Assertion    = AssertionUtil.GetBasicAssertion();
                var statements         = new List <StatementAbstract>(saml20Assertion.Items);
                var attributeStatments = (AttributeStatement)statements.Find(x => x is AttributeStatement);
                var attribute          = (SamlAttribute)attributeStatments.Items[0];

                var doc = new XmlDocument();

                saml20Assertion.Items = statements.ToArray();

                foreach (var samlns in Saml20Constants.SamlNamespaces)
                {
                    attribute.AnyAttr = new[] { doc.CreateAttribute("someprefix", "SamlQualified", samlns) };

                    Assert.Throws(typeof(Saml20FormatException), () =>
                    {
                        //"Attribute extension xml attributes MUST NOT use a namespace reserved by SAML"
                        var assertion = new Saml20Assertion(AssertionUtil.ConvertAssertionToXml(saml20Assertion).DocumentElement, null, false, TestConfiguration.Configuration);
                    });
                }
            }
示例#22
0
        public void TestSigning03()
        {
            // Load an unsigned assertion.
            var assertion = new Saml20Assertion(AssertionUtil.GetTestAssertion().DocumentElement, null, false, null);

            // Check that the assertion is not considered valid in any way.
            try
            {
                assertion.CheckValid(AssertionUtil.GetTrustedSigners(assertion.Issuer));
                //Assert.Fail("Unsigned assertion was passed off as valid.");
            }
            catch
            {
                // Added to make resharper happy
                Assert.True(true);
            }

            var cert = _context.Sts_Dev_cetificate;

            assertion.Sign(cert, null);

            // Check that the signature is now valid
            assertion.CheckValid(new[] { cert.PublicKey.Key });
        }
示例#23
0
 public void TestSaml20TokenVerification01()
 {
     AssertionUtil.DeserializeToken(Path.Combine("Assertions", "Saml2Assertion_01"));
     AssertionUtil.DeserializeToken(Path.Combine("Assertions", "Saml2Assertion_02"));
     AssertionUtil.DeserializeToken(Path.Combine("Assertions", "Saml2Assertion_03"));
 }