From: Scott Cantor Date: Wed, 11 Oct 2006 15:52:58 +0000 (+0000) Subject: SAML 2 Artifact decoder/test, with some API adjustments. X-Git-Tag: 2.0-alpha1~173 X-Git-Url: http://www.project-moonshot.org/gitweb/?p=shibboleth%2Fcpp-opensaml.git;a=commitdiff_plain;h=4239af10cc1e0d87b9b5bc62378cc077e787bb09 SAML 2 Artifact decoder/test, with some API adjustments. --- diff --git a/saml/Makefile.am b/saml/Makefile.am index c8e1d03..636ffac 100644 --- a/saml/Makefile.am +++ b/saml/Makefile.am @@ -74,6 +74,7 @@ saml2coreinclude_HEADERS = \ saml2bindinclude_HEADERS = \ saml2/binding/SAML2Artifact.h \ saml2/binding/SAML2ArtifactType0004.h \ + saml2/binding/SAML2ArtifactDecoder.h \ saml2/binding/SAML2ArtifactEncoder.h \ saml2/binding/SAML2POSTDecoder.h \ saml2/binding/SAML2POSTEncoder.h @@ -122,6 +123,7 @@ libsaml_la_SOURCES = \ saml2/metadata/impl/WhitelistMetadataFilter.cpp \ saml2/binding/impl/SAML2Artifact.cpp \ saml2/binding/impl/SAML2ArtifactType0004.cpp \ + saml2/binding/impl/SAML2ArtifactDecoder.cpp \ saml2/binding/impl/SAML2ArtifactEncoder.cpp \ saml2/binding/impl/SAML2POSTDecoder.cpp \ saml2/binding/impl/SAML2POSTEncoder.cpp \ diff --git a/saml/binding/MessageDecoder.h b/saml/binding/MessageDecoder.h index 0cfdbba..d0a29a0 100644 --- a/saml/binding/MessageDecoder.h +++ b/saml/binding/MessageDecoder.h @@ -36,6 +36,7 @@ namespace opensaml { }; namespace saml2p { class SAML_API SAML2Artifact; + class SAML_API ArtifactResponse; }; namespace saml2md { class SAML_API MetadataProvider; @@ -164,7 +165,7 @@ namespace opensaml { /** * Resolves a SAML 2.0 artifact into the corresponding SAML protocol message. - * The caller is responsible for the resulting XMLObject. + * The caller is responsible for the resulting ArtifactResponse message. * * @param authenticated output flag set to true iff the resolution channel was authenticated * @param artifact reference to a SAML 2.0 artifact @@ -172,7 +173,7 @@ namespace opensaml { * @param trustEngine optional pointer to X509TrustEngine supplied to MessageDecoder * @return the corresponding SAML protocol message or NULL */ - virtual xmltooling::XMLObject* resolve( + virtual saml2p::ArtifactResponse* resolve( bool& authenticated, const saml2p::SAML2Artifact& artifact, const saml2md::SSODescriptorType& ssoDescriptor, diff --git a/saml/binding/impl/MessageDecoder.cpp b/saml/binding/impl/MessageDecoder.cpp index 14a7d19..dbaff1a 100644 --- a/saml/binding/impl/MessageDecoder.cpp +++ b/saml/binding/impl/MessageDecoder.cpp @@ -43,6 +43,6 @@ void SAML_API opensaml::registerMessageDecoders() SAMLConfig& conf=SAMLConfig::getConfig(); conf.MessageDecoderManager.registerFactory(SAML1_ARTIFACT_DECODER, saml1p::SAML1ArtifactDecoderFactory); conf.MessageDecoderManager.registerFactory(SAML1_POST_DECODER, saml1p::SAML1POSTDecoderFactory); - //conf.MessageDecoderManager.registerFactory(SAML2_ARTIFACT_DECODER, saml2p::SAML2ArtifactDecoderFactory); + conf.MessageDecoderManager.registerFactory(SAML2_ARTIFACT_DECODER, saml2p::SAML2ArtifactDecoderFactory); conf.MessageDecoderManager.registerFactory(SAML2_POST_DECODER, saml2p::SAML2POSTDecoderFactory); } diff --git a/saml/saml.vcproj b/saml/saml.vcproj index 25beeeb..3f2c224 100644 --- a/saml/saml.vcproj +++ b/saml/saml.vcproj @@ -377,6 +377,10 @@ + + @@ -622,6 +626,10 @@ > + + diff --git a/saml/saml2/binding/SAML2ArtifactDecoder.h b/saml/saml2/binding/SAML2ArtifactDecoder.h new file mode 100644 index 0000000..fc681eb --- /dev/null +++ b/saml/saml2/binding/SAML2ArtifactDecoder.h @@ -0,0 +1,57 @@ +/* + * Copyright 2001-2006 Internet2 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @file saml/saml2/binding/SAML2ArtifactDecoder.h + * + * SAML 2.0 Artifact binding message decoder + */ + +#include + + +namespace opensaml { + namespace saml2 { + class SAML_API Issuer; + }; + + namespace saml2p { + + /** + * SAML 2.0 Artifact binding message decoder + */ + class SAML_API SAML2ArtifactDecoder : public MessageDecoder + { + public: + SAML2ArtifactDecoder(const DOMElement* e); + virtual ~SAML2ArtifactDecoder(); + + xmltooling::XMLObject* decode( + std::string& relayState, + const saml2md::RoleDescriptor*& issuer, + bool& issuerTrusted, + const HTTPRequest& httpRequest, + const saml2md::MetadataProvider* metadataProvider=NULL, + const xmltooling::QName* role=NULL, + const TrustEngine* trustEngine=NULL + ) const; + + protected: + bool issuerMatches(const saml2::Issuer* messageIssuer, const XMLCh* expectedIssuer) const; + }; + + }; +}; diff --git a/saml/saml2/binding/impl/SAML2ArtifactDecoder.cpp b/saml/saml2/binding/impl/SAML2ArtifactDecoder.cpp new file mode 100644 index 0000000..d484b2f --- /dev/null +++ b/saml/saml2/binding/impl/SAML2ArtifactDecoder.cpp @@ -0,0 +1,228 @@ +/* + * Copyright 2001-2006 Internet2 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * SAML2ArtifactDecoder.cpp + * + * SAML 2.0 Artifact binding message decoder + */ + +#include "internal.h" +#include "exceptions.h" +#include "saml/binding/SAMLArtifact.h" +#include "saml2/core/Protocols.h" +#include "saml2/metadata/Metadata.h" +#include "saml2/metadata/MetadataProvider.h" +#include "saml2/binding/SAML2Artifact.h" +#include "saml2/binding/SAML2ArtifactDecoder.h" +#include "security/X509TrustEngine.h" + +#include +#include +#include + +using namespace opensaml::saml2md; +using namespace opensaml::saml2p; +using namespace opensaml::saml2; +using namespace opensaml; +using namespace xmlsignature; +using namespace xmltooling; +using namespace log4cpp; +using namespace std; + +namespace opensaml { + namespace saml2p { + MessageDecoder* SAML_DLLLOCAL SAML2ArtifactDecoderFactory(const DOMElement* const & e) + { + return new SAML2ArtifactDecoder(e); + } + }; +}; + +SAML2ArtifactDecoder::SAML2ArtifactDecoder(const DOMElement* e) {} + +SAML2ArtifactDecoder::~SAML2ArtifactDecoder() {} + +XMLObject* SAML2ArtifactDecoder::decode( + string& relayState, + const RoleDescriptor*& issuer, + bool& issuerTrusted, + const HTTPRequest& httpRequest, + const MetadataProvider* metadataProvider, + const QName* role, + const opensaml::TrustEngine* trustEngine + ) const +{ +#ifdef _DEBUG + xmltooling::NDC ndc("decode"); +#endif + Category& log = Category::getInstance(SAML_LOGCAT".MessageDecoder.SAML2Artifact"); + + log.debug("validating input"); + const char* SAMLart = httpRequest.getParameter("SAMLart"); + if (!SAMLart) + return NULL; + const char* state = httpRequest.getParameter("RelayState"); + if (state) + relayState = state; + + if (!m_artifactResolver || !metadataProvider) + throw BindingException("Artifact binding requires ArtifactResolver and MetadataProvider implementations be supplied."); + + // Import the artifact. + SAMLArtifact* artifact=NULL; + ReplayCache* replayCache = XMLToolingConfig::getConfig().getReplayCache(); + try { + log.debug("processing encoded artifact (%s)", SAMLart); + + // Check replay. + if (replayCache) { + if (!replayCache->check("SAML2Artifact", SAMLart, time(NULL) + (2*XMLToolingConfig::getConfig().clock_skew_secs))) { + log.error("replay detected of artifact (%s)", SAMLart); + throw BindingException("Rejecting replayed artifact ($1).", params(1,SAMLart)); + } + } + else + log.warn("replay cache was not provided, this is a serious security risk!"); + + artifact = SAMLArtifact::parse(SAMLart); + } + catch (ArtifactException&) { + log.error("error parsing artifact (%s)", SAMLart); + throw; + } + + // Check the type. + auto_ptr artifact2(dynamic_cast(artifact)); + if (!artifact2.get()) { + throw BindingException("Artifact binding requires SAML 2.0 artifact."); + delete artifact; + } + + issuer = NULL; + issuerTrusted = false; + log.debug("attempting to determine source of artifact..."); + const EntityDescriptor* provider=metadataProvider->getEntityDescriptor(artifact); + if (!provider) { + log.error( + "metadata lookup failed, unable to determine issuer of artifact (0x%s)", + SAMLArtifact::toHex(artifact->getBytes()).c_str() + ); + throw BindingException("Metadata lookup failed, unable to determine artifact issuer."); + } + + if (log.isDebugEnabled()) { + auto_ptr_char issuer(provider->getEntityID()); + log.debug("lookup succeeded, artifact issued by (%s)", issuer.get()); + } + + log.debug("attempting to find artifact issuing role..."); + issuer=provider->getRoleDescriptor(*role, SAMLConstants::SAML20P_NS); + if (!issuer || !dynamic_cast(issuer)) { + log.error("unable to find compatible SAML role (%s) in metadata", role->toString().c_str()); + BindingException ex("Unable to find compatible metadata role for artifact issuer."); + annotateException(&ex,provider); // throws it + } + + try { + auto_ptr response( + m_artifactResolver->resolve( + issuerTrusted, + *(artifact2.get()), + dynamic_cast(*issuer), + dynamic_cast(trustEngine) + ) + ); + + // Check Issuer of outer message. + if (!issuerMatches(response->getIssuer(), provider->getEntityID())) { + log.error("issuer of ArtifactResponse did not match source of artifact"); + throw BindingException("Issuer of ArtifactResponse did not match source of artifact."); + } + + // Extract payload and check that Issuer. + XMLObject* payload = response->getPayload(); + RequestAbstractType* req = NULL; + StatusResponseType* res = dynamic_cast(payload); + if (!res) + req = dynamic_cast(payload); + if (!res && !req) + throw BindingException("ArtifactResponse payload was not a recognized SAML 2.0 protocol message."); + + if (!issuerMatches(res ? res->getIssuer() : req->getIssuer(), provider->getEntityID())) { + log.error("issuer of ArtifactResponse payload did not match source of artifact"); + throw BindingException("Issuer of ArtifactResponse payload did not match source of artifact."); + } + + // Check payload freshness. + time_t now = time(NULL); + if ((res ? res->getIssueInstant() : req->getIssueInstant())->getEpoch() < now-(2*XMLToolingConfig::getConfig().clock_skew_secs)) + throw BindingException("Detected expired ArtifactResponse payload."); + + // Check replay. + if (replayCache) { + auto_ptr_char mid(res ? res->getID() : req->getID()); + if (!replayCache->check("SAML2ArtifactPayload", mid.get(), now + (2*XMLToolingConfig::getConfig().clock_skew_secs))) { + log.error("replay detected of ArtifactResponse payload message ID (%s)", mid.get()); + throw BindingException("Rejecting replayed ArtifactResponse payload ($1).", params(1,mid.get())); + } + } + + // Check signatures. + if (trustEngine) { + if (response->getSignature()) { + issuerTrusted = trustEngine->validate(*(response->getSignature()), *issuer, metadataProvider->getKeyResolver()); + if (!issuerTrusted) { + log.error("unable to verify signature on ArtifactResponse message with supplied trust engine"); + throw BindingException("Message signature failed verification."); + } + } + Signature* sig = (res ? res->getSignature() : req->getSignature()); + if (sig) { + issuerTrusted = trustEngine->validate(*sig, *issuer, metadataProvider->getKeyResolver()); + if (!issuerTrusted) { + log.error("unable to verify signature on ArtifactResponse payload with supplied trust engine"); + throw BindingException("Message signature failed verification."); + } + } + } + + if (!issuerTrusted) { + log.warn("unable to verify integrity of ArtifactResponse message or payload, leaving untrusted"); + } + + // Return the payload only. + response.release(); + payload->detach(); + return payload; + } + catch (XMLToolingException& ex) { + annotateException(&ex,issuer,false); + throw; + } +} + +bool SAML2ArtifactDecoder::issuerMatches(const Issuer* messageIssuer, const XMLCh* expectedIssuer) const +{ + if (messageIssuer && messageIssuer->getName()) { + if (messageIssuer->getFormat() && !XMLString::equals(messageIssuer->getFormat(), NameIDType::ENTITY)) + return false; + else if (!XMLString::equals(expectedIssuer, messageIssuer->getName())) + return false; + } + return true; +} + diff --git a/samltest/Makefile.am b/samltest/Makefile.am index fa73fa7..cb82f02 100644 --- a/samltest/Makefile.am +++ b/samltest/Makefile.am @@ -20,8 +20,6 @@ samltest_h = \ signature/SAML2AssertionTest.h \ security/AbstractPKIXTrustEngineTest.h \ security/ExplicitKeyTrustEngineTest.h \ - saml1/binding/impl/SAML1ArtifactTest.h \ - saml1/binding/impl/SAML1POSTTest.h \ saml1/core/impl/ActionTest.h \ saml1/core/impl/AdviceTest.h \ saml1/core/impl/AssertionIDReferenceTest.h \ @@ -32,7 +30,8 @@ samltest_h = \ saml1/core/impl/AudienceRestrictionConditionTest.h \ saml1/core/impl/AudienceTest.h \ saml1/core/impl/AuthenticationStatementTest.h \ - saml2/binding/impl/SAML2POSTTest.h \ + saml1/binding/SAML1ArtifactTest.h \ + saml1/binding/SAML1POSTTest.h \ saml2/core/impl/Action20Test.h \ saml2/core/impl/Advice20Test.h \ saml2/core/impl/Artifact20Test.h \ @@ -90,6 +89,8 @@ samltest_h = \ saml2/core/impl/SubjectConfirmationData20Test.h\ saml2/core/impl/SubjectLocality20Test.h\ saml2/core/impl/Terminate20Test.h \ + saml2/binding/SAML2ArtifactTest.h \ + saml2/binding/SAML2POSTTest.h \ saml2/metadata/FilesystemMetadataProviderTest.h noinst_HEADERS = \ diff --git a/samltest/data/saml2/binding/SAML2Response.xml b/samltest/data/saml2/binding/SAML2Response.xml index feaf0c4..78e9c09 100644 --- a/samltest/data/saml2/binding/SAML2Response.xml +++ b/samltest/data/saml2/binding/SAML2Response.xml @@ -1,14 +1,6 @@ - https://idp.example.org/ - - - https://idp.example.org/ - John Doe - - - foo - - - - +IssueInstant="1970-01-02T01:01:02.100Z" Version="2.0" ID="rident" +Destination="https://sp.example.org/SAML/POST">https://idp.example.org/https://idp.example.org/John Doefoo \ No newline at end of file diff --git a/samltest/saml1/binding/SAML1ArtifactTest.h b/samltest/saml1/binding/SAML1ArtifactTest.h index decc34f..b36c040 100644 --- a/samltest/saml1/binding/SAML1ArtifactTest.h +++ b/samltest/saml1/binding/SAML1ArtifactTest.h @@ -131,7 +131,7 @@ public: return response.release(); } - XMLObject* resolve( + saml2p::ArtifactResponse* resolve( bool& authenticated, const saml2p::SAML2Artifact& artifact, const SSODescriptorType& ssoDescriptor, diff --git a/samltest/saml2/binding/SAML2ArtifactTest.h b/samltest/saml2/binding/SAML2ArtifactTest.h new file mode 100644 index 0000000..f555e13 --- /dev/null +++ b/samltest/saml2/binding/SAML2ArtifactTest.h @@ -0,0 +1,144 @@ +/* + * Copyright 2001-2005 Internet2 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "binding.h" + +#include +#include +#include + +using namespace opensaml::saml2p; +using namespace opensaml::saml2; + +class SAML2ArtifactTest : public CxxTest::TestSuite, + public SAMLBindingBaseTestCase, public MessageEncoder::ArtifactGenerator, public MessageDecoder::ArtifactResolver { +public: + void setUp() { + m_fields.clear(); + SAMLBindingBaseTestCase::setUp(); + } + + void tearDown() { + m_fields.clear(); + SAMLBindingBaseTestCase::tearDown(); + } + + void testSAML2Artifact() { + try { + // Read message to use from file. + string path = data_path + "saml2/binding/SAML2Response.xml"; + ifstream in(path.c_str()); + DOMDocument* doc=XMLToolingConfig::getConfig().getParser().parse(in); + XercesJanitor janitor(doc); + auto_ptr toSend( + dynamic_cast(XMLObjectBuilder::buildOneFromElement(doc->getDocumentElement(),true)) + ); + janitor.release(); + + // Freshen timestamp. + toSend->setIssueInstant(time(NULL)); + + // Encode message. + auto_ptr encoder(SAMLConfig::getConfig().MessageEncoderManager.newPlugin(SAML2_ARTIFACT_ENCODER, NULL)); + encoder->setArtifactGenerator(this); + encoder->encode(m_fields,toSend.get(),"https://sp.example.org/","state",m_creds); + toSend.release(); + + // Decode message. + string relayState; + const RoleDescriptor* issuer=NULL; + bool trusted=false; + QName idprole(SAMLConstants::SAML20MD_NS, IDPSSODescriptor::LOCAL_NAME); + auto_ptr decoder(SAMLConfig::getConfig().MessageDecoderManager.newPlugin(SAML2_ARTIFACT_DECODER, NULL)); + decoder->setArtifactResolver(this); + Locker locker(m_metadata); + auto_ptr response( + dynamic_cast( + decoder->decode(relayState,issuer,trusted,*this,m_metadata,&idprole,m_trust) + ) + ); + + // Test the results. + TSM_ASSERT_EQUALS("RelayState was not the expected result.", relayState, "state"); + TSM_ASSERT("SAML Response not decoded successfully.", response.get()); + TSM_ASSERT("Message was not verified.", issuer && trusted); + auto_ptr_char entityID(dynamic_cast(issuer->getParent())->getEntityID()); + TSM_ASSERT("Issuer was not expected.", !strcmp(entityID.get(),"https://idp.example.org/")); + TSM_ASSERT_EQUALS("Assertion count was not correct.", response->getAssertions().size(), 1); + + // Trigger a replay. + TSM_ASSERT_THROWS("Did not catch the replay.", + decoder->decode(relayState,issuer,trusted,*this,m_metadata,&idprole,m_trust), + BindingException); + } + catch (XMLToolingException& ex) { + TS_TRACE(ex.what()); + throw; + } + } + + const char* getMethod() const { + return "GET"; + } + + const char* getRequestURL() const { + return "https://sp.example.org/SAML/Artifact"; + } + + const char* getQueryString() const { + return NULL; + } + + SAMLArtifact* generateSAML1Artifact(const char* relyingParty) const { + throw BindingException("Not implemented."); + } + + saml2p::SAML2Artifact* generateSAML2Artifact(const char* relyingParty) const { + return new SAML2ArtifactType0004(SAMLConfig::getConfig().hashSHA1("https://idp.example.org/"),1); + } + + saml1p::Response* resolve( + bool& authenticated, + const vector& artifacts, + const IDPSSODescriptor& idpDescriptor, + const X509TrustEngine* trustEngine=NULL + ) const { + throw BindingException("Not implemented."); + } + + ArtifactResponse* resolve( + bool& authenticated, + const SAML2Artifact& artifact, + const SSODescriptorType& ssoDescriptor, + const X509TrustEngine* trustEngine=NULL + ) const { + XMLObject* xmlObject = + SAMLConfig::getConfig().getArtifactMap()->retrieveContent(&artifact, "https://sp.example.org/"); + Response* payload = dynamic_cast(xmlObject); + TSM_ASSERT("Not a response.", payload!=NULL); + auto_ptr response(ArtifactResponseBuilder::buildArtifactResponse()); + response->setPayload(payload); + Status* status = StatusBuilder::buildStatus(); + response->setStatus(status); + StatusCode* sc = StatusCodeBuilder::buildStatusCode(); + status->setStatusCode(sc); + sc->setValue(StatusCode::SUCCESS); + response->marshall(); + SchemaValidators.validate(response.get()); + authenticated = true; + return response.release(); + } +}; diff --git a/samltest/samltest.vcproj b/samltest/samltest.vcproj index f8eea0c..8970b8d 100644 --- a/samltest/samltest.vcproj +++ b/samltest/samltest.vcproj @@ -538,6 +538,10 @@ Name="binding" > + + @@ -2372,6 +2376,28 @@ Name="binding" > + + + + + + + +