Switch plugin ctors to shortcut methods, and default the Listener in config.
[shibboleth/sp.git] / shibsp / attribute / resolver / impl / QueryAttributeResolver.cpp
1 /*
2  *  Copyright 2001-2010 Internet2
3  *
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
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
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.
15  */
16
17 /**
18  * QueryAttributeResolver.cpp
19  *
20  * AttributeResolver based on SAML queries.
21  */
22
23 #include "internal.h"
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"
38
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>
51
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;
60 using namespace std;
61
62 namespace shibsp {
63
64     class SHIBSP_DLLLOCAL QueryContext : public ResolutionContext
65     {
66     public:
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());
72         }
73
74         QueryContext(
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) {
84
85             if (tokens) {
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()) {
89                         m_query = false;
90                     }
91                     else {
92                         const saml1::Assertion* token1 = dynamic_cast<const saml1::Assertion*>(*t);
93                         if (token1 && !token1->getAttributeStatements().empty()) {
94                             m_query = false;
95                         }
96                     }
97                 }
98             }
99         }
100
101         ~QueryContext() {
102             if (m_session) {
103                 XMLString::release((XMLCh**)&m_protocol);
104                 XMLString::release((XMLCh**)&m_class);
105                 XMLString::release((XMLCh**)&m_decl);
106             }
107             if (m_metadata)
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>());
111         }
112
113         bool doQuery() const {
114             return m_query;
115         }
116
117         const Application& getApplication() const {
118             return m_app;
119         }
120         const EntityDescriptor* getEntityDescriptor() const {
121             if (m_entity)
122                 return m_entity;
123             if (m_session && m_session->getEntityID()) {
124                 m_metadata = m_app.getMetadataProvider(false);
125                 if (m_metadata) {
126                     m_metadata->lock();
127                     return m_entity = m_metadata->getEntityDescriptor(MetadataProviderCriteria(m_app, m_session->getEntityID())).first;
128                 }
129             }
130             return nullptr;
131         }
132         const XMLCh* getProtocol() const {
133             return m_protocol;
134         }
135         const NameID* getNameID() const {
136             return m_session ? m_session->getNameID() : m_nameid;
137         }
138         const XMLCh* getClassRef() const {
139             return m_class;
140         }
141         const XMLCh* getDeclRef() const {
142             return m_decl;
143         }
144         const Session* getSession() const {
145             return m_session;
146         }
147         vector<shibsp::Attribute*>& getResolvedAttributes() {
148             return m_attributes;
149         }
150         vector<opensaml::Assertion*>& getResolvedAssertions() {
151             return m_assertions;
152         }
153
154     private:
155         bool m_query;
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;
163         const XMLCh* m_decl;
164         vector<shibsp::Attribute*> m_attributes;
165         vector<opensaml::Assertion*> m_assertions;
166     };
167
168     class SHIBSP_DLLLOCAL QueryResolver : public AttributeResolver
169     {
170     public:
171         QueryResolver(const DOMElement* e);
172         ~QueryResolver() {
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>());
175         }
176
177         Lockable* lock() {return this;}
178         void unlock() {}
179
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
189             ) const {
190             return new QueryContext(application,issuer,protocol,nameid,authncontext_class,authncontext_decl,tokens);
191         }
192
193         ResolutionContext* createResolutionContext(const Application& application, const Session& session) const {
194             return new QueryContext(application,session);
195         }
196
197         void resolveAttributes(ResolutionContext& ctx) const;
198
199         void getAttributeIds(vector<string>& attributes) const {
200             // Nothing to do, only the extractor would actually generate them.
201         }
202
203     private:
204         bool SAML1Query(QueryContext& ctx) const;
205         bool SAML2Query(QueryContext& ctx) const;
206
207         Category& m_log;
208         string m_policyId;
209         bool m_subjectMatch;
210         vector<AttributeDesignator*> m_SAML1Designators;
211         vector<saml2::Attribute*> m_SAML2Designators;
212     };
213
214     AttributeResolver* SHIBSP_DLLLOCAL QueryResolverFactory(const DOMElement* const & e)
215     {
216         return new QueryResolver(e);
217     }
218
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);
221 };
222
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))
227 {
228 #ifdef _DEBUG
229     xmltooling::NDC ndc("QueryResolver");
230 #endif
231
232     DOMElement* child = XMLHelper::getFirstChildElement(e);
233     while (child) {
234         try {
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());
238                 if (down) {
239                     m_SAML2Designators.push_back(down);
240                     obj.release();
241                 }
242             }
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());
246                 if (down) {
247                     m_SAML1Designators.push_back(down);
248                     obj.release();
249                 }
250             }
251         }
252         catch (exception& ex) {
253             m_log.error("exception loading attribute designator: %s", ex.what());
254         }
255         child = XMLHelper::getNextSiblingElement(child);
256     }
257 }
258
259 bool QueryResolver::SAML1Query(QueryContext& ctx) const
260 {
261 #ifdef _DEBUG
262     xmltooling::NDC ndc("query");
263 #endif
264
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()));
268     if (!AA) {
269         m_log.warn("no SAML 1.%d AttributeAuthority role found in metadata", version);
270         return false;
271     }
272
273     const Application& application = ctx.getApplication();
274     const PropertySet* relyingParty = application.getRelyingParty(ctx.getEntityDescriptor());
275
276     // Locate policy key.
277     const char* policyId = m_policyId.empty() ? application.getString("policyId").second : m_policyId.c_str();
278
279     // Set up policy and SOAP client.
280     auto_ptr<SecurityPolicy> policy(
281         application.getServiceProvider().getSecurityPolicyProvider()->createSecurityPolicy(application, nullptr, policyId)
282         );
283     policy->getAudiences().push_back(relyingParty->getXMLString("entityID").second);
284     MetadataCredentialCriteria mcc(*AA);
285     shibsp::SOAPClient soaper(*policy.get());
286
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())
292             continue;
293         auto_ptr_char loc((*ep)->getLocation());
294         try {
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);
309
310             SAML1SOAPClient client(soaper, false);
311             client.sendSAML(request, application.getId(), mcc, loc.get());
312             response = client.receiveSAML();
313         }
314         catch (exception& ex) {
315             m_log.error("exception during SAML query to %s: %s", loc.get(), ex.what());
316             soaper.reset();
317         }
318     }
319
320     if (!response) {
321         m_log.error("unable to obtain a SAML response from attribute authority");
322         return false;
323     }
324     else if (!response->getStatus() || !response->getStatus()->getStatusCode() || response->getStatus()->getStatusCode()->getValue()==nullptr ||
325             *(response->getStatus()->getStatusCode()->getValue()) != saml1p::StatusCode::SUCCESS) {
326         delete response;
327         m_log.error("attribute authority returned a SAML error");
328         return true;
329     }
330
331     const vector<saml1::Assertion*>& assertions = const_cast<const saml1p::Response*>(response)->getAssertions();
332     if (assertions.empty()) {
333         delete response;
334         m_log.warn("response from attribute authority was empty");
335         return true;
336     }
337     else if (assertions.size()>1)
338         m_log.warn("simple resolver only supports one assertion in the query response");
339
340     auto_ptr<saml1p::Response> wrapper(response);
341     saml1::Assertion* newtoken = assertions.front();
342
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");
346         return true;
347     }
348
349     try {
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.
352         policy->reset(true);
353         policy->setMessageID(newtoken->getAssertionID());
354         policy->setIssueInstant(newtoken->getIssueInstantEpoch());
355         policy->setIssuer(newtoken->getIssuer());
356         policy->evaluate(*newtoken);
357
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.");
361     }
362     catch (exception& ex) {
363         m_log.error("assertion failed policy validation: %s", ex.what());
364         return true;
365     }
366
367     newtoken->detach();
368     wrapper.release();  // detach blows away the Response
369     ctx.getResolvedAssertions().push_back(newtoken);
370
371     // Finally, extract and filter the result.
372     try {
373         AttributeExtractor* extractor = application.getAttributeExtractor();
374         if (extractor) {
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())) {
384                         if (respName)
385                             m_log.warnStream() << "ignoring AttributeStatement without strongly matching NameIdentifier in Subject: " <<
386                                 *respName << logging::eol;
387                         else
388                             m_log.warn("ignoring AttributeStatement without NameIdentifier in Subject");
389                         continue;
390                     }
391                 }
392                 extractor->extractAttributes(application, AA, *(*s), ctx.getResolvedAttributes());
393             }
394         }
395
396         AttributeFilter* filter = application.getAttributeFilter();
397         if (filter) {
398             BasicFilteringContext fc(application, ctx.getResolvedAttributes(), AA, ctx.getClassRef(), ctx.getDeclRef());
399             Locker filtlocker(filter);
400             filter->filterAttributes(fc, ctx.getResolvedAttributes());
401         }
402     }
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();
407     }
408
409     return true;
410 }
411
412 bool QueryResolver::SAML2Query(QueryContext& ctx) const
413 {
414 #ifdef _DEBUG
415     xmltooling::NDC ndc("query");
416 #endif
417
418     const AttributeAuthorityDescriptor* AA =
419         find_if(ctx.getEntityDescriptor()->getAttributeAuthorityDescriptors(), isValidForProtocol(samlconstants::SAML20P_NS));
420     if (!AA) {
421         m_log.warn("no SAML 2 AttributeAuthority role found in metadata");
422         return false;
423     }
424
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");
429
430     // Locate policy key.
431     const char* policyId = m_policyId.empty() ? application.getString("policyId").second : m_policyId.c_str();
432
433     // Set up policy and SOAP client.
434     auto_ptr<SecurityPolicy> policy(
435         application.getServiceProvider().getSecurityPolicyProvider()->createSecurityPolicy(application, nullptr, policyId)
436         );
437     policy->getAudiences().push_back(relyingParty->getXMLString("entityID").second);
438     MetadataCredentialCriteria mcc(*AA);
439     shibsp::SOAPClient soaper(*policy.get());
440
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())
446             continue;
447         auto_ptr_char loc((*ep)->getLocation());
448         try {
449             auto_ptr<saml2::Subject> subject(saml2::SubjectBuilder::buildSubject());
450
451             // Encrypt the NameID?
452             if (encryption.first && (!strcmp(encryption.second, "true") || !strcmp(encryption.second, "back"))) {
453                 auto_ptr<EncryptedID> encrypted(EncryptedIDBuilder::buildEncryptedID());
454                 encrypted->encrypt(
455                     *ctx.getNameID(),
456                     *(application.getMetadataProvider()),
457                     mcc,
458                     false,
459                     relyingParty->getXMLString("encryptionAlg").second
460                     );
461                 subject->setEncryptedID(encrypted.release());
462             }
463             else {
464                 subject->setNameID(ctx.getNameID()->cloneNameID());
465             }
466
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());
474
475             SAML2SOAPClient client(soaper, false);
476             client.sendSAML(query, application.getId(), mcc, loc.get());
477             srt = client.receiveSAML();
478         }
479         catch (exception& ex) {
480             m_log.error("exception during SAML query to %s: %s", loc.get(), ex.what());
481             soaper.reset();
482         }
483     }
484
485     if (!srt) {
486         m_log.error("unable to obtain a SAML response from attribute authority");
487         return false;
488     }
489
490     auto_ptr<saml2p::StatusResponseType> wrapper(srt);
491
492     saml2p::Response* response = dynamic_cast<saml2p::Response*>(srt);
493     if (!response) {
494         m_log.error("message was not a samlp:Response");
495         return true;
496     }
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");
500         return true;
501     }
502
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");
510             return true;
511         }
512         else if (encassertions.size() > 1) {
513             m_log.warn("simple resolver only supports one assertion in the query response");
514         }
515
516         CredentialResolver* cr=application.getCredentialResolver();
517         if (!cr) {
518             m_log.warn("found encrypted assertion, but no CredentialResolver was available");
519             return true;
520         }
521
522         // Attempt to decrypt it.
523         try {
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());
527             if (newtoken) {
528                 tokenwrapper.release();
529                 if (m_log.isDebugEnabled())
530                     m_log.debugStream() << "decrypted Assertion: " << *newtoken << logging::eol;
531             }
532         }
533         catch (exception& ex) {
534             m_log.error(ex.what());
535         }
536         if (newtoken) {
537             // Free the Response now, so we know this is a stand-alone token later.
538             delete wrapper.release();
539         }
540         else {
541             // Nothing decrypted, should already be logged.
542             return true;
543         }
544     }
545     else {
546         if (assertions.size() > 1)
547             m_log.warn("simple resolver only supports one assertion in the query response");
548         newtoken = assertions.front();
549     }
550
551     if (!newtoken->getSignature() && signedAssertions.first && signedAssertions.second) {
552         m_log.error("assertion unsigned, rejecting it based on signedAssertions policy");
553         if (!wrapper.get())
554             delete newtoken;
555         return true;
556     }
557
558     try {
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.
561         policy->reset(true);
562         policy->setMessageID(newtoken->getID());
563         policy->setIssueInstant(newtoken->getIssueInstantEpoch());
564         policy->setIssuer(newtoken->getIssuer());
565         policy->evaluate(*newtoken);
566
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.");
570
571         if (m_subjectMatch) {
572             // Check for subject match.
573             bool ownedName = false;
574             NameID* respName = newtoken->getSubject() ? newtoken->getSubject()->getNameID() : nullptr;
575             if (!respName) {
576                 // Check for encryption.
577                 EncryptedID* encname = newtoken->getSubject() ? newtoken->getSubject()->getEncryptedID() : nullptr;
578                 if (encname) {
579                     CredentialResolver* cr=application.getCredentialResolver();
580                     if (!cr)
581                         m_log.warn("found EncryptedID, but no CredentialResolver was available");
582                     else {
583                         Locker credlocker(cr);
584                         auto_ptr<XMLObject> decryptedID(encname->decrypt(*cr, relyingParty->getXMLString("entityID").second, &mcc));
585                         respName = dynamic_cast<NameID*>(decryptedID.get());
586                         if (respName) {
587                             ownedName = true;
588                             decryptedID.release();
589                             if (m_log.isDebugEnabled())
590                                 m_log.debugStream() << "decrypted NameID: " << *respName << logging::eol;
591                         }
592                     }
593                 }
594             }
595
596             auto_ptr<NameID> nameIDwrapper(ownedName ? respName : nullptr);
597
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())) {
602                 if (respName)
603                     m_log.warnStream() << "ignoring Assertion without strongly matching NameID in Subject: " <<
604                         *respName << logging::eol;
605                 else
606                     m_log.warn("ignoring Assertion without NameID in Subject");
607                 if (!wrapper.get())
608                     delete newtoken;
609                 return true;
610             }
611         }
612     }
613     catch (exception& ex) {
614         m_log.error("assertion failed policy validation: %s", ex.what());
615         if (!wrapper.get())
616             delete newtoken;
617         return true;
618     }
619
620     if (wrapper.get()) {
621         newtoken->detach();
622         wrapper.release();  // detach blows away the Response
623     }
624     ctx.getResolvedAssertions().push_back(newtoken);
625
626     // Finally, extract and filter the result.
627     try {
628         AttributeExtractor* extractor = application.getAttributeExtractor();
629         if (extractor) {
630             Locker extlocker(extractor);
631             extractor->extractAttributes(application, AA, *newtoken, ctx.getResolvedAttributes());
632         }
633
634         AttributeFilter* filter = application.getAttributeFilter();
635         if (filter) {
636             BasicFilteringContext fc(application, ctx.getResolvedAttributes(), AA, ctx.getClassRef(), ctx.getDeclRef());
637             Locker filtlocker(filter);
638             filter->filterAttributes(fc, ctx.getResolvedAttributes());
639         }
640     }
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();
645     }
646
647     return true;
648 }
649
650 void QueryResolver::resolveAttributes(ResolutionContext& ctx) const
651 {
652 #ifdef _DEBUG
653     xmltooling::NDC ndc("resolveAttributes");
654 #endif
655
656     QueryContext& qctx = dynamic_cast<QueryContext&>(ctx);
657     if (!qctx.doQuery()) {
658         m_log.debug("found AttributeStatement in input to new session, skipping query");
659         return;
660     }
661
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");
665             SAML2Query(qctx);
666         }
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");
670             SAML1Query(qctx);
671         }
672         else {
673             m_log.info("SSO protocol does not allow for attribute query");
674         }
675     }
676     else {
677         m_log.warn("can't attempt attribute query, either no NameID or no metadata to use");
678     }
679 }