Boost changes
[shibboleth/cpp-sp.git] / shibsp / attribute / resolver / impl / QueryAttributeResolver.cpp
1 /**
2  * Licensed to the University Corporation for Advanced Internet
3  * Development, Inc. (UCAID) under one or more contributor license
4  * agreements. See the NOTICE file distributed with this work for
5  * additional information regarding copyright ownership.
6  *
7  * UCAID licenses this file to you under the Apache License,
8  * Version 2.0 (the "License"); you may not use this file except
9  * in compliance with the License. You may obtain a copy of the
10  * License at
11  *
12  * http://www.apache.org/licenses/LICENSE-2.0
13  *
14  * Unless required by applicable law or agreed to in writing,
15  * software distributed under the License is distributed on an
16  * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
17  * either express or implied. See the License for the specific
18  * language governing permissions and limitations under the License.
19  */
20
21 /**
22  * QueryAttributeResolver.cpp
23  *
24  * AttributeResolver based on SAML queries.
25  */
26
27 #include "internal.h"
28 #include "Application.h"
29 #include "ServiceProvider.h"
30 #include "SessionCache.h"
31 #include "attribute/SimpleAttribute.h"
32 #include "attribute/filtering/AttributeFilter.h"
33 #include "attribute/filtering/BasicFilteringContext.h"
34 #include "attribute/resolver/AttributeExtractor.h"
35 #include "attribute/resolver/AttributeResolver.h"
36 #include "attribute/resolver/ResolutionContext.h"
37 #include "binding/SOAPClient.h"
38 #include "metadata/MetadataProviderCriteria.h"
39 #include "security/SecurityPolicy.h"
40 #include "security/SecurityPolicyProvider.h"
41 #include "util/SPConstants.h"
42
43 #include <boost/scoped_ptr.hpp>
44 #include <boost/iterator/indirect_iterator.hpp>
45 #include <boost/ptr_container/ptr_vector.hpp>
46 #include <saml/exceptions.h>
47 #include <saml/saml1/binding/SAML1SOAPClient.h>
48 #include <saml/saml1/core/Assertions.h>
49 #include <saml/saml1/core/Protocols.h>
50 #include <saml/saml2/binding/SAML2SOAPClient.h>
51 #include <saml/saml2/core/Protocols.h>
52 #include <saml/saml2/metadata/Metadata.h>
53 #include <saml/saml2/metadata/MetadataCredentialCriteria.h>
54 #include <saml/saml2/metadata/MetadataProvider.h>
55 #include <xmltooling/XMLToolingConfig.h>
56 #include <xmltooling/util/NDC.h>
57 #include <xmltooling/util/URLEncoder.h>
58 #include <xmltooling/util/XMLHelper.h>
59 #include <xercesc/util/XMLUniDefs.hpp>
60
61 using namespace shibsp;
62 using namespace opensaml::saml1;
63 using namespace opensaml::saml1p;
64 using namespace opensaml::saml2;
65 using namespace opensaml::saml2p;
66 using namespace opensaml::saml2md;
67 using namespace opensaml;
68 using namespace xmltooling;
69 using namespace boost;
70 using namespace std;
71
72 namespace shibsp {
73
74     class SHIBSP_DLLLOCAL QueryContext : public ResolutionContext
75     {
76     public:
77         QueryContext(const Application& application, const Session& session)
78                 : m_query(true), m_app(application), m_session(&session), m_metadata(nullptr), m_entity(nullptr), m_nameid(nullptr) {
79             m_protocol = XMLString::transcode(session.getProtocol());
80             m_class = XMLString::transcode(session.getAuthnContextClassRef());
81             m_decl = XMLString::transcode(session.getAuthnContextDeclRef());
82         }
83
84         QueryContext(
85             const Application& application,
86             const EntityDescriptor* issuer,
87             const XMLCh* protocol,
88             const NameID* nameid=nullptr,
89             const XMLCh* authncontext_class=nullptr,
90             const XMLCh* authncontext_decl=nullptr,
91             const vector<const opensaml::Assertion*>* tokens=nullptr
92             ) : m_query(true), m_app(application), m_session(nullptr), m_metadata(nullptr), m_entity(issuer),
93                 m_protocol(protocol), m_nameid(nameid), m_class(authncontext_class), m_decl(authncontext_decl) {
94
95             if (tokens) {
96                 for (vector<const opensaml::Assertion*>::const_iterator t = tokens->begin(); t!=tokens->end(); ++t) {
97                     const saml2::Assertion* token2 = dynamic_cast<const saml2::Assertion*>(*t);
98                     if (token2 && !token2->getAttributeStatements().empty()) {
99                         m_query = false;
100                     }
101                     else {
102                         const saml1::Assertion* token1 = dynamic_cast<const saml1::Assertion*>(*t);
103                         if (token1 && !token1->getAttributeStatements().empty()) {
104                             m_query = false;
105                         }
106                     }
107                 }
108             }
109         }
110
111         ~QueryContext() {
112             if (m_session) {
113                 XMLString::release((XMLCh**)&m_protocol);
114                 XMLString::release((XMLCh**)&m_class);
115                 XMLString::release((XMLCh**)&m_decl);
116             }
117             if (m_metadata)
118                 m_metadata->unlock();
119             for_each(m_attributes.begin(), m_attributes.end(), xmltooling::cleanup<shibsp::Attribute>());
120             for_each(m_assertions.begin(), m_assertions.end(), xmltooling::cleanup<opensaml::Assertion>());
121         }
122
123         bool doQuery() const {
124             return m_query;
125         }
126
127         const Application& getApplication() const {
128             return m_app;
129         }
130         const EntityDescriptor* getEntityDescriptor() const {
131             if (m_entity)
132                 return m_entity;
133             if (m_session && m_session->getEntityID()) {
134                 m_metadata = m_app.getMetadataProvider(false);
135                 if (m_metadata) {
136                     m_metadata->lock();
137                     return m_entity = m_metadata->getEntityDescriptor(MetadataProviderCriteria(m_app, m_session->getEntityID())).first;
138                 }
139             }
140             return nullptr;
141         }
142         const XMLCh* getProtocol() const {
143             return m_protocol;
144         }
145         const NameID* getNameID() const {
146             return m_session ? m_session->getNameID() : m_nameid;
147         }
148         const XMLCh* getClassRef() const {
149             return m_class;
150         }
151         const XMLCh* getDeclRef() const {
152             return m_decl;
153         }
154         const Session* getSession() const {
155             return m_session;
156         }
157         vector<shibsp::Attribute*>& getResolvedAttributes() {
158             return m_attributes;
159         }
160         vector<opensaml::Assertion*>& getResolvedAssertions() {
161             return m_assertions;
162         }
163
164     private:
165         bool m_query;
166         const Application& m_app;
167         const Session* m_session;
168         mutable MetadataProvider* m_metadata;
169         mutable const EntityDescriptor* m_entity;
170         const XMLCh* m_protocol;
171         const NameID* m_nameid;
172         const XMLCh* m_class;
173         const XMLCh* m_decl;
174         vector<shibsp::Attribute*> m_attributes;
175         vector<opensaml::Assertion*> m_assertions;
176     };
177
178     class SHIBSP_DLLLOCAL QueryResolver : public AttributeResolver
179     {
180     public:
181         QueryResolver(const DOMElement* e);
182         ~QueryResolver() {}
183
184         Lockable* lock() {return this;}
185         void unlock() {}
186
187         ResolutionContext* createResolutionContext(
188             const Application& application,
189             const EntityDescriptor* issuer,
190             const XMLCh* protocol,
191             const NameID* nameid=nullptr,
192             const XMLCh* authncontext_class=nullptr,
193             const XMLCh* authncontext_decl=nullptr,
194             const vector<const opensaml::Assertion*>* tokens=nullptr,
195             const vector<shibsp::Attribute*>* attributes=nullptr
196             ) const {
197             return new QueryContext(application,issuer,protocol,nameid,authncontext_class,authncontext_decl,tokens);
198         }
199
200         ResolutionContext* createResolutionContext(const Application& application, const Session& session) const {
201             return new QueryContext(application,session);
202         }
203
204         void resolveAttributes(ResolutionContext& ctx) const;
205
206         void getAttributeIds(vector<string>& attributes) const {
207             // Nothing to do, only the extractor would actually generate them.
208         }
209
210     private:
211         void SAML1Query(QueryContext& ctx) const;
212         void SAML2Query(QueryContext& ctx) const;
213
214         Category& m_log;
215         string m_policyId;
216         bool m_subjectMatch;
217         ptr_vector<AttributeDesignator> m_SAML1Designators;
218         ptr_vector<saml2::Attribute> m_SAML2Designators;
219         vector<string> m_exceptionId;
220     };
221
222     AttributeResolver* SHIBSP_DLLLOCAL QueryResolverFactory(const DOMElement* const & e)
223     {
224         return new QueryResolver(e);
225     }
226
227     static const XMLCh exceptionId[] =  UNICODE_LITERAL_11(e,x,c,e,p,t,i,o,n,I,d);
228     static const XMLCh policyId[] =     UNICODE_LITERAL_8(p,o,l,i,c,y,I,d);
229     static const XMLCh subjectMatch[] = UNICODE_LITERAL_12(s,u,b,j,e,c,t,M,a,t,c,h);
230 };
231
232 QueryResolver::QueryResolver(const DOMElement* e)
233     : m_log(Category::getInstance(SHIBSP_LOGCAT".AttributeResolver.Query")),
234         m_policyId(XMLHelper::getAttrString(e, nullptr, policyId)),
235         m_subjectMatch(XMLHelper::getAttrBool(e, false, subjectMatch))
236 {
237 #ifdef _DEBUG
238     xmltooling::NDC ndc("QueryResolver");
239 #endif
240
241     DOMElement* child = XMLHelper::getFirstChildElement(e);
242     while (child) {
243         try {
244             if (XMLHelper::isNodeNamed(child, samlconstants::SAML20_NS, saml2::Attribute::LOCAL_NAME)) {
245                 auto_ptr<XMLObject> obj(saml2::AttributeBuilder::buildOneFromElement(child));
246                 saml2::Attribute* down = dynamic_cast<saml2::Attribute*>(obj.get());
247                 if (down) {
248                     m_SAML2Designators.push_back(down);
249                     obj.release();
250                 }
251             }
252             else if (XMLHelper::isNodeNamed(child, samlconstants::SAML1_NS, AttributeDesignator::LOCAL_NAME)) {
253                 auto_ptr<XMLObject> obj(AttributeDesignatorBuilder::buildOneFromElement(child));
254                 AttributeDesignator* down = dynamic_cast<AttributeDesignator*>(obj.get());
255                 if (down) {
256                     m_SAML1Designators.push_back(down);
257                     obj.release();
258                 }
259             }
260         }
261         catch (exception& ex) {
262             m_log.error("exception loading attribute designator: %s", ex.what());
263         }
264         child = XMLHelper::getNextSiblingElement(child);
265     }
266
267     string exid(XMLHelper::getAttrString(e, nullptr, exceptionId));
268     if (!exid.empty())
269         m_exceptionId.push_back(exid);
270 }
271
272 void QueryResolver::SAML1Query(QueryContext& ctx) const
273 {
274 #ifdef _DEBUG
275     xmltooling::NDC ndc("query");
276 #endif
277
278     int version = XMLString::equals(ctx.getProtocol(), samlconstants::SAML11_PROTOCOL_ENUM) ? 1 : 0;
279     const AttributeAuthorityDescriptor* AA =
280         find_if(ctx.getEntityDescriptor()->getAttributeAuthorityDescriptors(), isValidForProtocol(ctx.getProtocol()));
281     if (!AA) {
282         m_log.warn("no SAML 1.%d AttributeAuthority role found in metadata", version);
283         return;
284     }
285
286     const Application& application = ctx.getApplication();
287     const PropertySet* relyingParty = application.getRelyingParty(ctx.getEntityDescriptor());
288
289     // Locate policy key.
290     const char* policyId = m_policyId.empty() ? application.getString("policyId").second : m_policyId.c_str();
291
292     // Set up policy and SOAP client.
293     scoped_ptr<SecurityPolicy> policy(
294         application.getServiceProvider().getSecurityPolicyProvider()->createSecurityPolicy(application, nullptr, policyId)
295         );
296     policy->getAudiences().push_back(relyingParty->getXMLString("entityID").second);
297     MetadataCredentialCriteria mcc(*AA);
298     shibsp::SOAPClient soaper(*policy);
299
300     auto_ptr_XMLCh binding(samlconstants::SAML1_BINDING_SOAP);
301     auto_ptr<saml1p::Response> response;
302     const vector<AttributeService*>& endpoints=AA->getAttributeServices();
303     for (indirect_iterator<vector<AttributeService*>::const_iterator> ep = make_indirect_iterator(endpoints.begin());
304             !response.get() && ep != make_indirect_iterator(endpoints.end()); ++ep) {
305         if (!XMLString::equals(ep->getBinding(), binding.get()) || !ep->getLocation())
306             continue;
307         auto_ptr_char loc(ep->getLocation());
308         try {
309             NameIdentifier* nameid = NameIdentifierBuilder::buildNameIdentifier();
310             nameid->setName(ctx.getNameID()->getName());
311             nameid->setFormat(ctx.getNameID()->getFormat());
312             nameid->setNameQualifier(ctx.getNameID()->getNameQualifier());
313             saml1::Subject* subject = saml1::SubjectBuilder::buildSubject();
314             subject->setNameIdentifier(nameid);
315             saml1p::AttributeQuery* query = saml1p::AttributeQueryBuilder::buildAttributeQuery();
316             query->setSubject(subject);
317             query->setResource(relyingParty->getXMLString("entityID").second);
318             for (ptr_vector<AttributeDesignator>::const_iterator ad = m_SAML1Designators.begin(); ad != m_SAML1Designators.end(); ++ad) {
319                 auto_ptr<AttributeDesignator> adwrapper(ad->cloneAttributeDesignator());
320                 query->getAttributeDesignators().push_back(adwrapper.get());
321                 adwrapper.release();
322             }
323             Request* request = RequestBuilder::buildRequest();
324             request->setAttributeQuery(query);
325             request->setMinorVersion(version);
326
327             SAML1SOAPClient client(soaper, false);
328             client.sendSAML(request, application.getId(), mcc, loc.get());
329             response.reset(client.receiveSAML());
330         }
331         catch (exception& ex) {
332             m_log.error("exception during SAML query to %s: %s", loc.get(), ex.what());
333             soaper.reset();
334         }
335     }
336
337     if (!response.get()) {
338         m_log.error("unable to obtain a SAML response from attribute authority");
339         throw BindingException("Unable to obtain a SAML response from attribute authority.");
340     }
341     else if (!response->getStatus() || !response->getStatus()->getStatusCode() || response->getStatus()->getStatusCode()->getValue()==nullptr ||
342             *(response->getStatus()->getStatusCode()->getValue()) != saml1p::StatusCode::SUCCESS) {
343         m_log.error("attribute authority returned a SAML error");
344         throw FatalProfileException("Attribute authority returned a SAML error.");
345     }
346
347     const vector<saml1::Assertion*>& assertions = const_cast<const saml1p::Response*>(response.get())->getAssertions();
348     if (assertions.empty()) {
349         m_log.warn("response from attribute authority was empty");
350         return;
351     }
352     else if (assertions.size() > 1) {
353         m_log.warn("simple resolver only supports one assertion in the query response");
354     }
355
356     saml1::Assertion* newtoken = assertions.front();
357
358     pair<bool,bool> signedAssertions = relyingParty->getBool("requireSignedAssertions");
359     if (!newtoken->getSignature() && signedAssertions.first && signedAssertions.second) {
360         m_log.error("assertion unsigned, rejecting it based on signedAssertions policy");
361         throw SecurityPolicyException("Rejected unsigned assertion based on local policy.");
362     }
363
364     try {
365         // We're going to insist that the assertion issuer is the same as the peer.
366         // Reset the policy's message bits and extract them from the assertion.
367         policy->reset(true);
368         policy->setMessageID(newtoken->getAssertionID());
369         policy->setIssueInstant(newtoken->getIssueInstantEpoch());
370         policy->setIssuer(newtoken->getIssuer());
371         policy->evaluate(*newtoken);
372
373         // Now we can check the security status of the policy.
374         if (!policy->isAuthenticated())
375             throw SecurityPolicyException("Security of SAML 1.x query result not established.");
376     }
377     catch (exception& ex) {
378         m_log.error("assertion failed policy validation: %s", ex.what());
379         throw;
380     }
381
382     newtoken->detach();
383     response.release();  // detach blows away the Response
384     ctx.getResolvedAssertions().push_back(newtoken);
385
386     // Finally, extract and filter the result.
387     try {
388         AttributeExtractor* extractor = application.getAttributeExtractor();
389         if (extractor) {
390             Locker extlocker(extractor);
391             const vector<saml1::AttributeStatement*>& statements = const_cast<const saml1::Assertion*>(newtoken)->getAttributeStatements();
392             for (indirect_iterator<vector<saml1::AttributeStatement*>::const_iterator> s = make_indirect_iterator(statements.begin());
393                     s != make_indirect_iterator(statements.end()); ++s) {
394                 if (m_subjectMatch) {
395                     // Check for subject match.
396                     const NameIdentifier* respName = s->getSubject() ? s->getSubject()->getNameIdentifier() : nullptr;
397                     if (!respName || !XMLString::equals(respName->getName(), ctx.getNameID()->getName()) ||
398                         !XMLString::equals(respName->getFormat(), ctx.getNameID()->getFormat()) ||
399                         !XMLString::equals(respName->getNameQualifier(), ctx.getNameID()->getNameQualifier())) {
400                         if (respName)
401                             m_log.warnStream() << "ignoring AttributeStatement without strongly matching NameIdentifier in Subject: " <<
402                                 *respName << logging::eol;
403                         else
404                             m_log.warn("ignoring AttributeStatement without NameIdentifier in Subject");
405                         continue;
406                     }
407                 }
408                 extractor->extractAttributes(application, AA, *s, ctx.getResolvedAttributes());
409             }
410         }
411
412         AttributeFilter* filter = application.getAttributeFilter();
413         if (filter) {
414             BasicFilteringContext fc(application, ctx.getResolvedAttributes(), AA, ctx.getClassRef(), ctx.getDeclRef());
415             Locker filtlocker(filter);
416             filter->filterAttributes(fc, ctx.getResolvedAttributes());
417         }
418     }
419     catch (exception& ex) {
420         m_log.error("caught exception extracting/filtering attributes from query result: %s", ex.what());
421         for_each(ctx.getResolvedAttributes().begin(), ctx.getResolvedAttributes().end(), xmltooling::cleanup<shibsp::Attribute>());
422         ctx.getResolvedAttributes().clear();
423         throw;
424     }
425 }
426
427 void QueryResolver::SAML2Query(QueryContext& ctx) const
428 {
429 #ifdef _DEBUG
430     xmltooling::NDC ndc("query");
431 #endif
432
433     const AttributeAuthorityDescriptor* AA =
434         find_if(ctx.getEntityDescriptor()->getAttributeAuthorityDescriptors(), isValidForProtocol(samlconstants::SAML20P_NS));
435     if (!AA) {
436         m_log.warn("no SAML 2 AttributeAuthority role found in metadata");
437         return;
438     }
439
440     const Application& application = ctx.getApplication();
441     const PropertySet* relyingParty = application.getRelyingParty(ctx.getEntityDescriptor());
442     pair<bool,bool> signedAssertions = relyingParty->getBool("requireSignedAssertions");
443     pair<bool,const char*> encryption = relyingParty->getString("encryption");
444
445     // Locate policy key.
446     const char* policyId = m_policyId.empty() ? application.getString("policyId").second : m_policyId.c_str();
447
448     // Set up policy and SOAP client.
449     scoped_ptr<SecurityPolicy> policy(
450         application.getServiceProvider().getSecurityPolicyProvider()->createSecurityPolicy(application, nullptr, policyId)
451         );
452     policy->getAudiences().push_back(relyingParty->getXMLString("entityID").second);
453     MetadataCredentialCriteria mcc(*AA);
454     shibsp::SOAPClient soaper(*policy);
455
456     auto_ptr_XMLCh binding(samlconstants::SAML20_BINDING_SOAP);
457     auto_ptr<saml2p::StatusResponseType> srt;
458     const vector<AttributeService*>& endpoints=AA->getAttributeServices();
459     for (indirect_iterator<vector<AttributeService*>::const_iterator> ep = make_indirect_iterator(endpoints.begin());
460             !srt.get() && ep != make_indirect_iterator(endpoints.end()); ++ep) {
461         if (!XMLString::equals(ep->getBinding(), binding.get())  || !ep->getLocation())
462             continue;
463         auto_ptr_char loc(ep->getLocation());
464         try {
465             auto_ptr<saml2::Subject> subject(saml2::SubjectBuilder::buildSubject());
466
467             // Encrypt the NameID?
468             if (encryption.first && (!strcmp(encryption.second, "true") || !strcmp(encryption.second, "back"))) {
469                 auto_ptr<EncryptedID> encrypted(EncryptedIDBuilder::buildEncryptedID());
470                 encrypted->encrypt(
471                     *ctx.getNameID(),
472                     *(application.getMetadataProvider()),
473                     mcc,
474                     false,
475                     relyingParty->getXMLString("encryptionAlg").second
476                     );
477                 subject->setEncryptedID(encrypted.get());
478                 encrypted.release();
479             }
480             else {
481                 auto_ptr<NameID> namewrapper(ctx.getNameID()->cloneNameID());
482                 subject->setNameID(namewrapper.get());
483                 namewrapper.release();
484             }
485
486             saml2p::AttributeQuery* query = saml2p::AttributeQueryBuilder::buildAttributeQuery();
487             query->setSubject(subject.release());
488             Issuer* iss = IssuerBuilder::buildIssuer();
489             iss->setName(relyingParty->getXMLString("entityID").second);
490             query->setIssuer(iss);
491             for (ptr_vector<saml2::Attribute>::const_iterator ad = m_SAML2Designators.begin(); ad != m_SAML2Designators.end(); ++ad) {
492                 auto_ptr<saml2::Attribute> adwrapper(ad->cloneAttribute());
493                 query->getAttributes().push_back(adwrapper.get());
494                 adwrapper.release();
495             }
496
497             SAML2SOAPClient client(soaper, false);
498             client.sendSAML(query, application.getId(), mcc, loc.get());
499             srt.reset(client.receiveSAML());
500         }
501         catch (exception& ex) {
502             m_log.error("exception during SAML query to %s: %s", loc.get(), ex.what());
503             soaper.reset();
504         }
505     }
506
507     if (!srt.get()) {
508         m_log.error("unable to obtain a SAML response from attribute authority");
509         throw BindingException("Unable to obtain a SAML response from attribute authority.");
510     }
511
512     saml2p::Response* response = dynamic_cast<saml2p::Response*>(srt.get());
513     if (!response) {
514         m_log.error("message was not a samlp:Response");
515         throw FatalProfileException("Attribute authority returned an unrecognized message.");
516     }
517     else if (!response->getStatus() || !response->getStatus()->getStatusCode() ||
518             !XMLString::equals(response->getStatus()->getStatusCode()->getValue(), saml2p::StatusCode::SUCCESS)) {
519         m_log.error("attribute authority returned a SAML error");
520         throw FatalProfileException("Attribute authority returned a SAML error.");
521     }
522
523     saml2::Assertion* newtoken = nullptr;
524     auto_ptr<saml2::Assertion> newtokenwrapper;
525     const vector<saml2::Assertion*>& assertions = const_cast<const saml2p::Response*>(response)->getAssertions();
526     if (assertions.empty()) {
527         // Check for encryption.
528         const vector<saml2::EncryptedAssertion*>& encassertions = const_cast<const saml2p::Response*>(response)->getEncryptedAssertions();
529         if (encassertions.empty()) {
530             m_log.warn("response from attribute authority was empty");
531             return;
532         }
533         else if (encassertions.size() > 1) {
534             m_log.warn("simple resolver only supports one assertion in the query response");
535         }
536
537         CredentialResolver* cr=application.getCredentialResolver();
538         if (!cr) {
539             m_log.warn("found encrypted assertion, but no CredentialResolver was available");
540             throw FatalProfileException("Assertion was encrypted, but no decryption credentials are available.");
541         }
542
543         // Attempt to decrypt it.
544         try {
545             Locker credlocker(cr);
546             auto_ptr<XMLObject> tokenwrapper(encassertions.front()->decrypt(*cr, relyingParty->getXMLString("entityID").second, &mcc));
547             newtoken = dynamic_cast<saml2::Assertion*>(tokenwrapper.get());
548             if (newtoken) {
549                 tokenwrapper.release();
550                 newtokenwrapper.reset(newtoken);
551                 if (m_log.isDebugEnabled())
552                     m_log.debugStream() << "decrypted Assertion: " << *newtoken << logging::eol;
553             }
554         }
555         catch (exception& ex) {
556             m_log.error(ex.what());
557             throw;
558         }
559     }
560     else {
561         if (assertions.size() > 1)
562             m_log.warn("simple resolver only supports one assertion in the query response");
563         newtoken = assertions.front();
564     }
565
566     if (!newtoken->getSignature() && signedAssertions.first && signedAssertions.second) {
567         m_log.error("assertion unsigned, rejecting it based on signedAssertions policy");
568         throw SecurityPolicyException("Rejected unsigned assertion based on local policy.");
569     }
570
571     try {
572         // We're going to insist that the assertion issuer is the same as the peer.
573         // Reset the policy's message bits and extract them from the assertion.
574         policy->reset(true);
575         policy->setMessageID(newtoken->getID());
576         policy->setIssueInstant(newtoken->getIssueInstantEpoch());
577         policy->setIssuer(newtoken->getIssuer());
578         policy->evaluate(*newtoken);
579
580         // Now we can check the security status of the policy.
581         if (!policy->isAuthenticated())
582             throw SecurityPolicyException("Security of SAML 2.0 query result not established.");
583
584         if (m_subjectMatch) {
585             // Check for subject match.
586             auto_ptr<NameID> nameIDwrapper;
587             NameID* respName = newtoken->getSubject() ? newtoken->getSubject()->getNameID() : nullptr;
588             if (!respName) {
589                 // Check for encryption.
590                 EncryptedID* encname = newtoken->getSubject() ? newtoken->getSubject()->getEncryptedID() : nullptr;
591                 if (encname) {
592                     CredentialResolver* cr=application.getCredentialResolver();
593                     if (!cr)
594                         m_log.warn("found EncryptedID, but no CredentialResolver was available");
595                     else {
596                         Locker credlocker(cr);
597                         auto_ptr<XMLObject> decryptedID(encname->decrypt(*cr, relyingParty->getXMLString("entityID").second, &mcc));
598                         respName = dynamic_cast<NameID*>(decryptedID.get());
599                         if (respName) {
600                             decryptedID.release();
601                             nameIDwrapper.reset(respName);
602                             if (m_log.isDebugEnabled())
603                                 m_log.debugStream() << "decrypted NameID: " << *respName << logging::eol;
604                         }
605                     }
606                 }
607             }
608
609             if (!respName || !XMLString::equals(respName->getName(), ctx.getNameID()->getName()) ||
610                 !XMLString::equals(respName->getFormat(), ctx.getNameID()->getFormat()) ||
611                 !XMLString::equals(respName->getNameQualifier(), ctx.getNameID()->getNameQualifier()) ||
612                 !XMLString::equals(respName->getSPNameQualifier(), ctx.getNameID()->getSPNameQualifier())) {
613                 if (respName)
614                     m_log.warnStream() << "ignoring Assertion without strongly matching NameID in Subject: " <<
615                         *respName << logging::eol;
616                 else
617                     m_log.warn("ignoring Assertion without NameID in Subject");
618                 return;
619             }
620         }
621     }
622     catch (exception& ex) {
623         m_log.error("assertion failed policy validation: %s", ex.what());
624         throw;
625     }
626
627     // If the token's embedded, detach it.
628     if (!newtokenwrapper.get()) {
629         newtoken->detach();
630         srt.release();  // detach blows away the Response, so avoid a double free
631         newtokenwrapper.reset(newtoken);
632     }
633     ctx.getResolvedAssertions().push_back(newtoken);
634     newtokenwrapper.release();
635
636     // Finally, extract and filter the result.
637     try {
638         AttributeExtractor* extractor = application.getAttributeExtractor();
639         if (extractor) {
640             Locker extlocker(extractor);
641             extractor->extractAttributes(application, AA, *newtoken, ctx.getResolvedAttributes());
642         }
643
644         AttributeFilter* filter = application.getAttributeFilter();
645         if (filter) {
646             BasicFilteringContext fc(application, ctx.getResolvedAttributes(), AA, ctx.getClassRef(), ctx.getDeclRef());
647             Locker filtlocker(filter);
648             filter->filterAttributes(fc, ctx.getResolvedAttributes());
649         }
650     }
651     catch (exception& ex) {
652         m_log.error("caught exception extracting/filtering attributes from query result: %s", ex.what());
653         for_each(ctx.getResolvedAttributes().begin(), ctx.getResolvedAttributes().end(), xmltooling::cleanup<shibsp::Attribute>());
654         ctx.getResolvedAttributes().clear();
655         throw;
656     }
657 }
658
659 void QueryResolver::resolveAttributes(ResolutionContext& ctx) const
660 {
661 #ifdef _DEBUG
662     xmltooling::NDC ndc("resolveAttributes");
663 #endif
664
665     QueryContext& qctx = dynamic_cast<QueryContext&>(ctx);
666     if (!qctx.doQuery()) {
667         m_log.debug("found AttributeStatement in input to new session, skipping query");
668         return;
669     }
670
671     try {
672         if (qctx.getNameID() && qctx.getEntityDescriptor()) {
673             if (XMLString::equals(qctx.getProtocol(), samlconstants::SAML20P_NS)) {
674                 m_log.debug("attempting SAML 2.0 attribute query");
675                 SAML2Query(qctx);
676             }
677             else if (XMLString::equals(qctx.getProtocol(), samlconstants::SAML11_PROTOCOL_ENUM) ||
678                     XMLString::equals(qctx.getProtocol(), samlconstants::SAML10_PROTOCOL_ENUM)) {
679                 m_log.debug("attempting SAML 1.x attribute query");
680                 SAML1Query(qctx);
681             }
682             else {
683                 m_log.info("SSO protocol does not allow for attribute query");
684             }
685         }
686         else {
687             m_log.warn("can't attempt attribute query, either no NameID or no metadata to use");
688         }
689     }
690     catch (exception& ex) {
691         // Already logged.
692         if (!m_exceptionId.empty()) {
693             auto_ptr<SimpleAttribute> attr(new SimpleAttribute(m_exceptionId));
694             attr->getValues().push_back(XMLToolingConfig::getConfig().getURLEncoder()->encode(ex.what()));
695             qctx.getResolvedAttributes().push_back(attr.get());
696             attr.release();
697         }
698     }
699 }