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