fb52752bb56ac82deffee0336179c3fe88817502
[shibboleth/cpp-sp.git] / shibsp / attribute / resolver / impl / SimpleAggregationAttributeResolver.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  * SimpleAggregationAttributeResolver.cpp
23  *
24  * AttributeResolver based on SAML queries to third-party AA sources.
25  */
26
27 #include "internal.h"
28 #include "exceptions.h"
29 #include "Application.h"
30 #include "ServiceProvider.h"
31 #include "SessionCache.h"
32 #include "attribute/NameIDAttribute.h"
33 #include "attribute/SimpleAttribute.h"
34 #include "attribute/filtering/AttributeFilter.h"
35 #include "attribute/filtering/BasicFilteringContext.h"
36 #include "attribute/resolver/AttributeExtractor.h"
37 #include "attribute/resolver/AttributeResolver.h"
38 #include "attribute/resolver/ResolutionContext.h"
39 #include "binding/SOAPClient.h"
40 #include "metadata/MetadataProviderCriteria.h"
41 #include "security/SecurityPolicy.h"
42 #include "security/SecurityPolicyProvider.h"
43 #include "util/SPConstants.h"
44
45 #include <boost/algorithm/string.hpp>
46 #include <boost/iterator/indirect_iterator.hpp>
47 #include <boost/ptr_container/ptr_vector.hpp>
48 #include <saml/exceptions.h>
49 #include <saml/SAMLConfig.h>
50 #include <saml/saml2/binding/SAML2SOAPClient.h>
51 #include <saml/saml2/core/Protocols.h>
52 #include <saml/saml2/metadata/Metadata.h>
53 #include <saml/saml2/metadata/MetadataCredentialCriteria.h>
54 #include <saml/saml2/metadata/MetadataProvider.h>
55 #include <xmltooling/XMLToolingConfig.h>
56 #include <xmltooling/security/TrustEngine.h>
57 #include <xmltooling/util/NDC.h>
58 #include <xmltooling/util/URLEncoder.h>
59 #include <xmltooling/util/XMLHelper.h>
60 #include <xercesc/util/XMLUniDefs.hpp>
61
62 using namespace shibsp;
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 SimpleAggregationContext : public ResolutionContext
74     {
75     public:
76         SimpleAggregationContext(const Application& application, const Session& session)
77             : m_app(application),
78               m_request(nullptr),
79               m_session(&session),
80               m_nameid(nullptr),
81               m_class(session.getAuthnContextClassRef()),
82               m_decl(session.getAuthnContextDeclRef()),
83               m_inputTokens(nullptr),
84               m_inputAttributes(nullptr) {
85         }
86
87         SimpleAggregationContext(
88             const Application& application,
89             const GenericRequest* request=nullptr,
90             const NameID* nameid=nullptr,
91             const XMLCh* entityID=nullptr,
92             const XMLCh* authncontext_class=nullptr,
93             const XMLCh* authncontext_decl=nullptr,
94             const vector<const opensaml::Assertion*>* tokens=nullptr,
95             const vector<shibsp::Attribute*>* attributes=nullptr
96             ) : m_app(application),
97                 m_request(request),
98                 m_session(nullptr),
99                 m_nameid(nameid),
100                 m_entityid(entityID),
101                 m_class(authncontext_class),
102                 m_decl(authncontext_decl),
103                 m_inputTokens(tokens),
104                 m_inputAttributes(attributes) {
105         }
106
107         ~SimpleAggregationContext() {
108             for_each(m_attributes.begin(), m_attributes.end(), xmltooling::cleanup<shibsp::Attribute>());
109             for_each(m_assertions.begin(), m_assertions.end(), xmltooling::cleanup<opensaml::Assertion>());
110         }
111
112         const Application& getApplication() const {
113             return m_app;
114         }
115         const GenericRequest* getRequest() const {
116             return m_request;
117         }
118         const char* getEntityID() const {
119             return m_session ? m_session->getEntityID() : m_entityid.get();
120         }
121         const NameID* getNameID() const {
122             return m_session ? m_session->getNameID() : m_nameid;
123         }
124         const XMLCh* getClassRef() const {
125             return m_class.get();
126         }
127         const XMLCh* getDeclRef() const {
128             return m_decl.get();
129         }
130         const Session* getSession() const {
131             return m_session;
132         }
133         const vector<shibsp::Attribute*>* getInputAttributes() const {
134             return m_inputAttributes;
135         }
136         const vector<const opensaml::Assertion*>* getInputTokens() const {
137             return m_inputTokens;
138         }
139         vector<shibsp::Attribute*>& getResolvedAttributes() {
140             return m_attributes;
141         }
142         vector<opensaml::Assertion*>& getResolvedAssertions() {
143             return m_assertions;
144         }
145
146     private:
147         const Application& m_app;
148         const GenericRequest* m_request;
149         const Session* m_session;
150         const NameID* m_nameid;
151         auto_ptr_char m_entityid;
152         auto_ptr_XMLCh m_class;
153         auto_ptr_XMLCh m_decl;
154         const vector<const opensaml::Assertion*>* m_inputTokens;
155         const vector<shibsp::Attribute*>* m_inputAttributes;
156         vector<shibsp::Attribute*> m_attributes;
157         vector<opensaml::Assertion*> m_assertions;
158     };
159
160     class SHIBSP_DLLLOCAL SimpleAggregationResolver : public AttributeResolver
161     {
162     public:
163         SimpleAggregationResolver(const DOMElement* e);
164         ~SimpleAggregationResolver() {}
165
166         Lockable* lock() {return this;}
167         void unlock() {}
168
169         // deprecated method
170         ResolutionContext* createResolutionContext(
171             const Application& application,
172             const EntityDescriptor* issuer,
173             const XMLCh* protocol,
174             const NameID* nameid=nullptr,
175             const XMLCh* authncontext_class=nullptr,
176             const XMLCh* authncontext_decl=nullptr,
177             const vector<const opensaml::Assertion*>* tokens=nullptr,
178             const vector<shibsp::Attribute*>* attributes=nullptr
179             ) const {
180             return createResolutionContext(application, nullptr, issuer, protocol, nameid, authncontext_class, authncontext_decl, tokens, attributes);
181         }
182
183         ResolutionContext* createResolutionContext(
184             const Application& application,
185             const GenericRequest* request,
186             const EntityDescriptor* issuer,
187             const XMLCh* protocol,
188             const NameID* nameid=nullptr,
189             const XMLCh* authncontext_class=nullptr,
190             const XMLCh* authncontext_decl=nullptr,
191             const vector<const opensaml::Assertion*>* tokens=nullptr,
192             const vector<shibsp::Attribute*>* attributes=nullptr
193             ) const {
194             return new SimpleAggregationContext(
195                 application, request, nameid, (issuer ? issuer->getEntityID() : nullptr), authncontext_class, authncontext_decl, tokens, attributes
196                 );
197         }
198
199         ResolutionContext* createResolutionContext(const Application& application, const Session& session) const {
200             return new SimpleAggregationContext(application,session);
201         }
202
203         void resolveAttributes(ResolutionContext& ctx) const;
204
205         void getAttributeIds(vector<string>& attributes) const {
206             if (m_extractor)
207                 m_extractor->getAttributeIds(attributes);
208         }
209
210     private:
211         void doQuery(SimpleAggregationContext& ctx, const char* entityID, const NameID* name) const;
212
213         Category& m_log;
214         string m_policyId;
215         bool m_subjectMatch;
216         vector<string> m_attributeIds;
217         xstring m_format;
218         scoped_ptr<MetadataProvider> m_metadata;
219         scoped_ptr<TrustEngine> m_trust;
220         scoped_ptr<AttributeExtractor> m_extractor;
221         scoped_ptr<AttributeFilter> m_filter;
222         ptr_vector<saml2::Attribute> m_designators;
223         vector< pair<string,bool> > m_sources;
224         vector<string> m_exceptionId;
225     };
226
227     AttributeResolver* SHIBSP_DLLLOCAL SimpleAggregationResolverFactory(const DOMElement* const & e)
228     {
229         return new SimpleAggregationResolver(e);
230     }
231
232     static const XMLCh _AttributeExtractor[] =  UNICODE_LITERAL_18(A,t,t,r,i,b,u,t,e,E,x,t,r,a,c,t,o,r);
233     static const XMLCh _AttributeFilter[] =     UNICODE_LITERAL_15(A,t,t,r,i,b,u,t,e,F,i,l,t,e,r);
234     static const XMLCh attributeId[] =          UNICODE_LITERAL_11(a,t,t,r,i,b,u,t,e,I,d);
235     static const XMLCh Entity[] =               UNICODE_LITERAL_6(E,n,t,i,t,y);
236     static const XMLCh EntityReference[] =      UNICODE_LITERAL_15(E,n,t,i,t,y,R,e,f,e,r,e,n,c,e);
237     static const XMLCh exceptionId[] =          UNICODE_LITERAL_11(e,x,c,e,p,t,i,o,n,I,d);
238     static const XMLCh format[] =               UNICODE_LITERAL_6(f,o,r,m,a,t);
239     static const XMLCh _MetadataProvider[] =    UNICODE_LITERAL_16(M,e,t,a,d,a,t,a,P,r,o,v,i,d,e,r);
240     static const XMLCh policyId[] =             UNICODE_LITERAL_8(p,o,l,i,c,y,I,d);
241     static const XMLCh subjectMatch[] =         UNICODE_LITERAL_12(s,u,b,j,e,c,t,M,a,t,c,h);
242     static const XMLCh _TrustEngine[] =         UNICODE_LITERAL_11(T,r,u,s,t,E,n,g,i,n,e);
243     static const XMLCh _type[] =                UNICODE_LITERAL_4(t,y,p,e);
244 };
245
246 SimpleAggregationResolver::SimpleAggregationResolver(const DOMElement* e)
247     : m_log(Category::getInstance(SHIBSP_LOGCAT".AttributeResolver.SimpleAggregation")),
248         m_policyId(XMLHelper::getAttrString(e, nullptr, policyId)),
249         m_subjectMatch(XMLHelper::getAttrBool(e, false, subjectMatch))
250 {
251 #ifdef _DEBUG
252     xmltooling::NDC ndc("SimpleAggregationResolver");
253 #endif
254
255     const XMLCh* aid = e ? e->getAttributeNS(nullptr, attributeId) : nullptr;
256     if (aid && *aid) {
257         auto_ptr_char dup(aid);
258         string sdup(dup.get());
259         split(m_attributeIds, sdup, is_space(), algorithm::token_compress_on);
260
261         aid = e->getAttributeNS(nullptr, format);
262         if (aid && *aid)
263             m_format = aid;
264     }
265
266     string exid(XMLHelper::getAttrString(e, nullptr, exceptionId));
267     if (!exid.empty())
268         m_exceptionId.push_back(exid);
269
270     DOMElement* child = XMLHelper::getFirstChildElement(e, _MetadataProvider);
271     if (child) {
272         string t(XMLHelper::getAttrString(child, nullptr, _type));
273         if (t.empty())
274             throw ConfigurationException("MetadataProvider element missing type attribute.");
275         m_log.info("building MetadataProvider of type %s...", t.c_str());
276         m_metadata.reset(SAMLConfig::getConfig().MetadataProviderManager.newPlugin(t.c_str(), child));
277         m_metadata->init();
278     }
279
280     child = XMLHelper::getFirstChildElement(e,  _TrustEngine);
281     if (child) {
282         string t(XMLHelper::getAttrString(child, nullptr, _type));
283         if (t.empty())
284             throw ConfigurationException("TrustEngine element missing type attribute.");
285         m_log.info("building TrustEngine of type %s...", t.c_str());
286         m_trust.reset(XMLToolingConfig::getConfig().TrustEngineManager.newPlugin(t.c_str(), child));
287     }
288
289     child = XMLHelper::getFirstChildElement(e,  _AttributeExtractor);
290     if (child) {
291         string t(XMLHelper::getAttrString(child, nullptr, _type));
292         if (t.empty())
293             throw ConfigurationException("AttributeExtractor element missing type attribute.");
294         m_log.info("building AttributeExtractor of type %s...", t.c_str());
295         m_extractor.reset(SPConfig::getConfig().AttributeExtractorManager.newPlugin(t.c_str(), child));
296     }
297
298     child = XMLHelper::getFirstChildElement(e,  _AttributeFilter);
299     if (child) {
300         string t(XMLHelper::getAttrString(child, nullptr, _type));
301         if (t.empty())
302             throw ConfigurationException("AttributeFilter element missing type attribute.");
303         m_log.info("building AttributeFilter of type %s...", t.c_str());
304         m_filter.reset(SPConfig::getConfig().AttributeFilterManager.newPlugin(t.c_str(), child));
305     }
306
307     child = XMLHelper::getFirstChildElement(e);
308     while (child) {
309         if (child->hasChildNodes() && XMLString::equals(child->getLocalName(), Entity)) {
310             aid = child->getFirstChild()->getNodeValue();
311             if (aid && *aid) {
312                 auto_ptr_char taid(aid);
313                 m_sources.push_back(pair<string,bool>(taid.get(),true));
314             }
315         }
316         else if (child->hasChildNodes() && XMLString::equals(child->getLocalName(), EntityReference)) {
317             aid = child->getFirstChild()->getNodeValue();
318             if (aid && *aid) {
319                 auto_ptr_char taid(aid);
320                 m_sources.push_back(pair<string,bool>(taid.get(),false));
321             }
322         }
323         else if (XMLHelper::isNodeNamed(child, samlconstants::SAML20_NS, saml2::Attribute::LOCAL_NAME)) {
324             try {
325                 auto_ptr<XMLObject> obj(saml2::AttributeBuilder::buildOneFromElement(child));
326                 saml2::Attribute* down = dynamic_cast<saml2::Attribute*>(obj.get());
327                 if (down) {
328                     m_designators.push_back(down);
329                     obj.release();
330                 }
331             }
332             catch (std::exception& ex) {
333                 m_log.error("exception loading attribute designator: %s", ex.what());
334             }
335         }
336         child = XMLHelper::getNextSiblingElement(child);
337     }
338 }
339
340 void SimpleAggregationResolver::doQuery(SimpleAggregationContext& ctx, const char* entityID, const NameID* name) const
341 {
342 #ifdef _DEBUG
343     xmltooling::NDC ndc("doQuery");
344 #endif
345     const Application& application = ctx.getApplication();
346     MetadataProviderCriteria mc(application, entityID, &AttributeAuthorityDescriptor::ELEMENT_QNAME, samlconstants::SAML20P_NS);
347     Locker mlocker(m_metadata.get());
348     const AttributeAuthorityDescriptor* AA=nullptr;
349     pair<const EntityDescriptor*,const RoleDescriptor*> mdresult =
350         (m_metadata ? m_metadata.get() : application.getMetadataProvider())->getEntityDescriptor(mc);
351     if (!mdresult.first) {
352         m_log.warn("unable to locate metadata for provider (%s)", entityID);
353         return;
354     }
355     else if (!(AA=dynamic_cast<const AttributeAuthorityDescriptor*>(mdresult.second))) {
356         m_log.warn("no SAML 2 AttributeAuthority role found in metadata for (%s)", entityID);
357         return;
358     }
359
360     const PropertySet* relyingParty = application.getRelyingParty(mdresult.first);
361     pair<bool,bool> signedAssertions = relyingParty->getBool("requireSignedAssertions");
362     pair<bool,const char*> encryption = relyingParty->getString("encryption");
363
364     // Locate policy key.
365     const char* policyId = m_policyId.empty() ? application.getString("policyId").second : m_policyId.c_str();
366
367     // Set up policy and SOAP client.
368     scoped_ptr<SecurityPolicy> policy(
369         application.getServiceProvider().getSecurityPolicyProvider()->createSecurityPolicy(application, nullptr, policyId)
370         );
371     if (m_metadata)
372         policy->setMetadataProvider(m_metadata.get());
373     if (m_trust)
374         policy->setTrustEngine(m_trust.get());
375     policy->getAudiences().push_back(relyingParty->getXMLString("entityID").second);
376
377     MetadataCredentialCriteria mcc(*AA);
378     shibsp::SOAPClient soaper(*policy.get());
379
380     auto_ptr_XMLCh binding(samlconstants::SAML20_BINDING_SOAP);
381     auto_ptr<saml2p::StatusResponseType> srt;
382     const vector<AttributeService*>& endpoints=AA->getAttributeServices();
383     for (indirect_iterator<vector<AttributeService*>::const_iterator> ep = make_indirect_iterator(endpoints.begin());
384             !srt.get() && ep != make_indirect_iterator(endpoints.end()); ++ep) {
385         if (!XMLString::equals(ep->getBinding(), binding.get())  || !ep->getLocation())
386             continue;
387         auto_ptr_char loc(ep->getLocation());
388         try {
389             auto_ptr<saml2::Subject> subject(saml2::SubjectBuilder::buildSubject());
390
391             // Encrypt the NameID?
392             if (encryption.first && (!strcmp(encryption.second, "true") || !strcmp(encryption.second, "back"))) {
393                 auto_ptr<EncryptedID> encrypted(EncryptedIDBuilder::buildEncryptedID());
394                 encrypted->encrypt(
395                     *name,
396                     *(policy->getMetadataProvider()),
397                     mcc,
398                     false,
399                     relyingParty->getXMLString("encryptionAlg").second
400                     );
401                 subject->setEncryptedID(encrypted.get());
402                 encrypted.release();
403             }
404             else {
405                 subject->setNameID(name->cloneNameID());
406             }
407
408             saml2p::AttributeQuery* query = saml2p::AttributeQueryBuilder::buildAttributeQuery();
409             query->setSubject(subject.release());
410             Issuer* iss = IssuerBuilder::buildIssuer();
411             iss->setName(relyingParty->getXMLString("entityID").second);
412             query->setIssuer(iss);
413             for (ptr_vector<saml2::Attribute>::const_iterator ad = m_designators.begin(); ad != m_designators.end(); ++ad) {
414                 auto_ptr<saml2::Attribute> adwrapper(ad->cloneAttribute());
415                 query->getAttributes().push_back(adwrapper.get());
416                 adwrapper.release();
417             }
418
419             SAML2SOAPClient client(soaper, false);
420             client.sendSAML(query, application.getId(), mcc, loc.get());
421             srt.reset(client.receiveSAML());
422         }
423         catch (std::exception& ex) {
424             m_log.error("exception during SAML query to %s: %s", loc.get(), ex.what());
425             soaper.reset();
426         }
427     }
428
429     if (!srt.get()) {
430         m_log.error("unable to obtain a SAML response from attribute authority (%s)", entityID);
431         throw BindingException("Unable to obtain a SAML response from attribute authority.");
432     }
433
434     saml2p::Response* response = dynamic_cast<saml2p::Response*>(srt.get());
435     if (!response) {
436         m_log.error("message was not a samlp:Response");
437         throw FatalProfileException("Attribute authority returned an unrecognized message.");
438     }
439     else if (!response->getStatus() || !response->getStatus()->getStatusCode() ||
440             !XMLString::equals(response->getStatus()->getStatusCode()->getValue(), saml2p::StatusCode::SUCCESS)) {
441         m_log.error("attribute authority (%s) returned a SAML error", entityID);
442         throw FatalProfileException("Attribute authority returned a SAML error.");
443     }
444
445     saml2::Assertion* newtoken = nullptr;
446     auto_ptr<saml2::Assertion> newtokenwrapper;
447     const vector<saml2::Assertion*>& assertions = const_cast<const saml2p::Response*>(response)->getAssertions();
448     if (assertions.empty()) {
449         // Check for encryption.
450         const vector<saml2::EncryptedAssertion*>& encassertions =
451             const_cast<const saml2p::Response*>(response)->getEncryptedAssertions();
452         if (encassertions.empty()) {
453             m_log.warn("response from attribute authority was empty");
454             return;
455         }
456         else if (encassertions.size() > 1) {
457             m_log.warn("simple resolver only supports one assertion in the query response");
458         }
459
460         CredentialResolver* cr=application.getCredentialResolver();
461         if (!cr) {
462             m_log.warn("found encrypted assertion, but no CredentialResolver was available");
463             throw FatalProfileException("Assertion was encrypted, but no decryption credentials are available.");
464         }
465
466         // With this flag on, we block unauthenticated ciphertext when decrypting,
467         // unless the protocol was authenticated.
468         pair<bool,bool> authenticatedCipher = application.getBool("requireAuthenticatedEncryption");
469         if (policy->isAuthenticated())
470             authenticatedCipher.second = false;
471
472         // Attempt to decrypt it.
473         try {
474             Locker credlocker(cr);
475             auto_ptr<XMLObject> tokenwrapper(
476                 encassertions.front()->decrypt(
477                     *cr, relyingParty->getXMLString("entityID").second, &mcc, authenticatedCipher.first && authenticatedCipher.second
478                     )
479                 );
480             newtoken = dynamic_cast<saml2::Assertion*>(tokenwrapper.get());
481             if (newtoken) {
482                 tokenwrapper.release();
483                 newtokenwrapper.reset(newtoken);
484                 if (m_log.isDebugEnabled())
485                     m_log.debugStream() << "decrypted assertion: " << *newtoken << logging::eol;
486             }
487         }
488         catch (std::exception& ex) {
489             m_log.error("failed to decrypt assertion: %s", ex.what());
490             throw;
491         }
492     }
493     else {
494         if (assertions.size() > 1)
495             m_log.warn("simple resolver only supports one assertion in the query response");
496         newtoken = assertions.front();
497     }
498
499     if (!newtoken->getSignature() && signedAssertions.first && signedAssertions.second) {
500         m_log.error("assertion unsigned, rejecting it based on signedAssertions policy");
501         throw SecurityPolicyException("Rejected unsigned assertion based on local policy.");
502     }
503
504     try {
505         // We're going to insist that the assertion issuer is the same as the peer.
506         // Reset the policy's message bits and extract them from the assertion.
507         policy->reset(true);
508         policy->setMessageID(newtoken->getID());
509         policy->setIssueInstant(newtoken->getIssueInstantEpoch());
510         policy->setIssuer(newtoken->getIssuer());
511         policy->evaluate(*newtoken);
512
513         // Now we can check the security status of the policy.
514         if (!policy->isAuthenticated())
515             throw SecurityPolicyException("Security of SAML 2.0 query result not established.");
516
517         if (m_subjectMatch) {
518             // Check for subject match.
519             auto_ptr<NameID> nameIDwrapper;
520             NameID* respName = newtoken->getSubject() ? newtoken->getSubject()->getNameID() : nullptr;
521             if (!respName) {
522                 // Check for encryption.
523                 EncryptedID* encname = newtoken->getSubject() ? newtoken->getSubject()->getEncryptedID() : nullptr;
524                 if (encname) {
525                     CredentialResolver* cr=application.getCredentialResolver();
526                     if (!cr)
527                         m_log.warn("found EncryptedID, but no CredentialResolver was available");
528                     else {
529                         Locker credlocker(cr);
530                         auto_ptr<XMLObject> decryptedID(encname->decrypt(*cr, relyingParty->getXMLString("entityID").second, &mcc));
531                         respName = dynamic_cast<NameID*>(decryptedID.get());
532                         if (respName) {
533                             decryptedID.release();
534                             nameIDwrapper.reset(respName);
535                             if (m_log.isDebugEnabled())
536                                 m_log.debugStream() << "decrypted NameID: " << *respName << logging::eol;
537                         }
538                     }
539                 }
540             }
541
542             if (!respName || !XMLString::equals(respName->getName(), name->getName()) ||
543                 !XMLString::equals(respName->getFormat(), name->getFormat()) ||
544                 !XMLString::equals(respName->getNameQualifier(), name->getNameQualifier()) ||
545                 !XMLString::equals(respName->getSPNameQualifier(), name->getSPNameQualifier())) {
546                 if (respName)
547                     m_log.warnStream() << "ignoring Assertion without strongly matching NameID in Subject: " <<
548                         *respName << logging::eol;
549                 else
550                     m_log.warn("ignoring Assertion without NameID in Subject");
551                 return;
552             }
553         }
554     }
555     catch (std::exception& ex) {
556         m_log.error("assertion failed policy validation: %s", ex.what());
557         throw;
558     }
559
560     // If the token's embedded, detach it.
561     if (!newtokenwrapper.get()) {
562         newtoken->detach();
563         srt.release();  // detach blows away the Response, so avoid a double free
564         newtokenwrapper.reset(newtoken);
565     }
566     ctx.getResolvedAssertions().push_back(newtoken);
567     newtokenwrapper.release();
568
569     // Finally, extract and filter the result.
570     try {
571         AttributeExtractor* extractor = m_extractor ? m_extractor.get() : application.getAttributeExtractor();
572         if (extractor) {
573             Locker extlocker(extractor);
574             extractor->extractAttributes(application, ctx.getRequest(), AA, *newtoken, ctx.getResolvedAttributes());
575         }
576
577         AttributeFilter* filter = m_filter ? m_filter.get() : application.getAttributeFilter();
578         if (filter) {
579             BasicFilteringContext fc(application, ctx.getResolvedAttributes(), AA, ctx.getClassRef(), ctx.getDeclRef());
580             Locker filtlocker(filter);
581             filter->filterAttributes(fc, ctx.getResolvedAttributes());
582         }
583     }
584     catch (std::exception& ex) {
585         m_log.error("caught exception extracting/filtering attributes from query result: %s", ex.what());
586         for_each(ctx.getResolvedAttributes().begin(), ctx.getResolvedAttributes().end(), xmltooling::cleanup<shibsp::Attribute>());
587         ctx.getResolvedAttributes().clear();
588         throw;
589     }
590 }
591
592 void SimpleAggregationResolver::resolveAttributes(ResolutionContext& ctx) const
593 {
594 #ifdef _DEBUG
595     xmltooling::NDC ndc("resolveAttributes");
596 #endif
597
598     SimpleAggregationContext& qctx = dynamic_cast<SimpleAggregationContext&>(ctx);
599
600     // First we manufacture the appropriate NameID to use.
601     scoped_ptr<NameID> n;
602     for (vector<string>::const_iterator a = m_attributeIds.begin(); !n.get() && a != m_attributeIds.end(); ++a) {
603         const Attribute* attr=nullptr;
604         if (qctx.getSession()) {
605             // Input attributes should be available via multimap.
606             pair<multimap<string,const Attribute*>::const_iterator, multimap<string,const Attribute*>::const_iterator> range =
607                 qctx.getSession()->getIndexedAttributes().equal_range(*a);
608             for (; !attr && range.first != range.second; ++range.first) {
609                 if (range.first->second->valueCount() > 0)
610                     attr = range.first->second;
611             }
612         }
613         else if (qctx.getInputAttributes()) {
614             // Have to loop over unindexed set.
615             const vector<Attribute*>* matches = qctx.getInputAttributes();
616             for (indirect_iterator<vector<Attribute*>::const_iterator> match = make_indirect_iterator(matches->begin());
617                     !attr && match != make_indirect_iterator(matches->end()); ++match) {
618                 if (*a == match->getId() && match->valueCount() > 0)
619                     attr = &(*match);
620             }
621         }
622
623         if (attr) {
624             m_log.debug("using input attribute (%s) as identifier for queries", attr->getId());
625             n.reset(NameIDBuilder::buildNameID());
626             const NameIDAttribute* down = dynamic_cast<const NameIDAttribute*>(attr);
627             if (down) {
628                 // We can create a NameID directly from the source material.
629                 const NameIDAttribute::Value& v = down->getValues().front();
630                 auto_arrayptr<XMLCh> val(fromUTF8(v.m_Name.c_str()));
631                 n->setName(val.get());
632
633                 if (!v.m_Format.empty()) {
634                     auto_arrayptr<XMLCh> format(fromUTF8(v.m_Format.c_str()));
635                     n->setFormat(format.get());
636                 }
637                 if (!v.m_NameQualifier.empty()) {
638                     auto_arrayptr<XMLCh> nq(fromUTF8(v.m_NameQualifier.c_str()));
639                     n->setNameQualifier(nq.get());
640                 }
641                 if (!v.m_SPNameQualifier.empty()) {
642                     auto_arrayptr<XMLCh> spnq(fromUTF8(v.m_SPNameQualifier.c_str()));
643                     n->setSPNameQualifier(spnq.get());
644                 }
645                 if (!v.m_SPProvidedID.empty()) {
646                     auto_arrayptr<XMLCh> sppid(fromUTF8(v.m_SPProvidedID.c_str()));
647                     n->setSPProvidedID(sppid.get());
648                 }
649             }
650             else {
651                 // We have to mock up the NameID.
652                 auto_arrayptr<XMLCh> val(fromUTF8(attr->getSerializedValues().front().c_str()));
653                 n->setName(val.get());
654                 if (!m_format.empty())
655                     n->setFormat(m_format.c_str());
656             }
657         }
658     }
659
660     if (!n) {
661         if (qctx.getNameID() && m_attributeIds.empty()) {
662             m_log.debug("using authenticated NameID as identifier for queries");
663         }
664         else {
665             m_log.warn("unable to resolve attributes, no suitable query identifier found");
666             return;
667         }
668     }
669
670     set<string> history;
671
672     // Put initial IdP into history to prevent extra query.
673     if (qctx.getEntityID())
674         history.insert(qctx.getEntityID());
675
676     // Prepare to track exceptions.
677     auto_ptr<SimpleAttribute> exceptAttr;
678     if (!m_exceptionId.empty())
679         exceptAttr.reset(new SimpleAttribute(m_exceptionId));
680
681     // We have a master loop over all the possible sources of material.
682     for (vector< pair<string,bool> >::const_iterator source = m_sources.begin(); source != m_sources.end(); ++source) {
683         if (source->second) {
684             // A literal entityID to query.
685             if (history.count(source->first) == 0) {
686                 m_log.debug("issuing SAML query to (%s)", source->first.c_str());
687                 try {
688                     doQuery(qctx, source->first.c_str(), n ? n.get() : qctx.getNameID());
689                 }
690                 catch (std::exception& ex) {
691                     if (exceptAttr.get())
692                         exceptAttr->getValues().push_back(XMLToolingConfig::getConfig().getURLEncoder()->encode(ex.what()));
693                 }
694                 history.insert(source->first);
695             }
696             else {
697                 m_log.debug("skipping previously queried attribute source (%s)", source->first.c_str());
698             }
699         }
700         else {
701             m_log.debug("using attribute sources referenced in attribute (%s)", source->first.c_str());
702             if (qctx.getSession()) {
703                 // Input attributes should be available via multimap.
704                 pair<multimap<string,const Attribute*>::const_iterator, multimap<string,const Attribute*>::const_iterator> range =
705                     qctx.getSession()->getIndexedAttributes().equal_range(source->first);
706                 for (; range.first != range.second; ++range.first) {
707                     const vector<string>& links = range.first->second->getSerializedValues();
708                     for (vector<string>::const_iterator link = links.begin(); link != links.end(); ++link) {
709                         if (history.count(*link) == 0) {
710                             m_log.debug("issuing SAML query to (%s)", link->c_str());
711                             try {
712                                 doQuery(qctx, link->c_str(), n ? n.get() : qctx.getNameID());
713                             }
714                             catch (std::exception& ex) {
715                                 if (exceptAttr.get())
716                                     exceptAttr->getValues().push_back(XMLToolingConfig::getConfig().getURLEncoder()->encode(ex.what()));
717                             }
718                             history.insert(*link);
719                         }
720                         else {
721                             m_log.debug("skipping previously queried attribute source (%s)", link->c_str());
722                         }
723                     }
724                 }
725             }
726             else if (qctx.getInputAttributes()) {
727                 // Have to loop over unindexed set.
728                 const vector<Attribute*>* matches = qctx.getInputAttributes();
729                 for (indirect_iterator<vector<Attribute*>::const_iterator> match = make_indirect_iterator(matches->begin());
730                         match != make_indirect_iterator(matches->end()); ++match) {
731                     if (source->first == match->getId()) {
732                         const vector<string>& links = match->getSerializedValues();
733                         for (vector<string>::const_iterator link = links.begin(); link != links.end(); ++link) {
734                             if (history.count(*link) == 0) {
735                                 m_log.debug("issuing SAML query to (%s)", link->c_str());
736                                 try {
737                                     doQuery(qctx, link->c_str(), n ? n.get() : qctx.getNameID());
738                                 }
739                                 catch (std::exception& ex) {
740                                     if (exceptAttr.get())
741                                         exceptAttr->getValues().push_back(XMLToolingConfig::getConfig().getURLEncoder()->encode(ex.what()));
742                                 }
743                                 history.insert(*link);
744                             }
745                             else {
746                                 m_log.debug("skipping previously queried attribute source (%s)", link->c_str());
747                             }
748                         }
749                     }
750                 }
751             }
752         }
753     }
754
755     if (exceptAttr.get()) {
756         qctx.getResolvedAttributes().push_back(exceptAttr.get());
757         exceptAttr.release();
758     }
759 }