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/MetadataProvider.h>
45 #include <xmltooling/XMLToolingConfig.h>
46 #include <xmltooling/security/TrustEngine.h>
47 #include <xmltooling/util/NDC.h>
48 #include <xmltooling/util/XMLHelper.h>
49 #include <xercesc/util/XMLUniDefs.hpp>
51 using namespace shibsp;
52 using namespace opensaml::saml2;
53 using namespace opensaml::saml2p;
54 using namespace opensaml::saml2md;
55 using namespace opensaml;
56 using namespace xmltooling;
61 class SHIBSP_DLLLOCAL SimpleAggregationContext : public ResolutionContext
64 SimpleAggregationContext(const Application& application, const Session& session)
68 m_class(XMLString::transcode(session.getAuthnContextClassRef())),
69 m_decl(XMLString::transcode(session.getAuthnContextDeclRef())),
71 m_inputAttributes(NULL) {
74 SimpleAggregationContext(
75 const Application& application,
76 const NameID* nameid=NULL,
77 const XMLCh* authncontext_class=NULL,
78 const XMLCh* authncontext_decl=NULL,
79 const vector<const opensaml::Assertion*>* tokens=NULL,
80 const vector<shibsp::Attribute*>* attributes=NULL
81 ) : m_app(application),
84 m_class(const_cast<XMLCh*>(authncontext_class)),
85 m_decl(const_cast<XMLCh*>(authncontext_decl)),
86 m_inputTokens(tokens),
87 m_inputAttributes(attributes) {
90 ~SimpleAggregationContext() {
91 for_each(m_attributes.begin(), m_attributes.end(), xmltooling::cleanup<shibsp::Attribute>());
92 for_each(m_assertions.begin(), m_assertions.end(), xmltooling::cleanup<opensaml::Assertion>());
94 XMLString::release(&m_class);
95 XMLString::release(&m_decl);
99 const Application& getApplication() const {
102 const NameID* getNameID() const {
103 return m_session ? m_session->getNameID() : m_nameid;
105 const XMLCh* getClassRef() const {
108 const XMLCh* getDeclRef() const {
111 const Session* getSession() const {
114 const vector<shibsp::Attribute*>* getInputAttributes() const {
115 return m_inputAttributes;
117 const vector<const opensaml::Assertion*>* getInputTokens() const {
118 return m_inputTokens;
120 vector<shibsp::Attribute*>& getResolvedAttributes() {
123 vector<opensaml::Assertion*>& getResolvedAssertions() {
128 const Application& m_app;
129 const Session* m_session;
130 const NameID* m_nameid;
133 const vector<const opensaml::Assertion*>* m_inputTokens;
134 const vector<shibsp::Attribute*>* m_inputAttributes;
135 vector<shibsp::Attribute*> m_attributes;
136 vector<opensaml::Assertion*> m_assertions;
139 class SHIBSP_DLLLOCAL SimpleAggregationResolver : public AttributeResolver
142 SimpleAggregationResolver(const DOMElement* e);
143 ~SimpleAggregationResolver() {
146 for_each(m_designators.begin(), m_designators.end(), xmltooling::cleanup<saml2::Attribute>());
149 Lockable* lock() {return this;}
152 ResolutionContext* createResolutionContext(
153 const Application& application,
154 const EntityDescriptor* issuer,
155 const XMLCh* protocol,
156 const NameID* nameid=NULL,
157 const XMLCh* authncontext_class=NULL,
158 const XMLCh* authncontext_decl=NULL,
159 const vector<const opensaml::Assertion*>* tokens=NULL,
160 const vector<shibsp::Attribute*>* attributes=NULL
162 return new SimpleAggregationContext(application,nameid,authncontext_class,authncontext_decl,tokens,attributes);
165 ResolutionContext* createResolutionContext(const Application& application, const Session& session) const {
166 return new SimpleAggregationContext(application,session);
169 void resolveAttributes(ResolutionContext& ctx) const;
171 void getAttributeIds(vector<string>& attributes) const {
172 // Nothing to do, only the extractor would actually generate them.
176 bool doQuery(SimpleAggregationContext& ctx, const char* entityID, const NameID* name) const;
180 vector<string> m_attributeIds;
182 MetadataProvider* m_metadata;
183 TrustEngine* m_trust;
184 vector<saml2::Attribute*> m_designators;
185 vector< pair<string,bool> > m_sources;
188 AttributeResolver* SHIBSP_DLLLOCAL SimpleAggregationResolverFactory(const DOMElement* const & e)
190 return new SimpleAggregationResolver(e);
193 static const XMLCh attributeId[] = UNICODE_LITERAL_11(a,t,t,r,i,b,u,t,e,I,d);
194 static const XMLCh Entity[] = UNICODE_LITERAL_6(E,n,t,i,t,y);
195 static const XMLCh EntityReference[] = UNICODE_LITERAL_15(E,n,t,i,t,y,R,e,f,e,r,e,n,c,e);
196 static const XMLCh format[] = UNICODE_LITERAL_6(f,o,r,m,a,t);
197 static const XMLCh _MetadataProvider[] = UNICODE_LITERAL_16(M,e,t,a,d,a,t,a,P,r,o,v,i,d,e,r);
198 static const XMLCh policyId[] = UNICODE_LITERAL_8(p,o,l,i,c,y,I,d);
199 static const XMLCh _TrustEngine[] = UNICODE_LITERAL_11(T,r,u,s,t,E,n,g,i,n,e);
200 static const XMLCh _type[] = UNICODE_LITERAL_4(t,y,p,e);
203 SimpleAggregationResolver::SimpleAggregationResolver(const DOMElement* e)
204 : m_log(Category::getInstance(SHIBSP_LOGCAT".AttributeResolver.SimpleAggregation")), m_metadata(NULL), m_trust(NULL)
207 xmltooling::NDC ndc("SimpleAggregationResolver");
210 const XMLCh* pid = e ? e->getAttributeNS(NULL, policyId) : NULL;
212 auto_ptr_char temp(pid);
213 m_policyId = temp.get();
216 pid = e ? e->getAttributeNS(NULL, attributeId) : NULL;
218 char* dup = XMLString::transcode(pid);
221 while (start && *start) {
222 while (*start && isspace(*start))
226 pos = strchr(start,' ');
229 m_attributeIds.push_back(start);
230 start = pos ? pos+1 : NULL;
232 XMLString::release(&dup);
234 pid = e->getAttributeNS(NULL, format);
240 DOMElement* child = XMLHelper::getFirstChildElement(e, _MetadataProvider);
242 auto_ptr_char type(child->getAttributeNS(NULL, _type));
243 if (!type.get() || !*type.get())
244 throw ConfigurationException("MetadataProvider element missing type attribute.");
245 m_log.info("building MetadataProvider of type %s...", type.get());
246 auto_ptr<MetadataProvider> mp(SAMLConfig::getConfig().MetadataProviderManager.newPlugin(type.get(), child));
248 m_metadata = mp.release();
251 child = XMLHelper::getFirstChildElement(e, _TrustEngine);
254 auto_ptr_char type(child->getAttributeNS(NULL, _type));
255 if (!type.get() || !*type.get())
256 throw ConfigurationException("TrustEngine element missing type attribute.");
257 m_log.info("building TrustEngine of type %s...", type.get());
258 m_trust = XMLToolingConfig::getConfig().TrustEngineManager.newPlugin(type.get(), child);
266 child = XMLHelper::getFirstChildElement(e);
268 if (child->hasChildNodes() && XMLString::equals(child->getLocalName(), Entity)) {
269 pid = child->getFirstChild()->getNodeValue();
271 auto_ptr_char tpid(pid);
272 m_sources.push_back(pair<string,bool>(tpid.get(),true));
275 else if (child->hasChildNodes() && XMLString::equals(child->getLocalName(), EntityReference)) {
276 pid = child->getFirstChild()->getNodeValue();
278 auto_ptr_char tpid(pid);
279 m_sources.push_back(pair<string,bool>(tpid.get(),false));
282 else if (XMLHelper::isNodeNamed(child, samlconstants::SAML20_NS, saml2::Attribute::LOCAL_NAME)) {
284 auto_ptr<XMLObject> obj(saml2::AttributeBuilder::buildOneFromElement(child));
285 saml2::Attribute* down = dynamic_cast<saml2::Attribute*>(obj.get());
287 m_designators.push_back(down);
291 catch (exception& ex) {
292 m_log.error("exception loading attribute designator: %s", ex.what());
295 child = XMLHelper::getNextSiblingElement(child);
300 bool SimpleAggregationResolver::doQuery(SimpleAggregationContext& ctx, const char* entityID, const NameID* name) const
303 xmltooling::NDC ndc("doQuery");
305 const Application& application = ctx.getApplication();
306 MetadataProviderCriteria mc(application, entityID, &AttributeAuthorityDescriptor::ELEMENT_QNAME, samlconstants::SAML20P_NS);
307 Locker mlocker(m_metadata);
308 const AttributeAuthorityDescriptor* AA=NULL;
309 pair<const EntityDescriptor*,const RoleDescriptor*> mdresult =
310 (m_metadata ? m_metadata : application.getMetadataProvider())->getEntityDescriptor(mc);
311 if (!mdresult.first) {
312 m_log.warn("unable to locate metadata for provider (%s)", entityID);
315 else if (!(AA=dynamic_cast<const AttributeAuthorityDescriptor*>(mdresult.second))) {
316 m_log.warn("no SAML 2 AttributeAuthority role found in metadata for (%s)", entityID);
320 const PropertySet* relyingParty = application.getRelyingParty(mdresult.first);
322 // Locate policy key.
323 const char* policyId = m_policyId.empty() ? application.getString("policyId").second : m_policyId.c_str();
325 // Access policy properties.
326 const PropertySet* settings = application.getServiceProvider().getPolicySettings(policyId);
327 pair<bool,bool> validate = settings->getBool("validate");
329 pair<bool,bool> signedAssertions = relyingParty->getBool("requireSignedAssertions");
330 pair<bool,const char*> encryption = relyingParty->getString("encryption");
332 shibsp::SecurityPolicy policy(application, NULL, validate.first && validate.second, policyId);
334 policy.setMetadataProvider(m_metadata);
336 policy.setTrustEngine(m_trust);
337 policy.getAudiences().push_back(relyingParty->getXMLString("entityID").second);
339 MetadataCredentialCriteria mcc(*AA);
340 shibsp::SOAPClient soaper(policy);
342 auto_ptr_XMLCh binding(samlconstants::SAML20_BINDING_SOAP);
343 saml2p::StatusResponseType* srt=NULL;
344 const vector<AttributeService*>& endpoints=AA->getAttributeServices();
345 for (vector<AttributeService*>::const_iterator ep=endpoints.begin(); !srt && ep!=endpoints.end(); ++ep) {
346 if (!XMLString::equals((*ep)->getBinding(),binding.get()) || !(*ep)->getLocation())
348 auto_ptr_char loc((*ep)->getLocation());
350 auto_ptr<saml2::Subject> subject(saml2::SubjectBuilder::buildSubject());
352 // Encrypt the NameID?
353 if (encryption.first && (!strcmp(encryption.second, "true") || !strcmp(encryption.second, "back"))) {
354 auto_ptr<EncryptedID> encrypted(EncryptedIDBuilder::buildEncryptedID());
355 MetadataCredentialCriteria mcc(*AA);
358 *(policy.getMetadataProvider()),
361 relyingParty->getXMLString("encryptionAlg").second
363 subject->setEncryptedID(encrypted.release());
366 subject->setNameID(name->cloneNameID());
369 saml2p::AttributeQuery* query = saml2p::AttributeQueryBuilder::buildAttributeQuery();
370 query->setSubject(subject.release());
371 Issuer* iss = IssuerBuilder::buildIssuer();
372 iss->setName(relyingParty->getXMLString("entityID").second);
373 query->setIssuer(iss);
374 for (vector<saml2::Attribute*>::const_iterator ad = m_designators.begin(); ad!=m_designators.end(); ++ad)
375 query->getAttributes().push_back((*ad)->cloneAttribute());
377 SAML2SOAPClient client(soaper, false);
378 client.sendSAML(query, application.getId(), mcc, loc.get());
379 srt = client.receiveSAML();
381 catch (exception& ex) {
382 m_log.error("exception during SAML query to %s: %s", loc.get(), ex.what());
388 m_log.error("unable to obtain a SAML response from attribute authority (%s)", entityID);
391 saml2p::Response* response = dynamic_cast<saml2p::Response*>(srt);
394 m_log.error("message was not a samlp:Response");
397 else if (!response->getStatus() || !response->getStatus()->getStatusCode() ||
398 !XMLString::equals(response->getStatus()->getStatusCode()->getValue(), saml2p::StatusCode::SUCCESS)) {
400 m_log.error("attribute authority (%s) returned a SAML error", entityID);
404 const vector<saml2::Assertion*>& assertions = const_cast<const saml2p::Response*>(response)->getAssertions();
405 if (assertions.empty()) {
407 m_log.warn("response from attribute authority (%s) was empty", entityID);
410 else if (assertions.size()>1)
411 m_log.warn("resolver only supports one assertion in the query response");
413 auto_ptr<saml2p::StatusResponseType> wrapper(srt);
414 saml2::Assertion* newtoken = assertions.front();
416 if (!newtoken->getSignature() && signedAssertions.first && signedAssertions.second) {
417 m_log.error("assertion unsigned, rejecting it based on signedAssertions policy");
422 // We're going to insist that the assertion issuer is the same as the peer.
423 // Reset the policy's message bits and extract them from the assertion.
425 policy.setMessageID(newtoken->getID());
426 policy.setIssueInstant(newtoken->getIssueInstantEpoch());
427 policy.setIssuer(newtoken->getIssuer());
428 policy.evaluate(*newtoken);
430 // Now we can check the security status of the policy.
431 if (!policy.isAuthenticated())
432 throw SecurityPolicyException("Security of SAML 2.0 query result not established.");
434 catch (exception& ex) {
435 m_log.error("assertion failed policy validation: %s", ex.what());
441 ctx.getResolvedAssertions().push_back(newtoken);
443 // Finally, extract and filter the result.
445 AttributeExtractor* extractor = application.getAttributeExtractor();
447 Locker extlocker(extractor);
448 extractor->extractAttributes(application, AA, *newtoken, ctx.getResolvedAttributes());
451 AttributeFilter* filter = application.getAttributeFilter();
453 BasicFilteringContext fc(application, ctx.getResolvedAttributes(), AA, ctx.getClassRef(), ctx.getDeclRef());
454 Locker filtlocker(filter);
455 filter->filterAttributes(fc, ctx.getResolvedAttributes());
458 catch (exception& ex) {
459 m_log.error("caught exception extracting/filtering attributes from query result: %s", ex.what());
460 for_each(ctx.getResolvedAttributes().begin(), ctx.getResolvedAttributes().end(), xmltooling::cleanup<shibsp::Attribute>());
461 ctx.getResolvedAttributes().clear();
467 void SimpleAggregationResolver::resolveAttributes(ResolutionContext& ctx) const
470 xmltooling::NDC ndc("resolveAttributes");
473 SimpleAggregationContext& qctx = dynamic_cast<SimpleAggregationContext&>(ctx);
475 // First we manufacture the appropriate NameID to use.
477 for (vector<string>::const_iterator a = m_attributeIds.begin(); !n && a != m_attributeIds.end(); ++a) {
478 const Attribute* attr=NULL;
479 if (qctx.getSession()) {
480 // Input attributes should be available via multimap.
481 pair<multimap<string,const Attribute*>::const_iterator, multimap<string,const Attribute*>::const_iterator> range =
482 qctx.getSession()->getIndexedAttributes().equal_range(*a);
483 for (; !attr && range.first != range.second; ++range.first) {
484 if (range.first->second->valueCount() > 0)
485 attr = range.first->second;
488 else if (qctx.getInputAttributes()) {
489 // Have to loop over unindexed set.
490 const vector<Attribute*>* matches = qctx.getInputAttributes();
491 for (vector<Attribute*>::const_iterator match = matches->begin(); !attr && match != matches->end(); ++match) {
492 if (*a == (*match)->getId() && (*match)->valueCount() > 0)
498 m_log.debug("using input attribute (%s) as identifier for queries", attr->getId());
499 n = NameIDBuilder::buildNameID();
500 const NameIDAttribute* down = dynamic_cast<const NameIDAttribute*>(attr);
502 // We can create a NameID directly from the source material.
503 const NameIDAttribute::Value& v = down->getValues().front();
504 XMLCh* val = fromUTF8(v.m_Name.c_str());
507 if (!v.m_Format.empty()) {
508 val = fromUTF8(v.m_Format.c_str());
512 if (!v.m_NameQualifier.empty()) {
513 val = fromUTF8(v.m_NameQualifier.c_str());
514 n->setNameQualifier(val);
517 if (!v.m_SPNameQualifier.empty()) {
518 val = fromUTF8(v.m_SPNameQualifier.c_str());
519 n->setSPNameQualifier(val);
522 if (!v.m_SPProvidedID.empty()) {
523 val = fromUTF8(v.m_SPProvidedID.c_str());
524 n->setSPProvidedID(val);
529 // We have to mock up the NameID.
530 XMLCh* val = fromUTF8(attr->getSerializedValues().front().c_str());
533 if (!m_format.empty())
534 n->setFormat(m_format.c_str());
540 if (qctx.getNameID() && m_attributeIds.empty()) {
541 m_log.debug("using authenticated NameID as identifier for queries");
544 m_log.warn("unable to resolve attributes, no suitable query identifier found");
549 auto_ptr<NameID> wrapper(n);
553 // We have a master loop over all the possible sources of material.
554 for (vector< pair<string,bool> >::const_iterator source = m_sources.begin(); source != m_sources.end(); ++source) {
555 if (source->second) {
556 // A literal entityID to query.
557 if (history.count(source->first) == 0) {
558 m_log.debug("issuing SAML query to (%s)", source->first.c_str());
559 doQuery(qctx, source->first.c_str(), n ? n : qctx.getNameID());
560 history.insert(source->first);
563 m_log.debug("skipping previously queried attribute source (%s)", source->first.c_str());
567 m_log.debug("using attribute sources referenced in attribute (%s)", source->first.c_str());
568 if (qctx.getSession()) {
569 // Input attributes should be available via multimap.
570 pair<multimap<string,const Attribute*>::const_iterator, multimap<string,const Attribute*>::const_iterator> range =
571 qctx.getSession()->getIndexedAttributes().equal_range(source->first);
572 for (; range.first != range.second; ++range.first) {
573 const vector<string>& links = range.first->second->getSerializedValues();
574 for (vector<string>::const_iterator link = links.begin(); link != links.end(); ++link) {
575 if (history.count(*link) == 0) {
576 m_log.debug("issuing SAML query to (%s)", link->c_str());
577 doQuery(qctx, link->c_str(), n ? n : qctx.getNameID());
578 history.insert(*link);
581 m_log.debug("skipping previously queried attribute source (%s)", link->c_str());
586 else if (qctx.getInputAttributes()) {
587 // Have to loop over unindexed set.
588 const vector<Attribute*>* matches = qctx.getInputAttributes();
589 for (vector<Attribute*>::const_iterator match = matches->begin(); match != matches->end(); ++match) {
590 if (source->first == (*match)->getId()) {
591 const vector<string>& links = (*match)->getSerializedValues();
592 for (vector<string>::const_iterator link = links.begin(); link != links.end(); ++link) {
593 if (history.count(*link) == 0) {
594 m_log.debug("issuing SAML query to (%s)", link->c_str());
595 doQuery(qctx, link->c_str(), n ? n : qctx.getNameID());
596 history.insert(*link);
599 m_log.debug("skipping previously queried attribute source (%s)", link->c_str());