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