https://bugs.internet2.edu/jira/browse/SSPCPP-293
[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) : m_log(Category::getInstance(SHIBSP_LOGCAT".AttributeResolver.Query")), m_subjectMatch(false)
224 {
225 #ifdef _DEBUG
226     xmltooling::NDC ndc("QueryResolver");
227 #endif
228
229     const XMLCh* pid = e ? e->getAttributeNS(nullptr, policyId) : nullptr;
230     if (pid && *pid) {
231         auto_ptr_char temp(pid);
232         m_policyId = temp.get();
233     }
234     pid = e ? e->getAttributeNS(nullptr, subjectMatch) : nullptr;
235     if (pid && (*pid == chLatin_t || *pid == chDigit_1))
236         m_subjectMatch = true;
237
238     DOMElement* child = XMLHelper::getFirstChildElement(e);
239     while (child) {
240         try {
241             if (XMLHelper::isNodeNamed(child, samlconstants::SAML20_NS, saml2::Attribute::LOCAL_NAME)) {
242                 auto_ptr<XMLObject> obj(saml2::AttributeBuilder::buildOneFromElement(child));
243                 saml2::Attribute* down = dynamic_cast<saml2::Attribute*>(obj.get());
244                 if (down) {
245                     m_SAML2Designators.push_back(down);
246                     obj.release();
247                 }
248             }
249             else if (XMLHelper::isNodeNamed(child, samlconstants::SAML1_NS, AttributeDesignator::LOCAL_NAME)) {
250                 auto_ptr<XMLObject> obj(AttributeDesignatorBuilder::buildOneFromElement(child));
251                 AttributeDesignator* down = dynamic_cast<AttributeDesignator*>(obj.get());
252                 if (down) {
253                     m_SAML1Designators.push_back(down);
254                     obj.release();
255                 }
256             }
257         }
258         catch (exception& ex) {
259             m_log.error("exception loading attribute designator: %s", ex.what());
260         }
261         child = XMLHelper::getNextSiblingElement(child);
262     }
263 }
264
265 bool QueryResolver::SAML1Query(QueryContext& ctx) const
266 {
267 #ifdef _DEBUG
268     xmltooling::NDC ndc("query");
269 #endif
270
271     int version = XMLString::equals(ctx.getProtocol(), samlconstants::SAML11_PROTOCOL_ENUM) ? 1 : 0;
272     const AttributeAuthorityDescriptor* AA =
273         find_if(ctx.getEntityDescriptor()->getAttributeAuthorityDescriptors(), isValidForProtocol(ctx.getProtocol()));
274     if (!AA) {
275         m_log.warn("no SAML 1.%d AttributeAuthority role found in metadata", version);
276         return false;
277     }
278
279     const Application& application = ctx.getApplication();
280     const PropertySet* relyingParty = application.getRelyingParty(ctx.getEntityDescriptor());
281
282     // Locate policy key.
283     const char* policyId = m_policyId.empty() ? application.getString("policyId").second : m_policyId.c_str();
284
285     // Set up policy and SOAP client.
286     auto_ptr<SecurityPolicy> policy(
287         application.getServiceProvider().getSecurityPolicyProvider()->createSecurityPolicy(application, nullptr, policyId)
288         );
289     policy->getAudiences().push_back(relyingParty->getXMLString("entityID").second);
290     MetadataCredentialCriteria mcc(*AA);
291     shibsp::SOAPClient soaper(*policy.get());
292
293     auto_ptr_XMLCh binding(samlconstants::SAML1_BINDING_SOAP);
294     saml1p::Response* response=nullptr;
295     const vector<AttributeService*>& endpoints=AA->getAttributeServices();
296     for (vector<AttributeService*>::const_iterator ep=endpoints.begin(); !response && ep!=endpoints.end(); ++ep) {
297         if (!XMLString::equals((*ep)->getBinding(),binding.get()) || !(*ep)->getLocation())
298             continue;
299         auto_ptr_char loc((*ep)->getLocation());
300         try {
301             NameIdentifier* nameid = NameIdentifierBuilder::buildNameIdentifier();
302             nameid->setName(ctx.getNameID()->getName());
303             nameid->setFormat(ctx.getNameID()->getFormat());
304             nameid->setNameQualifier(ctx.getNameID()->getNameQualifier());
305             saml1::Subject* subject = saml1::SubjectBuilder::buildSubject();
306             subject->setNameIdentifier(nameid);
307             saml1p::AttributeQuery* query = saml1p::AttributeQueryBuilder::buildAttributeQuery();
308             query->setSubject(subject);
309             query->setResource(relyingParty->getXMLString("entityID").second);
310             for (vector<AttributeDesignator*>::const_iterator ad = m_SAML1Designators.begin(); ad!=m_SAML1Designators.end(); ++ad)
311                 query->getAttributeDesignators().push_back((*ad)->cloneAttributeDesignator());
312             Request* request = RequestBuilder::buildRequest();
313             request->setAttributeQuery(query);
314             request->setMinorVersion(version);
315
316             SAML1SOAPClient client(soaper, false);
317             client.sendSAML(request, application.getId(), mcc, loc.get());
318             response = client.receiveSAML();
319         }
320         catch (exception& ex) {
321             m_log.error("exception during SAML query to %s: %s", loc.get(), ex.what());
322             soaper.reset();
323         }
324     }
325
326     if (!response) {
327         m_log.error("unable to obtain a SAML response from attribute authority");
328         return false;
329     }
330     else if (!response->getStatus() || !response->getStatus()->getStatusCode() || response->getStatus()->getStatusCode()->getValue()==nullptr ||
331             *(response->getStatus()->getStatusCode()->getValue()) != saml1p::StatusCode::SUCCESS) {
332         delete response;
333         m_log.error("attribute authority returned a SAML error");
334         return true;
335     }
336
337     const vector<saml1::Assertion*>& assertions = const_cast<const saml1p::Response*>(response)->getAssertions();
338     if (assertions.empty()) {
339         delete response;
340         m_log.warn("response from attribute authority was empty");
341         return true;
342     }
343     else if (assertions.size()>1)
344         m_log.warn("simple resolver only supports one assertion in the query response");
345
346     auto_ptr<saml1p::Response> wrapper(response);
347     saml1::Assertion* newtoken = assertions.front();
348
349     pair<bool,bool> signedAssertions = relyingParty->getBool("requireSignedAssertions");
350     if (!newtoken->getSignature() && signedAssertions.first && signedAssertions.second) {
351         m_log.error("assertion unsigned, rejecting it based on signedAssertions policy");
352         return true;
353     }
354
355     try {
356         // We're going to insist that the assertion issuer is the same as the peer.
357         // Reset the policy's message bits and extract them from the assertion.
358         policy->reset(true);
359         policy->setMessageID(newtoken->getAssertionID());
360         policy->setIssueInstant(newtoken->getIssueInstantEpoch());
361         policy->setIssuer(newtoken->getIssuer());
362         policy->evaluate(*newtoken);
363
364         // Now we can check the security status of the policy.
365         if (!policy->isAuthenticated())
366             throw SecurityPolicyException("Security of SAML 1.x query result not established.");
367     }
368     catch (exception& ex) {
369         m_log.error("assertion failed policy validation: %s", ex.what());
370         return true;
371     }
372
373     newtoken->detach();
374     wrapper.release();  // detach blows away the Response
375     ctx.getResolvedAssertions().push_back(newtoken);
376
377     // Finally, extract and filter the result.
378     try {
379         AttributeExtractor* extractor = application.getAttributeExtractor();
380         if (extractor) {
381             Locker extlocker(extractor);
382             const vector<saml1::AttributeStatement*>& statements = const_cast<const saml1::Assertion*>(newtoken)->getAttributeStatements();
383             for (vector<saml1::AttributeStatement*>::const_iterator s = statements.begin(); s!=statements.end(); ++s) {
384                 if (m_subjectMatch) {
385                     // Check for subject match.
386                     const NameIdentifier* respName = (*s)->getSubject() ? (*s)->getSubject()->getNameIdentifier() : nullptr;
387                     if (!respName || !XMLString::equals(respName->getName(), ctx.getNameID()->getName()) ||
388                         !XMLString::equals(respName->getFormat(), ctx.getNameID()->getFormat()) ||
389                         !XMLString::equals(respName->getNameQualifier(), ctx.getNameID()->getNameQualifier())) {
390                         if (respName)
391                             m_log.warnStream() << "ignoring AttributeStatement without strongly matching NameIdentifier in Subject: " <<
392                                 *respName << logging::eol;
393                         else
394                             m_log.warn("ignoring AttributeStatement without NameIdentifier in Subject");
395                         continue;
396                     }
397                 }
398                 extractor->extractAttributes(application, AA, *(*s), ctx.getResolvedAttributes());
399             }
400         }
401
402         AttributeFilter* filter = application.getAttributeFilter();
403         if (filter) {
404             BasicFilteringContext fc(application, ctx.getResolvedAttributes(), AA, ctx.getClassRef(), ctx.getDeclRef());
405             Locker filtlocker(filter);
406             filter->filterAttributes(fc, ctx.getResolvedAttributes());
407         }
408     }
409     catch (exception& ex) {
410         m_log.error("caught exception extracting/filtering attributes from query result: %s", ex.what());
411         for_each(ctx.getResolvedAttributes().begin(), ctx.getResolvedAttributes().end(), xmltooling::cleanup<shibsp::Attribute>());
412         ctx.getResolvedAttributes().clear();
413     }
414
415     return true;
416 }
417
418 bool QueryResolver::SAML2Query(QueryContext& ctx) const
419 {
420 #ifdef _DEBUG
421     xmltooling::NDC ndc("query");
422 #endif
423
424     const AttributeAuthorityDescriptor* AA =
425         find_if(ctx.getEntityDescriptor()->getAttributeAuthorityDescriptors(), isValidForProtocol(samlconstants::SAML20P_NS));
426     if (!AA) {
427         m_log.warn("no SAML 2 AttributeAuthority role found in metadata");
428         return false;
429     }
430
431     const Application& application = ctx.getApplication();
432     const PropertySet* relyingParty = application.getRelyingParty(ctx.getEntityDescriptor());
433     pair<bool,bool> signedAssertions = relyingParty->getBool("requireSignedAssertions");
434     pair<bool,const char*> encryption = relyingParty->getString("encryption");
435
436     // Locate policy key.
437     const char* policyId = m_policyId.empty() ? application.getString("policyId").second : m_policyId.c_str();
438
439     // Set up policy and SOAP client.
440     auto_ptr<SecurityPolicy> policy(
441         application.getServiceProvider().getSecurityPolicyProvider()->createSecurityPolicy(application, nullptr, policyId)
442         );
443     policy->getAudiences().push_back(relyingParty->getXMLString("entityID").second);
444     MetadataCredentialCriteria mcc(*AA);
445     shibsp::SOAPClient soaper(*policy.get());
446
447     auto_ptr_XMLCh binding(samlconstants::SAML20_BINDING_SOAP);
448     saml2p::StatusResponseType* srt=nullptr;
449     const vector<AttributeService*>& endpoints=AA->getAttributeServices();
450     for (vector<AttributeService*>::const_iterator ep=endpoints.begin(); !srt && ep!=endpoints.end(); ++ep) {
451         if (!XMLString::equals((*ep)->getBinding(),binding.get())  || !(*ep)->getLocation())
452             continue;
453         auto_ptr_char loc((*ep)->getLocation());
454         try {
455             auto_ptr<saml2::Subject> subject(saml2::SubjectBuilder::buildSubject());
456
457             // Encrypt the NameID?
458             if (encryption.first && (!strcmp(encryption.second, "true") || !strcmp(encryption.second, "back"))) {
459                 auto_ptr<EncryptedID> encrypted(EncryptedIDBuilder::buildEncryptedID());
460                 encrypted->encrypt(
461                     *ctx.getNameID(),
462                     *(application.getMetadataProvider()),
463                     mcc,
464                     false,
465                     relyingParty->getXMLString("encryptionAlg").second
466                     );
467                 subject->setEncryptedID(encrypted.release());
468             }
469             else {
470                 subject->setNameID(ctx.getNameID()->cloneNameID());
471             }
472
473             saml2p::AttributeQuery* query = saml2p::AttributeQueryBuilder::buildAttributeQuery();
474             query->setSubject(subject.release());
475             Issuer* iss = IssuerBuilder::buildIssuer();
476             iss->setName(relyingParty->getXMLString("entityID").second);
477             query->setIssuer(iss);
478             for (vector<saml2::Attribute*>::const_iterator ad = m_SAML2Designators.begin(); ad!=m_SAML2Designators.end(); ++ad)
479                 query->getAttributes().push_back((*ad)->cloneAttribute());
480
481             SAML2SOAPClient client(soaper, false);
482             client.sendSAML(query, application.getId(), mcc, loc.get());
483             srt = client.receiveSAML();
484         }
485         catch (exception& ex) {
486             m_log.error("exception during SAML query to %s: %s", loc.get(), ex.what());
487             soaper.reset();
488         }
489     }
490
491     if (!srt) {
492         m_log.error("unable to obtain a SAML response from attribute authority");
493         return false;
494     }
495
496     auto_ptr<saml2p::StatusResponseType> wrapper(srt);
497
498     saml2p::Response* response = dynamic_cast<saml2p::Response*>(srt);
499     if (!response) {
500         m_log.error("message was not a samlp:Response");
501         return true;
502     }
503     else if (!response->getStatus() || !response->getStatus()->getStatusCode() ||
504             !XMLString::equals(response->getStatus()->getStatusCode()->getValue(), saml2p::StatusCode::SUCCESS)) {
505         m_log.error("attribute authority returned a SAML error");
506         return true;
507     }
508
509     saml2::Assertion* newtoken = nullptr;
510     const vector<saml2::Assertion*>& assertions = const_cast<const saml2p::Response*>(response)->getAssertions();
511     if (assertions.empty()) {
512         // Check for encryption.
513         const vector<saml2::EncryptedAssertion*>& encassertions = const_cast<const saml2p::Response*>(response)->getEncryptedAssertions();
514         if (encassertions.empty()) {
515             m_log.warn("response from attribute authority was empty");
516             return true;
517         }
518         else if (encassertions.size() > 1) {
519             m_log.warn("simple resolver only supports one assertion in the query response");
520         }
521
522         CredentialResolver* cr=application.getCredentialResolver();
523         if (!cr) {
524             m_log.warn("found encrypted assertion, but no CredentialResolver was available");
525             return true;
526         }
527
528         // Attempt to decrypt it.
529         try {
530             Locker credlocker(cr);
531             auto_ptr<XMLObject> tokenwrapper(encassertions.front()->decrypt(*cr, relyingParty->getXMLString("entityID").second, &mcc));
532             newtoken = dynamic_cast<saml2::Assertion*>(tokenwrapper.get());
533             if (newtoken) {
534                 tokenwrapper.release();
535                 if (m_log.isDebugEnabled())
536                     m_log.debugStream() << "decrypted Assertion: " << *newtoken << logging::eol;
537             }
538         }
539         catch (exception& ex) {
540             m_log.error(ex.what());
541         }
542         if (newtoken) {
543             // Free the Response now, so we know this is a stand-alone token later.
544             delete wrapper.release();
545         }
546         else {
547             // Nothing decrypted, should already be logged.
548             return true;
549         }
550     }
551     else {
552         if (assertions.size() > 1)
553             m_log.warn("simple resolver only supports one assertion in the query response");
554         newtoken = assertions.front();
555     }
556
557     if (!newtoken->getSignature() && signedAssertions.first && signedAssertions.second) {
558         m_log.error("assertion unsigned, rejecting it based on signedAssertions policy");
559         if (!wrapper.get())
560             delete newtoken;
561         return true;
562     }
563
564     try {
565         // We're going to insist that the assertion issuer is the same as the peer.
566         // Reset the policy's message bits and extract them from the assertion.
567         policy->reset(true);
568         policy->setMessageID(newtoken->getID());
569         policy->setIssueInstant(newtoken->getIssueInstantEpoch());
570         policy->setIssuer(newtoken->getIssuer());
571         policy->evaluate(*newtoken);
572
573         // Now we can check the security status of the policy.
574         if (!policy->isAuthenticated())
575             throw SecurityPolicyException("Security of SAML 2.0 query result not established.");
576
577         if (m_subjectMatch) {
578             // Check for subject match.
579             bool ownedName = false;
580             NameID* respName = newtoken->getSubject() ? newtoken->getSubject()->getNameID() : nullptr;
581             if (!respName) {
582                 // Check for encryption.
583                 EncryptedID* encname = newtoken->getSubject() ? newtoken->getSubject()->getEncryptedID() : nullptr;
584                 if (encname) {
585                     CredentialResolver* cr=application.getCredentialResolver();
586                     if (!cr)
587                         m_log.warn("found EncryptedID, but no CredentialResolver was available");
588                     else {
589                         Locker credlocker(cr);
590                         auto_ptr<XMLObject> decryptedID(encname->decrypt(*cr, relyingParty->getXMLString("entityID").second, &mcc));
591                         respName = dynamic_cast<NameID*>(decryptedID.get());
592                         if (respName) {
593                             ownedName = true;
594                             decryptedID.release();
595                             if (m_log.isDebugEnabled())
596                                 m_log.debugStream() << "decrypted NameID: " << *respName << logging::eol;
597                         }
598                     }
599                 }
600             }
601
602             auto_ptr<NameID> nameIDwrapper(ownedName ? respName : nullptr);
603
604             if (!respName || !XMLString::equals(respName->getName(), ctx.getNameID()->getName()) ||
605                 !XMLString::equals(respName->getFormat(), ctx.getNameID()->getFormat()) ||
606                 !XMLString::equals(respName->getNameQualifier(), ctx.getNameID()->getNameQualifier()) ||
607                 !XMLString::equals(respName->getSPNameQualifier(), ctx.getNameID()->getSPNameQualifier())) {
608                 if (respName)
609                     m_log.warnStream() << "ignoring Assertion without strongly matching NameID in Subject: " <<
610                         *respName << logging::eol;
611                 else
612                     m_log.warn("ignoring Assertion without NameID in Subject");
613                 if (!wrapper.get())
614                     delete newtoken;
615                 return true;
616             }
617         }
618     }
619     catch (exception& ex) {
620         m_log.error("assertion failed policy validation: %s", ex.what());
621         if (!wrapper.get())
622             delete newtoken;
623         return true;
624     }
625
626     if (wrapper.get()) {
627         newtoken->detach();
628         wrapper.release();  // detach blows away the Response
629     }
630     ctx.getResolvedAssertions().push_back(newtoken);
631
632     // Finally, extract and filter the result.
633     try {
634         AttributeExtractor* extractor = application.getAttributeExtractor();
635         if (extractor) {
636             Locker extlocker(extractor);
637             extractor->extractAttributes(application, AA, *newtoken, ctx.getResolvedAttributes());
638         }
639
640         AttributeFilter* filter = application.getAttributeFilter();
641         if (filter) {
642             BasicFilteringContext fc(application, ctx.getResolvedAttributes(), AA, ctx.getClassRef(), ctx.getDeclRef());
643             Locker filtlocker(filter);
644             filter->filterAttributes(fc, ctx.getResolvedAttributes());
645         }
646     }
647     catch (exception& ex) {
648         m_log.error("caught exception extracting/filtering attributes from query result: %s", ex.what());
649         for_each(ctx.getResolvedAttributes().begin(), ctx.getResolvedAttributes().end(), xmltooling::cleanup<shibsp::Attribute>());
650         ctx.getResolvedAttributes().clear();
651     }
652
653     return true;
654 }
655
656 void QueryResolver::resolveAttributes(ResolutionContext& ctx) const
657 {
658 #ifdef _DEBUG
659     xmltooling::NDC ndc("resolveAttributes");
660 #endif
661
662     QueryContext& qctx = dynamic_cast<QueryContext&>(ctx);
663     if (!qctx.doQuery()) {
664         m_log.debug("found AttributeStatement in input to new session, skipping query");
665         return;
666     }
667
668     if (qctx.getNameID() && qctx.getEntityDescriptor()) {
669         if (XMLString::equals(qctx.getProtocol(), samlconstants::SAML20P_NS)) {
670             m_log.debug("attempting SAML 2.0 attribute query");
671             SAML2Query(qctx);
672         }
673         else if (XMLString::equals(qctx.getProtocol(), samlconstants::SAML11_PROTOCOL_ENUM) ||
674                 XMLString::equals(qctx.getProtocol(), samlconstants::SAML10_PROTOCOL_ENUM)) {
675             m_log.debug("attempting SAML 1.x attribute query");
676             SAML1Query(qctx);
677         }
678         else {
679             m_log.info("SSO protocol does not allow for attribute query");
680         }
681     }
682     else {
683         m_log.warn("can't attempt attribute query, either no NameID or no metadata to use");
684     }
685 }