2 * Copyright 2009 Internet2
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
18 * SimpleAggregationAttributeResolver.cpp
20 * AttributeResolver based on SAML queries to third-party AA sources.
24 #include "Application.h"
25 #include "ServiceProvider.h"
26 #include "SessionCache.h"
27 #include "attribute/NameIDAttribute.h"
28 #include "attribute/filtering/AttributeFilter.h"
29 #include "attribute/filtering/BasicFilteringContext.h"
30 #include "attribute/resolver/AttributeExtractor.h"
31 #include "attribute/resolver/AttributeResolver.h"
32 #include "attribute/resolver/ResolutionContext.h"
33 #include "binding/SOAPClient.h"
34 #include "metadata/MetadataProviderCriteria.h"
35 #include "util/SPConstants.h"
37 #include <saml/exceptions.h>
38 #include <saml/SAMLConfig.h>
39 #include <saml/binding/SecurityPolicy.h>
40 #include <saml/saml2/binding/SAML2SOAPClient.h>
41 #include <saml/saml2/core/Protocols.h>
42 #include <saml/saml2/metadata/MetadataProvider.h>
43 #include <xmltooling/util/NDC.h>
44 #include <xmltooling/util/XMLHelper.h>
45 #include <xercesc/util/XMLUniDefs.hpp>
47 using namespace shibsp;
48 using namespace opensaml::saml2;
49 using namespace opensaml::saml2p;
50 using namespace opensaml::saml2md;
51 using namespace opensaml;
52 using namespace xmltooling;
57 class SHIBSP_DLLLOCAL SimpleAggregationContext : public ResolutionContext
60 SimpleAggregationContext(const Application& application, const Session& session)
64 m_class(XMLString::transcode(session.getAuthnContextClassRef())),
65 m_decl(XMLString::transcode(session.getAuthnContextDeclRef())),
67 m_inputAttributes(NULL) {
70 SimpleAggregationContext(
71 const Application& application,
72 const NameID* nameid=NULL,
73 const XMLCh* authncontext_class=NULL,
74 const XMLCh* authncontext_decl=NULL,
75 const vector<const opensaml::Assertion*>* tokens=NULL,
76 const vector<shibsp::Attribute*>* attributes=NULL
77 ) : m_app(application),
80 m_class(const_cast<XMLCh*>(authncontext_class)),
81 m_decl(const_cast<XMLCh*>(authncontext_decl)),
82 m_inputTokens(tokens),
83 m_inputAttributes(attributes) {
86 ~SimpleAggregationContext() {
87 for_each(m_attributes.begin(), m_attributes.end(), xmltooling::cleanup<shibsp::Attribute>());
88 for_each(m_assertions.begin(), m_assertions.end(), xmltooling::cleanup<opensaml::Assertion>());
90 XMLString::release(&m_class);
91 XMLString::release(&m_decl);
95 const Application& getApplication() const {
98 const NameID* getNameID() const {
99 return m_session ? m_session->getNameID() : m_nameid;
101 const XMLCh* getClassRef() const {
104 const XMLCh* getDeclRef() const {
107 const Session* getSession() const {
110 const vector<shibsp::Attribute*>* getInputAttributes() const {
111 return m_inputAttributes;
113 const vector<const opensaml::Assertion*>* getInputTokens() const {
114 return m_inputTokens;
116 vector<shibsp::Attribute*>& getResolvedAttributes() {
119 vector<opensaml::Assertion*>& getResolvedAssertions() {
124 const Application& m_app;
125 const Session* m_session;
126 const NameID* m_nameid;
129 const vector<const opensaml::Assertion*>* m_inputTokens;
130 const vector<shibsp::Attribute*>* m_inputAttributes;
131 vector<shibsp::Attribute*> m_attributes;
132 vector<opensaml::Assertion*> m_assertions;
135 class SHIBSP_DLLLOCAL SimpleAggregationResolver : public AttributeResolver
138 SimpleAggregationResolver(const DOMElement* e);
139 ~SimpleAggregationResolver() {
142 for_each(m_designators.begin(), m_designators.end(), xmltooling::cleanup<saml2::Attribute>());
145 Lockable* lock() {return this;}
148 ResolutionContext* createResolutionContext(
149 const Application& application,
150 const EntityDescriptor* issuer,
151 const XMLCh* protocol,
152 const NameID* nameid=NULL,
153 const XMLCh* authncontext_class=NULL,
154 const XMLCh* authncontext_decl=NULL,
155 const vector<const opensaml::Assertion*>* tokens=NULL,
156 const vector<shibsp::Attribute*>* attributes=NULL
158 return new SimpleAggregationContext(application,nameid,authncontext_class,authncontext_decl,tokens,attributes);
161 ResolutionContext* createResolutionContext(const Application& application, const Session& session) const {
162 return new SimpleAggregationContext(application,session);
165 void resolveAttributes(ResolutionContext& ctx) const;
167 void getAttributeIds(vector<string>& attributes) const {
168 // Nothing to do, only the extractor would actually generate them.
172 bool doQuery(SimpleAggregationContext& ctx, const char* entityID, const NameID* name) const;
176 vector<string> m_attributeIds;
178 MetadataProvider* m_metadata;
179 TrustEngine* m_trust;
180 vector<saml2::Attribute*> m_designators;
181 vector< pair<string,bool> > m_sources;
184 AttributeResolver* SHIBSP_DLLLOCAL SimpleAggregationResolverFactory(const DOMElement* const & e)
186 return new SimpleAggregationResolver(e);
189 static const XMLCh attributeId[] = UNICODE_LITERAL_11(a,t,t,r,i,b,u,t,e,I,d);
190 static const XMLCh Entity[] = UNICODE_LITERAL_6(E,n,t,i,t,y);
191 static const XMLCh EntityReference[] = UNICODE_LITERAL_15(E,n,t,i,t,y,R,e,f,e,r,e,n,c,e);
192 static const XMLCh format[] = UNICODE_LITERAL_6(f,o,r,m,a,t);
193 static const XMLCh _MetadataProvider[] = UNICODE_LITERAL_16(M,e,t,a,d,a,t,a,P,r,o,v,i,d,e,r);
194 static const XMLCh policyId[] = UNICODE_LITERAL_8(p,o,l,i,c,y,I,d);
195 static const XMLCh _TrustEngine[] = UNICODE_LITERAL_11(T,r,u,s,t,E,n,g,i,n,e);
196 static const XMLCh _type[] = UNICODE_LITERAL_4(t,y,p,e);
199 SimpleAggregationResolver::SimpleAggregationResolver(const DOMElement* e)
200 : m_log(Category::getInstance(SHIBSP_LOGCAT".AttributeResolver.SimpleAggregation")), m_metadata(NULL), m_trust(NULL)
203 xmltooling::NDC ndc("SimpleAggregationResolver");
206 const XMLCh* pid = e ? e->getAttributeNS(NULL, policyId) : NULL;
208 auto_ptr_char temp(pid);
209 m_policyId = temp.get();
212 pid = e ? e->getAttributeNS(NULL, attributeId) : NULL;
214 char* dup = XMLString::transcode(pid);
217 while (start && *start) {
218 while (*start && isspace(*start))
222 pos = strchr(start,' ');
225 m_attributeIds.push_back(start);
226 start = pos ? pos+1 : NULL;
228 XMLString::release(&dup);
230 pid = e->getAttributeNS(NULL, format);
236 DOMElement* child = XMLHelper::getFirstChildElement(e, _MetadataProvider);
238 auto_ptr_char type(child->getAttributeNS(NULL, _type));
239 if (!type.get() || !*type.get())
240 throw ConfigurationException("MetadataProvider element missing type attribute.");
241 m_log.info("building MetadataProvider of type %s...", type.get());
242 auto_ptr<MetadataProvider> mp(SAMLConfig::getConfig().MetadataProviderManager.newPlugin(type.get(), child));
244 m_metadata = mp.release();
247 child = XMLHelper::getFirstChildElement(e, _TrustEngine);
250 auto_ptr_char type(child->getAttributeNS(NULL, _type));
251 if (!type.get() || !*type.get())
252 throw ConfigurationException("TrustEngine element missing type attribute.");
253 m_log.info("building TrustEngine of type %s...", type.get());
254 m_trust = XMLToolingConfig::getConfig().TrustEngineManager.newPlugin(type.get(), child);
262 child = XMLHelper::getFirstChildElement(e);
264 if (child->hasChildNodes() && XMLString::equals(child->getLocalName(), Entity)) {
265 pid = child->getFirstChild()->getNodeValue();
267 auto_ptr_char tpid(pid);
268 m_sources.push_back(pair<string,bool>(tpid.get(),true));
271 else if (child->hasChildNodes() && XMLString::equals(child->getLocalName(), EntityReference)) {
272 pid = child->getFirstChild()->getNodeValue();
274 auto_ptr_char tpid(pid);
275 m_sources.push_back(pair<string,bool>(tpid.get(),false));
278 else if (XMLHelper::isNodeNamed(child, samlconstants::SAML20_NS, saml2::Attribute::LOCAL_NAME)) {
280 auto_ptr<XMLObject> obj(saml2::AttributeBuilder::buildOneFromElement(child));
281 saml2::Attribute* down = dynamic_cast<saml2::Attribute*>(obj.get());
283 m_designators.push_back(down);
287 catch (exception& ex) {
288 m_log.error("exception loading attribute designator: %s", ex.what());
291 child = XMLHelper::getNextSiblingElement(child);
296 bool SimpleAggregationResolver::doQuery(SimpleAggregationContext& ctx, const char* entityID, const NameID* name) const
299 xmltooling::NDC ndc("doQuery");
301 const Application& application = ctx.getApplication();
302 MetadataProviderCriteria mc(application, entityID, &AttributeAuthorityDescriptor::ELEMENT_QNAME, samlconstants::SAML20P_NS);
303 Locker mlocker(m_metadata);
304 const AttributeAuthorityDescriptor* AA=NULL;
305 pair<const EntityDescriptor*,const RoleDescriptor*> mdresult =
306 (m_metadata ? m_metadata : application.getMetadataProvider())->getEntityDescriptor(mc);
307 if (!mdresult.first) {
308 m_log.warn("unable to locate metadata for provider (%s)", entityID);
311 else if (!(AA=dynamic_cast<const AttributeAuthorityDescriptor*>(mdresult.second))) {
312 m_log.warn("no SAML 2 AttributeAuthority role found in metadata for (%s)", entityID);
316 const PropertySet* relyingParty = application.getRelyingParty(mdresult.first);
318 // Locate policy key.
319 const char* policyId = m_policyId.empty() ? application.getString("policyId").second : m_policyId.c_str();
321 // Access policy properties.
322 const PropertySet* settings = application.getServiceProvider().getPolicySettings(policyId);
323 pair<bool,bool> validate = settings->getBool("validate");
325 pair<bool,bool> signedAssertions = relyingParty->getBool("requireSignedAssertions");
326 pair<bool,const char*> encryption = relyingParty->getString("encryption");
328 shibsp::SecurityPolicy policy(application, NULL, validate.first && validate.second, policyId);
330 policy.setMetadataProvider(m_metadata);
332 policy.setTrustEngine(m_trust);
333 policy.getAudiences().push_back(relyingParty->getXMLString("entityID").second);
335 MetadataCredentialCriteria mcc(*AA);
336 shibsp::SOAPClient soaper(policy);
338 auto_ptr_XMLCh binding(samlconstants::SAML20_BINDING_SOAP);
339 saml2p::StatusResponseType* srt=NULL;
340 const vector<AttributeService*>& endpoints=AA->getAttributeServices();
341 for (vector<AttributeService*>::const_iterator ep=endpoints.begin(); !srt && ep!=endpoints.end(); ++ep) {
342 if (!XMLString::equals((*ep)->getBinding(),binding.get()) || !(*ep)->getLocation())
344 auto_ptr_char loc((*ep)->getLocation());
346 auto_ptr<saml2::Subject> subject(saml2::SubjectBuilder::buildSubject());
348 // Encrypt the NameID?
349 if (encryption.first && (!strcmp(encryption.second, "true") || !strcmp(encryption.second, "back"))) {
350 auto_ptr<EncryptedID> encrypted(EncryptedIDBuilder::buildEncryptedID());
351 MetadataCredentialCriteria mcc(*AA);
354 *(policy.getMetadataProvider()),
357 relyingParty->getXMLString("encryptionAlg").second
359 subject->setEncryptedID(encrypted.release());
362 subject->setNameID(name->cloneNameID());
365 saml2p::AttributeQuery* query = saml2p::AttributeQueryBuilder::buildAttributeQuery();
366 query->setSubject(subject.release());
367 Issuer* iss = IssuerBuilder::buildIssuer();
368 iss->setName(relyingParty->getXMLString("entityID").second);
369 query->setIssuer(iss);
370 for (vector<saml2::Attribute*>::const_iterator ad = m_designators.begin(); ad!=m_designators.end(); ++ad)
371 query->getAttributes().push_back((*ad)->cloneAttribute());
373 SAML2SOAPClient client(soaper, false);
374 client.sendSAML(query, application.getId(), mcc, loc.get());
375 srt = client.receiveSAML();
377 catch (exception& ex) {
378 m_log.error("exception during SAML query to %s: %s", loc.get(), ex.what());
384 m_log.error("unable to obtain a SAML response from attribute authority (%s)", entityID);
387 saml2p::Response* response = dynamic_cast<saml2p::Response*>(srt);
390 m_log.error("message was not a samlp:Response");
393 else if (!response->getStatus() || !response->getStatus()->getStatusCode() ||
394 !XMLString::equals(response->getStatus()->getStatusCode()->getValue(), saml2p::StatusCode::SUCCESS)) {
396 m_log.error("attribute authority (%s) returned a SAML error", entityID);
400 const vector<saml2::Assertion*>& assertions = const_cast<const saml2p::Response*>(response)->getAssertions();
401 if (assertions.empty()) {
403 m_log.warn("response from attribute authority (%s) was empty", entityID);
406 else if (assertions.size()>1)
407 m_log.warn("resolver only supports one assertion in the query response");
409 auto_ptr<saml2p::StatusResponseType> wrapper(srt);
410 saml2::Assertion* newtoken = assertions.front();
412 if (!newtoken->getSignature() && signedAssertions.first && signedAssertions.second) {
413 m_log.error("assertion unsigned, rejecting it based on signedAssertions policy");
418 // We're going to insist that the assertion issuer is the same as the peer.
419 // Reset the policy's message bits and extract them from the assertion.
421 policy.setMessageID(newtoken->getID());
422 policy.setIssueInstant(newtoken->getIssueInstantEpoch());
423 policy.setIssuer(newtoken->getIssuer());
424 policy.evaluate(*newtoken);
426 // Now we can check the security status of the policy.
427 if (!policy.isAuthenticated())
428 throw SecurityPolicyException("Security of SAML 2.0 query result not established.");
430 catch (exception& ex) {
431 m_log.error("assertion failed policy validation: %s", ex.what());
437 ctx.getResolvedAssertions().push_back(newtoken);
439 // Finally, extract and filter the result.
441 AttributeExtractor* extractor = application.getAttributeExtractor();
443 Locker extlocker(extractor);
444 extractor->extractAttributes(application, AA, *newtoken, ctx.getResolvedAttributes());
447 AttributeFilter* filter = application.getAttributeFilter();
449 BasicFilteringContext fc(application, ctx.getResolvedAttributes(), AA, ctx.getClassRef(), ctx.getDeclRef());
450 Locker filtlocker(filter);
451 filter->filterAttributes(fc, ctx.getResolvedAttributes());
454 catch (exception& ex) {
455 m_log.error("caught exception extracting/filtering attributes from query result: %s", ex.what());
456 for_each(ctx.getResolvedAttributes().begin(), ctx.getResolvedAttributes().end(), xmltooling::cleanup<shibsp::Attribute>());
457 ctx.getResolvedAttributes().clear();
463 void SimpleAggregationResolver::resolveAttributes(ResolutionContext& ctx) const
466 xmltooling::NDC ndc("resolveAttributes");
469 SimpleAggregationContext& qctx = dynamic_cast<SimpleAggregationContext&>(ctx);
471 // First we manufacture the appropriate NameID to use.
473 for (vector<string>::const_iterator a = m_attributeIds.begin(); !n && a != m_attributeIds.end(); ++a) {
474 const Attribute* attr=NULL;
475 if (qctx.getSession()) {
476 // Input attributes should be available via multimap.
477 pair<multimap<string,const Attribute*>::const_iterator, multimap<string,const Attribute*>::const_iterator> range =
478 qctx.getSession()->getIndexedAttributes().equal_range(*a);
479 for (; !attr && range.first != range.second; ++range.first) {
480 if (range.first->second->valueCount() > 0)
481 attr = range.first->second;
484 else if (qctx.getInputAttributes()) {
485 // Have to loop over unindexed set.
486 const vector<Attribute*>* matches = qctx.getInputAttributes();
487 for (vector<Attribute*>::const_iterator match = matches->begin(); !attr && match != matches->end(); ++match) {
488 if (*a == (*match)->getId() && (*match)->valueCount() > 0)
494 m_log.debug("using input attribute (%s) as identifier for queries", attr->getId());
495 n = NameIDBuilder::buildNameID();
496 const NameIDAttribute* down = dynamic_cast<const NameIDAttribute*>(attr);
498 // We can create a NameID directly from the source material.
499 const NameIDAttribute::Value& v = down->getValues().front();
500 XMLCh* val = fromUTF8(v.m_Name.c_str());
503 if (!v.m_Format.empty()) {
504 val = fromUTF8(v.m_Format.c_str());
508 if (!v.m_NameQualifier.empty()) {
509 val = fromUTF8(v.m_NameQualifier.c_str());
510 n->setNameQualifier(val);
513 if (!v.m_SPNameQualifier.empty()) {
514 val = fromUTF8(v.m_SPNameQualifier.c_str());
515 n->setSPNameQualifier(val);
518 if (!v.m_SPProvidedID.empty()) {
519 val = fromUTF8(v.m_SPProvidedID.c_str());
520 n->setSPProvidedID(val);
525 // We have to mock up the NameID.
526 XMLCh* val = fromUTF8(attr->getSerializedValues().front().c_str());
529 if (!m_format.empty())
530 n->setFormat(m_format.c_str());
536 if (qctx.getNameID() && m_attributeIds.empty()) {
537 m_log.debug("using authenticated NameID as identifier for queries");
540 m_log.warn("unable to resolve attributes, no suitable query identifier found");
545 auto_ptr<NameID> wrapper(n);
549 // We have a master loop over all the possible sources of material.
550 for (vector< pair<string,bool> >::const_iterator source = m_sources.begin(); source != m_sources.end(); ++source) {
551 if (source->second) {
552 // A literal entityID to query.
553 if (history.count(source->first) == 0) {
554 m_log.debug("issuing SAML query to (%s)", source->first.c_str());
555 doQuery(qctx, source->first.c_str(), n ? n : qctx.getNameID());
556 history.insert(source->first);
559 m_log.debug("skipping previously queried attribute source (%s)", source->first.c_str());
563 m_log.debug("using attribute sources referenced in attribute (%s)", source->first.c_str());
564 if (qctx.getSession()) {
565 // Input attributes should be available via multimap.
566 pair<multimap<string,const Attribute*>::const_iterator, multimap<string,const Attribute*>::const_iterator> range =
567 qctx.getSession()->getIndexedAttributes().equal_range(source->first);
568 for (; range.first != range.second; ++range.first) {
569 const vector<string>& links = range.first->second->getSerializedValues();
570 for (vector<string>::const_iterator link = links.begin(); link != links.end(); ++link) {
571 if (history.count(*link) == 0) {
572 m_log.debug("issuing SAML query to (%s)", link->c_str());
573 doQuery(qctx, link->c_str(), n ? n : qctx.getNameID());
574 history.insert(*link);
577 m_log.debug("skipping previously queried attribute source (%s)", link->c_str());
582 else if (qctx.getInputAttributes()) {
583 // Have to loop over unindexed set.
584 const vector<Attribute*>* matches = qctx.getInputAttributes();
585 for (vector<Attribute*>::const_iterator match = matches->begin(); match != matches->end(); ++match) {
586 if (source->first == (*match)->getId()) {
587 const vector<string>& links = (*match)->getSerializedValues();
588 for (vector<string>::const_iterator link = links.begin(); link != links.end(); ++link) {
589 if (history.count(*link) == 0) {
590 m_log.debug("issuing SAML query to (%s)", link->c_str());
591 doQuery(qctx, link->c_str(), n ? n : qctx.getNameID());
592 history.insert(*link);
595 m_log.debug("skipping previously queried attribute source (%s)", link->c_str());