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.
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
12 * http://www.apache.org/licenses/LICENSE-2.0
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.
22 * XMLAttributeExtractor.cpp
24 * AttributeExtractor based on an XML mapping file.
28 #include "exceptions.h"
29 #include "Application.h"
30 #include "ServiceProvider.h"
31 #include "attribute/Attribute.h"
32 #include "attribute/AttributeDecoder.h"
33 #include "attribute/filtering/AttributeFilter.h"
34 #include "attribute/filtering/BasicFilteringContext.h"
35 #include "attribute/resolver/AttributeExtractor.h"
36 #include "remoting/ddf.h"
37 #include "security/SecurityPolicy.h"
38 #include "util/SPConstants.h"
40 #include <boost/bind.hpp>
41 #include <boost/scoped_ptr.hpp>
42 #include <boost/shared_ptr.hpp>
43 #include <boost/algorithm/string.hpp>
44 #include <boost/iterator/indirect_iterator.hpp>
45 #include <boost/ptr_container/ptr_vector.hpp>
46 #include <boost/tuple/tuple.hpp>
47 #include <saml/SAMLConfig.h>
48 #include <saml/saml1/core/Assertions.h>
49 #include <saml/saml2/core/Assertions.h>
50 #include <saml/saml2/metadata/Metadata.h>
51 #include <saml/saml2/metadata/MetadataCredentialCriteria.h>
52 #include <saml/saml2/metadata/ObservableMetadataProvider.h>
53 #include <xmltooling/XMLToolingConfig.h>
54 #include <xmltooling/security/TrustEngine.h>
55 #include <xmltooling/util/NDC.h>
56 #include <xmltooling/util/ReloadableXMLFile.h>
57 #include <xmltooling/util/Threads.h>
58 #include <xmltooling/util/XMLHelper.h>
59 #include <xercesc/util/XMLUniDefs.hpp>
61 using namespace shibsp;
62 using namespace opensaml::saml2md;
63 using namespace opensaml;
64 using namespace xmltooling;
65 using namespace boost;
67 using saml1::NameIdentifier;
69 using saml2::EncryptedAttribute;
73 #if defined (_MSC_VER)
74 #pragma warning( push )
75 #pragma warning( disable : 4250 )
78 class XMLExtractorImpl : public ObservableMetadataProvider::Observer
81 XMLExtractorImpl(const DOMElement* e, Category& log);
83 for (map<const ObservableMetadataProvider*,decoded_t>::iterator i=m_decodedMap.begin(); i!=m_decodedMap.end(); ++i) {
84 i->first->removeObserver(this);
85 for (decoded_t::iterator attrs = i->second.begin(); attrs!=i->second.end(); ++attrs)
86 for_each(attrs->second.begin(), attrs->second.end(), mem_fun_ref<DDF&,DDF>(&DDF::destroy));
89 m_document->release();
92 void setDocument(DOMDocument* doc) {
96 void onEvent(const ObservableMetadataProvider& metadata) const {
97 // Destroy attributes we cached from this provider.
99 SharedLock wrapper(m_attrLock, false);
100 decoded_t& d = m_decodedMap[&metadata];
101 for (decoded_t::iterator a = d.begin(); a!=d.end(); ++a)
102 for_each(a->second.begin(), a->second.end(), mem_fun_ref<DDF&,DDF>(&DDF::destroy));
106 void extractAttributes(
107 const Application& application,
108 const char* assertingParty,
109 const char* relyingParty,
110 const NameIdentifier& nameid,
111 ptr_vector<Attribute>& attributes
113 void extractAttributes(
114 const Application& application,
115 const char* assertingParty,
116 const char* relyingParty,
117 const NameID& nameid,
118 ptr_vector<Attribute>& attributes
120 void extractAttributes(
121 const Application& application,
122 const char* assertingParty,
123 const char* relyingParty,
124 const saml1::Attribute& attr,
125 ptr_vector<Attribute>& attributes
127 void extractAttributes(
128 const Application& application,
129 const char* assertingParty,
130 const char* relyingParty,
131 const saml2::Attribute& attr,
132 ptr_vector<Attribute>& attributes
134 void extractAttributes(
135 const Application& application,
136 const char* assertingParty,
137 const char* relyingParty,
138 const saml1::AttributeStatement& statement,
139 ptr_vector<Attribute>& attributes
141 void extractAttributes(
142 const Application& application,
143 const char* assertingParty,
144 const char* relyingParty,
145 const saml2::AttributeStatement& statement,
146 ptr_vector<Attribute>& attributes
148 void extractAttributes(
149 const Application& application,
150 const ObservableMetadataProvider* observable,
151 const XMLCh* entityID,
152 const char* relyingParty,
153 const Extensions& ext,
154 ptr_vector<Attribute>& attributes
157 void getAttributeIds(vector<string>& attributes) const {
158 attributes.insert(attributes.end(), m_attributeIds.begin(), m_attributeIds.end());
161 void generateMetadata(SPSSODescriptor& role) const;
165 DOMDocument* m_document;
166 typedef map< pair<xstring,xstring>,pair< boost::shared_ptr<AttributeDecoder>,vector<string> > > attrmap_t;
168 vector<string> m_attributeIds;
169 vector< tuple<xstring,xstring,bool> > m_requestedAttrs;
171 // settings for embedded assertions in metadata
173 scoped_ptr<AttributeFilter> m_filter;
174 scoped_ptr<MetadataProvider> m_metadata;
175 scoped_ptr<TrustEngine> m_trust;
176 bool m_entityAssertions;
178 // manages caching of decoded Attributes
179 scoped_ptr<RWLock> m_attrLock;
180 typedef map< const EntityAttributes*,vector<DDF> > decoded_t;
181 mutable map<const ObservableMetadataProvider*,decoded_t> m_decodedMap;
184 class XMLExtractor : public AttributeExtractor, public ReloadableXMLFile
187 XMLExtractor(const DOMElement* e) : ReloadableXMLFile(e, Category::getInstance(SHIBSP_LOGCAT".AttributeExtractor.XML")) {
194 void extractAttributes(
195 const Application& application, const RoleDescriptor* issuer, const XMLObject& xmlObject, vector<Attribute*>& attributes
198 void getAttributeIds(std::vector<std::string>& attributes) const {
200 m_impl->getAttributeIds(attributes);
203 void generateMetadata(SPSSODescriptor& role) const {
205 m_impl->generateMetadata(role);
209 pair<bool,DOMElement*> background_load();
212 scoped_ptr<XMLExtractorImpl> m_impl;
214 void extractAttributes(
215 const Application& application, const RoleDescriptor* issuer, const XMLObject& xmlObject, ptr_vector<Attribute>& attributes
219 #if defined (_MSC_VER)
220 #pragma warning( pop )
223 AttributeExtractor* SHIBSP_DLLLOCAL XMLAttributeExtractorFactory(const DOMElement* const & e)
225 return new XMLExtractor(e);
228 static const XMLCh _aliases[] = UNICODE_LITERAL_7(a,l,i,a,s,e,s);
229 static const XMLCh _AttributeDecoder[] = UNICODE_LITERAL_16(A,t,t,r,i,b,u,t,e,D,e,c,o,d,e,r);
230 static const XMLCh _AttributeFilter[] = UNICODE_LITERAL_15(A,t,t,r,i,b,u,t,e,F,i,l,t,e,r);
231 static const XMLCh Attributes[] = UNICODE_LITERAL_10(A,t,t,r,i,b,u,t,e,s);
232 static const XMLCh _id[] = UNICODE_LITERAL_2(i,d);
233 static const XMLCh isRequested[] = UNICODE_LITERAL_11(i,s,R,e,q,u,e,s,t,e,d);
234 static const XMLCh _MetadataProvider[] = UNICODE_LITERAL_16(M,e,t,a,d,a,t,a,P,r,o,v,i,d,e,r);
235 static const XMLCh _name[] = UNICODE_LITERAL_4(n,a,m,e);
236 static const XMLCh nameFormat[] = UNICODE_LITERAL_10(n,a,m,e,F,o,r,m,a,t);
237 static const XMLCh metadataPolicyId[] = UNICODE_LITERAL_16(m,e,t,a,d,a,t,a,P,o,l,i,c,y,I,d);
238 static const XMLCh _TrustEngine[] = UNICODE_LITERAL_11(T,r,u,s,t,E,n,g,i,n,e);
239 static const XMLCh _type[] = UNICODE_LITERAL_4(t,y,p,e);
242 XMLExtractorImpl::XMLExtractorImpl(const DOMElement* e, Category& log)
245 m_policyId(XMLHelper::getAttrString(e, nullptr, metadataPolicyId)),
246 m_entityAssertions(true)
249 xmltooling::NDC ndc("XMLExtractorImpl");
252 if (!XMLHelper::isNodeNamed(e, shibspconstants::SHIB2ATTRIBUTEMAP_NS, Attributes))
253 throw ConfigurationException("XML AttributeExtractor requires am:Attributes at root of configuration.");
255 DOMElement* child = XMLHelper::getFirstChildElement(e, shibspconstants::SHIB2ATTRIBUTEMAP_NS, _MetadataProvider);
258 string t(XMLHelper::getAttrString(child, nullptr, _type));
260 throw ConfigurationException("MetadataProvider element missing type attribute.");
261 m_log.info("building MetadataProvider of type %s...", t.c_str());
262 m_metadata.reset(SAMLConfig::getConfig().MetadataProviderManager.newPlugin(t.c_str(), child));
265 catch (std::exception& ex) {
267 m_entityAssertions = false;
268 m_log.crit("error building/initializing dedicated MetadataProvider: %s", ex.what());
269 m_log.crit("disabling support for Assertions in EntityAttributes extension");
273 if (m_entityAssertions) {
274 child = XMLHelper::getFirstChildElement(e, shibspconstants::SHIB2ATTRIBUTEMAP_NS, _TrustEngine);
277 string t(XMLHelper::getAttrString(child, nullptr, _type));
279 throw ConfigurationException("TrustEngine element missing type attribute.");
280 m_log.info("building TrustEngine of type %s...", t.c_str());
281 m_trust.reset(XMLToolingConfig::getConfig().TrustEngineManager.newPlugin(t.c_str(), child));
283 catch (std::exception& ex) {
284 m_entityAssertions = false;
285 m_log.crit("error building/initializing dedicated TrustEngine: %s", ex.what());
286 m_log.crit("disabling support for Assertions in EntityAttributes extension");
291 if (m_entityAssertions) {
292 child = XMLHelper::getFirstChildElement(e, shibspconstants::SHIB2ATTRIBUTEMAP_NS, _AttributeFilter);
295 string t(XMLHelper::getAttrString(child, nullptr, _type));
297 throw ConfigurationException("AttributeFilter element missing type attribute.");
298 m_log.info("building AttributeFilter of type %s...", t.c_str());
299 m_filter.reset(SPConfig::getConfig().AttributeFilterManager.newPlugin(t.c_str(), child));
301 catch (std::exception& ex) {
302 m_entityAssertions = false;
303 m_log.crit("error building/initializing dedicated AttributeFilter: %s", ex.what());
304 m_log.crit("disabling support for Assertions in EntityAttributes extension");
309 child = XMLHelper::getFirstChildElement(e, shibspconstants::SHIB2ATTRIBUTEMAP_NS, saml1::Attribute::LOCAL_NAME);
311 // Check for missing name or id.
312 const XMLCh* name = child->getAttributeNS(nullptr, _name);
313 if (!name || !*name) {
314 m_log.warn("skipping Attribute with no name");
315 child = XMLHelper::getNextSiblingElement(child, shibspconstants::SHIB2ATTRIBUTEMAP_NS, saml1::Attribute::LOCAL_NAME);
319 auto_ptr_char id(child->getAttributeNS(nullptr, _id));
320 if (!id.get() || !*id.get()) {
321 m_log.warn("skipping Attribute with no id");
322 child = XMLHelper::getNextSiblingElement(child, shibspconstants::SHIB2ATTRIBUTEMAP_NS, saml1::Attribute::LOCAL_NAME);
325 else if (!strcmp(id.get(), "REMOTE_USER")) {
326 m_log.warn("skipping Attribute, id of REMOTE_USER is a reserved name");
327 child = XMLHelper::getNextSiblingElement(child, shibspconstants::SHIB2ATTRIBUTEMAP_NS, saml1::Attribute::LOCAL_NAME);
331 boost::shared_ptr<AttributeDecoder> decoder;
333 DOMElement* dchild = XMLHelper::getFirstChildElement(child, shibspconstants::SHIB2ATTRIBUTEMAP_NS, _AttributeDecoder);
335 auto_ptr<xmltooling::QName> q(XMLHelper::getXSIType(dchild));
337 decoder.reset(SPConfig::getConfig().AttributeDecoderManager.newPlugin(*q.get(), dchild));
340 decoder.reset(SPConfig::getConfig().AttributeDecoderManager.newPlugin(StringAttributeDecoderType, nullptr));
342 catch (std::exception& ex) {
343 m_log.error("skipping Attribute (%s), error building AttributeDecoder: %s", id.get(), ex.what());
347 child = XMLHelper::getNextSiblingElement(child, shibspconstants::SHIB2ATTRIBUTEMAP_NS, saml1::Attribute::LOCAL_NAME);
351 // Empty NameFormat implies the usual Shib URI naming defaults.
352 const XMLCh* format = child->getAttributeNS(nullptr, nameFormat);
353 if (!format || XMLString::equals(format, shibspconstants::SHIB1_ATTRIBUTE_NAMESPACE_URI) ||
354 XMLString::equals(format, saml2::Attribute::URI_REFERENCE))
355 format = &chNull; // ignore default Format/Namespace values
357 // Fetch/create the map entry and see if it's a duplicate rule.
358 pair< boost::shared_ptr<AttributeDecoder>,vector<string> >& decl = m_attrMap[pair<xstring,xstring>(name,format)];
360 m_log.warn("skipping duplicate Attribute mapping (same name and nameFormat)");
361 child = XMLHelper::getNextSiblingElement(child, shibspconstants::SHIB2ATTRIBUTEMAP_NS, saml1::Attribute::LOCAL_NAME);
365 if (m_log.isInfoEnabled()) {
366 auto_ptr_char n(name);
367 auto_ptr_char f(format);
368 m_log.info("creating mapping for Attribute %s%s%s", n.get(), *f.get() ? ", Format/Namespace:" : "", f.get());
371 decl.first = decoder;
372 decl.second.push_back(id.get());
373 m_attributeIds.push_back(id.get());
375 // Check for isRequired/isRequested.
376 bool requested = XMLHelper::getAttrBool(child, false, isRequested);
377 bool required = XMLHelper::getAttrBool(child, false, RequestedAttribute::ISREQUIRED_ATTRIB_NAME);
378 if (required || requested)
379 m_requestedAttrs.push_back(tuple<xstring,xstring,bool>(name,format,required));
381 name = child->getAttributeNS(nullptr, _aliases);
383 auto_ptr_char aliases(name);
384 string dup(aliases.get());
385 set<string> new_aliases;
386 split(new_aliases, dup, is_space(), algorithm::token_compress_on);
387 set<string>::iterator ru = new_aliases.find("REMOTE_USER");
388 if (ru != new_aliases.end()) {
389 m_log.warn("skipping alias, REMOTE_USER is a reserved name");
390 new_aliases.erase(ru);
392 m_attributeIds.insert(m_attributeIds.end(), new_aliases.begin(), new_aliases.end());
395 child = XMLHelper::getNextSiblingElement(child, shibspconstants::SHIB2ATTRIBUTEMAP_NS, saml1::Attribute::LOCAL_NAME);
398 m_attrLock.reset(RWLock::create());
401 void XMLExtractorImpl::generateMetadata(SPSSODescriptor& role) const
403 if (m_requestedAttrs.empty())
406 const vector<AttributeConsumingService*>& svcs = const_cast<const SPSSODescriptor*>(&role)->getAttributeConsumingServices();
407 for (vector<AttributeConsumingService*>::const_iterator s =svcs.begin(); s != svcs.end(); ++s) {
408 pair<bool,int> i = (*s)->getIndex();
409 if (i.first && index == i.second)
410 index = i.second + 1;
412 AttributeConsumingService* svc = AttributeConsumingServiceBuilder::buildAttributeConsumingService();
413 role.getAttributeConsumingServices().push_back(svc);
414 svc->setIndex(index);
415 ServiceName* sn = ServiceNameBuilder::buildServiceName();
416 svc->getServiceNames().push_back(sn);
417 sn->setName(dynamic_cast<EntityDescriptor*>(role.getParent())->getEntityID());
418 static const XMLCh english[] = UNICODE_LITERAL_2(e,n);
419 sn->setLang(english);
421 for (vector< tuple<xstring,xstring,bool> >::const_iterator i = m_requestedAttrs.begin(); i != m_requestedAttrs.end(); ++i) {
422 RequestedAttribute* req = RequestedAttributeBuilder::buildRequestedAttribute();
423 svc->getRequestedAttributes().push_back(req);
424 req->setName(i->get<0>().c_str());
425 if (i->get<1>().empty())
426 req->setNameFormat(saml2::Attribute::URI_REFERENCE);
428 req->setNameFormat(i->get<1>().c_str());
430 req->isRequired(true);
434 void XMLExtractorImpl::extractAttributes(
435 const Application& application,
436 const char* assertingParty,
437 const char* relyingParty,
438 const NameIdentifier& nameid,
439 ptr_vector<Attribute>& attributes
442 const XMLCh* format = nameid.getFormat();
443 if (!format || !*format)
444 format = NameIdentifier::UNSPECIFIED;
445 attrmap_t::const_iterator rule;
446 if ((rule = m_attrMap.find(pair<xstring,xstring>(format,xstring()))) != m_attrMap.end()) {
447 auto_ptr<Attribute> a(rule->second.first->decode(rule->second.second, &nameid, assertingParty, relyingParty));
449 attributes.push_back(a);
452 else if (m_log.isDebugEnabled()) {
453 auto_ptr_char temp(format);
454 m_log.debug("skipping unmapped NameIdentifier with format (%s)", temp.get());
458 void XMLExtractorImpl::extractAttributes(
459 const Application& application,
460 const char* assertingParty,
461 const char* relyingParty,
462 const NameID& nameid,
463 ptr_vector<Attribute>& attributes
466 const XMLCh* format = nameid.getFormat();
467 if (!format || !*format)
468 format = NameID::UNSPECIFIED;
469 attrmap_t::const_iterator rule;
470 if ((rule = m_attrMap.find(pair<xstring,xstring>(format,xstring()))) != m_attrMap.end()) {
471 auto_ptr<Attribute> a(rule->second.first->decode(rule->second.second, &nameid, assertingParty, relyingParty));
473 attributes.push_back(a);
476 else if (m_log.isDebugEnabled()) {
477 auto_ptr_char temp(format);
478 m_log.debug("skipping unmapped NameID with format (%s)", temp.get());
482 void XMLExtractorImpl::extractAttributes(
483 const Application& application,
484 const char* assertingParty,
485 const char* relyingParty,
486 const saml1::Attribute& attr,
487 ptr_vector<Attribute>& attributes
490 const XMLCh* name = attr.getAttributeName();
491 const XMLCh* format = attr.getAttributeNamespace();
494 if (!format || XMLString::equals(format, shibspconstants::SHIB1_ATTRIBUTE_NAMESPACE_URI))
496 attrmap_t::const_iterator rule;
497 if ((rule = m_attrMap.find(pair<xstring,xstring>(name,format))) != m_attrMap.end()) {
498 auto_ptr<Attribute> a(rule->second.first->decode(rule->second.second, &attr, assertingParty, relyingParty));
500 attributes.push_back(a);
503 else if (m_log.isInfoEnabled()) {
504 auto_ptr_char temp1(name);
505 auto_ptr_char temp2(format);
506 m_log.info("skipping unmapped SAML 1.x Attribute with Name: %s%s%s", temp1.get(), *temp2.get() ? ", Namespace:" : "", temp2.get());
510 void XMLExtractorImpl::extractAttributes(
511 const Application& application,
512 const char* assertingParty,
513 const char* relyingParty,
514 const saml2::Attribute& attr,
515 ptr_vector<Attribute>& attributes
518 const XMLCh* name = attr.getName();
519 const XMLCh* format = attr.getNameFormat();
522 if (!format || !*format)
523 format = saml2::Attribute::UNSPECIFIED;
524 else if (XMLString::equals(format, saml2::Attribute::URI_REFERENCE))
526 attrmap_t::const_iterator rule;
527 if ((rule = m_attrMap.find(pair<xstring,xstring>(name,format))) != m_attrMap.end()) {
528 auto_ptr<Attribute> a(rule->second.first->decode(rule->second.second, &attr, assertingParty, relyingParty));
530 attributes.push_back(a);
534 else if (XMLString::equals(format, saml2::Attribute::UNSPECIFIED)) {
535 // As a fallback, if the format is "unspecified", null out the value and re-map.
536 if ((rule = m_attrMap.find(pair<xstring,xstring>(name,xstring()))) != m_attrMap.end()) {
537 auto_ptr<Attribute> a(rule->second.first->decode(rule->second.second, &attr, assertingParty, relyingParty));
539 attributes.push_back(a.get());
546 if (m_log.isInfoEnabled()) {
547 auto_ptr_char temp1(name);
548 auto_ptr_char temp2(format);
549 m_log.info("skipping unmapped SAML 2.0 Attribute with Name: %s%s%s", temp1.get(), *temp2.get() ? ", Format:" : "", temp2.get());
553 void XMLExtractorImpl::extractAttributes(
554 const Application& application,
555 const char* assertingParty,
556 const char* relyingParty,
557 const saml1::AttributeStatement& statement,
558 ptr_vector<Attribute>& attributes
561 static void (XMLExtractorImpl::* extract)(
562 const Application&, const char*, const char*, const saml1::Attribute&, ptr_vector<Attribute>&
563 ) const = &XMLExtractorImpl::extractAttributes;
565 make_indirect_iterator(statement.getAttributes().begin()), make_indirect_iterator(statement.getAttributes().end()),
566 boost::bind(extract, this, boost::ref(application), assertingParty, relyingParty, _1, boost::ref(attributes))
570 void XMLExtractorImpl::extractAttributes(
571 const Application& application,
572 const char* assertingParty,
573 const char* relyingParty,
574 const saml2::AttributeStatement& statement,
575 ptr_vector<Attribute>& attributes
578 static void (XMLExtractorImpl::* extract)(
579 const Application&, const char*, const char*, const saml2::Attribute&, ptr_vector<Attribute>&
580 ) const = &XMLExtractorImpl::extractAttributes;
582 make_indirect_iterator(statement.getAttributes().begin()), make_indirect_iterator(statement.getAttributes().end()),
583 boost::bind(extract, this, boost::ref(application), assertingParty, relyingParty, _1, boost::ref(attributes))
587 void XMLExtractorImpl::extractAttributes(
588 const Application& application,
589 const ObservableMetadataProvider* observable,
590 const XMLCh* entityID,
591 const char* relyingParty,
592 const Extensions& ext,
593 ptr_vector<Attribute>& attributes
596 const vector<XMLObject*>& exts = ext.getUnknownXMLObjects();
597 for (vector<XMLObject*>::const_iterator i = exts.begin(); i != exts.end(); ++i) {
598 const EntityAttributes* container = dynamic_cast<const EntityAttributes*>(*i);
602 bool useCache = false;
603 map<const ObservableMetadataProvider*,decoded_t>::iterator cacheEntry;
605 // Check for cached result.
607 m_attrLock->rdlock();
608 cacheEntry = m_decodedMap.find(observable);
609 if (cacheEntry == m_decodedMap.end()) {
610 // We need to elevate the lock and retry.
611 m_attrLock->unlock();
612 m_attrLock->wrlock();
613 cacheEntry = m_decodedMap.find(observable);
614 if (cacheEntry == m_decodedMap.end()) {
615 SharedLock locker(m_attrLock, false); // guard in case these throw
617 // It's still brand new, so hook it for cache activation.
618 observable->addObserver(this);
620 // Prime the map reference with an empty decoded map.
621 cacheEntry = m_decodedMap.insert(make_pair(observable,decoded_t())).first;
623 // Downgrade the lock.
624 // We don't have to recheck because we never erase the master map entry entirely, even on changes.
625 locker.release(); // unguard for lock downgrade
626 m_attrLock->unlock();
627 m_attrLock->rdlock();
634 // We're holding the lock, so check the cache.
635 decoded_t::iterator d = cacheEntry->second.find(container);
636 if (d != cacheEntry->second.end()) {
637 SharedLock locker(m_attrLock, false); // pop the lock when we're done
638 for (vector<DDF>::iterator obj = d->second.begin(); obj != d->second.end(); ++obj) {
639 auto_ptr<Attribute> wrapper(Attribute::unmarshall(*obj));
640 m_log.debug("recovered cached metadata attribute (%s)", wrapper->getId());
641 attributes.push_back(wrapper);
647 // Add a guard for the lock if we're caching.
648 SharedLock locker(useCache ? m_attrLock.get() : nullptr, false);
650 // Use a holding area to support caching.
651 ptr_vector<Attribute> holding;
653 // Extract attributes into holding area with no asserting party set.
654 static void (XMLExtractorImpl::* extractV2Attr)(
655 const Application&, const char*, const char*, const saml2::Attribute&, ptr_vector<Attribute>&
656 ) const = &XMLExtractorImpl::extractAttributes;
658 make_indirect_iterator(container->getAttributes().begin()), make_indirect_iterator(container->getAttributes().end()),
659 boost::bind(extractV2Attr, this, boost::ref(application), (const char*)nullptr, relyingParty, _1, boost::ref(holding))
662 if (entityID && m_entityAssertions) {
663 const vector<saml2::Assertion*>& asserts = container->getAssertions();
664 for (indirect_iterator<vector<saml2::Assertion*>::const_iterator> assert = make_indirect_iterator(asserts.begin());
665 assert != make_indirect_iterator(asserts.end()); ++assert) {
666 if (!(assert->getSignature())) {
667 if (m_log.isDebugEnabled()) {
668 auto_ptr_char eid(entityID);
669 m_log.debug("skipping unsigned assertion in metadata extension for entity (%s)", eid.get());
673 else if (assert->getAttributeStatements().empty()) {
674 if (m_log.isDebugEnabled()) {
675 auto_ptr_char eid(entityID);
676 m_log.debug("skipping assertion with no AttributeStatement in metadata extension for entity (%s)", eid.get());
682 const NameID* subject = assert->getSubject() ? assert->getSubject()->getNameID() : nullptr;
684 !XMLString::equals(subject->getFormat(), NameID::ENTITY) ||
685 !XMLString::equals(subject->getName(), entityID)) {
686 if (m_log.isDebugEnabled()) {
687 auto_ptr_char eid(entityID);
688 m_log.debug("skipping assertion with improper Subject in metadata extension for entity (%s)", eid.get());
695 // Set up and evaluate a policy for an AA asserting attributes to us.
696 shibsp::SecurityPolicy policy(application, &AttributeAuthorityDescriptor::ELEMENT_QNAME, false, m_policyId.c_str());
697 Locker locker(m_metadata.get());
699 policy.setMetadataProvider(m_metadata.get());
701 policy.setTrustEngine(m_trust.get());
702 // Populate recipient as audience.
703 const XMLCh* issuer = assert->getIssuer() ? assert->getIssuer()->getName() : nullptr;
704 policy.getAudiences().push_back(application.getRelyingParty(issuer)->getXMLString("entityID").second);
706 // Extract assertion information for policy.
707 policy.setMessageID(assert->getID());
708 policy.setIssueInstant(assert->getIssueInstantEpoch());
709 policy.setIssuer(assert->getIssuer());
711 // Look up metadata for issuer.
712 if (policy.getIssuer() && policy.getMetadataProvider()) {
713 if (policy.getIssuer()->getFormat() && !XMLString::equals(policy.getIssuer()->getFormat(), saml2::NameIDType::ENTITY)) {
714 m_log.debug("non-system entity issuer, skipping metadata lookup");
717 m_log.debug("searching metadata for entity assertion issuer...");
718 pair<const EntityDescriptor*,const RoleDescriptor*> lookup;
719 MetadataProvider::Criteria& mc = policy.getMetadataProviderCriteria();
720 mc.entityID_unicode = policy.getIssuer()->getName();
721 mc.role = &AttributeAuthorityDescriptor::ELEMENT_QNAME;
722 mc.protocol = samlconstants::SAML20P_NS;
723 lookup = policy.getMetadataProvider()->getEntityDescriptor(mc);
725 auto_ptr_char iname(policy.getIssuer()->getName());
726 m_log.debug("no metadata found, can't establish identity of issuer (%s)", iname.get());
728 else if (!lookup.second) {
729 m_log.debug("unable to find compatible AA role in metadata");
732 policy.setIssuerMetadata(lookup.second);
737 // Authenticate the assertion. We have to clone and marshall it to establish the signature for verification.
738 scoped_ptr<saml2::Assertion> tokencopy(assert->cloneAssertion());
739 tokencopy->marshall();
740 policy.evaluate(*tokencopy);
741 if (!policy.isAuthenticated()) {
742 if (m_log.isDebugEnabled()) {
743 auto_ptr_char tempid(tokencopy->getID());
744 auto_ptr_char eid(entityID);
746 "failed to authenticate assertion (%s) in metadata extension for entity (%s)", tempid.get(), eid.get()
752 // Override the asserting/relying party names based on this new issuer.
753 const EntityDescriptor* inlineEntity =
754 policy.getIssuerMetadata() ? dynamic_cast<const EntityDescriptor*>(policy.getIssuerMetadata()->getParent()) : nullptr;
755 auto_ptr_char inlineAssertingParty(inlineEntity ? inlineEntity->getEntityID() : nullptr);
756 relyingParty = application.getRelyingParty(inlineEntity)->getString("entityID").second;
758 // Use a private holding area for filtering purposes.
759 ptr_vector<Attribute> holding2;
760 const vector<saml2::Attribute*>& attrs2 =
761 const_cast<const saml2::AttributeStatement*>(tokencopy->getAttributeStatements().front())->getAttributes();
763 make_indirect_iterator(attrs2.begin()), make_indirect_iterator(attrs2.end()),
764 boost::bind(extractV2Attr, this, boost::ref(application), inlineAssertingParty.get(), relyingParty, _1, boost::ref(holding2))
767 // Now we locally filter the attributes so that the actual issuer can be properly set.
768 // If we relied on outside filtering, the attributes couldn't be distinguished from the
769 // ones that come from the user's IdP.
770 if (m_filter && !holding2.empty()) {
772 // The filter API uses an unsafe container, so we have to transfer everything into one and back.
773 vector<Attribute*> unsafe_holding2;
775 // Use a local exception context since the container is unsafe.
777 while (!holding2.empty()) {
778 ptr_vector<Attribute>::auto_type ptr = holding2.pop_back();
779 unsafe_holding2.push_back(ptr.get());
782 BasicFilteringContext fc(application, unsafe_holding2, policy.getIssuerMetadata());
783 Locker filtlocker(m_filter.get());
784 m_filter->filterAttributes(fc, unsafe_holding2);
786 // Transfer back to safe container
787 while (!unsafe_holding2.empty()) {
788 auto_ptr<Attribute> ptr(unsafe_holding2.back());
789 unsafe_holding2.pop_back();
790 holding2.push_back(ptr);
793 catch (std::exception& ex) {
794 m_log.error("caught exception filtering attributes: %s", ex.what());
795 m_log.error("dumping extracted attributes due to filtering exception");
796 for_each(unsafe_holding2.begin(), unsafe_holding2.end(), xmltooling::cleanup<Attribute>());
797 holding2.clear(); // in case the exception was during transfer between containers
801 if (!holding2.empty()) {
802 // Copy them over to the main holding tank, which transfers ownership.
803 holding.transfer(holding.end(), holding2);
806 catch (std::exception& ex) {
807 // Known exceptions are handled gracefully by skipping the assertion.
808 if (m_log.isDebugEnabled()) {
809 auto_ptr_char tempid(assert->getID());
810 auto_ptr_char eid(entityID);
812 "exception authenticating assertion (%s) in metadata extension for entity (%s): %s",
823 if (!holding.empty()) {
825 locker.release(); // unguard to upgrade lock
826 m_attrLock->unlock();
827 m_attrLock->wrlock();
828 SharedLock locker2(m_attrLock, false); // pop the lock when we're done
829 if (cacheEntry->second.count(container) == 0) {
830 static void (vector<DDF>::* push_back)(DDF const &) = &vector<DDF>::push_back;
831 vector<DDF>& marshalled = cacheEntry->second[container];
833 holding.begin(), holding.end(),
834 boost::bind(push_back, boost::ref(marshalled), boost::bind(&Attribute::marshall, _1))
839 // Copy them to the output parameter, which transfers ownership.
840 attributes.transfer(attributes.end(), holding);
843 // If the lock is held, it's guarded.
845 break; // only process a single extension element
849 void XMLExtractor::extractAttributes(
850 const Application& application, const RoleDescriptor* issuer, const XMLObject& xmlObject, vector<Attribute*>& attributes
856 ptr_vector<Attribute> holding;
857 extractAttributes(application, issuer, xmlObject, holding);
859 // Transfer ownership from the ptr_vector to the unsafe vector for API compatibility.
860 // Any throws should leave each container in a consistent state. The holding container
861 // is freed by us, and the result container by the caller.
862 while (!holding.empty()) {
863 ptr_vector<Attribute>::auto_type ptr = holding.pop_back();
864 attributes.push_back(ptr.get());
869 void XMLExtractor::extractAttributes(
870 const Application& application, const RoleDescriptor* issuer, const XMLObject& xmlObject, ptr_vector<Attribute>& attributes
873 static void (XMLExtractor::* extractEncrypted)(
874 const Application&, const RoleDescriptor*, const XMLObject&, ptr_vector<Attribute>&
875 ) const = &XMLExtractor::extractAttributes;
876 static void (XMLExtractorImpl::* extractV1Statement)(
877 const Application&, const char*, const char*, const saml1::AttributeStatement&, ptr_vector<Attribute>&
878 ) const = &XMLExtractorImpl::extractAttributes;
880 const EntityDescriptor* entity = issuer ? dynamic_cast<const EntityDescriptor*>(issuer->getParent()) : nullptr;
881 const char* relyingParty = application.getRelyingParty(entity)->getString("entityID").second;
883 // Check for statements.
884 if (XMLString::equals(xmlObject.getElementQName().getLocalPart(), saml1::AttributeStatement::LOCAL_NAME)) {
885 const saml2::AttributeStatement* statement2 = dynamic_cast<const saml2::AttributeStatement*>(&xmlObject);
887 auto_ptr_char assertingParty(entity ? entity->getEntityID() : nullptr);
888 m_impl->extractAttributes(application, assertingParty.get(), relyingParty, *statement2, attributes);
889 // Handle EncryptedAttributes inline so we have access to the role descriptor.
890 const vector<saml2::EncryptedAttribute*>& encattrs = statement2->getEncryptedAttributes();
892 make_indirect_iterator(encattrs.begin()), make_indirect_iterator(encattrs.end()),
893 boost::bind(extractEncrypted, this, boost::ref(application), issuer, _1, boost::ref(attributes))
898 const saml1::AttributeStatement* statement1 = dynamic_cast<const saml1::AttributeStatement*>(&xmlObject);
900 auto_ptr_char assertingParty(entity ? entity->getEntityID() : nullptr);
901 m_impl->extractAttributes(application, assertingParty.get(), relyingParty, *statement1, attributes);
905 throw AttributeExtractionException("Unable to extract attributes, unknown object type.");
908 // Check for assertions.
909 if (XMLString::equals(xmlObject.getElementQName().getLocalPart(), saml1::Assertion::LOCAL_NAME)) {
910 const saml2::Assertion* token2 = dynamic_cast<const saml2::Assertion*>(&xmlObject);
912 auto_ptr_char assertingParty(entity ? entity->getEntityID() : nullptr);
913 const vector<saml2::AttributeStatement*>& statements = token2->getAttributeStatements();
914 for (indirect_iterator<vector<saml2::AttributeStatement*>::const_iterator> s = make_indirect_iterator(statements.begin());
915 s != make_indirect_iterator(statements.end()); ++s) {
916 m_impl->extractAttributes(application, assertingParty.get(), relyingParty, *s, attributes);
917 // Handle EncryptedAttributes inline so we have access to the role descriptor.
918 const vector<saml2::EncryptedAttribute*>& encattrs = const_cast<const saml2::AttributeStatement&>(*s).getEncryptedAttributes();
920 make_indirect_iterator(encattrs.begin()), make_indirect_iterator(encattrs.end()),
921 boost::bind(extractEncrypted, this, boost::ref(application), issuer, _1, boost::ref(attributes))
927 const saml1::Assertion* token1 = dynamic_cast<const saml1::Assertion*>(&xmlObject);
929 auto_ptr_char assertingParty(entity ? entity->getEntityID() : nullptr);
930 const vector<saml1::AttributeStatement*>& statements = token1->getAttributeStatements();
931 for_each(make_indirect_iterator(statements.begin()), make_indirect_iterator(statements.end()),
932 boost::bind(extractV1Statement, m_impl.get(), boost::ref(application), assertingParty.get(), relyingParty, _1, boost::ref(attributes))
937 throw AttributeExtractionException("Unable to extract attributes, unknown object type.");
940 // Check for metadata.
941 if (XMLString::equals(xmlObject.getElementQName().getNamespaceURI(), samlconstants::SAML20MD_NS)) {
942 const RoleDescriptor* roleToExtract = dynamic_cast<const RoleDescriptor*>(&xmlObject);
943 const EntityDescriptor* entityToExtract = roleToExtract ? dynamic_cast<const EntityDescriptor*>(roleToExtract->getParent()) : nullptr;
944 if (!entityToExtract)
945 throw AttributeExtractionException("Unable to extract attributes, unknown metadata object type.");
946 const Extensions* ext = entityToExtract->getExtensions();
948 m_impl->extractAttributes(
950 dynamic_cast<const ObservableMetadataProvider*>(application.getMetadataProvider(false)),
951 entityToExtract->getEntityID(),
957 const EntitiesDescriptor* group = dynamic_cast<const EntitiesDescriptor*>(entityToExtract->getParent());
959 ext = group->getExtensions();
961 m_impl->extractAttributes(
963 dynamic_cast<const ObservableMetadataProvider*>(application.getMetadataProvider(false)),
964 nullptr, // not an entity, so inline assertions won't be processed
970 group = dynamic_cast<const EntitiesDescriptor*>(group->getParent());
975 // Check for attributes.
976 if (XMLString::equals(xmlObject.getElementQName().getLocalPart(), saml1::Attribute::LOCAL_NAME)) {
977 auto_ptr_char assertingParty(entity ? entity->getEntityID() : nullptr);
978 const saml2::Attribute* attr2 = dynamic_cast<const saml2::Attribute*>(&xmlObject);
980 return m_impl->extractAttributes(application, assertingParty.get(), relyingParty, *attr2, attributes);
982 const saml1::Attribute* attr1 = dynamic_cast<const saml1::Attribute*>(&xmlObject);
984 return m_impl->extractAttributes(application, assertingParty.get(), relyingParty, *attr1, attributes);
986 throw AttributeExtractionException("Unable to extract attributes, unknown object type.");
989 if (XMLString::equals(xmlObject.getElementQName().getLocalPart(), EncryptedAttribute::LOCAL_NAME)) {
990 const EncryptedAttribute* encattr = dynamic_cast<const EncryptedAttribute*>(&xmlObject);
992 const XMLCh* recipient = application.getXMLString("entityID").second;
993 CredentialResolver* cr = application.getCredentialResolver();
995 m_log.warn("found encrypted attribute, but no CredentialResolver was available");
1000 Locker credlocker(cr);
1002 MetadataCredentialCriteria mcc(*issuer);
1003 scoped_ptr<XMLObject> decrypted(encattr->decrypt(*cr, recipient, &mcc));
1004 if (m_log.isDebugEnabled())
1005 m_log.debugStream() << "decrypted Attribute: " << *decrypted << logging::eol;
1006 return extractAttributes(application, issuer, *decrypted, attributes);
1009 scoped_ptr<XMLObject> decrypted(encattr->decrypt(*cr, recipient));
1010 if (m_log.isDebugEnabled())
1011 m_log.debugStream() << "decrypted Attribute: " << *decrypted << logging::eol;
1012 return extractAttributes(application, issuer, *decrypted, attributes);
1015 catch (std::exception& ex) {
1016 m_log.error("caught exception decrypting Attribute: %s", ex.what());
1022 // Check for NameIDs.
1023 const NameID* name2 = dynamic_cast<const NameID*>(&xmlObject);
1025 auto_ptr_char assertingParty(entity ? entity->getEntityID() : nullptr);
1026 return m_impl->extractAttributes(application, assertingParty.get(), relyingParty, *name2, attributes);
1029 const NameIdentifier* name1 = dynamic_cast<const NameIdentifier*>(&xmlObject);
1031 auto_ptr_char assertingParty(entity ? entity->getEntityID() : nullptr);
1032 return m_impl->extractAttributes(application, assertingParty.get(), relyingParty, *name1, attributes);
1035 m_log.debug("unable to extract attributes, unknown XML object type: %s", xmlObject.getElementQName().toString().c_str());
1038 pair<bool,DOMElement*> XMLExtractor::background_load()
1040 // Load from source using base class.
1041 pair<bool,DOMElement*> raw = ReloadableXMLFile::load();
1043 // If we own it, wrap it.
1044 XercesJanitor<DOMDocument> docjanitor(raw.first ? raw.second->getOwnerDocument() : nullptr);
1046 scoped_ptr<XMLExtractorImpl> impl(new XMLExtractorImpl(raw.second, m_log));
1048 // If we held the document, transfer it to the impl. If we didn't, it's a no-op.
1049 impl->setDocument(docjanitor.release());
1051 // Perform the swap inside a lock.
1054 SharedLock locker(m_lock, false);
1057 return make_pair(false,(DOMElement*)nullptr);