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 "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"
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>
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;
62 class SHIBSP_DLLLOCAL SimpleAggregationContext : public ResolutionContext
65 SimpleAggregationContext(const Application& application, const Session& session)
69 m_class(XMLString::transcode(session.getAuthnContextClassRef())),
70 m_decl(XMLString::transcode(session.getAuthnContextDeclRef())),
72 m_inputAttributes(NULL) {
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),
85 m_class(const_cast<XMLCh*>(authncontext_class)),
86 m_decl(const_cast<XMLCh*>(authncontext_decl)),
87 m_inputTokens(tokens),
88 m_inputAttributes(attributes) {
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>());
95 XMLString::release(&m_class);
96 XMLString::release(&m_decl);
100 const Application& getApplication() const {
103 const NameID* getNameID() const {
104 return m_session ? m_session->getNameID() : m_nameid;
106 const XMLCh* getClassRef() const {
109 const XMLCh* getDeclRef() const {
112 const Session* getSession() const {
115 const vector<shibsp::Attribute*>* getInputAttributes() const {
116 return m_inputAttributes;
118 const vector<const opensaml::Assertion*>* getInputTokens() const {
119 return m_inputTokens;
121 vector<shibsp::Attribute*>& getResolvedAttributes() {
124 vector<opensaml::Assertion*>& getResolvedAssertions() {
129 const Application& m_app;
130 const Session* m_session;
131 const NameID* m_nameid;
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;
140 class SHIBSP_DLLLOCAL SimpleAggregationResolver : public AttributeResolver
143 SimpleAggregationResolver(const DOMElement* e);
144 ~SimpleAggregationResolver() {
147 for_each(m_designators.begin(), m_designators.end(), xmltooling::cleanup<saml2::Attribute>());
150 Lockable* lock() {return this;}
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
163 return new SimpleAggregationContext(application,nameid,authncontext_class,authncontext_decl,tokens,attributes);
166 ResolutionContext* createResolutionContext(const Application& application, const Session& session) const {
167 return new SimpleAggregationContext(application,session);
170 void resolveAttributes(ResolutionContext& ctx) const;
172 void getAttributeIds(vector<string>& attributes) const {
173 // Nothing to do, only the extractor would actually generate them.
177 bool doQuery(SimpleAggregationContext& ctx, const char* entityID, const NameID* name) const;
181 vector<string> m_attributeIds;
183 MetadataProvider* m_metadata;
184 TrustEngine* m_trust;
185 vector<saml2::Attribute*> m_designators;
186 vector< pair<string,bool> > m_sources;
189 AttributeResolver* SHIBSP_DLLLOCAL SimpleAggregationResolverFactory(const DOMElement* const & e)
191 return new SimpleAggregationResolver(e);
194 static const XMLCh attributeId[] = UNICODE_LITERAL_11(a,t,t,r,i,b,u,t,e,I,d);
195 static const XMLCh Entity[] = UNICODE_LITERAL_6(E,n,t,i,t,y);
196 static const XMLCh EntityReference[] = UNICODE_LITERAL_15(E,n,t,i,t,y,R,e,f,e,r,e,n,c,e);
197 static const XMLCh format[] = UNICODE_LITERAL_6(f,o,r,m,a,t);
198 static const XMLCh _MetadataProvider[] = UNICODE_LITERAL_16(M,e,t,a,d,a,t,a,P,r,o,v,i,d,e,r);
199 static const XMLCh policyId[] = UNICODE_LITERAL_8(p,o,l,i,c,y,I,d);
200 static const XMLCh _TrustEngine[] = UNICODE_LITERAL_11(T,r,u,s,t,E,n,g,i,n,e);
201 static const XMLCh _type[] = UNICODE_LITERAL_4(t,y,p,e);
204 SimpleAggregationResolver::SimpleAggregationResolver(const DOMElement* e)
205 : m_log(Category::getInstance(SHIBSP_LOGCAT".AttributeResolver.SimpleAggregation")), m_metadata(NULL), m_trust(NULL)
208 xmltooling::NDC ndc("SimpleAggregationResolver");
211 const XMLCh* pid = e ? e->getAttributeNS(NULL, policyId) : NULL;
213 auto_ptr_char temp(pid);
214 m_policyId = temp.get();
217 pid = e ? e->getAttributeNS(NULL, attributeId) : NULL;
219 char* dup = XMLString::transcode(pid);
222 while (start && *start) {
223 while (*start && isspace(*start))
227 pos = strchr(start,' ');
230 m_attributeIds.push_back(start);
231 start = pos ? pos+1 : NULL;
233 XMLString::release(&dup);
235 pid = e->getAttributeNS(NULL, format);
241 DOMElement* child = XMLHelper::getFirstChildElement(e, _MetadataProvider);
243 auto_ptr_char type(child->getAttributeNS(NULL, _type));
244 if (!type.get() || !*type.get())
245 throw ConfigurationException("MetadataProvider element missing type attribute.");
246 m_log.info("building MetadataProvider of type %s...", type.get());
247 auto_ptr<MetadataProvider> mp(SAMLConfig::getConfig().MetadataProviderManager.newPlugin(type.get(), child));
249 m_metadata = mp.release();
252 child = XMLHelper::getFirstChildElement(e, _TrustEngine);
255 auto_ptr_char type(child->getAttributeNS(NULL, _type));
256 if (!type.get() || !*type.get())
257 throw ConfigurationException("TrustEngine element missing type attribute.");
258 m_log.info("building TrustEngine of type %s...", type.get());
259 m_trust = XMLToolingConfig::getConfig().TrustEngineManager.newPlugin(type.get(), child);
267 child = XMLHelper::getFirstChildElement(e);
269 if (child->hasChildNodes() && XMLString::equals(child->getLocalName(), Entity)) {
270 pid = child->getFirstChild()->getNodeValue();
272 auto_ptr_char tpid(pid);
273 m_sources.push_back(pair<string,bool>(tpid.get(),true));
276 else if (child->hasChildNodes() && XMLString::equals(child->getLocalName(), EntityReference)) {
277 pid = child->getFirstChild()->getNodeValue();
279 auto_ptr_char tpid(pid);
280 m_sources.push_back(pair<string,bool>(tpid.get(),false));
283 else if (XMLHelper::isNodeNamed(child, samlconstants::SAML20_NS, saml2::Attribute::LOCAL_NAME)) {
285 auto_ptr<XMLObject> obj(saml2::AttributeBuilder::buildOneFromElement(child));
286 saml2::Attribute* down = dynamic_cast<saml2::Attribute*>(obj.get());
288 m_designators.push_back(down);
292 catch (exception& ex) {
293 m_log.error("exception loading attribute designator: %s", ex.what());
296 child = XMLHelper::getNextSiblingElement(child);
301 bool SimpleAggregationResolver::doQuery(SimpleAggregationContext& ctx, const char* entityID, const NameID* name) const
304 xmltooling::NDC ndc("doQuery");
306 const Application& application = ctx.getApplication();
307 MetadataProviderCriteria mc(application, entityID, &AttributeAuthorityDescriptor::ELEMENT_QNAME, samlconstants::SAML20P_NS);
308 Locker mlocker(m_metadata);
309 const AttributeAuthorityDescriptor* AA=NULL;
310 pair<const EntityDescriptor*,const RoleDescriptor*> mdresult =
311 (m_metadata ? m_metadata : application.getMetadataProvider())->getEntityDescriptor(mc);
312 if (!mdresult.first) {
313 m_log.warn("unable to locate metadata for provider (%s)", entityID);
316 else if (!(AA=dynamic_cast<const AttributeAuthorityDescriptor*>(mdresult.second))) {
317 m_log.warn("no SAML 2 AttributeAuthority role found in metadata for (%s)", entityID);
321 const PropertySet* relyingParty = application.getRelyingParty(mdresult.first);
323 // Locate policy key.
324 const char* policyId = m_policyId.empty() ? application.getString("policyId").second : m_policyId.c_str();
326 // Access policy properties.
327 const PropertySet* settings = application.getServiceProvider().getPolicySettings(policyId);
328 pair<bool,bool> validate = settings->getBool("validate");
330 pair<bool,bool> signedAssertions = relyingParty->getBool("requireSignedAssertions");
331 pair<bool,const char*> encryption = relyingParty->getString("encryption");
333 shibsp::SecurityPolicy policy(application, NULL, validate.first && validate.second, policyId);
335 policy.setMetadataProvider(m_metadata);
337 policy.setTrustEngine(m_trust);
338 policy.getAudiences().push_back(relyingParty->getXMLString("entityID").second);
340 MetadataCredentialCriteria mcc(*AA);
341 shibsp::SOAPClient soaper(policy);
343 auto_ptr_XMLCh binding(samlconstants::SAML20_BINDING_SOAP);
344 saml2p::StatusResponseType* srt=NULL;
345 const vector<AttributeService*>& endpoints=AA->getAttributeServices();
346 for (vector<AttributeService*>::const_iterator ep=endpoints.begin(); !srt && ep!=endpoints.end(); ++ep) {
347 if (!XMLString::equals((*ep)->getBinding(),binding.get()) || !(*ep)->getLocation())
349 auto_ptr_char loc((*ep)->getLocation());
351 auto_ptr<saml2::Subject> subject(saml2::SubjectBuilder::buildSubject());
353 // Encrypt the NameID?
354 if (encryption.first && (!strcmp(encryption.second, "true") || !strcmp(encryption.second, "back"))) {
355 auto_ptr<EncryptedID> encrypted(EncryptedIDBuilder::buildEncryptedID());
356 MetadataCredentialCriteria mcc(*AA);
359 *(policy.getMetadataProvider()),
362 relyingParty->getXMLString("encryptionAlg").second
364 subject->setEncryptedID(encrypted.release());
367 subject->setNameID(name->cloneNameID());
370 saml2p::AttributeQuery* query = saml2p::AttributeQueryBuilder::buildAttributeQuery();
371 query->setSubject(subject.release());
372 Issuer* iss = IssuerBuilder::buildIssuer();
373 iss->setName(relyingParty->getXMLString("entityID").second);
374 query->setIssuer(iss);
375 for (vector<saml2::Attribute*>::const_iterator ad = m_designators.begin(); ad!=m_designators.end(); ++ad)
376 query->getAttributes().push_back((*ad)->cloneAttribute());
378 SAML2SOAPClient client(soaper, false);
379 client.sendSAML(query, application.getId(), mcc, loc.get());
380 srt = client.receiveSAML();
382 catch (exception& ex) {
383 m_log.error("exception during SAML query to %s: %s", loc.get(), ex.what());
389 m_log.error("unable to obtain a SAML response from attribute authority (%s)", entityID);
392 saml2p::Response* response = dynamic_cast<saml2p::Response*>(srt);
395 m_log.error("message was not a samlp:Response");
398 else if (!response->getStatus() || !response->getStatus()->getStatusCode() ||
399 !XMLString::equals(response->getStatus()->getStatusCode()->getValue(), saml2p::StatusCode::SUCCESS)) {
401 m_log.error("attribute authority (%s) returned a SAML error", entityID);
405 const vector<saml2::Assertion*>& assertions = const_cast<const saml2p::Response*>(response)->getAssertions();
406 if (assertions.empty()) {
408 m_log.warn("response from attribute authority (%s) was empty", entityID);
411 else if (assertions.size()>1)
412 m_log.warn("resolver only supports one assertion in the query response");
414 auto_ptr<saml2p::StatusResponseType> wrapper(srt);
415 saml2::Assertion* newtoken = assertions.front();
417 if (!newtoken->getSignature() && signedAssertions.first && signedAssertions.second) {
418 m_log.error("assertion unsigned, rejecting it based on signedAssertions policy");
423 // We're going to insist that the assertion issuer is the same as the peer.
424 // Reset the policy's message bits and extract them from the assertion.
426 policy.setMessageID(newtoken->getID());
427 policy.setIssueInstant(newtoken->getIssueInstantEpoch());
428 policy.setIssuer(newtoken->getIssuer());
429 policy.evaluate(*newtoken);
431 // Now we can check the security status of the policy.
432 if (!policy.isAuthenticated())
433 throw SecurityPolicyException("Security of SAML 2.0 query result not established.");
435 catch (exception& ex) {
436 m_log.error("assertion failed policy validation: %s", ex.what());
442 ctx.getResolvedAssertions().push_back(newtoken);
444 // Finally, extract and filter the result.
446 AttributeExtractor* extractor = application.getAttributeExtractor();
448 Locker extlocker(extractor);
449 extractor->extractAttributes(application, AA, *newtoken, ctx.getResolvedAttributes());
452 AttributeFilter* filter = application.getAttributeFilter();
454 BasicFilteringContext fc(application, ctx.getResolvedAttributes(), AA, ctx.getClassRef(), ctx.getDeclRef());
455 Locker filtlocker(filter);
456 filter->filterAttributes(fc, ctx.getResolvedAttributes());
459 catch (exception& ex) {
460 m_log.error("caught exception extracting/filtering attributes from query result: %s", ex.what());
461 for_each(ctx.getResolvedAttributes().begin(), ctx.getResolvedAttributes().end(), xmltooling::cleanup<shibsp::Attribute>());
462 ctx.getResolvedAttributes().clear();
468 void SimpleAggregationResolver::resolveAttributes(ResolutionContext& ctx) const
471 xmltooling::NDC ndc("resolveAttributes");
474 SimpleAggregationContext& qctx = dynamic_cast<SimpleAggregationContext&>(ctx);
476 // First we manufacture the appropriate NameID to use.
478 for (vector<string>::const_iterator a = m_attributeIds.begin(); !n && a != m_attributeIds.end(); ++a) {
479 const Attribute* attr=NULL;
480 if (qctx.getSession()) {
481 // Input attributes should be available via multimap.
482 pair<multimap<string,const Attribute*>::const_iterator, multimap<string,const Attribute*>::const_iterator> range =
483 qctx.getSession()->getIndexedAttributes().equal_range(*a);
484 for (; !attr && range.first != range.second; ++range.first) {
485 if (range.first->second->valueCount() > 0)
486 attr = range.first->second;
489 else if (qctx.getInputAttributes()) {
490 // Have to loop over unindexed set.
491 const vector<Attribute*>* matches = qctx.getInputAttributes();
492 for (vector<Attribute*>::const_iterator match = matches->begin(); !attr && match != matches->end(); ++match) {
493 if (*a == (*match)->getId() && (*match)->valueCount() > 0)
499 m_log.debug("using input attribute (%s) as identifier for queries", attr->getId());
500 n = NameIDBuilder::buildNameID();
501 const NameIDAttribute* down = dynamic_cast<const NameIDAttribute*>(attr);
503 // We can create a NameID directly from the source material.
504 const NameIDAttribute::Value& v = down->getValues().front();
505 XMLCh* val = fromUTF8(v.m_Name.c_str());
508 if (!v.m_Format.empty()) {
509 val = fromUTF8(v.m_Format.c_str());
513 if (!v.m_NameQualifier.empty()) {
514 val = fromUTF8(v.m_NameQualifier.c_str());
515 n->setNameQualifier(val);
518 if (!v.m_SPNameQualifier.empty()) {
519 val = fromUTF8(v.m_SPNameQualifier.c_str());
520 n->setSPNameQualifier(val);
523 if (!v.m_SPProvidedID.empty()) {
524 val = fromUTF8(v.m_SPProvidedID.c_str());
525 n->setSPProvidedID(val);
530 // We have to mock up the NameID.
531 XMLCh* val = fromUTF8(attr->getSerializedValues().front().c_str());
534 if (!m_format.empty())
535 n->setFormat(m_format.c_str());
541 if (qctx.getNameID() && m_attributeIds.empty()) {
542 m_log.debug("using authenticated NameID as identifier for queries");
545 m_log.warn("unable to resolve attributes, no suitable query identifier found");
550 auto_ptr<NameID> wrapper(n);
554 // We have a master loop over all the possible sources of material.
555 for (vector< pair<string,bool> >::const_iterator source = m_sources.begin(); source != m_sources.end(); ++source) {
556 if (source->second) {
557 // A literal entityID to query.
558 if (history.count(source->first) == 0) {
559 m_log.debug("issuing SAML query to (%s)", source->first.c_str());
560 doQuery(qctx, source->first.c_str(), n ? n : qctx.getNameID());
561 history.insert(source->first);
564 m_log.debug("skipping previously queried attribute source (%s)", source->first.c_str());
568 m_log.debug("using attribute sources referenced in attribute (%s)", source->first.c_str());
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(source->first);
573 for (; range.first != range.second; ++range.first) {
574 const vector<string>& links = range.first->second->getSerializedValues();
575 for (vector<string>::const_iterator link = links.begin(); link != links.end(); ++link) {
576 if (history.count(*link) == 0) {
577 m_log.debug("issuing SAML query to (%s)", link->c_str());
578 doQuery(qctx, link->c_str(), n ? n : qctx.getNameID());
579 history.insert(*link);
582 m_log.debug("skipping previously queried attribute source (%s)", link->c_str());
587 else if (qctx.getInputAttributes()) {
588 // Have to loop over unindexed set.
589 const vector<Attribute*>* matches = qctx.getInputAttributes();
590 for (vector<Attribute*>::const_iterator match = matches->begin(); match != matches->end(); ++match) {
591 if (source->first == (*match)->getId()) {
592 const vector<string>& links = (*match)->getSerializedValues();
593 for (vector<string>::const_iterator link = links.begin(); link != links.end(); ++link) {
594 if (history.count(*link) == 0) {
595 m_log.debug("issuing SAML query to (%s)", link->c_str());
596 doQuery(qctx, link->c_str(), n ? n : qctx.getNameID());
597 history.insert(*link);
600 m_log.debug("skipping previously queried attribute source (%s)", link->c_str());