f0800889ce0fc30cf398074212f06b5fe2cf9a23
[shibboleth/sp.git] / shibsp / attribute / resolver / impl / QueryAttributeResolver.cpp
1 /*
2  *  Copyright 2001-2009 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 "util/SPConstants.h"
37
38 #include <saml/exceptions.h>
39 #include <saml/saml1/binding/SAML1SOAPClient.h>
40 #include <saml/saml1/core/Assertions.h>
41 #include <saml/saml1/core/Protocols.h>
42 #include <saml/saml2/binding/SAML2SOAPClient.h>
43 #include <saml/saml2/core/Protocols.h>
44 #include <saml/saml2/metadata/Metadata.h>
45 #include <saml/saml2/metadata/MetadataCredentialCriteria.h>
46 #include <saml/saml2/metadata/MetadataProvider.h>
47 #include <xmltooling/util/NDC.h>
48 #include <xmltooling/util/XMLHelper.h>
49 #include <xercesc/util/XMLUniDefs.hpp>
50
51 using namespace shibsp;
52 using namespace opensaml::saml1;
53 using namespace opensaml::saml1p;
54 using namespace opensaml::saml2;
55 using namespace opensaml::saml2p;
56 using namespace opensaml::saml2md;
57 using namespace opensaml;
58 using namespace xmltooling;
59 using namespace std;
60
61 namespace shibsp {
62
63     class SHIBSP_DLLLOCAL QueryContext : public ResolutionContext
64     {
65     public:
66         QueryContext(const Application& application, const Session& session)
67                 : m_query(true), m_app(application), m_session(&session), m_metadata(NULL), m_entity(NULL), m_nameid(NULL) {
68             m_protocol = XMLString::transcode(session.getProtocol());
69             m_class = XMLString::transcode(session.getAuthnContextClassRef());
70             m_decl = XMLString::transcode(session.getAuthnContextDeclRef());
71         }
72
73         QueryContext(
74             const Application& application,
75             const EntityDescriptor* issuer,
76             const XMLCh* protocol,
77             const NameID* nameid=NULL,
78             const XMLCh* authncontext_class=NULL,
79             const XMLCh* authncontext_decl=NULL,
80             const vector<const opensaml::Assertion*>* tokens=NULL
81             ) : m_query(true), m_app(application), m_session(NULL), m_metadata(NULL), m_entity(issuer),
82                 m_protocol(protocol), m_nameid(nameid), m_class(authncontext_class), m_decl(authncontext_decl) {
83
84             if (tokens) {
85                 for (vector<const opensaml::Assertion*>::const_iterator t = tokens->begin(); t!=tokens->end(); ++t) {
86                     const saml2::Assertion* token2 = dynamic_cast<const saml2::Assertion*>(*t);
87                     if (token2 && !token2->getAttributeStatements().empty()) {
88                         m_query = false;
89                     }
90                     else {
91                         const saml1::Assertion* token1 = dynamic_cast<const saml1::Assertion*>(*t);
92                         if (token1 && !token1->getAttributeStatements().empty()) {
93                             m_query = false;
94                         }
95                     }
96                 }
97             }
98         }
99
100         ~QueryContext() {
101             if (m_session) {
102                 XMLString::release((XMLCh**)&m_protocol);
103                 XMLString::release((XMLCh**)&m_class);
104                 XMLString::release((XMLCh**)&m_decl);
105             }
106             if (m_metadata)
107                 m_metadata->unlock();
108             for_each(m_attributes.begin(), m_attributes.end(), xmltooling::cleanup<shibsp::Attribute>());
109             for_each(m_assertions.begin(), m_assertions.end(), xmltooling::cleanup<opensaml::Assertion>());
110         }
111
112         bool doQuery() const {
113             return m_query;
114         }
115
116         const Application& getApplication() const {
117             return m_app;
118         }
119         const EntityDescriptor* getEntityDescriptor() const {
120             if (m_entity)
121                 return m_entity;
122             if (m_session && m_session->getEntityID()) {
123                 m_metadata = m_app.getMetadataProvider(false);
124                 if (m_metadata) {
125                     m_metadata->lock();
126                     return m_entity = m_metadata->getEntityDescriptor(MetadataProviderCriteria(m_app, m_session->getEntityID())).first;
127                 }
128             }
129             return NULL;
130         }
131         const XMLCh* getProtocol() const {
132             return m_protocol;
133         }
134         const NameID* getNameID() const {
135             return m_session ? m_session->getNameID() : m_nameid;
136         }
137         const XMLCh* getClassRef() const {
138             return m_class;
139         }
140         const XMLCh* getDeclRef() const {
141             return m_decl;
142         }
143         const Session* getSession() const {
144             return m_session;
145         }
146         vector<shibsp::Attribute*>& getResolvedAttributes() {
147             return m_attributes;
148         }
149         vector<opensaml::Assertion*>& getResolvedAssertions() {
150             return m_assertions;
151         }
152
153     private:
154         bool m_query;
155         const Application& m_app;
156         const Session* m_session;
157         mutable MetadataProvider* m_metadata;
158         mutable const EntityDescriptor* m_entity;
159         const XMLCh* m_protocol;
160         const NameID* m_nameid;
161         const XMLCh* m_class;
162         const XMLCh* m_decl;
163         vector<shibsp::Attribute*> m_attributes;
164         vector<opensaml::Assertion*> m_assertions;
165     };
166
167     class SHIBSP_DLLLOCAL QueryResolver : public AttributeResolver
168     {
169     public:
170         QueryResolver(const DOMElement* e);
171         ~QueryResolver() {
172             for_each(m_SAML1Designators.begin(), m_SAML1Designators.end(), xmltooling::cleanup<AttributeDesignator>());
173             for_each(m_SAML2Designators.begin(), m_SAML2Designators.end(), xmltooling::cleanup<saml2::Attribute>());
174         }
175
176         Lockable* lock() {return this;}
177         void unlock() {}
178
179         ResolutionContext* createResolutionContext(
180             const Application& application,
181             const EntityDescriptor* issuer,
182             const XMLCh* protocol,
183             const NameID* nameid=NULL,
184             const XMLCh* authncontext_class=NULL,
185             const XMLCh* authncontext_decl=NULL,
186             const vector<const opensaml::Assertion*>* tokens=NULL,
187             const vector<shibsp::Attribute*>* attributes=NULL
188             ) const {
189             return new QueryContext(application,issuer,protocol,nameid,authncontext_class,authncontext_decl,tokens);
190         }
191
192         ResolutionContext* createResolutionContext(const Application& application, const Session& session) const {
193             return new QueryContext(application,session);
194         }
195
196         void resolveAttributes(ResolutionContext& ctx) const;
197
198         void getAttributeIds(vector<string>& attributes) const {
199             // Nothing to do, only the extractor would actually generate them.
200         }
201
202     private:
203         bool SAML1Query(QueryContext& ctx) const;
204         bool SAML2Query(QueryContext& ctx) const;
205
206         Category& m_log;
207         string m_policyId;
208         bool m_subjectMatch;
209         vector<AttributeDesignator*> m_SAML1Designators;
210         vector<saml2::Attribute*> m_SAML2Designators;
211     };
212
213     AttributeResolver* SHIBSP_DLLLOCAL QueryResolverFactory(const DOMElement* const & e)
214     {
215         return new QueryResolver(e);
216     }
217
218     static const XMLCh policyId[] =     UNICODE_LITERAL_8(p,o,l,i,c,y,I,d);
219     static const XMLCh subjectMatch[] = UNICODE_LITERAL_12(s,u,b,j,e,c,t,M,a,t,c,h);
220 };
221
222 QueryResolver::QueryResolver(const DOMElement* e) : m_log(Category::getInstance(SHIBSP_LOGCAT".AttributeResolver.Query")), m_subjectMatch(false)
223 {
224 #ifdef _DEBUG
225     xmltooling::NDC ndc("QueryResolver");
226 #endif
227
228     const XMLCh* pid = e ? e->getAttributeNS(NULL, policyId) : NULL;
229     if (pid && *pid) {
230         auto_ptr_char temp(pid);
231         m_policyId = temp.get();
232     }
233     pid = e ? e->getAttributeNS(NULL, subjectMatch) : NULL;
234     if (pid && (*pid == chLatin_t || *pid == chDigit_1))
235         m_subjectMatch = true;
236
237     DOMElement* child = XMLHelper::getFirstChildElement(e);
238     while (child) {
239         try {
240             if (XMLHelper::isNodeNamed(child, samlconstants::SAML20_NS, saml2::Attribute::LOCAL_NAME)) {
241                 auto_ptr<XMLObject> obj(saml2::AttributeBuilder::buildOneFromElement(child));
242                 saml2::Attribute* down = dynamic_cast<saml2::Attribute*>(obj.get());
243                 if (down) {
244                     m_SAML2Designators.push_back(down);
245                     obj.release();
246                 }
247             }
248             else if (XMLHelper::isNodeNamed(child, samlconstants::SAML1_NS, AttributeDesignator::LOCAL_NAME)) {
249                 auto_ptr<XMLObject> obj(AttributeDesignatorBuilder::buildOneFromElement(child));
250                 AttributeDesignator* down = dynamic_cast<AttributeDesignator*>(obj.get());
251                 if (down) {
252                     m_SAML1Designators.push_back(down);
253                     obj.release();
254                 }
255             }
256         }
257         catch (exception& ex) {
258             m_log.error("exception loading attribute designator: %s", ex.what());
259         }
260         child = XMLHelper::getNextSiblingElement(child);
261     }
262 }
263
264 bool QueryResolver::SAML1Query(QueryContext& ctx) const
265 {
266 #ifdef _DEBUG
267     xmltooling::NDC ndc("query");
268 #endif
269
270     int version = XMLString::equals(ctx.getProtocol(), samlconstants::SAML11_PROTOCOL_ENUM) ? 1 : 0;
271     const AttributeAuthorityDescriptor* AA =
272         find_if(ctx.getEntityDescriptor()->getAttributeAuthorityDescriptors(), isValidForProtocol(ctx.getProtocol()));
273     if (!AA) {
274         m_log.warn("no SAML 1.%d AttributeAuthority role found in metadata", version);
275         return false;
276     }
277
278     const Application& application = ctx.getApplication();
279     const PropertySet* relyingParty = application.getRelyingParty(ctx.getEntityDescriptor());
280
281     // Locate policy key.
282     const char* policyId = m_policyId.empty() ? application.getString("policyId").second : m_policyId.c_str();
283
284     // Access policy properties.
285     const PropertySet* settings = application.getServiceProvider().getPolicySettings(policyId);
286     pair<bool,bool> validate = settings->getBool("validate");
287
288     shibsp::SecurityPolicy policy(application, NULL, validate.first && validate.second, policyId);
289     policy.getAudiences().push_back(relyingParty->getXMLString("entityID").second);
290     MetadataCredentialCriteria mcc(*AA);
291     shibsp::SOAPClient soaper(policy);
292
293     auto_ptr_XMLCh binding(samlconstants::SAML1_BINDING_SOAP);
294     saml1p::Response* response=NULL;
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()==NULL ||
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() : NULL;
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
434     // Locate policy key.
435     const char* policyId = m_policyId.empty() ? application.getString("policyId").second : m_policyId.c_str();
436
437     // Access policy properties.
438     const PropertySet* settings = application.getServiceProvider().getPolicySettings(policyId);
439     pair<bool,bool> validate = settings->getBool("validate");
440
441     pair<bool,bool> signedAssertions = relyingParty->getBool("requireSignedAssertions");
442     pair<bool,const char*> encryption = relyingParty->getString("encryption");
443
444     shibsp::SecurityPolicy policy(application, NULL, validate.first && validate.second, policyId);
445     policy.getAudiences().push_back(relyingParty->getXMLString("entityID").second);
446     MetadataCredentialCriteria mcc(*AA);
447     shibsp::SOAPClient soaper(policy);
448
449     auto_ptr_XMLCh binding(samlconstants::SAML20_BINDING_SOAP);
450     saml2p::StatusResponseType* srt=NULL;
451     const vector<AttributeService*>& endpoints=AA->getAttributeServices();
452     for (vector<AttributeService*>::const_iterator ep=endpoints.begin(); !srt && ep!=endpoints.end(); ++ep) {
453         if (!XMLString::equals((*ep)->getBinding(),binding.get())  || !(*ep)->getLocation())
454             continue;
455         auto_ptr_char loc((*ep)->getLocation());
456         try {
457             auto_ptr<saml2::Subject> subject(saml2::SubjectBuilder::buildSubject());
458
459             // Encrypt the NameID?
460             if (encryption.first && (!strcmp(encryption.second, "true") || !strcmp(encryption.second, "back"))) {
461                 auto_ptr<EncryptedID> encrypted(EncryptedIDBuilder::buildEncryptedID());
462                 encrypted->encrypt(
463                     *ctx.getNameID(),
464                     *(application.getMetadataProvider()),
465                     mcc,
466                     false,
467                     relyingParty->getXMLString("encryptionAlg").second
468                     );
469                 subject->setEncryptedID(encrypted.release());
470             }
471             else {
472                 subject->setNameID(ctx.getNameID()->cloneNameID());
473             }
474
475             saml2p::AttributeQuery* query = saml2p::AttributeQueryBuilder::buildAttributeQuery();
476             query->setSubject(subject.release());
477             Issuer* iss = IssuerBuilder::buildIssuer();
478             iss->setName(relyingParty->getXMLString("entityID").second);
479             query->setIssuer(iss);
480             for (vector<saml2::Attribute*>::const_iterator ad = m_SAML2Designators.begin(); ad!=m_SAML2Designators.end(); ++ad)
481                 query->getAttributes().push_back((*ad)->cloneAttribute());
482
483             SAML2SOAPClient client(soaper, false);
484             client.sendSAML(query, application.getId(), mcc, loc.get());
485             srt = client.receiveSAML();
486         }
487         catch (exception& ex) {
488             m_log.error("exception during SAML query to %s: %s", loc.get(), ex.what());
489             soaper.reset();
490         }
491     }
492
493     if (!srt) {
494         m_log.error("unable to obtain a SAML response from attribute authority");
495         return false;
496     }
497
498     auto_ptr<saml2p::StatusResponseType> wrapper(srt);
499
500     saml2p::Response* response = dynamic_cast<saml2p::Response*>(srt);
501     if (!response) {
502         m_log.error("message was not a samlp:Response");
503         return true;
504     }
505     else if (!response->getStatus() || !response->getStatus()->getStatusCode() ||
506             !XMLString::equals(response->getStatus()->getStatusCode()->getValue(), saml2p::StatusCode::SUCCESS)) {
507         m_log.error("attribute authority returned a SAML error");
508         return true;
509     }
510
511     saml2::Assertion* newtoken = NULL;
512     const vector<saml2::Assertion*>& assertions = const_cast<const saml2p::Response*>(response)->getAssertions();
513     if (assertions.empty()) {
514         // Check for encryption.
515         const vector<saml2::EncryptedAssertion*>& encassertions = const_cast<const saml2p::Response*>(response)->getEncryptedAssertions();
516         if (encassertions.empty()) {
517             m_log.warn("response from attribute authority was empty");
518             return true;
519         }
520         else if (encassertions.size() > 1) {
521             m_log.warn("simple resolver only supports one assertion in the query response");
522         }
523
524         CredentialResolver* cr=application.getCredentialResolver();
525         if (!cr) {
526             m_log.warn("found encrypted assertion, but no CredentialResolver was available");
527             return true;
528         }
529
530         // Attempt to decrypt it.
531         try {
532             Locker credlocker(cr);
533             auto_ptr<XMLObject> tokenwrapper(encassertions.front()->decrypt(*cr, relyingParty->getXMLString("entityID").second, &mcc));
534             newtoken = dynamic_cast<saml2::Assertion*>(tokenwrapper.get());
535             if (newtoken) {
536                 tokenwrapper.release();
537                 if (m_log.isDebugEnabled())
538                     m_log.debugStream() << "decrypted Assertion: " << *newtoken << logging::eol;
539             }
540         }
541         catch (exception& ex) {
542             m_log.error(ex.what());
543         }
544         if (newtoken) {
545             // Free the Response now, so we know this is a stand-alone token later.
546             delete wrapper.release();
547         }
548         else {
549             // Nothing decrypted, should already be logged.
550             return true;
551         }
552     }
553     else {
554         if (assertions.size() > 1)
555             m_log.warn("simple resolver only supports one assertion in the query response");
556         newtoken = assertions.front();
557     }
558
559     if (!newtoken->getSignature() && signedAssertions.first && signedAssertions.second) {
560         m_log.error("assertion unsigned, rejecting it based on signedAssertions policy");
561         if (!wrapper.get())
562             delete newtoken;
563         return true;
564     }
565
566     try {
567         // We're going to insist that the assertion issuer is the same as the peer.
568         // Reset the policy's message bits and extract them from the assertion.
569         policy.reset(true);
570         policy.setMessageID(newtoken->getID());
571         policy.setIssueInstant(newtoken->getIssueInstantEpoch());
572         policy.setIssuer(newtoken->getIssuer());
573         policy.evaluate(*newtoken);
574
575         // Now we can check the security status of the policy.
576         if (!policy.isAuthenticated())
577             throw SecurityPolicyException("Security of SAML 2.0 query result not established.");
578
579         if (m_subjectMatch) {
580             // Check for subject match.
581             bool ownedName = false;
582             NameID* respName = newtoken->getSubject() ? newtoken->getSubject()->getNameID() : NULL;
583             if (!respName) {
584                 // Check for encryption.
585                 EncryptedID* encname = newtoken->getSubject() ? newtoken->getSubject()->getEncryptedID() : NULL;
586                 if (encname) {
587                     CredentialResolver* cr=application.getCredentialResolver();
588                     if (!cr)
589                         m_log.warn("found EncryptedID, but no CredentialResolver was available");
590                     else {
591                         Locker credlocker(cr);
592                         auto_ptr<XMLObject> decryptedID(encname->decrypt(*cr, relyingParty->getXMLString("entityID").second, &mcc));
593                         respName = dynamic_cast<NameID*>(decryptedID.get());
594                         if (respName) {
595                             ownedName = true;
596                             decryptedID.release();
597                             if (m_log.isDebugEnabled())
598                                 m_log.debugStream() << "decrypted NameID: " << *respName << logging::eol;
599                         }
600                     }
601                 }
602             }
603
604             auto_ptr<NameID> nameIDwrapper(ownedName ? respName : NULL);
605
606             if (!respName || !XMLString::equals(respName->getName(), ctx.getNameID()->getName()) ||
607                 !XMLString::equals(respName->getFormat(), ctx.getNameID()->getFormat()) ||
608                 !XMLString::equals(respName->getNameQualifier(), ctx.getNameID()->getNameQualifier()) ||
609                 !XMLString::equals(respName->getSPNameQualifier(), ctx.getNameID()->getSPNameQualifier())) {
610                 if (respName)
611                     m_log.warnStream() << "ignoring Assertion without strongly matching NameID in Subject: " <<
612                         *respName << logging::eol;
613                 else
614                     m_log.warn("ignoring Assertion without NameID in Subject");
615                 if (!wrapper.get())
616                     delete newtoken;
617                 return true;
618             }
619         }
620     }
621     catch (exception& ex) {
622         m_log.error("assertion failed policy validation: %s", ex.what());
623         if (!wrapper.get())
624             delete newtoken;
625         return true;
626     }
627
628     if (wrapper.get()) {
629         newtoken->detach();
630         wrapper.release();  // detach blows away the Response
631     }
632     ctx.getResolvedAssertions().push_back(newtoken);
633
634     // Finally, extract and filter the result.
635     try {
636         AttributeExtractor* extractor = application.getAttributeExtractor();
637         if (extractor) {
638             Locker extlocker(extractor);
639             extractor->extractAttributes(application, AA, *newtoken, ctx.getResolvedAttributes());
640         }
641
642         AttributeFilter* filter = application.getAttributeFilter();
643         if (filter) {
644             BasicFilteringContext fc(application, ctx.getResolvedAttributes(), AA, ctx.getClassRef(), ctx.getDeclRef());
645             Locker filtlocker(filter);
646             filter->filterAttributes(fc, ctx.getResolvedAttributes());
647         }
648     }
649     catch (exception& ex) {
650         m_log.error("caught exception extracting/filtering attributes from query result: %s", ex.what());
651         for_each(ctx.getResolvedAttributes().begin(), ctx.getResolvedAttributes().end(), xmltooling::cleanup<shibsp::Attribute>());
652         ctx.getResolvedAttributes().clear();
653     }
654
655     return true;
656 }
657
658 void QueryResolver::resolveAttributes(ResolutionContext& ctx) const
659 {
660 #ifdef _DEBUG
661     xmltooling::NDC ndc("resolveAttributes");
662 #endif
663
664     QueryContext& qctx = dynamic_cast<QueryContext&>(ctx);
665     if (!qctx.doQuery()) {
666         m_log.debug("found AttributeStatement in input to new session, skipping query");
667         return;
668     }
669
670     if (qctx.getNameID() && qctx.getEntityDescriptor()) {
671         if (XMLString::equals(qctx.getProtocol(), samlconstants::SAML20P_NS)) {
672             m_log.debug("attempting SAML 2.0 attribute query");
673             SAML2Query(qctx);
674         }
675         else if (XMLString::equals(qctx.getProtocol(), samlconstants::SAML11_PROTOCOL_ENUM) ||
676                 XMLString::equals(qctx.getProtocol(), samlconstants::SAML10_PROTOCOL_ENUM)) {
677             m_log.debug("attempting SAML 1.x attribute query");
678             SAML1Query(qctx);
679         }
680         else {
681             m_log.info("SSO protocol does not allow for attribute query");
682         }
683     }
684     else {
685         m_log.warn("can't attempt attribute query, either no NameID or no metadata to use");
686     }
687 }