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/XMLToolingConfig.h>
44 #include <xmltooling/util/NDC.h>
45 #include <xmltooling/util/XMLHelper.h>
46 #include <xercesc/util/XMLUniDefs.hpp>
48 using namespace shibsp;
49 using namespace opensaml::saml2;
50 using namespace opensaml::saml2p;
51 using namespace opensaml::saml2md;
52 using namespace opensaml;
53 using namespace xmltooling;
58 class SHIBSP_DLLLOCAL SimpleAggregationContext : public ResolutionContext
61 SimpleAggregationContext(const Application& application, const Session& session)
65 m_class(XMLString::transcode(session.getAuthnContextClassRef())),
66 m_decl(XMLString::transcode(session.getAuthnContextDeclRef())),
68 m_inputAttributes(NULL) {
71 SimpleAggregationContext(
72 const Application& application,
73 const NameID* nameid=NULL,
74 const XMLCh* authncontext_class=NULL,
75 const XMLCh* authncontext_decl=NULL,
76 const vector<const opensaml::Assertion*>* tokens=NULL,
77 const vector<shibsp::Attribute*>* attributes=NULL
78 ) : m_app(application),
81 m_class(const_cast<XMLCh*>(authncontext_class)),
82 m_decl(const_cast<XMLCh*>(authncontext_decl)),
83 m_inputTokens(tokens),
84 m_inputAttributes(attributes) {
87 ~SimpleAggregationContext() {
88 for_each(m_attributes.begin(), m_attributes.end(), xmltooling::cleanup<shibsp::Attribute>());
89 for_each(m_assertions.begin(), m_assertions.end(), xmltooling::cleanup<opensaml::Assertion>());
91 XMLString::release(&m_class);
92 XMLString::release(&m_decl);
96 const Application& getApplication() const {
99 const NameID* getNameID() const {
100 return m_session ? m_session->getNameID() : m_nameid;
102 const XMLCh* getClassRef() const {
105 const XMLCh* getDeclRef() const {
108 const Session* getSession() const {
111 const vector<shibsp::Attribute*>* getInputAttributes() const {
112 return m_inputAttributes;
114 const vector<const opensaml::Assertion*>* getInputTokens() const {
115 return m_inputTokens;
117 vector<shibsp::Attribute*>& getResolvedAttributes() {
120 vector<opensaml::Assertion*>& getResolvedAssertions() {
125 const Application& m_app;
126 const Session* m_session;
127 const NameID* m_nameid;
130 const vector<const opensaml::Assertion*>* m_inputTokens;
131 const vector<shibsp::Attribute*>* m_inputAttributes;
132 vector<shibsp::Attribute*> m_attributes;
133 vector<opensaml::Assertion*> m_assertions;
136 class SHIBSP_DLLLOCAL SimpleAggregationResolver : public AttributeResolver
139 SimpleAggregationResolver(const DOMElement* e);
140 ~SimpleAggregationResolver() {
143 for_each(m_designators.begin(), m_designators.end(), xmltooling::cleanup<saml2::Attribute>());
146 Lockable* lock() {return this;}
149 ResolutionContext* createResolutionContext(
150 const Application& application,
151 const EntityDescriptor* issuer,
152 const XMLCh* protocol,
153 const NameID* nameid=NULL,
154 const XMLCh* authncontext_class=NULL,
155 const XMLCh* authncontext_decl=NULL,
156 const vector<const opensaml::Assertion*>* tokens=NULL,
157 const vector<shibsp::Attribute*>* attributes=NULL
159 return new SimpleAggregationContext(application,nameid,authncontext_class,authncontext_decl,tokens,attributes);
162 ResolutionContext* createResolutionContext(const Application& application, const Session& session) const {
163 return new SimpleAggregationContext(application,session);
166 void resolveAttributes(ResolutionContext& ctx) const;
168 void getAttributeIds(vector<string>& attributes) const {
169 // Nothing to do, only the extractor would actually generate them.
173 bool doQuery(SimpleAggregationContext& ctx, const char* entityID, const NameID* name) const;
177 vector<string> m_attributeIds;
179 MetadataProvider* m_metadata;
180 TrustEngine* m_trust;
181 vector<saml2::Attribute*> m_designators;
182 vector< pair<string,bool> > m_sources;
185 AttributeResolver* SHIBSP_DLLLOCAL SimpleAggregationResolverFactory(const DOMElement* const & e)
187 return new SimpleAggregationResolver(e);
190 static const XMLCh attributeId[] = UNICODE_LITERAL_11(a,t,t,r,i,b,u,t,e,I,d);
191 static const XMLCh Entity[] = UNICODE_LITERAL_6(E,n,t,i,t,y);
192 static const XMLCh EntityReference[] = UNICODE_LITERAL_15(E,n,t,i,t,y,R,e,f,e,r,e,n,c,e);
193 static const XMLCh format[] = UNICODE_LITERAL_6(f,o,r,m,a,t);
194 static const XMLCh _MetadataProvider[] = UNICODE_LITERAL_16(M,e,t,a,d,a,t,a,P,r,o,v,i,d,e,r);
195 static const XMLCh policyId[] = UNICODE_LITERAL_8(p,o,l,i,c,y,I,d);
196 static const XMLCh _TrustEngine[] = UNICODE_LITERAL_11(T,r,u,s,t,E,n,g,i,n,e);
197 static const XMLCh _type[] = UNICODE_LITERAL_4(t,y,p,e);
200 SimpleAggregationResolver::SimpleAggregationResolver(const DOMElement* e)
201 : m_log(Category::getInstance(SHIBSP_LOGCAT".AttributeResolver.SimpleAggregation")), m_metadata(NULL), m_trust(NULL)
204 xmltooling::NDC ndc("SimpleAggregationResolver");
207 const XMLCh* pid = e ? e->getAttributeNS(NULL, policyId) : NULL;
209 auto_ptr_char temp(pid);
210 m_policyId = temp.get();
213 pid = e ? e->getAttributeNS(NULL, attributeId) : NULL;
215 char* dup = XMLString::transcode(pid);
218 while (start && *start) {
219 while (*start && isspace(*start))
223 pos = strchr(start,' ');
226 m_attributeIds.push_back(start);
227 start = pos ? pos+1 : NULL;
229 XMLString::release(&dup);
231 pid = e->getAttributeNS(NULL, format);
237 DOMElement* child = XMLHelper::getFirstChildElement(e, _MetadataProvider);
239 auto_ptr_char type(child->getAttributeNS(NULL, _type));
240 if (!type.get() || !*type.get())
241 throw ConfigurationException("MetadataProvider element missing type attribute.");
242 m_log.info("building MetadataProvider of type %s...", type.get());
243 auto_ptr<MetadataProvider> mp(SAMLConfig::getConfig().MetadataProviderManager.newPlugin(type.get(), child));
245 m_metadata = mp.release();
248 child = XMLHelper::getFirstChildElement(e, _TrustEngine);
251 auto_ptr_char type(child->getAttributeNS(NULL, _type));
252 if (!type.get() || !*type.get())
253 throw ConfigurationException("TrustEngine element missing type attribute.");
254 m_log.info("building TrustEngine of type %s...", type.get());
255 m_trust = XMLToolingConfig::getConfig().TrustEngineManager.newPlugin(type.get(), child);
263 child = XMLHelper::getFirstChildElement(e);
265 if (child->hasChildNodes() && XMLString::equals(child->getLocalName(), Entity)) {
266 pid = child->getFirstChild()->getNodeValue();
268 auto_ptr_char tpid(pid);
269 m_sources.push_back(pair<string,bool>(tpid.get(),true));
272 else if (child->hasChildNodes() && XMLString::equals(child->getLocalName(), EntityReference)) {
273 pid = child->getFirstChild()->getNodeValue();
275 auto_ptr_char tpid(pid);
276 m_sources.push_back(pair<string,bool>(tpid.get(),false));
279 else if (XMLHelper::isNodeNamed(child, samlconstants::SAML20_NS, saml2::Attribute::LOCAL_NAME)) {
281 auto_ptr<XMLObject> obj(saml2::AttributeBuilder::buildOneFromElement(child));
282 saml2::Attribute* down = dynamic_cast<saml2::Attribute*>(obj.get());
284 m_designators.push_back(down);
288 catch (exception& ex) {
289 m_log.error("exception loading attribute designator: %s", ex.what());
292 child = XMLHelper::getNextSiblingElement(child);
297 bool SimpleAggregationResolver::doQuery(SimpleAggregationContext& ctx, const char* entityID, const NameID* name) const
300 xmltooling::NDC ndc("doQuery");
302 const Application& application = ctx.getApplication();
303 MetadataProviderCriteria mc(application, entityID, &AttributeAuthorityDescriptor::ELEMENT_QNAME, samlconstants::SAML20P_NS);
304 Locker mlocker(m_metadata);
305 const AttributeAuthorityDescriptor* AA=NULL;
306 pair<const EntityDescriptor*,const RoleDescriptor*> mdresult =
307 (m_metadata ? m_metadata : application.getMetadataProvider())->getEntityDescriptor(mc);
308 if (!mdresult.first) {
309 m_log.warn("unable to locate metadata for provider (%s)", entityID);
312 else if (!(AA=dynamic_cast<const AttributeAuthorityDescriptor*>(mdresult.second))) {
313 m_log.warn("no SAML 2 AttributeAuthority role found in metadata for (%s)", entityID);
317 const PropertySet* relyingParty = application.getRelyingParty(mdresult.first);
319 // Locate policy key.
320 const char* policyId = m_policyId.empty() ? application.getString("policyId").second : m_policyId.c_str();
322 // Access policy properties.
323 const PropertySet* settings = application.getServiceProvider().getPolicySettings(policyId);
324 pair<bool,bool> validate = settings->getBool("validate");
326 pair<bool,bool> signedAssertions = relyingParty->getBool("requireSignedAssertions");
327 pair<bool,const char*> encryption = relyingParty->getString("encryption");
329 shibsp::SecurityPolicy policy(application, NULL, validate.first && validate.second, policyId);
331 policy.setMetadataProvider(m_metadata);
333 policy.setTrustEngine(m_trust);
334 policy.getAudiences().push_back(relyingParty->getXMLString("entityID").second);
336 MetadataCredentialCriteria mcc(*AA);
337 shibsp::SOAPClient soaper(policy);
339 auto_ptr_XMLCh binding(samlconstants::SAML20_BINDING_SOAP);
340 saml2p::StatusResponseType* srt=NULL;
341 const vector<AttributeService*>& endpoints=AA->getAttributeServices();
342 for (vector<AttributeService*>::const_iterator ep=endpoints.begin(); !srt && ep!=endpoints.end(); ++ep) {
343 if (!XMLString::equals((*ep)->getBinding(),binding.get()) || !(*ep)->getLocation())
345 auto_ptr_char loc((*ep)->getLocation());
347 auto_ptr<saml2::Subject> subject(saml2::SubjectBuilder::buildSubject());
349 // Encrypt the NameID?
350 if (encryption.first && (!strcmp(encryption.second, "true") || !strcmp(encryption.second, "back"))) {
351 auto_ptr<EncryptedID> encrypted(EncryptedIDBuilder::buildEncryptedID());
352 MetadataCredentialCriteria mcc(*AA);
355 *(policy.getMetadataProvider()),
358 relyingParty->getXMLString("encryptionAlg").second
360 subject->setEncryptedID(encrypted.release());
363 subject->setNameID(name->cloneNameID());
366 saml2p::AttributeQuery* query = saml2p::AttributeQueryBuilder::buildAttributeQuery();
367 query->setSubject(subject.release());
368 Issuer* iss = IssuerBuilder::buildIssuer();
369 iss->setName(relyingParty->getXMLString("entityID").second);
370 query->setIssuer(iss);
371 for (vector<saml2::Attribute*>::const_iterator ad = m_designators.begin(); ad!=m_designators.end(); ++ad)
372 query->getAttributes().push_back((*ad)->cloneAttribute());
374 SAML2SOAPClient client(soaper, false);
375 client.sendSAML(query, application.getId(), mcc, loc.get());
376 srt = client.receiveSAML();
378 catch (exception& ex) {
379 m_log.error("exception during SAML query to %s: %s", loc.get(), ex.what());
385 m_log.error("unable to obtain a SAML response from attribute authority (%s)", entityID);
388 saml2p::Response* response = dynamic_cast<saml2p::Response*>(srt);
391 m_log.error("message was not a samlp:Response");
394 else if (!response->getStatus() || !response->getStatus()->getStatusCode() ||
395 !XMLString::equals(response->getStatus()->getStatusCode()->getValue(), saml2p::StatusCode::SUCCESS)) {
397 m_log.error("attribute authority (%s) returned a SAML error", entityID);
401 const vector<saml2::Assertion*>& assertions = const_cast<const saml2p::Response*>(response)->getAssertions();
402 if (assertions.empty()) {
404 m_log.warn("response from attribute authority (%s) was empty", entityID);
407 else if (assertions.size()>1)
408 m_log.warn("resolver only supports one assertion in the query response");
410 auto_ptr<saml2p::StatusResponseType> wrapper(srt);
411 saml2::Assertion* newtoken = assertions.front();
413 if (!newtoken->getSignature() && signedAssertions.first && signedAssertions.second) {
414 m_log.error("assertion unsigned, rejecting it based on signedAssertions policy");
419 // We're going to insist that the assertion issuer is the same as the peer.
420 // Reset the policy's message bits and extract them from the assertion.
422 policy.setMessageID(newtoken->getID());
423 policy.setIssueInstant(newtoken->getIssueInstantEpoch());
424 policy.setIssuer(newtoken->getIssuer());
425 policy.evaluate(*newtoken);
427 // Now we can check the security status of the policy.
428 if (!policy.isAuthenticated())
429 throw SecurityPolicyException("Security of SAML 2.0 query result not established.");
431 catch (exception& ex) {
432 m_log.error("assertion failed policy validation: %s", ex.what());
438 ctx.getResolvedAssertions().push_back(newtoken);
440 // Finally, extract and filter the result.
442 AttributeExtractor* extractor = application.getAttributeExtractor();
444 Locker extlocker(extractor);
445 extractor->extractAttributes(application, AA, *newtoken, ctx.getResolvedAttributes());
448 AttributeFilter* filter = application.getAttributeFilter();
450 BasicFilteringContext fc(application, ctx.getResolvedAttributes(), AA, ctx.getClassRef(), ctx.getDeclRef());
451 Locker filtlocker(filter);
452 filter->filterAttributes(fc, ctx.getResolvedAttributes());
455 catch (exception& ex) {
456 m_log.error("caught exception extracting/filtering attributes from query result: %s", ex.what());
457 for_each(ctx.getResolvedAttributes().begin(), ctx.getResolvedAttributes().end(), xmltooling::cleanup<shibsp::Attribute>());
458 ctx.getResolvedAttributes().clear();
464 void SimpleAggregationResolver::resolveAttributes(ResolutionContext& ctx) const
467 xmltooling::NDC ndc("resolveAttributes");
470 SimpleAggregationContext& qctx = dynamic_cast<SimpleAggregationContext&>(ctx);
472 // First we manufacture the appropriate NameID to use.
474 for (vector<string>::const_iterator a = m_attributeIds.begin(); !n && a != m_attributeIds.end(); ++a) {
475 const Attribute* attr=NULL;
476 if (qctx.getSession()) {
477 // Input attributes should be available via multimap.
478 pair<multimap<string,const Attribute*>::const_iterator, multimap<string,const Attribute*>::const_iterator> range =
479 qctx.getSession()->getIndexedAttributes().equal_range(*a);
480 for (; !attr && range.first != range.second; ++range.first) {
481 if (range.first->second->valueCount() > 0)
482 attr = range.first->second;
485 else if (qctx.getInputAttributes()) {
486 // Have to loop over unindexed set.
487 const vector<Attribute*>* matches = qctx.getInputAttributes();
488 for (vector<Attribute*>::const_iterator match = matches->begin(); !attr && match != matches->end(); ++match) {
489 if (*a == (*match)->getId() && (*match)->valueCount() > 0)
495 m_log.debug("using input attribute (%s) as identifier for queries", attr->getId());
496 n = NameIDBuilder::buildNameID();
497 const NameIDAttribute* down = dynamic_cast<const NameIDAttribute*>(attr);
499 // We can create a NameID directly from the source material.
500 const NameIDAttribute::Value& v = down->getValues().front();
501 XMLCh* val = fromUTF8(v.m_Name.c_str());
504 if (!v.m_Format.empty()) {
505 val = fromUTF8(v.m_Format.c_str());
509 if (!v.m_NameQualifier.empty()) {
510 val = fromUTF8(v.m_NameQualifier.c_str());
511 n->setNameQualifier(val);
514 if (!v.m_SPNameQualifier.empty()) {
515 val = fromUTF8(v.m_SPNameQualifier.c_str());
516 n->setSPNameQualifier(val);
519 if (!v.m_SPProvidedID.empty()) {
520 val = fromUTF8(v.m_SPProvidedID.c_str());
521 n->setSPProvidedID(val);
526 // We have to mock up the NameID.
527 XMLCh* val = fromUTF8(attr->getSerializedValues().front().c_str());
530 if (!m_format.empty())
531 n->setFormat(m_format.c_str());
537 if (qctx.getNameID() && m_attributeIds.empty()) {
538 m_log.debug("using authenticated NameID as identifier for queries");
541 m_log.warn("unable to resolve attributes, no suitable query identifier found");
546 auto_ptr<NameID> wrapper(n);
550 // We have a master loop over all the possible sources of material.
551 for (vector< pair<string,bool> >::const_iterator source = m_sources.begin(); source != m_sources.end(); ++source) {
552 if (source->second) {
553 // A literal entityID to query.
554 if (history.count(source->first) == 0) {
555 m_log.debug("issuing SAML query to (%s)", source->first.c_str());
556 doQuery(qctx, source->first.c_str(), n ? n : qctx.getNameID());
557 history.insert(source->first);
560 m_log.debug("skipping previously queried attribute source (%s)", source->first.c_str());
564 m_log.debug("using attribute sources referenced in attribute (%s)", source->first.c_str());
565 if (qctx.getSession()) {
566 // Input attributes should be available via multimap.
567 pair<multimap<string,const Attribute*>::const_iterator, multimap<string,const Attribute*>::const_iterator> range =
568 qctx.getSession()->getIndexedAttributes().equal_range(source->first);
569 for (; range.first != range.second; ++range.first) {
570 const vector<string>& links = range.first->second->getSerializedValues();
571 for (vector<string>::const_iterator link = links.begin(); link != links.end(); ++link) {
572 if (history.count(*link) == 0) {
573 m_log.debug("issuing SAML query to (%s)", link->c_str());
574 doQuery(qctx, link->c_str(), n ? n : qctx.getNameID());
575 history.insert(*link);
578 m_log.debug("skipping previously queried attribute source (%s)", link->c_str());
583 else if (qctx.getInputAttributes()) {
584 // Have to loop over unindexed set.
585 const vector<Attribute*>* matches = qctx.getInputAttributes();
586 for (vector<Attribute*>::const_iterator match = matches->begin(); match != matches->end(); ++match) {
587 if (source->first == (*match)->getId()) {
588 const vector<string>& links = (*match)->getSerializedValues();
589 for (vector<string>::const_iterator link = links.begin(); link != links.end(); ++link) {
590 if (history.count(*link) == 0) {
591 m_log.debug("issuing SAML query to (%s)", link->c_str());
592 doQuery(qctx, link->c_str(), n ? n : qctx.getNameID());
593 history.insert(*link);
596 m_log.debug("skipping previously queried attribute source (%s)", link->c_str());