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