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