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