コード例 #1
0
        public void SetUp()
        {
            var xml = new FileSystem().ReadStringFromFile("sample.xml");
            theReader = new SamlResponseXmlReader(xml);

            theResponse = theReader.Read();
        }
コード例 #2
0
        // virtual for testing
        public virtual bool MatchesIssuer(SamlResponse response)
        {
            var samlCertificate = _repository.Find(response.Issuer);
            if (samlCertificate == null) return false;

            return response.Certificates.Any(x => samlCertificate.Matches(x));
        }
コード例 #3
0
 public void Validate(SamlResponse response)
 {
     if (response.Signed != SignatureStatus.Signed)
     {
         response.LogError(new SamlError(response.Signed));
     }
 }
コード例 #4
0
        public void add_a_single_key_attribute()
        {
            var response = new SamlResponse();
            response.AddAttribute("a", "1");

            response.Attributes.Get("a").ShouldEqual("1");
        }
コード例 #5
0
        public void only_has_to_match_on_one_cert()
        {
            var certs = new ICertificate[]
            {
                new InMemoryCertificate(),
                new InMemoryCertificate(),
                new InMemoryCertificate(),
                new InMemoryCertificate()
            };

            var response = new SamlResponse
            {
                Issuer       = "this:guy",
                Certificates = certs
            };

            var samlCert = ObjectMother.SamlCertificateMatching(response.Issuer, certs[3]);

            MockFor <ISamlCertificateRepository>().Stub(x => x.Find(response.Issuer))
            .Return(samlCert);


            ClassUnderTest.MatchesIssuer(response)
            .ShouldBeTrue();
        }
コード例 #6
0
 public void Validate(SamlResponse response)
 {
     if (response.Signed != SignatureStatus.Signed)
     {
         response.LogError(new SamlError(response.Signed));
     }
 }
        protected bool TryGetSamlResponse(HttpContext context, out SamlResponse response, out BindingType binding)
        {
            const string name   = "SAMLResponse";
            var          reader = GetXmlReader(context, name, out var b);

            if (reader == null || !b.HasValue)
            {
                response = null;
                binding  = default;
                return(false);
            }

            binding = b.Value;

            if (!Options.SupportedBindings.Contains(binding))
            {
                throw new SecurityException($"SAML2P response sent using unsupported binding ({binding}).");
            }

            using (reader)
            {
                Logger.LogDebug($"Reading '{name}' using '{binding}' binding.");
                response            = Serializer.DeserializeSamlResponse(reader);
                response.RelayState = GetRelayState(context, binding);
                return(response != null);
            }
        }
コード例 #8
0
        public void ShouldWriteSamlResponseStatusCodeElement(string expected)
        {
            var uri      = new Uri(expected);
            var response = new SamlResponse
            {
                Status = new Status
                {
                    StatusCode = new StatusCode
                    {
                        Value = uri
                    }
                }
            };

            var serialized = _serializer.SerializeSamlResponse(response);

            Assert.NotNull(serialized);

            var doc    = XDocument.Parse(serialized);
            var root   = doc.Root;
            var status = root.Element(XName.Get("Status", _protocolNamespace));

            Assert.NotNull(status);
            var code = status.Element(XName.Get("StatusCode", _protocolNamespace));

            Assert.NotNull(code);
            var attribute = code.Attribute("Value");

            Assert.NotNull(attribute?.Value);
            Assert.Equal(expected, attribute.Value);
        }
コード例 #9
0
        public void ShouldWriterSamlResponseAssertionElement()
        {
            var issuer    = new Saml2NameIdentifier("issuer");
            var assertion = new Saml2Assertion(issuer)
            {
                Subject = new Saml2Subject(new Saml2NameIdentifier("subject"))
            };

            var token = new Saml2SecurityToken(assertion);

            var response = new SamlResponse
            {
                SecurityToken = token
            };

            var serialized = _serializer.SerializeSamlResponse(response);

            Assert.NotNull(serialized);

            var doc  = XDocument.Parse(serialized);
            var root = doc.Root;

            _mockHandler.Verify(h => h.WriteToken(It.IsAny <XmlWriter>(), token), Times.Once());
            var element = root.Element(XName.Get("Assertion", _assertionNamespace));

            Assert.NotNull(element);
        }
コード例 #10
0
        public SamlResponse Create(ISaml2pServiceProvider partner, Status status, string authnRequestId = null, string relayState = null, Saml2SecurityToken token = null)
        {
            var destination = new Uri(partner.BaseUrl, partner.AssertionConsumerServiceEndpoint);

            if (token != null)
            {
                if (authnRequestId != null)
                {
                    token.SetRecipient(destination, authnRequestId);
                }
                else
                {
                    token.SetRecipient(destination);
                }
                token.SetNotOnOrAfter();
            }

            var response = new SamlResponse
            {
                Id            = $"_{Guid.NewGuid()}", // TODO: create id factory
                SecurityToken = token,
                Destination   = destination,
                IssueInstant  = token?.Assertion.IssueInstant,
                Issuer        = partner.ExpectedIssuer ?? _options.DefaultIssuer,
                Status        = status,
                InResponseTo  = authnRequestId,
                RelayState    = relayState
            };

            return(response);
        }
コード例 #11
0
 public SamlAuthenticationFailed(SamlResponse response)
 {
     Errors = response.Errors.Select(x => x.Message).ToArray();
     Name   = response.Subject.Name.Value;
     Issuer = response.Issuer;
     SamlId = response.Id;
 }
コード例 #12
0
        // This assumes signing cert is embedded in the signature
        private void readSignaturesAndCertificates(SamlResponse response)
        {
            var element = find(Signature, "http://www.w3.org/2000/09/xmldsig#");

            if (element == null)
            {
                response.Signed = SignatureStatus.NotSigned;
                return;
            }

            var signedXml = new SignedXml(_document);

            signedXml.LoadXml(element);

            response.Signed = signedXml.CheckSignature()
                                  ? SignatureStatus.Signed
                                  : SignatureStatus.InvalidSignature;

            response.Certificates = signedXml
                                    .KeyInfo.OfType <KeyInfoX509Data>()
                                    .SelectMany(x => {
                return(x.Certificates.OfType <X509Certificate2>()
                       .Select(cert => new X509CertificateWrapper(cert)));
            });
        }
コード例 #13
0
 public void Validate(SamlResponse response)
 {
     var now = _systemTime.UtcNow();
     if (now < response.Conditions.NotBefore || now >= response.Conditions.NotOnOrAfter)
     {
         response.LogError(SamlValidationKeys.TimeFrameDoesNotMatch);
     }
 }
コード例 #14
0
        public SamlValidationKeys Validate(SamlResponse response)
        {
            if (!MatchesIssuer(response)) return SamlValidationKeys.CannotMatchIssuer;

            return response.Certificates.Any(x => x.IsVerified)
                       ? SamlValidationKeys.ValidCertificate
                       : SamlValidationKeys.NoValidCertificates;
        }
コード例 #15
0
        public void add_a_single_key_attribute()
        {
            var response = new SamlResponse();

            response.AddAttribute("a", "1");

            response.Attributes.Get("a").ShouldEqual("1");
        }
コード例 #16
0
 public void Validate(SamlResponse response)
 {
     var key = _service.Validate(response);
     if (key != SamlValidationKeys.ValidCertificate)
     {
         response.LogError(key);
     }
 }
コード例 #17
0
        public void SetUp()
        {
            var xml = new FileSystem().ReadStringFromFile("sample.xml");

            theReader = new SamlResponseXmlReader(xml);

            theResponse = theReader.Read();
        }
コード例 #18
0
        public void Validate(SamlResponse response)
        {
            var key = _service.Validate(response);

            if (key != SamlValidationKeys.ValidCertificate)
            {
                response.LogError(key);
            }
        }
コード例 #19
0
        public void Validate(SamlResponse response)
        {
            var now = _systemTime.UtcNow();

            if (now < response.Conditions.NotBefore || now >= response.Conditions.NotOnOrAfter)
            {
                response.LogError(SamlValidationKeys.TimeFrameDoesNotMatch);
            }
        }
コード例 #20
0
        public SamlValidationKeys Validate(SamlResponse response)
        {
            if (response.Issuer == _certificate.Issuer)
            {
                return(SamlValidationKeys.ValidCertificate);
            }

            return(SamlValidationKeys.CannotMatchIssuer);
        }
コード例 #21
0
        public void Validate(SamlResponse response)
        {
            var restrictions = response.AudienceRestrictions;
            if (!restrictions.Any()) return;

            if (!_audiences.Any(x => restrictions.Any(r => r.Audiences.Contains(x))))
            {
                response.LogError(new SamlError(SamlValidationKeys.AudiencesDoNotMatch));
            }
        }
コード例 #22
0
        public void add_multiple_values_for_the_same_key()
        {
            var response = new SamlResponse();

            response.AddAttribute("a", "1");
            response.AddAttribute("a", "2");
            response.AddAttribute("a", "3");

            response.Attributes.Get("a").As <IEnumerable <string> >()
            .ShouldHaveTheSameElementsAs("1", "2", "3");
        }
コード例 #23
0
        public void SetUp()
        {
            var xml = new FileSystem().ReadStringFromFile("sample.xml");
            theOriginalResponse = new SamlResponseXmlReader(xml).Read();

            document = new SamlResponseXmlWriter(theOriginalResponse).Write();
            
            Debug.WriteLine(document.OuterXml);
            
            theSecondResponse = new SamlResponseXmlReader(document.OuterXml).Read();
        }
コード例 #24
0
        // virtual for testing
        public virtual bool MatchesIssuer(SamlResponse response)
        {
            var samlCertificate = _repository.Find(response.Issuer);

            if (samlCertificate == null)
            {
                return(false);
            }

            return(response.Certificates.Any(x => samlCertificate.Matches(x)));
        }
コード例 #25
0
        public void add_multiple_values_for_the_same_key()
        {
            var response = new SamlResponse();

            response.AddAttribute("a", "1");
            response.AddAttribute("a", "2");
            response.AddAttribute("a", "3");

            response.Attributes.Get("a").As<IEnumerable<string>>()
                .ShouldHaveTheSameElementsAs("1", "2", "3");
        }
コード例 #26
0
        public void no_errors_if_response_is_signed()
        {
            var response = new SamlResponse
            {
                Signed = SignatureStatus.Signed
            };

            new SignatureIsRequired().Validate(response);

            response.Errors.Any().ShouldBeFalse();
        }
コード例 #27
0
        public void no_errors_if_response_is_signed()
        {
            var response = new SamlResponse
            {
                Signed = SignatureStatus.Signed
            };

            new SignatureIsRequired().Validate(response);

            response.Errors.Any().ShouldBeFalse();
        }
コード例 #28
0
        public void returns_CannotMatchIssuer_if_the_cert_does_not_match_the_issuers_we_are_aware_of()
        {
            Services.PartialMockTheClassUnderTest();

            var response = new SamlResponse();

            ClassUnderTest.Expect(x => x.MatchesIssuer(response)).Return(false);

            ClassUnderTest.Validate(response)
            .ShouldBe(SamlValidationKeys.CannotMatchIssuer);
        }
コード例 #29
0
        public SamlValidationKeys Validate(SamlResponse response)
        {
            if (!MatchesIssuer(response))
            {
                return(SamlValidationKeys.CannotMatchIssuer);
            }

            return(response.Certificates.Any(x => x.IsVerified)
                       ? SamlValidationKeys.ValidCertificate
                       : SamlValidationKeys.NoValidCertificates);
        }
コード例 #30
0
        public void error_if_signature_is_missing()
        {
            var response = new SamlResponse
            {
                Signed = SignatureStatus.NotSigned
            };

            new SignatureIsRequired().Validate(response);

            response.Errors.Single()
            .ShouldEqual(new SamlError(SignatureStatus.NotSigned));
        }
コード例 #31
0
        public void error_if_signature_is_invalid()
        {
            var response = new SamlResponse
            {
                Signed = SignatureStatus.InvalidSignature
            };

            new SignatureIsRequired().Validate(response);

            response.Errors.Single()
            .ShouldBe(new SamlError(SignatureStatus.InvalidSignature));
        }
コード例 #32
0
        public void error_if_signature_is_invalid()
        {
            var response = new SamlResponse
            {
                Signed = SignatureStatus.InvalidSignature
            };

            new SignatureIsRequired().Validate(response);

            response.Errors.Single()
                    .ShouldEqual(new SamlError(SignatureStatus.InvalidSignature));
        }
コード例 #33
0
        public void SetUp()
        {
            var xml = new FileSystem().ReadStringFromFile("sample.xml");

            theOriginalResponse = new SamlResponseXmlReader(xml).Read();

            document = new SamlResponseXmlWriter(theOriginalResponse).Write();

            Debug.WriteLine(document.OuterXml);

            theSecondResponse = new SamlResponseXmlReader(document.OuterXml).Read();
        }
コード例 #34
0
        protected override void beforeEach()
        {
            theRules = Services.CreateMockArrayFor <ISamlValidationRule>(5);

            theResponse = new SamlResponse();
            theXml      = "<Response />";

            MockFor <ISamlResponseReader>().Stub(x => x.Read(theXml)).Return(theResponse);

            theHandlers = Services.CreateMockArrayFor <ISamlResponseHandler>(3);

            ClassUnderTest.ProcessSamlResponseXml(theXml);
        }
コード例 #35
0
        public void Validate(SamlResponse response)
        {
            var restrictions = response.AudienceRestrictions;

            if (!restrictions.Any())
            {
                return;
            }

            if (!_audiences.Any(x => restrictions.Any(r => r.Audiences.Contains(x))))
            {
                response.LogError(new SamlError(SamlValidationKeys.AudiencesDoNotMatch));
            }
        }
コード例 #36
0
        public void does_not_match_issuer_if_all_strategies_fail()
        {
            var cert     = ObjectMother.Certificate1();
            var response = new SamlResponse
            {
                Issuer       = "this:guy",
                Certificates = new ICertificate[] { cert }
            };

            // The mock SamlCertificateRepository will return a null

            ClassUnderTest.MatchesIssuer(response)
            .ShouldBeFalse();
        }
コード例 #37
0
        public void return_verified_if_any_certificate_matches_and_is_verified()
        {
            var response = new SamlResponse();
            var certs    = Services.CreateMockArrayFor <ICertificate>(3);

            certs[2].Stub(x => x.IsVerified).Return(true);
            response.Certificates = certs;

            Services.PartialMockTheClassUnderTest();
            ClassUnderTest.Expect(x => x.MatchesIssuer(response)).Return(true);

            ClassUnderTest.Validate(response)
            .ShouldBe(SamlValidationKeys.ValidCertificate);
        }
コード例 #38
0
        public void return_certificate_is_not_valid_if_all_of_them_fail()
        {
            var response = new SamlResponse();
            var certs    = Services.CreateMockArrayFor <ICertificate>(3);

            certs.Each(x => x.Stub(o => o.IsVerified).Return(false));
            response.Certificates = certs;

            Services.PartialMockTheClassUnderTest();
            ClassUnderTest.Expect(x => x.MatchesIssuer(response)).Return(true);

            ClassUnderTest.Validate(response)
            .ShouldBe(SamlValidationKeys.NoValidCertificates);
        }
コード例 #39
0
        public string Write(SamlResponse response)
        {
            if (response.Status == null) throw new ArgumentOutOfRangeException("SamlResponse must have a Status");

            var xml = new SamlResponseXmlWriter(response).Write();
            var certificate = _certificates.LoadCertificate(response.Issuer);

            _xmlSigner.ApplySignature(response, certificate, xml);
            _encryptor.Encrypt(xml, certificate);

            var rawXml = xml.OuterXml;

            return Convert.ToBase64String(Encoding.UTF8.GetBytes(rawXml));
        }
コード例 #40
0
        public void invalid_because_it_is_before_the_not_before()
        {
            var response = new SamlResponse
            {
                Conditions = new ConditionGroup
                {
                    NotBefore    = systemTime.UtcNow().AddMinutes(1),
                    NotOnOrAfter = systemTime.UtcNow().AddMinutes(5)
                }
            };

            theCondition.Validate(response);
            response.Errors.Single().ShouldBe(new SamlError(SamlValidationKeys.TimeFrameDoesNotMatch));
        }
コード例 #41
0
        public void invalid_because_it_is_after_to_the_after_time()
        {
            var response = new SamlResponse
            {
                Conditions = new ConditionGroup
                {
                    NotBefore    = systemTime.UtcNow().AddMinutes(-5),
                    NotOnOrAfter = systemTime.UtcNow().AddMinutes(-1)
                }
            };

            new ConditionTimeFrame(systemTime).Validate(response);
            response.Errors.Single().ShouldEqual(new SamlError(SamlValidationKeys.TimeFrameDoesNotMatch));
        }
コード例 #42
0
ファイル: HomeEndpoint.cs プロジェクト: kalash-/FubuMVC.Saml2
        public HtmlDocument get_failure_page(SamlResponse response)
        {
            var document = new HtmlDocument();

            document.Title = "Failure Page";

            document.Add("h1").Text("This is the failure page");

            document.Push("ul");

            response.Errors.Each(x => document.Add("li").Text(x.Message));

            return(document);
        }
コード例 #43
0
        public void valid()
        {
            var response = new SamlResponse
            {
                Conditions = new ConditionGroup
                {
                    NotBefore    = systemTime.UtcNow().AddMinutes(-5),
                    NotOnOrAfter = systemTime.UtcNow().AddMinutes(5)
                }
            };

            theCondition.Validate(response);
            response.Errors.Any().ShouldBeFalse();
        }
コード例 #44
0
        public void valid()
        {
            var response = new SamlResponse
            {
                Conditions = new ConditionGroup
                {
                    NotBefore = systemTime.UtcNow().AddMinutes(-5),
                    NotOnOrAfter = systemTime.UtcNow().AddMinutes(5)
                }
            };

            theCondition.Validate(response);
            response.Errors.Any().ShouldBeFalse();
        }
コード例 #45
0
        public void invalid_because_it_is_after_to_the_after_time()
        {
            var response = new SamlResponse
            {
                Conditions = new ConditionGroup
                {
                    NotBefore = systemTime.UtcNow().AddMinutes(-5),
                    NotOnOrAfter = systemTime.UtcNow().AddMinutes(-1)
                }
            };

            new ConditionTimeFrame(systemTime).Validate(response);
            response.Errors.Single().ShouldEqual(new SamlError(SamlValidationKeys.TimeFrameDoesNotMatch));
        }
コード例 #46
0
        public SamlResponseXmlWriter(SamlResponse response)
        {
            _response = response;

            var nameTable = new NameTable();
            var namespaceManager = new XmlNamespaceManager(nameTable);
            namespaceManager.AddNamespace("saml2", AssertionXsd);
            namespaceManager.AddNamespace("samlp", ProtocolXsd);

            _document = new XmlDocument(nameTable);
            _root = _document.CreateElement("Response", ProtocolXsd);
            _document.AppendChild(_root);

            _root.SetAttribute("Version", "2.0");
        }
コード例 #47
0
        public SamlResponse Read()
        {
            var response = new SamlResponse
            {
                Id = _root.GetAttribute(ID),
                Destination = _root.GetAttribute(Destination).ToUri(),
                IssueInstant = _root.ReadAttribute<DateTimeOffset>(IssueInstant),
                Issuer = ReadIssuer(),
                Status = readStatusCode(),
                Conditions = new ConditionGroup(find(ConditionsElem, AssertionXsd)),
                Subject = new Subject(find(Subject, AssertionXsd)),
                Authentication = new AuthenticationStatement(_document)
            };

            readSignaturesAndCertificates(response);
            readAttributes(response);

            return response;
        }
        public void SetUp()
        {
            samlResponse = ObjectMother.Response();

            samlResponse.ShouldNotBeNull();
            samlResponse.Status.ShouldNotBeNull();

            cert = ObjectMother.Certificate2();
            samlCert = ObjectMother.SamlCertificateMatching(samlResponse.Issuer, new X509CertificateWrapper(cert));

            var store = new X509Store(StoreName.My, StoreLocation.LocalMachine);
            store.Open(OpenFlags.ReadWrite);
            store.Add(cert);

            var certificates = new InMemoryCertificateService(samlCert, cert);

            var xml = new SamlResponseWriter(certificates, new SamlResponseXmlSigner(), new AssertionXmlEncryptor()).Write(samlResponse);

            readResponse = new SamlResponseReader(certificates, new AssertionXmlDecryptor()).Read(xml);
        }
コード例 #49
0
        public void ApplySignature(SamlResponse response, X509Certificate2 certificate, XmlDocument document)
        {
            var keyInfo = new KeyInfo();
            keyInfo.AddClause(new KeyInfoX509Data(certificate));

            var signedXml = new SignedXml(document)
            {
                SigningKey = certificate.PrivateKey,
                KeyInfo = keyInfo
            };

            var reference = new Reference(AssertionIdPrefix + response.Id);
            reference.AddTransform(new XmlDsigEnvelopedSignatureTransform());
            signedXml.AddReference(reference);
            signedXml.ComputeSignature();

            var xml = signedXml.GetXml();

            document.FindChild(AssertionElem).AppendChild(xml);
        }
コード例 #50
0
        // This assumes signing cert is embedded in the signature
        private void readSignaturesAndCertificates(SamlResponse response)
        {
            var element = find(Signature, "http://www.w3.org/2000/09/xmldsig#");
            if (element == null)
            {
                response.Signed = SignatureStatus.NotSigned;
                return;
            }

            var signedXml = new SignedXml(_document);
            signedXml.LoadXml(element);

            response.Signed = signedXml.CheckSignature()
                                  ? SignatureStatus.Signed
                                  : SignatureStatus.InvalidSignature;

            response.Certificates = signedXml
                .KeyInfo.OfType<KeyInfoX509Data>()
                .SelectMany(x => {
                    return x.Certificates.OfType<X509Certificate2>()
                    .Select(cert => new X509CertificateWrapper(cert));
                });
        }
        public SamlValidationKeys Validate(SamlResponse response)
        {
            if (response.Issuer == _certificate.Issuer) return SamlValidationKeys.ValidCertificate;

            return SamlValidationKeys.CannotMatchIssuer;
        }
コード例 #52
0
        public void SetUp()
        {
            response = new SamlResponse();

            theRule = new AudienceValidationRule("foo:bar", "bar:foo");
        }
コード例 #53
0
        // TODO -- test payload w/o attributes
        private void readAttributes(SamlResponse response)
        {
            XmlElement attributes = find(AttributeStatement, AssertionXsd);
            if (attributes == null) return;

            foreach (XmlElement attElement in attributes.GetElementsByTagName(Attribute, AssertionXsd))
            {
                string key = attElement.GetAttribute(NameAtt);
                foreach (XmlElement valueElement in attElement.GetElementsByTagName(AttributeValue, AssertionXsd))
                {
                    response.AddAttribute(key, valueElement.InnerText);
                }
            }
        }