2 * Copyright 2001-2010 Internet2
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
18 * QueryAttributeResolver.cpp
20 * AttributeResolver based on SAML queries.
24 #include "Application.h"
25 #include "ServiceProvider.h"
26 #include "SessionCache.h"
27 #include "attribute/Attribute.h"
28 #include "attribute/filtering/AttributeFilter.h"
29 #include "attribute/filtering/BasicFilteringContext.h"
30 #include "attribute/resolver/AttributeExtractor.h"
31 #include "attribute/resolver/AttributeResolver.h"
32 #include "attribute/resolver/ResolutionContext.h"
33 #include "binding/SOAPClient.h"
34 #include "metadata/MetadataProviderCriteria.h"
35 #include "security/SecurityPolicy.h"
36 #include "security/SecurityPolicyProvider.h"
37 #include "util/SPConstants.h"
39 #include <saml/exceptions.h>
40 #include <saml/saml1/binding/SAML1SOAPClient.h>
41 #include <saml/saml1/core/Assertions.h>
42 #include <saml/saml1/core/Protocols.h>
43 #include <saml/saml2/binding/SAML2SOAPClient.h>
44 #include <saml/saml2/core/Protocols.h>
45 #include <saml/saml2/metadata/Metadata.h>
46 #include <saml/saml2/metadata/MetadataCredentialCriteria.h>
47 #include <saml/saml2/metadata/MetadataProvider.h>
48 #include <xmltooling/util/NDC.h>
49 #include <xmltooling/util/XMLHelper.h>
50 #include <xercesc/util/XMLUniDefs.hpp>
52 using namespace shibsp;
53 using namespace opensaml::saml1;
54 using namespace opensaml::saml1p;
55 using namespace opensaml::saml2;
56 using namespace opensaml::saml2p;
57 using namespace opensaml::saml2md;
58 using namespace opensaml;
59 using namespace xmltooling;
64 class SHIBSP_DLLLOCAL QueryContext : public ResolutionContext
67 QueryContext(const Application& application, const Session& session)
68 : m_query(true), m_app(application), m_session(&session), m_metadata(nullptr), m_entity(nullptr), m_nameid(nullptr) {
69 m_protocol = XMLString::transcode(session.getProtocol());
70 m_class = XMLString::transcode(session.getAuthnContextClassRef());
71 m_decl = XMLString::transcode(session.getAuthnContextDeclRef());
75 const Application& application,
76 const EntityDescriptor* issuer,
77 const XMLCh* protocol,
78 const NameID* nameid=nullptr,
79 const XMLCh* authncontext_class=nullptr,
80 const XMLCh* authncontext_decl=nullptr,
81 const vector<const opensaml::Assertion*>* tokens=nullptr
82 ) : m_query(true), m_app(application), m_session(nullptr), m_metadata(nullptr), m_entity(issuer),
83 m_protocol(protocol), m_nameid(nameid), m_class(authncontext_class), m_decl(authncontext_decl) {
86 for (vector<const opensaml::Assertion*>::const_iterator t = tokens->begin(); t!=tokens->end(); ++t) {
87 const saml2::Assertion* token2 = dynamic_cast<const saml2::Assertion*>(*t);
88 if (token2 && !token2->getAttributeStatements().empty()) {
92 const saml1::Assertion* token1 = dynamic_cast<const saml1::Assertion*>(*t);
93 if (token1 && !token1->getAttributeStatements().empty()) {
103 XMLString::release((XMLCh**)&m_protocol);
104 XMLString::release((XMLCh**)&m_class);
105 XMLString::release((XMLCh**)&m_decl);
108 m_metadata->unlock();
109 for_each(m_attributes.begin(), m_attributes.end(), xmltooling::cleanup<shibsp::Attribute>());
110 for_each(m_assertions.begin(), m_assertions.end(), xmltooling::cleanup<opensaml::Assertion>());
113 bool doQuery() const {
117 const Application& getApplication() const {
120 const EntityDescriptor* getEntityDescriptor() const {
123 if (m_session && m_session->getEntityID()) {
124 m_metadata = m_app.getMetadataProvider(false);
127 return m_entity = m_metadata->getEntityDescriptor(MetadataProviderCriteria(m_app, m_session->getEntityID())).first;
132 const XMLCh* getProtocol() const {
135 const NameID* getNameID() const {
136 return m_session ? m_session->getNameID() : m_nameid;
138 const XMLCh* getClassRef() const {
141 const XMLCh* getDeclRef() const {
144 const Session* getSession() const {
147 vector<shibsp::Attribute*>& getResolvedAttributes() {
150 vector<opensaml::Assertion*>& getResolvedAssertions() {
156 const Application& m_app;
157 const Session* m_session;
158 mutable MetadataProvider* m_metadata;
159 mutable const EntityDescriptor* m_entity;
160 const XMLCh* m_protocol;
161 const NameID* m_nameid;
162 const XMLCh* m_class;
164 vector<shibsp::Attribute*> m_attributes;
165 vector<opensaml::Assertion*> m_assertions;
168 class SHIBSP_DLLLOCAL QueryResolver : public AttributeResolver
171 QueryResolver(const DOMElement* e);
173 for_each(m_SAML1Designators.begin(), m_SAML1Designators.end(), xmltooling::cleanup<AttributeDesignator>());
174 for_each(m_SAML2Designators.begin(), m_SAML2Designators.end(), xmltooling::cleanup<saml2::Attribute>());
177 Lockable* lock() {return this;}
180 ResolutionContext* createResolutionContext(
181 const Application& application,
182 const EntityDescriptor* issuer,
183 const XMLCh* protocol,
184 const NameID* nameid=nullptr,
185 const XMLCh* authncontext_class=nullptr,
186 const XMLCh* authncontext_decl=nullptr,
187 const vector<const opensaml::Assertion*>* tokens=nullptr,
188 const vector<shibsp::Attribute*>* attributes=nullptr
190 return new QueryContext(application,issuer,protocol,nameid,authncontext_class,authncontext_decl,tokens);
193 ResolutionContext* createResolutionContext(const Application& application, const Session& session) const {
194 return new QueryContext(application,session);
197 void resolveAttributes(ResolutionContext& ctx) const;
199 void getAttributeIds(vector<string>& attributes) const {
200 // Nothing to do, only the extractor would actually generate them.
204 bool SAML1Query(QueryContext& ctx) const;
205 bool SAML2Query(QueryContext& ctx) const;
210 vector<AttributeDesignator*> m_SAML1Designators;
211 vector<saml2::Attribute*> m_SAML2Designators;
214 AttributeResolver* SHIBSP_DLLLOCAL QueryResolverFactory(const DOMElement* const & e)
216 return new QueryResolver(e);
219 static const XMLCh policyId[] = UNICODE_LITERAL_8(p,o,l,i,c,y,I,d);
220 static const XMLCh subjectMatch[] = UNICODE_LITERAL_12(s,u,b,j,e,c,t,M,a,t,c,h);
223 QueryResolver::QueryResolver(const DOMElement* e)
224 : m_log(Category::getInstance(SHIBSP_LOGCAT".AttributeResolver.Query")),
225 m_policyId(XMLHelper::getAttrString(e, nullptr, policyId)),
226 m_subjectMatch(XMLHelper::getAttrBool(e, false, subjectMatch))
229 xmltooling::NDC ndc("QueryResolver");
232 DOMElement* child = XMLHelper::getFirstChildElement(e);
235 if (XMLHelper::isNodeNamed(child, samlconstants::SAML20_NS, saml2::Attribute::LOCAL_NAME)) {
236 auto_ptr<XMLObject> obj(saml2::AttributeBuilder::buildOneFromElement(child));
237 saml2::Attribute* down = dynamic_cast<saml2::Attribute*>(obj.get());
239 m_SAML2Designators.push_back(down);
243 else if (XMLHelper::isNodeNamed(child, samlconstants::SAML1_NS, AttributeDesignator::LOCAL_NAME)) {
244 auto_ptr<XMLObject> obj(AttributeDesignatorBuilder::buildOneFromElement(child));
245 AttributeDesignator* down = dynamic_cast<AttributeDesignator*>(obj.get());
247 m_SAML1Designators.push_back(down);
252 catch (exception& ex) {
253 m_log.error("exception loading attribute designator: %s", ex.what());
255 child = XMLHelper::getNextSiblingElement(child);
259 bool QueryResolver::SAML1Query(QueryContext& ctx) const
262 xmltooling::NDC ndc("query");
265 int version = XMLString::equals(ctx.getProtocol(), samlconstants::SAML11_PROTOCOL_ENUM) ? 1 : 0;
266 const AttributeAuthorityDescriptor* AA =
267 find_if(ctx.getEntityDescriptor()->getAttributeAuthorityDescriptors(), isValidForProtocol(ctx.getProtocol()));
269 m_log.warn("no SAML 1.%d AttributeAuthority role found in metadata", version);
273 const Application& application = ctx.getApplication();
274 const PropertySet* relyingParty = application.getRelyingParty(ctx.getEntityDescriptor());
276 // Locate policy key.
277 const char* policyId = m_policyId.empty() ? application.getString("policyId").second : m_policyId.c_str();
279 // Set up policy and SOAP client.
280 auto_ptr<SecurityPolicy> policy(
281 application.getServiceProvider().getSecurityPolicyProvider()->createSecurityPolicy(application, nullptr, policyId)
283 policy->getAudiences().push_back(relyingParty->getXMLString("entityID").second);
284 MetadataCredentialCriteria mcc(*AA);
285 shibsp::SOAPClient soaper(*policy.get());
287 auto_ptr_XMLCh binding(samlconstants::SAML1_BINDING_SOAP);
288 saml1p::Response* response=nullptr;
289 const vector<AttributeService*>& endpoints=AA->getAttributeServices();
290 for (vector<AttributeService*>::const_iterator ep=endpoints.begin(); !response && ep!=endpoints.end(); ++ep) {
291 if (!XMLString::equals((*ep)->getBinding(),binding.get()) || !(*ep)->getLocation())
293 auto_ptr_char loc((*ep)->getLocation());
295 NameIdentifier* nameid = NameIdentifierBuilder::buildNameIdentifier();
296 nameid->setName(ctx.getNameID()->getName());
297 nameid->setFormat(ctx.getNameID()->getFormat());
298 nameid->setNameQualifier(ctx.getNameID()->getNameQualifier());
299 saml1::Subject* subject = saml1::SubjectBuilder::buildSubject();
300 subject->setNameIdentifier(nameid);
301 saml1p::AttributeQuery* query = saml1p::AttributeQueryBuilder::buildAttributeQuery();
302 query->setSubject(subject);
303 query->setResource(relyingParty->getXMLString("entityID").second);
304 for (vector<AttributeDesignator*>::const_iterator ad = m_SAML1Designators.begin(); ad!=m_SAML1Designators.end(); ++ad)
305 query->getAttributeDesignators().push_back((*ad)->cloneAttributeDesignator());
306 Request* request = RequestBuilder::buildRequest();
307 request->setAttributeQuery(query);
308 request->setMinorVersion(version);
310 SAML1SOAPClient client(soaper, false);
311 client.sendSAML(request, application.getId(), mcc, loc.get());
312 response = client.receiveSAML();
314 catch (exception& ex) {
315 m_log.error("exception during SAML query to %s: %s", loc.get(), ex.what());
321 m_log.error("unable to obtain a SAML response from attribute authority");
324 else if (!response->getStatus() || !response->getStatus()->getStatusCode() || response->getStatus()->getStatusCode()->getValue()==nullptr ||
325 *(response->getStatus()->getStatusCode()->getValue()) != saml1p::StatusCode::SUCCESS) {
327 m_log.error("attribute authority returned a SAML error");
331 const vector<saml1::Assertion*>& assertions = const_cast<const saml1p::Response*>(response)->getAssertions();
332 if (assertions.empty()) {
334 m_log.warn("response from attribute authority was empty");
337 else if (assertions.size()>1)
338 m_log.warn("simple resolver only supports one assertion in the query response");
340 auto_ptr<saml1p::Response> wrapper(response);
341 saml1::Assertion* newtoken = assertions.front();
343 pair<bool,bool> signedAssertions = relyingParty->getBool("requireSignedAssertions");
344 if (!newtoken->getSignature() && signedAssertions.first && signedAssertions.second) {
345 m_log.error("assertion unsigned, rejecting it based on signedAssertions policy");
350 // We're going to insist that the assertion issuer is the same as the peer.
351 // Reset the policy's message bits and extract them from the assertion.
353 policy->setMessageID(newtoken->getAssertionID());
354 policy->setIssueInstant(newtoken->getIssueInstantEpoch());
355 policy->setIssuer(newtoken->getIssuer());
356 policy->evaluate(*newtoken);
358 // Now we can check the security status of the policy.
359 if (!policy->isAuthenticated())
360 throw SecurityPolicyException("Security of SAML 1.x query result not established.");
362 catch (exception& ex) {
363 m_log.error("assertion failed policy validation: %s", ex.what());
368 wrapper.release(); // detach blows away the Response
369 ctx.getResolvedAssertions().push_back(newtoken);
371 // Finally, extract and filter the result.
373 AttributeExtractor* extractor = application.getAttributeExtractor();
375 Locker extlocker(extractor);
376 const vector<saml1::AttributeStatement*>& statements = const_cast<const saml1::Assertion*>(newtoken)->getAttributeStatements();
377 for (vector<saml1::AttributeStatement*>::const_iterator s = statements.begin(); s!=statements.end(); ++s) {
378 if (m_subjectMatch) {
379 // Check for subject match.
380 const NameIdentifier* respName = (*s)->getSubject() ? (*s)->getSubject()->getNameIdentifier() : nullptr;
381 if (!respName || !XMLString::equals(respName->getName(), ctx.getNameID()->getName()) ||
382 !XMLString::equals(respName->getFormat(), ctx.getNameID()->getFormat()) ||
383 !XMLString::equals(respName->getNameQualifier(), ctx.getNameID()->getNameQualifier())) {
385 m_log.warnStream() << "ignoring AttributeStatement without strongly matching NameIdentifier in Subject: " <<
386 *respName << logging::eol;
388 m_log.warn("ignoring AttributeStatement without NameIdentifier in Subject");
392 extractor->extractAttributes(application, AA, *(*s), ctx.getResolvedAttributes());
396 AttributeFilter* filter = application.getAttributeFilter();
398 BasicFilteringContext fc(application, ctx.getResolvedAttributes(), AA, ctx.getClassRef(), ctx.getDeclRef());
399 Locker filtlocker(filter);
400 filter->filterAttributes(fc, ctx.getResolvedAttributes());
403 catch (exception& ex) {
404 m_log.error("caught exception extracting/filtering attributes from query result: %s", ex.what());
405 for_each(ctx.getResolvedAttributes().begin(), ctx.getResolvedAttributes().end(), xmltooling::cleanup<shibsp::Attribute>());
406 ctx.getResolvedAttributes().clear();
412 bool QueryResolver::SAML2Query(QueryContext& ctx) const
415 xmltooling::NDC ndc("query");
418 const AttributeAuthorityDescriptor* AA =
419 find_if(ctx.getEntityDescriptor()->getAttributeAuthorityDescriptors(), isValidForProtocol(samlconstants::SAML20P_NS));
421 m_log.warn("no SAML 2 AttributeAuthority role found in metadata");
425 const Application& application = ctx.getApplication();
426 const PropertySet* relyingParty = application.getRelyingParty(ctx.getEntityDescriptor());
427 pair<bool,bool> signedAssertions = relyingParty->getBool("requireSignedAssertions");
428 pair<bool,const char*> encryption = relyingParty->getString("encryption");
430 // Locate policy key.
431 const char* policyId = m_policyId.empty() ? application.getString("policyId").second : m_policyId.c_str();
433 // Set up policy and SOAP client.
434 auto_ptr<SecurityPolicy> policy(
435 application.getServiceProvider().getSecurityPolicyProvider()->createSecurityPolicy(application, nullptr, policyId)
437 policy->getAudiences().push_back(relyingParty->getXMLString("entityID").second);
438 MetadataCredentialCriteria mcc(*AA);
439 shibsp::SOAPClient soaper(*policy.get());
441 auto_ptr_XMLCh binding(samlconstants::SAML20_BINDING_SOAP);
442 saml2p::StatusResponseType* srt=nullptr;
443 const vector<AttributeService*>& endpoints=AA->getAttributeServices();
444 for (vector<AttributeService*>::const_iterator ep=endpoints.begin(); !srt && ep!=endpoints.end(); ++ep) {
445 if (!XMLString::equals((*ep)->getBinding(),binding.get()) || !(*ep)->getLocation())
447 auto_ptr_char loc((*ep)->getLocation());
449 auto_ptr<saml2::Subject> subject(saml2::SubjectBuilder::buildSubject());
451 // Encrypt the NameID?
452 if (encryption.first && (!strcmp(encryption.second, "true") || !strcmp(encryption.second, "back"))) {
453 auto_ptr<EncryptedID> encrypted(EncryptedIDBuilder::buildEncryptedID());
456 *(application.getMetadataProvider()),
459 relyingParty->getXMLString("encryptionAlg").second
461 subject->setEncryptedID(encrypted.release());
464 subject->setNameID(ctx.getNameID()->cloneNameID());
467 saml2p::AttributeQuery* query = saml2p::AttributeQueryBuilder::buildAttributeQuery();
468 query->setSubject(subject.release());
469 Issuer* iss = IssuerBuilder::buildIssuer();
470 iss->setName(relyingParty->getXMLString("entityID").second);
471 query->setIssuer(iss);
472 for (vector<saml2::Attribute*>::const_iterator ad = m_SAML2Designators.begin(); ad!=m_SAML2Designators.end(); ++ad)
473 query->getAttributes().push_back((*ad)->cloneAttribute());
475 SAML2SOAPClient client(soaper, false);
476 client.sendSAML(query, application.getId(), mcc, loc.get());
477 srt = client.receiveSAML();
479 catch (exception& ex) {
480 m_log.error("exception during SAML query to %s: %s", loc.get(), ex.what());
486 m_log.error("unable to obtain a SAML response from attribute authority");
490 auto_ptr<saml2p::StatusResponseType> wrapper(srt);
492 saml2p::Response* response = dynamic_cast<saml2p::Response*>(srt);
494 m_log.error("message was not a samlp:Response");
497 else if (!response->getStatus() || !response->getStatus()->getStatusCode() ||
498 !XMLString::equals(response->getStatus()->getStatusCode()->getValue(), saml2p::StatusCode::SUCCESS)) {
499 m_log.error("attribute authority returned a SAML error");
503 saml2::Assertion* newtoken = nullptr;
504 const vector<saml2::Assertion*>& assertions = const_cast<const saml2p::Response*>(response)->getAssertions();
505 if (assertions.empty()) {
506 // Check for encryption.
507 const vector<saml2::EncryptedAssertion*>& encassertions = const_cast<const saml2p::Response*>(response)->getEncryptedAssertions();
508 if (encassertions.empty()) {
509 m_log.warn("response from attribute authority was empty");
512 else if (encassertions.size() > 1) {
513 m_log.warn("simple resolver only supports one assertion in the query response");
516 CredentialResolver* cr=application.getCredentialResolver();
518 m_log.warn("found encrypted assertion, but no CredentialResolver was available");
522 // Attempt to decrypt it.
524 Locker credlocker(cr);
525 auto_ptr<XMLObject> tokenwrapper(encassertions.front()->decrypt(*cr, relyingParty->getXMLString("entityID").second, &mcc));
526 newtoken = dynamic_cast<saml2::Assertion*>(tokenwrapper.get());
528 tokenwrapper.release();
529 if (m_log.isDebugEnabled())
530 m_log.debugStream() << "decrypted Assertion: " << *newtoken << logging::eol;
533 catch (exception& ex) {
534 m_log.error(ex.what());
537 // Free the Response now, so we know this is a stand-alone token later.
538 delete wrapper.release();
541 // Nothing decrypted, should already be logged.
546 if (assertions.size() > 1)
547 m_log.warn("simple resolver only supports one assertion in the query response");
548 newtoken = assertions.front();
551 if (!newtoken->getSignature() && signedAssertions.first && signedAssertions.second) {
552 m_log.error("assertion unsigned, rejecting it based on signedAssertions policy");
559 // We're going to insist that the assertion issuer is the same as the peer.
560 // Reset the policy's message bits and extract them from the assertion.
562 policy->setMessageID(newtoken->getID());
563 policy->setIssueInstant(newtoken->getIssueInstantEpoch());
564 policy->setIssuer(newtoken->getIssuer());
565 policy->evaluate(*newtoken);
567 // Now we can check the security status of the policy.
568 if (!policy->isAuthenticated())
569 throw SecurityPolicyException("Security of SAML 2.0 query result not established.");
571 if (m_subjectMatch) {
572 // Check for subject match.
573 bool ownedName = false;
574 NameID* respName = newtoken->getSubject() ? newtoken->getSubject()->getNameID() : nullptr;
576 // Check for encryption.
577 EncryptedID* encname = newtoken->getSubject() ? newtoken->getSubject()->getEncryptedID() : nullptr;
579 CredentialResolver* cr=application.getCredentialResolver();
581 m_log.warn("found EncryptedID, but no CredentialResolver was available");
583 Locker credlocker(cr);
584 auto_ptr<XMLObject> decryptedID(encname->decrypt(*cr, relyingParty->getXMLString("entityID").second, &mcc));
585 respName = dynamic_cast<NameID*>(decryptedID.get());
588 decryptedID.release();
589 if (m_log.isDebugEnabled())
590 m_log.debugStream() << "decrypted NameID: " << *respName << logging::eol;
596 auto_ptr<NameID> nameIDwrapper(ownedName ? respName : nullptr);
598 if (!respName || !XMLString::equals(respName->getName(), ctx.getNameID()->getName()) ||
599 !XMLString::equals(respName->getFormat(), ctx.getNameID()->getFormat()) ||
600 !XMLString::equals(respName->getNameQualifier(), ctx.getNameID()->getNameQualifier()) ||
601 !XMLString::equals(respName->getSPNameQualifier(), ctx.getNameID()->getSPNameQualifier())) {
603 m_log.warnStream() << "ignoring Assertion without strongly matching NameID in Subject: " <<
604 *respName << logging::eol;
606 m_log.warn("ignoring Assertion without NameID in Subject");
613 catch (exception& ex) {
614 m_log.error("assertion failed policy validation: %s", ex.what());
622 wrapper.release(); // detach blows away the Response
624 ctx.getResolvedAssertions().push_back(newtoken);
626 // Finally, extract and filter the result.
628 AttributeExtractor* extractor = application.getAttributeExtractor();
630 Locker extlocker(extractor);
631 extractor->extractAttributes(application, AA, *newtoken, ctx.getResolvedAttributes());
634 AttributeFilter* filter = application.getAttributeFilter();
636 BasicFilteringContext fc(application, ctx.getResolvedAttributes(), AA, ctx.getClassRef(), ctx.getDeclRef());
637 Locker filtlocker(filter);
638 filter->filterAttributes(fc, ctx.getResolvedAttributes());
641 catch (exception& ex) {
642 m_log.error("caught exception extracting/filtering attributes from query result: %s", ex.what());
643 for_each(ctx.getResolvedAttributes().begin(), ctx.getResolvedAttributes().end(), xmltooling::cleanup<shibsp::Attribute>());
644 ctx.getResolvedAttributes().clear();
650 void QueryResolver::resolveAttributes(ResolutionContext& ctx) const
653 xmltooling::NDC ndc("resolveAttributes");
656 QueryContext& qctx = dynamic_cast<QueryContext&>(ctx);
657 if (!qctx.doQuery()) {
658 m_log.debug("found AttributeStatement in input to new session, skipping query");
662 if (qctx.getNameID() && qctx.getEntityDescriptor()) {
663 if (XMLString::equals(qctx.getProtocol(), samlconstants::SAML20P_NS)) {
664 m_log.debug("attempting SAML 2.0 attribute query");
667 else if (XMLString::equals(qctx.getProtocol(), samlconstants::SAML11_PROTOCOL_ENUM) ||
668 XMLString::equals(qctx.getProtocol(), samlconstants::SAML10_PROTOCOL_ENUM)) {
669 m_log.debug("attempting SAML 1.x attribute query");
673 m_log.info("SSO protocol does not allow for attribute query");
677 m_log.warn("can't attempt attribute query, either no NameID or no metadata to use");