https://issues.shibboleth.net/jira/browse/SSPCPP-398
[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/iterator/indirect_iterator.hpp>
44 #include <boost/ptr_container/ptr_vector.hpp>
45 #include <saml/exceptions.h>
46 #include <saml/saml1/binding/SAML1SOAPClient.h>
47 #include <saml/saml1/core/Assertions.h>
48 #include <saml/saml1/core/Protocols.h>
49 #include <saml/saml2/binding/SAML2SOAPClient.h>
50 #include <saml/saml2/core/Protocols.h>
51 #include <saml/saml2/metadata/Metadata.h>
52 #include <saml/saml2/metadata/MetadataCredentialCriteria.h>
53 #include <saml/saml2/metadata/MetadataProvider.h>
54 #include <xmltooling/XMLToolingConfig.h>
55 #include <xmltooling/util/NDC.h>
56 #include <xmltooling/util/URLEncoder.h>
57 #include <xmltooling/util/XMLHelper.h>
58 #include <xercesc/util/XMLUniDefs.hpp>
59
60 using namespace shibsp;
61 using namespace opensaml::saml1;
62 using namespace opensaml::saml1p;
63 using namespace opensaml::saml2;
64 using namespace opensaml::saml2p;
65 using namespace opensaml::saml2md;
66 using namespace opensaml;
67 using namespace xmltooling;
68 using namespace boost;
69 using namespace std;
70
71 namespace shibsp {
72
73     class SHIBSP_DLLLOCAL QueryContext : public ResolutionContext
74     {
75     public:
76         QueryContext(const Application& application, const Session& session)
77                 : m_query(true), m_app(application), m_session(&session), m_metadata(nullptr), m_entity(nullptr), m_nameid(nullptr) {
78             m_protocol = XMLString::transcode(session.getProtocol());
79             m_class = XMLString::transcode(session.getAuthnContextClassRef());
80             m_decl = XMLString::transcode(session.getAuthnContextDeclRef());
81         }
82
83         QueryContext(
84             const Application& application,
85             const EntityDescriptor* issuer,
86             const XMLCh* protocol,
87             const NameID* nameid=nullptr,
88             const XMLCh* authncontext_class=nullptr,
89             const XMLCh* authncontext_decl=nullptr,
90             const vector<const opensaml::Assertion*>* tokens=nullptr
91             ) : m_query(true), m_app(application), m_session(nullptr), m_metadata(nullptr), m_entity(issuer),
92                 m_protocol(protocol), m_nameid(nameid), m_class(authncontext_class), m_decl(authncontext_decl) {
93
94             if (tokens) {
95                 for (vector<const opensaml::Assertion*>::const_iterator t = tokens->begin(); t!=tokens->end(); ++t) {
96                     const saml2::Assertion* token2 = dynamic_cast<const saml2::Assertion*>(*t);
97                     if (token2 && !token2->getAttributeStatements().empty()) {
98                         m_query = false;
99                     }
100                     else {
101                         const saml1::Assertion* token1 = dynamic_cast<const saml1::Assertion*>(*t);
102                         if (token1 && !token1->getAttributeStatements().empty()) {
103                             m_query = false;
104                         }
105                     }
106                 }
107             }
108         }
109
110         ~QueryContext() {
111             if (m_session) {
112                 XMLString::release((XMLCh**)&m_protocol);
113                 XMLString::release((XMLCh**)&m_class);
114                 XMLString::release((XMLCh**)&m_decl);
115             }
116             if (m_metadata)
117                 m_metadata->unlock();
118             for_each(m_attributes.begin(), m_attributes.end(), xmltooling::cleanup<shibsp::Attribute>());
119             for_each(m_assertions.begin(), m_assertions.end(), xmltooling::cleanup<opensaml::Assertion>());
120         }
121
122         bool doQuery() const {
123             return m_query;
124         }
125
126         const Application& getApplication() const {
127             return m_app;
128         }
129         const EntityDescriptor* getEntityDescriptor() const {
130             if (m_entity)
131                 return m_entity;
132             if (m_session && m_session->getEntityID()) {
133                 m_metadata = m_app.getMetadataProvider(false);
134                 if (m_metadata) {
135                     m_metadata->lock();
136                     return m_entity = m_metadata->getEntityDescriptor(MetadataProviderCriteria(m_app, m_session->getEntityID())).first;
137                 }
138             }
139             return nullptr;
140         }
141         const XMLCh* getProtocol() const {
142             return m_protocol;
143         }
144         const NameID* getNameID() const {
145             return m_session ? m_session->getNameID() : m_nameid;
146         }
147         const XMLCh* getClassRef() const {
148             return m_class;
149         }
150         const XMLCh* getDeclRef() const {
151             return m_decl;
152         }
153         const Session* getSession() const {
154             return m_session;
155         }
156         vector<shibsp::Attribute*>& getResolvedAttributes() {
157             return m_attributes;
158         }
159         vector<opensaml::Assertion*>& getResolvedAssertions() {
160             return m_assertions;
161         }
162
163     private:
164         bool m_query;
165         const Application& m_app;
166         const Session* m_session;
167         mutable MetadataProvider* m_metadata;
168         mutable const EntityDescriptor* m_entity;
169         const XMLCh* m_protocol;
170         const NameID* m_nameid;
171         const XMLCh* m_class;
172         const XMLCh* m_decl;
173         vector<shibsp::Attribute*> m_attributes;
174         vector<opensaml::Assertion*> m_assertions;
175     };
176
177     class SHIBSP_DLLLOCAL QueryResolver : public AttributeResolver
178     {
179     public:
180         QueryResolver(const DOMElement* e);
181         ~QueryResolver() {}
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         ptr_vector<AttributeDesignator> m_SAML1Designators;
217         ptr_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     scoped_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);
298
299     auto_ptr_XMLCh binding(samlconstants::SAML1_BINDING_SOAP);
300     auto_ptr<saml1p::Response> response;
301     const vector<AttributeService*>& endpoints=AA->getAttributeServices();
302     for (indirect_iterator<vector<AttributeService*>::const_iterator> ep = make_indirect_iterator(endpoints.begin());
303             !response.get() && ep != make_indirect_iterator(endpoints.end()); ++ep) {
304         if (!XMLString::equals(ep->getBinding(), binding.get()) || !ep->getLocation())
305             continue;
306         auto_ptr_char loc(ep->getLocation());
307         try {
308             NameIdentifier* nameid = NameIdentifierBuilder::buildNameIdentifier();
309             nameid->setName(ctx.getNameID()->getName());
310             nameid->setFormat(ctx.getNameID()->getFormat());
311             nameid->setNameQualifier(ctx.getNameID()->getNameQualifier());
312             saml1::Subject* subject = saml1::SubjectBuilder::buildSubject();
313             subject->setNameIdentifier(nameid);
314             saml1p::AttributeQuery* query = saml1p::AttributeQueryBuilder::buildAttributeQuery();
315             query->setSubject(subject);
316             query->setResource(relyingParty->getXMLString("entityID").second);
317             for (ptr_vector<AttributeDesignator>::const_iterator ad = m_SAML1Designators.begin(); ad != m_SAML1Designators.end(); ++ad) {
318                 auto_ptr<AttributeDesignator> adwrapper(ad->cloneAttributeDesignator());
319                 query->getAttributeDesignators().push_back(adwrapper.get());
320                 adwrapper.release();
321             }
322             Request* request = RequestBuilder::buildRequest();
323             request->setAttributeQuery(query);
324             request->setMinorVersion(version);
325
326             SAML1SOAPClient client(soaper, false);
327             client.sendSAML(request, application.getId(), mcc, loc.get());
328             response.reset(client.receiveSAML());
329         }
330         catch (exception& ex) {
331             m_log.error("exception during SAML query to %s: %s", loc.get(), ex.what());
332             soaper.reset();
333         }
334     }
335
336     if (!response.get()) {
337         m_log.error("unable to obtain a SAML response from attribute authority");
338         throw BindingException("Unable to obtain a SAML response from attribute authority.");
339     }
340     else if (!response->getStatus() || !response->getStatus()->getStatusCode() || response->getStatus()->getStatusCode()->getValue()==nullptr ||
341             *(response->getStatus()->getStatusCode()->getValue()) != saml1p::StatusCode::SUCCESS) {
342         m_log.error("attribute authority returned a SAML error");
343         throw FatalProfileException("Attribute authority returned a SAML error.");
344     }
345
346     const vector<saml1::Assertion*>& assertions = const_cast<const saml1p::Response*>(response.get())->getAssertions();
347     if (assertions.empty()) {
348         m_log.warn("response from attribute authority was empty");
349         return;
350     }
351     else if (assertions.size() > 1) {
352         m_log.warn("simple resolver only supports one assertion in the query response");
353     }
354
355     saml1::Assertion* newtoken = assertions.front();
356
357     pair<bool,bool> signedAssertions = relyingParty->getBool("requireSignedAssertions");
358     if (!newtoken->getSignature() && signedAssertions.first && signedAssertions.second) {
359         m_log.error("assertion unsigned, rejecting it based on signedAssertions policy");
360         throw SecurityPolicyException("Rejected unsigned assertion based on local policy.");
361     }
362
363     try {
364         // We're going to insist that the assertion issuer is the same as the peer.
365         // Reset the policy's message bits and extract them from the assertion.
366         policy->reset(true);
367         policy->setMessageID(newtoken->getAssertionID());
368         policy->setIssueInstant(newtoken->getIssueInstantEpoch());
369         policy->setIssuer(newtoken->getIssuer());
370         policy->evaluate(*newtoken);
371
372         // Now we can check the security status of the policy.
373         if (!policy->isAuthenticated())
374             throw SecurityPolicyException("Security of SAML 1.x query result not established.");
375     }
376     catch (exception& ex) {
377         m_log.error("assertion failed policy validation: %s", ex.what());
378         throw;
379     }
380
381     newtoken->detach();
382     response.release();  // detach blows away the Response
383     ctx.getResolvedAssertions().push_back(newtoken);
384
385     // Finally, extract and filter the result.
386     try {
387         AttributeExtractor* extractor = application.getAttributeExtractor();
388         if (extractor) {
389             Locker extlocker(extractor);
390             const vector<saml1::AttributeStatement*>& statements = const_cast<const saml1::Assertion*>(newtoken)->getAttributeStatements();
391             for (indirect_iterator<vector<saml1::AttributeStatement*>::const_iterator> s = make_indirect_iterator(statements.begin());
392                     s != make_indirect_iterator(statements.end()); ++s) {
393                 if (m_subjectMatch) {
394                     // Check for subject match.
395                     const NameIdentifier* respName = s->getSubject() ? s->getSubject()->getNameIdentifier() : nullptr;
396                     if (!respName || !XMLString::equals(respName->getName(), ctx.getNameID()->getName()) ||
397                         !XMLString::equals(respName->getFormat(), ctx.getNameID()->getFormat()) ||
398                         !XMLString::equals(respName->getNameQualifier(), ctx.getNameID()->getNameQualifier())) {
399                         if (respName)
400                             m_log.warnStream() << "ignoring AttributeStatement without strongly matching NameIdentifier in Subject: " <<
401                                 *respName << logging::eol;
402                         else
403                             m_log.warn("ignoring AttributeStatement without NameIdentifier in Subject");
404                         continue;
405                     }
406                 }
407                 extractor->extractAttributes(application, AA, *s, ctx.getResolvedAttributes());
408             }
409         }
410
411         AttributeFilter* filter = application.getAttributeFilter();
412         if (filter) {
413             BasicFilteringContext fc(application, ctx.getResolvedAttributes(), AA, ctx.getClassRef(), ctx.getDeclRef());
414             Locker filtlocker(filter);
415             filter->filterAttributes(fc, ctx.getResolvedAttributes());
416         }
417     }
418     catch (exception& ex) {
419         m_log.error("caught exception extracting/filtering attributes from query result: %s", ex.what());
420         for_each(ctx.getResolvedAttributes().begin(), ctx.getResolvedAttributes().end(), xmltooling::cleanup<shibsp::Attribute>());
421         ctx.getResolvedAttributes().clear();
422         throw;
423     }
424 }
425
426 void QueryResolver::SAML2Query(QueryContext& ctx) const
427 {
428 #ifdef _DEBUG
429     xmltooling::NDC ndc("query");
430 #endif
431
432     const AttributeAuthorityDescriptor* AA =
433         find_if(ctx.getEntityDescriptor()->getAttributeAuthorityDescriptors(), isValidForProtocol(samlconstants::SAML20P_NS));
434     if (!AA) {
435         m_log.warn("no SAML 2 AttributeAuthority role found in metadata");
436         return;
437     }
438
439     const Application& application = ctx.getApplication();
440     const PropertySet* relyingParty = application.getRelyingParty(ctx.getEntityDescriptor());
441     pair<bool,bool> signedAssertions = relyingParty->getBool("requireSignedAssertions");
442     pair<bool,const char*> encryption = relyingParty->getString("encryption");
443
444     // Locate policy key.
445     const char* policyId = m_policyId.empty() ? application.getString("policyId").second : m_policyId.c_str();
446
447     // Set up policy and SOAP client.
448     scoped_ptr<SecurityPolicy> policy(
449         application.getServiceProvider().getSecurityPolicyProvider()->createSecurityPolicy(application, nullptr, policyId)
450         );
451     policy->getAudiences().push_back(relyingParty->getXMLString("entityID").second);
452     MetadataCredentialCriteria mcc(*AA);
453     shibsp::SOAPClient soaper(*policy);
454
455     auto_ptr_XMLCh binding(samlconstants::SAML20_BINDING_SOAP);
456     auto_ptr<saml2p::StatusResponseType> srt;
457     const vector<AttributeService*>& endpoints=AA->getAttributeServices();
458     for (indirect_iterator<vector<AttributeService*>::const_iterator> ep = make_indirect_iterator(endpoints.begin());
459             !srt.get() && ep != make_indirect_iterator(endpoints.end()); ++ep) {
460         if (!XMLString::equals(ep->getBinding(), binding.get())  || !ep->getLocation())
461             continue;
462         auto_ptr_char loc(ep->getLocation());
463         try {
464             auto_ptr<saml2::Subject> subject(saml2::SubjectBuilder::buildSubject());
465
466             // Encrypt the NameID?
467             if (encryption.first && (!strcmp(encryption.second, "true") || !strcmp(encryption.second, "back"))) {
468                 auto_ptr<EncryptedID> encrypted(EncryptedIDBuilder::buildEncryptedID());
469                 encrypted->encrypt(
470                     *ctx.getNameID(),
471                     *(application.getMetadataProvider()),
472                     mcc,
473                     false,
474                     relyingParty->getXMLString("encryptionAlg").second
475                     );
476                 subject->setEncryptedID(encrypted.get());
477                 encrypted.release();
478             }
479             else {
480                 auto_ptr<NameID> namewrapper(ctx.getNameID()->cloneNameID());
481                 subject->setNameID(namewrapper.get());
482                 namewrapper.release();
483             }
484
485             saml2p::AttributeQuery* query = saml2p::AttributeQueryBuilder::buildAttributeQuery();
486             query->setSubject(subject.release());
487             Issuer* iss = IssuerBuilder::buildIssuer();
488             iss->setName(relyingParty->getXMLString("entityID").second);
489             query->setIssuer(iss);
490             for (ptr_vector<saml2::Attribute>::const_iterator ad = m_SAML2Designators.begin(); ad != m_SAML2Designators.end(); ++ad) {
491                 auto_ptr<saml2::Attribute> adwrapper(ad->cloneAttribute());
492                 query->getAttributes().push_back(adwrapper.get());
493                 adwrapper.release();
494             }
495
496             SAML2SOAPClient client(soaper, false);
497             client.sendSAML(query, application.getId(), mcc, loc.get());
498             srt.reset(client.receiveSAML());
499         }
500         catch (exception& ex) {
501             m_log.error("exception during SAML query to %s: %s", loc.get(), ex.what());
502             soaper.reset();
503         }
504     }
505
506     if (!srt.get()) {
507         m_log.error("unable to obtain a SAML response from attribute authority");
508         throw BindingException("Unable to obtain a SAML response from attribute authority.");
509     }
510
511     saml2p::Response* response = dynamic_cast<saml2p::Response*>(srt.get());
512     if (!response) {
513         m_log.error("message was not a samlp:Response");
514         throw FatalProfileException("Attribute authority returned an unrecognized message.");
515     }
516     else if (!response->getStatus() || !response->getStatus()->getStatusCode() ||
517             !XMLString::equals(response->getStatus()->getStatusCode()->getValue(), saml2p::StatusCode::SUCCESS)) {
518         m_log.error("attribute authority returned a SAML error");
519         throw FatalProfileException("Attribute authority returned a SAML error.");
520     }
521
522     saml2::Assertion* newtoken = nullptr;
523     auto_ptr<saml2::Assertion> newtokenwrapper;
524     const vector<saml2::Assertion*>& assertions = const_cast<const saml2p::Response*>(response)->getAssertions();
525     if (assertions.empty()) {
526         // Check for encryption.
527         const vector<saml2::EncryptedAssertion*>& encassertions = const_cast<const saml2p::Response*>(response)->getEncryptedAssertions();
528         if (encassertions.empty()) {
529             m_log.warn("response from attribute authority was empty");
530             return;
531         }
532         else if (encassertions.size() > 1) {
533             m_log.warn("simple resolver only supports one assertion in the query response");
534         }
535
536         CredentialResolver* cr = application.getCredentialResolver();
537         if (!cr) {
538             m_log.warn("found encrypted assertion, but no CredentialResolver was available");
539             throw FatalProfileException("Assertion was encrypted, but no decryption credentials are available.");
540         }
541
542         // With this flag on, we block unauthenticated ciphertext when decrypting,
543         // unless the protocol was authenticated.
544         pair<bool,bool> authenticatedCipher = application.getBool("requireAuthenticatedCipher");
545         if (policy->isAuthenticated())
546             authenticatedCipher.second = false;
547
548         // Attempt to decrypt it.
549         try {
550             Locker credlocker(cr);
551             auto_ptr<XMLObject> tokenwrapper(
552                 encassertions.front()->decrypt(
553                     *cr, relyingParty->getXMLString("entityID").second, &mcc, authenticatedCipher.first && authenticatedCipher.second
554                     )
555                 );
556             newtoken = dynamic_cast<saml2::Assertion*>(tokenwrapper.get());
557             if (newtoken) {
558                 tokenwrapper.release();
559                 newtokenwrapper.reset(newtoken);
560                 if (m_log.isDebugEnabled())
561                     m_log.debugStream() << "decrypted Assertion: " << *newtoken << logging::eol;
562             }
563         }
564         catch (exception& ex) {
565             m_log.error(ex.what());
566             throw;
567         }
568     }
569     else {
570         if (assertions.size() > 1)
571             m_log.warn("simple resolver only supports one assertion in the query response");
572         newtoken = assertions.front();
573     }
574
575     if (!newtoken->getSignature() && signedAssertions.first && signedAssertions.second) {
576         m_log.error("assertion unsigned, rejecting it based on signedAssertions policy");
577         throw SecurityPolicyException("Rejected unsigned assertion based on local policy.");
578     }
579
580     try {
581         // We're going to insist that the assertion issuer is the same as the peer.
582         // Reset the policy's message bits and extract them from the assertion.
583         policy->reset(true);
584         policy->setMessageID(newtoken->getID());
585         policy->setIssueInstant(newtoken->getIssueInstantEpoch());
586         policy->setIssuer(newtoken->getIssuer());
587         policy->evaluate(*newtoken);
588
589         // Now we can check the security status of the policy.
590         if (!policy->isAuthenticated())
591             throw SecurityPolicyException("Security of SAML 2.0 query result not established.");
592
593         if (m_subjectMatch) {
594             // Check for subject match.
595             auto_ptr<NameID> nameIDwrapper;
596             NameID* respName = newtoken->getSubject() ? newtoken->getSubject()->getNameID() : nullptr;
597             if (!respName) {
598                 // Check for encryption.
599                 EncryptedID* encname = newtoken->getSubject() ? newtoken->getSubject()->getEncryptedID() : nullptr;
600                 if (encname) {
601                     CredentialResolver* cr=application.getCredentialResolver();
602                     if (!cr)
603                         m_log.warn("found EncryptedID, but no CredentialResolver was available");
604                     else {
605                         Locker credlocker(cr);
606                         auto_ptr<XMLObject> decryptedID(encname->decrypt(*cr, relyingParty->getXMLString("entityID").second, &mcc));
607                         respName = dynamic_cast<NameID*>(decryptedID.get());
608                         if (respName) {
609                             decryptedID.release();
610                             nameIDwrapper.reset(respName);
611                             if (m_log.isDebugEnabled())
612                                 m_log.debugStream() << "decrypted NameID: " << *respName << logging::eol;
613                         }
614                     }
615                 }
616             }
617
618             if (!respName || !XMLString::equals(respName->getName(), ctx.getNameID()->getName()) ||
619                 !XMLString::equals(respName->getFormat(), ctx.getNameID()->getFormat()) ||
620                 !XMLString::equals(respName->getNameQualifier(), ctx.getNameID()->getNameQualifier()) ||
621                 !XMLString::equals(respName->getSPNameQualifier(), ctx.getNameID()->getSPNameQualifier())) {
622                 if (respName)
623                     m_log.warnStream() << "ignoring Assertion without strongly matching NameID in Subject: " <<
624                         *respName << logging::eol;
625                 else
626                     m_log.warn("ignoring Assertion without NameID in Subject");
627                 return;
628             }
629         }
630     }
631     catch (exception& ex) {
632         m_log.error("assertion failed policy validation: %s", ex.what());
633         throw;
634     }
635
636     // If the token's embedded, detach it.
637     if (!newtokenwrapper.get()) {
638         newtoken->detach();
639         srt.release();  // detach blows away the Response, so avoid a double free
640         newtokenwrapper.reset(newtoken);
641     }
642     ctx.getResolvedAssertions().push_back(newtoken);
643     newtokenwrapper.release();
644
645     // Finally, extract and filter the result.
646     try {
647         AttributeExtractor* extractor = application.getAttributeExtractor();
648         if (extractor) {
649             Locker extlocker(extractor);
650             extractor->extractAttributes(application, AA, *newtoken, ctx.getResolvedAttributes());
651         }
652
653         AttributeFilter* filter = application.getAttributeFilter();
654         if (filter) {
655             BasicFilteringContext fc(application, ctx.getResolvedAttributes(), AA, ctx.getClassRef(), ctx.getDeclRef());
656             Locker filtlocker(filter);
657             filter->filterAttributes(fc, ctx.getResolvedAttributes());
658         }
659     }
660     catch (exception& ex) {
661         m_log.error("caught exception extracting/filtering attributes from query result: %s", ex.what());
662         for_each(ctx.getResolvedAttributes().begin(), ctx.getResolvedAttributes().end(), xmltooling::cleanup<shibsp::Attribute>());
663         ctx.getResolvedAttributes().clear();
664         throw;
665     }
666 }
667
668 void QueryResolver::resolveAttributes(ResolutionContext& ctx) const
669 {
670 #ifdef _DEBUG
671     xmltooling::NDC ndc("resolveAttributes");
672 #endif
673
674     QueryContext& qctx = dynamic_cast<QueryContext&>(ctx);
675     if (!qctx.doQuery()) {
676         m_log.debug("found AttributeStatement in input to new session, skipping query");
677         return;
678     }
679
680     try {
681         if (qctx.getNameID() && qctx.getEntityDescriptor()) {
682             if (XMLString::equals(qctx.getProtocol(), samlconstants::SAML20P_NS)) {
683                 m_log.debug("attempting SAML 2.0 attribute query");
684                 SAML2Query(qctx);
685             }
686             else if (XMLString::equals(qctx.getProtocol(), samlconstants::SAML11_PROTOCOL_ENUM) ||
687                     XMLString::equals(qctx.getProtocol(), samlconstants::SAML10_PROTOCOL_ENUM)) {
688                 m_log.debug("attempting SAML 1.x attribute query");
689                 SAML1Query(qctx);
690             }
691             else {
692                 m_log.info("SSO protocol does not allow for attribute query");
693             }
694         }
695         else {
696             m_log.warn("can't attempt attribute query, either no NameID or no metadata to use");
697         }
698     }
699     catch (exception& ex) {
700         // Already logged.
701         if (!m_exceptionId.empty()) {
702             auto_ptr<SimpleAttribute> attr(new SimpleAttribute(m_exceptionId));
703             attr->getValues().push_back(XMLToolingConfig::getConfig().getURLEncoder()->encode(ex.what()));
704             qctx.getResolvedAttributes().push_back(attr.get());
705             attr.release();
706         }
707     }
708 }