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