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