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/shared_ptr.hpp>
42 #include <boost/algorithm/string.hpp>
43 #include <boost/iterator/indirect_iterator.hpp>
44 #include <boost/ptr_container/ptr_vector.hpp>
45 #include <boost/tuple/tuple.hpp>
46 #include <saml/SAMLConfig.h>
47 #include <saml/saml1/core/Assertions.h>
48 #include <saml/saml2/core/Assertions.h>
49 #include <saml/saml2/metadata/Metadata.h>
50 #include <saml/saml2/metadata/MetadataCredentialCriteria.h>
51 #include <saml/saml2/metadata/ObservableMetadataProvider.h>
52 #include <xmltooling/XMLToolingConfig.h>
53 #include <xmltooling/security/TrustEngine.h>
54 #include <xmltooling/util/NDC.h>
55 #include <xmltooling/util/ReloadableXMLFile.h>
56 #include <xmltooling/util/Threads.h>
57 #include <xmltooling/util/XMLHelper.h>
58 #include <xercesc/util/XMLUniDefs.hpp>
60 using namespace shibsp;
61 using namespace opensaml::saml2md;
62 using namespace opensaml;
63 using namespace xmltooling;
64 using namespace boost;
66 using saml1::NameIdentifier;
68 using saml2::EncryptedAttribute;
72 #if defined (_MSC_VER)
73 #pragma warning( push )
74 #pragma warning( disable : 4250 )
77 class XMLExtractorImpl : public ObservableMetadataProvider::Observer
80 XMLExtractorImpl(const DOMElement* e, Category& log);
82 for (map<const ObservableMetadataProvider*,decoded_t>::iterator i=m_decodedMap.begin(); i!=m_decodedMap.end(); ++i) {
83 i->first->removeObserver(this);
84 for (decoded_t::iterator attrs = i->second.begin(); attrs!=i->second.end(); ++attrs)
85 for_each(attrs->second.begin(), attrs->second.end(), mem_fun_ref<DDF&,DDF>(&DDF::destroy));
88 m_document->release();
91 void setDocument(DOMDocument* doc) {
95 void onEvent(const ObservableMetadataProvider& metadata) const {
96 // Destroy attributes we cached from this provider.
98 SharedLock wrapper(m_attrLock, false);
99 decoded_t& d = m_decodedMap[&metadata];
100 for (decoded_t::iterator a = d.begin(); a!=d.end(); ++a)
101 for_each(a->second.begin(), a->second.end(), mem_fun_ref<DDF&,DDF>(&DDF::destroy));
105 void extractAttributes(const Application&, const char*, const char*, const NameIdentifier&, ptr_vector<Attribute>&) const;
106 void extractAttributes(const Application&, const char*, const char*, const NameID&, ptr_vector<Attribute>&) const;
107 void extractAttributes(const Application&, const GenericRequest*, const char*, const char*, const saml1::Attribute&, ptr_vector<Attribute>&) const;
108 void extractAttributes(const Application&, const GenericRequest*, const char*, const char*, const saml2::Attribute&, ptr_vector<Attribute>&) const;
109 void extractAttributes(const Application&, const GenericRequest*, const char*, const char*, const saml1::AttributeStatement&, ptr_vector<Attribute>&) const;
110 void extractAttributes(const Application&, const GenericRequest*, const char*, const char*, const saml2::AttributeStatement&, ptr_vector<Attribute>&) const;
111 void extractAttributes(
112 const Application&, const GenericRequest*, const ObservableMetadataProvider*, const XMLCh*, const char*, const Extensions&, ptr_vector<Attribute>&
115 void getAttributeIds(vector<string>& attributes) const {
116 attributes.insert(attributes.end(), m_attributeIds.begin(), m_attributeIds.end());
119 void generateMetadata(SPSSODescriptor& role) const;
123 DOMDocument* m_document;
124 typedef map< pair<xstring,xstring>,pair< boost::shared_ptr<AttributeDecoder>,vector<string> > > attrmap_t;
126 vector<string> m_attributeIds;
127 vector< tuple<xstring,xstring,bool> > m_requestedAttrs;
129 // settings for embedded assertions in metadata
131 scoped_ptr<AttributeFilter> m_filter;
132 scoped_ptr<MetadataProvider> m_metadata;
133 scoped_ptr<TrustEngine> m_trust;
134 bool m_entityAssertions,m_metaAttrCaching;
136 // manages caching of decoded Attributes
137 scoped_ptr<RWLock> m_attrLock;
138 typedef map< const EntityAttributes*,vector<DDF> > decoded_t;
139 mutable map<const ObservableMetadataProvider*,decoded_t> m_decodedMap;
142 class XMLExtractor : public AttributeExtractor, public ReloadableXMLFile
145 XMLExtractor(const DOMElement* e) : ReloadableXMLFile(e, Category::getInstance(SHIBSP_LOGCAT".AttributeExtractor.XML")) {
146 if (m_local && m_lock)
147 m_log.warn("attribute mappings are reloadable; be sure to restart web server when adding new attribute IDs");
155 void extractAttributes(
156 const Application& application, const RoleDescriptor* issuer, const XMLObject& xmlObject, vector<Attribute*>& attributes
158 extractAttributes(application, nullptr, issuer, xmlObject, attributes);
161 void extractAttributes(const Application&, const GenericRequest*, const RoleDescriptor*, const XMLObject&, vector<Attribute*>&) const;
163 void getAttributeIds(std::vector<std::string>& attributes) const {
165 m_impl->getAttributeIds(attributes);
168 void generateMetadata(SPSSODescriptor& role) const {
170 m_impl->generateMetadata(role);
174 pair<bool,DOMElement*> background_load();
177 scoped_ptr<XMLExtractorImpl> m_impl;
179 void extractAttributes(const Application&, const GenericRequest*, const RoleDescriptor*, const XMLObject&, ptr_vector<Attribute>&) const;
182 #if defined (_MSC_VER)
183 #pragma warning( pop )
186 AttributeExtractor* SHIBSP_DLLLOCAL XMLAttributeExtractorFactory(const DOMElement* const & e)
188 return new XMLExtractor(e);
191 static const XMLCh _aliases[] = UNICODE_LITERAL_7(a,l,i,a,s,e,s);
192 static const XMLCh _AttributeDecoder[] = UNICODE_LITERAL_16(A,t,t,r,i,b,u,t,e,D,e,c,o,d,e,r);
193 static const XMLCh _AttributeFilter[] = UNICODE_LITERAL_15(A,t,t,r,i,b,u,t,e,F,i,l,t,e,r);
194 static const XMLCh Attributes[] = UNICODE_LITERAL_10(A,t,t,r,i,b,u,t,e,s);
195 static const XMLCh _id[] = UNICODE_LITERAL_2(i,d);
196 static const XMLCh isRequested[] = UNICODE_LITERAL_11(i,s,R,e,q,u,e,s,t,e,d);
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 metadataAttributeCaching[] = UNICODE_LITERAL_24(m,e,t,a,d,a,t,a,A,t,t,r,i,b,u,t,e,C,a,c,h,i,n,g);
199 static const XMLCh metadataPolicyId[] = UNICODE_LITERAL_16(m,e,t,a,d,a,t,a,P,o,l,i,c,y,I,d);
200 static const XMLCh _name[] = UNICODE_LITERAL_4(n,a,m,e);
201 static const XMLCh nameFormat[] = UNICODE_LITERAL_10(n,a,m,e,F,o,r,m,a,t);
202 static const XMLCh _TrustEngine[] = UNICODE_LITERAL_11(T,r,u,s,t,E,n,g,i,n,e);
203 static const XMLCh _type[] = UNICODE_LITERAL_4(t,y,p,e);
206 XMLExtractorImpl::XMLExtractorImpl(const DOMElement* e, Category& log)
209 m_policyId(XMLHelper::getAttrString(e, nullptr, metadataPolicyId)),
210 m_entityAssertions(true),
211 m_metaAttrCaching(XMLHelper::getAttrBool(e, true, metadataAttributeCaching))
214 xmltooling::NDC ndc("XMLExtractorImpl");
217 if (!XMLHelper::isNodeNamed(e, shibspconstants::SHIB2ATTRIBUTEMAP_NS, Attributes))
218 throw ConfigurationException("XML AttributeExtractor requires am:Attributes at root of configuration.");
220 DOMElement* child = XMLHelper::getFirstChildElement(e, shibspconstants::SHIB2ATTRIBUTEMAP_NS, _MetadataProvider);
223 string t(XMLHelper::getAttrString(child, nullptr, _type));
225 throw ConfigurationException("MetadataProvider element missing type attribute.");
226 m_log.info("building MetadataProvider of type %s...", t.c_str());
227 m_metadata.reset(SAMLConfig::getConfig().MetadataProviderManager.newPlugin(t.c_str(), child));
230 catch (std::exception& ex) {
232 m_entityAssertions = false;
233 m_log.crit("error building/initializing dedicated MetadataProvider: %s", ex.what());
234 m_log.crit("disabling support for Assertions in EntityAttributes extension");
238 if (m_entityAssertions) {
239 child = XMLHelper::getFirstChildElement(e, shibspconstants::SHIB2ATTRIBUTEMAP_NS, _TrustEngine);
242 string t(XMLHelper::getAttrString(child, nullptr, _type));
244 throw ConfigurationException("TrustEngine element missing type attribute.");
245 m_log.info("building TrustEngine of type %s...", t.c_str());
246 m_trust.reset(XMLToolingConfig::getConfig().TrustEngineManager.newPlugin(t.c_str(), child));
248 catch (std::exception& ex) {
249 m_entityAssertions = false;
250 m_log.crit("error building/initializing dedicated TrustEngine: %s", ex.what());
251 m_log.crit("disabling support for Assertions in EntityAttributes extension");
256 if (m_entityAssertions) {
257 child = XMLHelper::getFirstChildElement(e, shibspconstants::SHIB2ATTRIBUTEMAP_NS, _AttributeFilter);
260 string t(XMLHelper::getAttrString(child, nullptr, _type));
262 throw ConfigurationException("AttributeFilter element missing type attribute.");
263 m_log.info("building AttributeFilter of type %s...", t.c_str());
264 m_filter.reset(SPConfig::getConfig().AttributeFilterManager.newPlugin(t.c_str(), child));
266 catch (std::exception& ex) {
267 m_entityAssertions = false;
268 m_log.crit("error building/initializing dedicated AttributeFilter: %s", ex.what());
269 m_log.crit("disabling support for Assertions in EntityAttributes extension");
274 child = XMLHelper::getFirstChildElement(e, shibspconstants::SHIB2ATTRIBUTEMAP_NS, saml1::Attribute::LOCAL_NAME);
276 // Check for missing name or id.
277 const XMLCh* name = child->getAttributeNS(nullptr, _name);
278 if (!name || !*name) {
279 m_log.warn("skipping Attribute with no name");
280 child = XMLHelper::getNextSiblingElement(child, shibspconstants::SHIB2ATTRIBUTEMAP_NS, saml1::Attribute::LOCAL_NAME);
284 auto_ptr_char id(child->getAttributeNS(nullptr, _id));
285 if (!id.get() || !*id.get()) {
286 m_log.warn("skipping Attribute with no id");
287 child = XMLHelper::getNextSiblingElement(child, shibspconstants::SHIB2ATTRIBUTEMAP_NS, saml1::Attribute::LOCAL_NAME);
290 else if (!strcmp(id.get(), "REMOTE_USER")) {
291 m_log.warn("skipping Attribute, id of REMOTE_USER is a reserved name");
292 child = XMLHelper::getNextSiblingElement(child, shibspconstants::SHIB2ATTRIBUTEMAP_NS, saml1::Attribute::LOCAL_NAME);
296 boost::shared_ptr<AttributeDecoder> decoder;
298 DOMElement* dchild = XMLHelper::getFirstChildElement(child, shibspconstants::SHIB2ATTRIBUTEMAP_NS, _AttributeDecoder);
300 auto_ptr<xmltooling::QName> q(XMLHelper::getXSIType(dchild));
302 decoder.reset(SPConfig::getConfig().AttributeDecoderManager.newPlugin(*q.get(), dchild));
305 decoder.reset(SPConfig::getConfig().AttributeDecoderManager.newPlugin(StringAttributeDecoderType, nullptr));
307 catch (std::exception& ex) {
308 m_log.error("skipping Attribute (%s), error building AttributeDecoder: %s", id.get(), ex.what());
312 child = XMLHelper::getNextSiblingElement(child, shibspconstants::SHIB2ATTRIBUTEMAP_NS, saml1::Attribute::LOCAL_NAME);
316 // Empty NameFormat implies the usual Shib URI naming defaults.
317 const XMLCh* format = child->getAttributeNS(nullptr, nameFormat);
318 if (!format || XMLString::equals(format, shibspconstants::SHIB1_ATTRIBUTE_NAMESPACE_URI) ||
319 XMLString::equals(format, saml2::Attribute::URI_REFERENCE))
320 format = &chNull; // ignore default Format/Namespace values
322 // Fetch/create the map entry and see if it's a duplicate rule.
323 pair< boost::shared_ptr<AttributeDecoder>,vector<string> >& decl = m_attrMap[pair<xstring,xstring>(name,format)];
325 m_log.warn("skipping duplicate Attribute mapping (same name and nameFormat)");
326 child = XMLHelper::getNextSiblingElement(child, shibspconstants::SHIB2ATTRIBUTEMAP_NS, saml1::Attribute::LOCAL_NAME);
330 if (m_log.isInfoEnabled()) {
331 auto_ptr_char n(name);
332 auto_ptr_char f(format);
333 m_log.info("creating mapping for Attribute %s%s%s", n.get(), *f.get() ? ", Format/Namespace:" : "", f.get());
336 decl.first = decoder;
337 decl.second.push_back(id.get());
338 m_attributeIds.push_back(id.get());
340 // Check for isRequired/isRequested.
341 bool requested = XMLHelper::getAttrBool(child, false, isRequested);
342 bool required = XMLHelper::getAttrBool(child, false, RequestedAttribute::ISREQUIRED_ATTRIB_NAME);
343 if (required || requested)
344 m_requestedAttrs.push_back(tuple<xstring,xstring,bool>(name,format,required));
346 name = child->getAttributeNS(nullptr, _aliases);
348 m_log.warn("attribute mapping rule (%s) uses deprecated aliases feature, consider revising", id.get());
349 auto_ptr_char aliases(name);
350 string dup(aliases.get());
352 set<string> new_aliases;
353 split(new_aliases, dup, is_space(), algorithm::token_compress_on);
354 set<string>::iterator ru = new_aliases.find("REMOTE_USER");
355 if (ru != new_aliases.end()) {
356 m_log.warn("skipping alias, REMOTE_USER is a reserved name");
357 new_aliases.erase(ru);
359 decl.second.insert(decl.second.end(), new_aliases.begin(), new_aliases.end());
360 m_attributeIds.insert(m_attributeIds.end(), new_aliases.begin(), new_aliases.end());
363 child = XMLHelper::getNextSiblingElement(child, shibspconstants::SHIB2ATTRIBUTEMAP_NS, saml1::Attribute::LOCAL_NAME);
366 if (m_metaAttrCaching)
367 m_attrLock.reset(RWLock::create());
370 void XMLExtractorImpl::generateMetadata(SPSSODescriptor& role) const
372 if (m_requestedAttrs.empty())
375 const vector<AttributeConsumingService*>& svcs = const_cast<const SPSSODescriptor*>(&role)->getAttributeConsumingServices();
376 for (vector<AttributeConsumingService*>::const_iterator s =svcs.begin(); s != svcs.end(); ++s) {
377 pair<bool,int> i = (*s)->getIndex();
378 if (i.first && index == i.second)
379 index = i.second + 1;
381 AttributeConsumingService* svc = AttributeConsumingServiceBuilder::buildAttributeConsumingService();
382 role.getAttributeConsumingServices().push_back(svc);
383 svc->setIndex(index);
384 ServiceName* sn = ServiceNameBuilder::buildServiceName();
385 svc->getServiceNames().push_back(sn);
386 sn->setName(dynamic_cast<EntityDescriptor*>(role.getParent())->getEntityID());
387 static const XMLCh english[] = UNICODE_LITERAL_2(e,n);
388 sn->setLang(english);
390 for (vector< tuple<xstring,xstring,bool> >::const_iterator i = m_requestedAttrs.begin(); i != m_requestedAttrs.end(); ++i) {
391 RequestedAttribute* req = RequestedAttributeBuilder::buildRequestedAttribute();
392 svc->getRequestedAttributes().push_back(req);
393 req->setName(i->get<0>().c_str());
394 if (i->get<1>().empty())
395 req->setNameFormat(saml2::Attribute::URI_REFERENCE);
397 req->setNameFormat(i->get<1>().c_str());
399 req->isRequired(true);
403 void XMLExtractorImpl::extractAttributes(
404 const Application& application,
405 const char* assertingParty,
406 const char* relyingParty,
407 const NameIdentifier& nameid,
408 ptr_vector<Attribute>& attributes
411 const XMLCh* format = nameid.getFormat();
412 if (!format || !*format)
413 format = NameIdentifier::UNSPECIFIED;
414 attrmap_t::const_iterator rule;
415 if ((rule = m_attrMap.find(pair<xstring,xstring>(format,xstring()))) != m_attrMap.end()) {
416 auto_ptr<Attribute> a(rule->second.first->decode(nullptr, rule->second.second, &nameid, assertingParty, relyingParty));
418 attributes.push_back(a.get());
422 else if (m_log.isDebugEnabled()) {
423 auto_ptr_char temp(format);
424 m_log.debug("skipping unmapped NameIdentifier with format (%s)", temp.get());
428 void XMLExtractorImpl::extractAttributes(
429 const Application& application,
430 const char* assertingParty,
431 const char* relyingParty,
432 const NameID& nameid,
433 ptr_vector<Attribute>& attributes
436 const XMLCh* format = nameid.getFormat();
437 if (!format || !*format)
438 format = NameID::UNSPECIFIED;
439 attrmap_t::const_iterator rule;
440 if ((rule = m_attrMap.find(pair<xstring,xstring>(format,xstring()))) != m_attrMap.end()) {
441 auto_ptr<Attribute> a(rule->second.first->decode(nullptr, rule->second.second, &nameid, assertingParty, relyingParty));
443 attributes.push_back(a.get());
447 else if (m_log.isDebugEnabled()) {
448 auto_ptr_char temp(format);
449 m_log.debug("skipping unmapped NameID with format (%s)", temp.get());
453 void XMLExtractorImpl::extractAttributes(
454 const Application& application,
455 const GenericRequest* request,
456 const char* assertingParty,
457 const char* relyingParty,
458 const saml1::Attribute& attr,
459 ptr_vector<Attribute>& attributes
462 const XMLCh* name = attr.getAttributeName();
463 const XMLCh* format = attr.getAttributeNamespace();
466 if (!format || XMLString::equals(format, shibspconstants::SHIB1_ATTRIBUTE_NAMESPACE_URI))
468 attrmap_t::const_iterator rule;
469 if ((rule = m_attrMap.find(pair<xstring,xstring>(name,format))) != m_attrMap.end()) {
470 auto_ptr<Attribute> a(rule->second.first->decode(request, rule->second.second, &attr, assertingParty, relyingParty));
472 attributes.push_back(a.get());
476 else if (m_log.isInfoEnabled()) {
477 auto_ptr_char temp1(name);
478 auto_ptr_char temp2(format);
479 m_log.info("skipping unmapped SAML 1.x Attribute with Name: %s%s%s", temp1.get(), *temp2.get() ? ", Namespace:" : "", temp2.get());
483 void XMLExtractorImpl::extractAttributes(
484 const Application& application,
485 const GenericRequest* request,
486 const char* assertingParty,
487 const char* relyingParty,
488 const saml2::Attribute& attr,
489 ptr_vector<Attribute>& attributes
492 const XMLCh* name = attr.getName();
493 const XMLCh* format = attr.getNameFormat();
496 if (!format || !*format)
497 format = saml2::Attribute::UNSPECIFIED;
498 else if (XMLString::equals(format, saml2::Attribute::URI_REFERENCE))
500 attrmap_t::const_iterator rule;
501 if ((rule = m_attrMap.find(pair<xstring,xstring>(name,format))) != m_attrMap.end()) {
502 auto_ptr<Attribute> a(rule->second.first->decode(request, rule->second.second, &attr, assertingParty, relyingParty));
504 attributes.push_back(a.get());
509 else if (XMLString::equals(format, saml2::Attribute::UNSPECIFIED)) {
510 // As a fallback, if the format is "unspecified", null out the value and re-map.
511 if ((rule = m_attrMap.find(pair<xstring,xstring>(name,xstring()))) != m_attrMap.end()) {
512 auto_ptr<Attribute> a(rule->second.first->decode(request, rule->second.second, &attr, assertingParty, relyingParty));
514 attributes.push_back(a.get());
521 if (m_log.isInfoEnabled()) {
522 auto_ptr_char temp1(name);
523 auto_ptr_char temp2(format);
524 m_log.info("skipping unmapped SAML 2.0 Attribute with Name: %s%s%s", temp1.get(), *temp2.get() ? ", Format:" : "", temp2.get());
528 void XMLExtractorImpl::extractAttributes(
529 const Application& application,
530 const GenericRequest* request,
531 const char* assertingParty,
532 const char* relyingParty,
533 const saml1::AttributeStatement& statement,
534 ptr_vector<Attribute>& attributes
537 static void (XMLExtractorImpl::* extract)(
538 const Application&, const GenericRequest*, const char*, const char*, const saml1::Attribute&, ptr_vector<Attribute>&
539 ) const = &XMLExtractorImpl::extractAttributes;
541 make_indirect_iterator(statement.getAttributes().begin()), make_indirect_iterator(statement.getAttributes().end()),
542 boost::bind(extract, this, boost::cref(application), request, assertingParty, relyingParty, _1, boost::ref(attributes))
546 void XMLExtractorImpl::extractAttributes(
547 const Application& application,
548 const GenericRequest* request,
549 const char* assertingParty,
550 const char* relyingParty,
551 const saml2::AttributeStatement& statement,
552 ptr_vector<Attribute>& attributes
555 static void (XMLExtractorImpl::* extract)(
556 const Application&, const GenericRequest*, const char*, const char*, const saml2::Attribute&, ptr_vector<Attribute>&
557 ) const = &XMLExtractorImpl::extractAttributes;
559 make_indirect_iterator(statement.getAttributes().begin()), make_indirect_iterator(statement.getAttributes().end()),
560 boost::bind(extract, this, boost::cref(application), request, assertingParty, relyingParty, _1, boost::ref(attributes))
564 void XMLExtractorImpl::extractAttributes(
565 const Application& application,
566 const GenericRequest* request,
567 const ObservableMetadataProvider* observable,
568 const XMLCh* entityID,
569 const char* relyingParty,
570 const Extensions& ext,
571 ptr_vector<Attribute>& attributes
574 const vector<XMLObject*>& exts = ext.getUnknownXMLObjects();
575 for (vector<XMLObject*>::const_iterator i = exts.begin(); i != exts.end(); ++i) {
576 const EntityAttributes* container = dynamic_cast<const EntityAttributes*>(*i);
580 bool useCache = false;
581 map<const ObservableMetadataProvider*,decoded_t>::iterator cacheEntry;
583 // Check for cached result.
584 if (observable && m_metaAttrCaching) {
585 m_attrLock->rdlock();
586 cacheEntry = m_decodedMap.find(observable);
587 if (cacheEntry == m_decodedMap.end()) {
588 // We need to elevate the lock and retry.
589 m_attrLock->unlock();
590 m_attrLock->wrlock();
591 cacheEntry = m_decodedMap.find(observable);
592 if (cacheEntry == m_decodedMap.end()) {
593 SharedLock locker(m_attrLock, false); // guard in case these throw
595 // It's still brand new, so hook it for cache activation.
596 observable->addObserver(this);
598 // Prime the map reference with an empty decoded map.
599 cacheEntry = m_decodedMap.insert(make_pair(observable,decoded_t())).first;
601 // Downgrade the lock.
602 // We don't have to recheck because we never erase the master map entry entirely, even on changes.
603 locker.release(); // unguard for lock downgrade
604 m_attrLock->unlock();
605 m_attrLock->rdlock();
612 // We're holding the lock, so check the cache.
613 decoded_t::iterator d = cacheEntry->second.find(container);
614 if (d != cacheEntry->second.end()) {
615 SharedLock locker(m_attrLock, false); // pop the lock when we're done
616 for (vector<DDF>::iterator obj = d->second.begin(); obj != d->second.end(); ++obj) {
617 auto_ptr<Attribute> wrapper(Attribute::unmarshall(*obj));
618 m_log.debug("recovered cached metadata attribute (%s)", wrapper->getId());
619 attributes.push_back(wrapper.get());
626 // Add a guard for the lock if we're caching.
627 SharedLock locker(useCache ? m_attrLock.get() : nullptr, false);
629 // Use a holding area to support caching.
630 ptr_vector<Attribute> holding;
632 // Extract attributes into holding area with no asserting party set.
633 static void (XMLExtractorImpl::* extractV2Attr)(
634 const Application&, const GenericRequest*, const char*, const char*, const saml2::Attribute&, ptr_vector<Attribute>&
635 ) const = &XMLExtractorImpl::extractAttributes;
637 make_indirect_iterator(container->getAttributes().begin()), make_indirect_iterator(container->getAttributes().end()),
638 boost::bind(extractV2Attr, this, boost::ref(application), request, (const char*)nullptr, relyingParty, _1, boost::ref(holding))
641 if (entityID && m_entityAssertions) {
642 const vector<saml2::Assertion*>& asserts = container->getAssertions();
643 for (indirect_iterator<vector<saml2::Assertion*>::const_iterator> assert = make_indirect_iterator(asserts.begin());
644 assert != make_indirect_iterator(asserts.end()); ++assert) {
645 if (!(assert->getSignature())) {
646 if (m_log.isDebugEnabled()) {
647 auto_ptr_char eid(entityID);
648 m_log.debug("skipping unsigned assertion in metadata extension for entity (%s)", eid.get());
652 else if (assert->getAttributeStatements().empty()) {
653 if (m_log.isDebugEnabled()) {
654 auto_ptr_char eid(entityID);
655 m_log.debug("skipping assertion with no AttributeStatement in metadata extension for entity (%s)", eid.get());
661 const NameID* subject = assert->getSubject() ? assert->getSubject()->getNameID() : nullptr;
663 !XMLString::equals(subject->getFormat(), NameID::ENTITY) ||
664 !XMLString::equals(subject->getName(), entityID)) {
665 if (m_log.isDebugEnabled()) {
666 auto_ptr_char eid(entityID);
667 m_log.debug("skipping assertion with improper Subject in metadata extension for entity (%s)", eid.get());
674 // Set up and evaluate a policy for an AA asserting attributes to us.
675 shibsp::SecurityPolicy policy(application, &AttributeAuthorityDescriptor::ELEMENT_QNAME, false, m_policyId.c_str());
676 Locker locker(m_metadata.get());
678 policy.setMetadataProvider(m_metadata.get());
680 policy.setTrustEngine(m_trust.get());
681 // Populate recipient as audience.
682 const XMLCh* issuer = assert->getIssuer() ? assert->getIssuer()->getName() : nullptr;
683 policy.getAudiences().push_back(application.getRelyingParty(issuer)->getXMLString("entityID").second);
685 // Extract assertion information for policy.
686 policy.setMessageID(assert->getID());
687 policy.setIssueInstant(assert->getIssueInstantEpoch());
688 policy.setIssuer(assert->getIssuer());
690 // Look up metadata for issuer.
691 if (policy.getIssuer() && policy.getMetadataProvider()) {
692 if (policy.getIssuer()->getFormat() && !XMLString::equals(policy.getIssuer()->getFormat(), saml2::NameIDType::ENTITY)) {
693 m_log.debug("non-system entity issuer, skipping metadata lookup");
696 m_log.debug("searching metadata for entity assertion issuer...");
697 pair<const EntityDescriptor*,const RoleDescriptor*> lookup;
698 MetadataProvider::Criteria& mc = policy.getMetadataProviderCriteria();
699 mc.entityID_unicode = policy.getIssuer()->getName();
700 mc.role = &AttributeAuthorityDescriptor::ELEMENT_QNAME;
701 mc.protocol = samlconstants::SAML20P_NS;
702 lookup = policy.getMetadataProvider()->getEntityDescriptor(mc);
704 auto_ptr_char iname(policy.getIssuer()->getName());
705 m_log.debug("no metadata found, can't establish identity of issuer (%s)", iname.get());
707 else if (!lookup.second) {
708 m_log.debug("unable to find compatible AA role in metadata");
711 policy.setIssuerMetadata(lookup.second);
716 // Authenticate the assertion. We have to clone and marshall it to establish the signature for verification.
717 scoped_ptr<saml2::Assertion> tokencopy(assert->cloneAssertion());
718 tokencopy->marshall();
719 policy.evaluate(*tokencopy);
720 if (!policy.isAuthenticated()) {
721 if (m_log.isDebugEnabled()) {
722 auto_ptr_char tempid(tokencopy->getID());
723 auto_ptr_char eid(entityID);
725 "failed to authenticate assertion (%s) in metadata extension for entity (%s)", tempid.get(), eid.get()
731 // Override the asserting/relying party names based on this new issuer.
732 const EntityDescriptor* inlineEntity =
733 policy.getIssuerMetadata() ? dynamic_cast<const EntityDescriptor*>(policy.getIssuerMetadata()->getParent()) : nullptr;
734 auto_ptr_char inlineAssertingParty(inlineEntity ? inlineEntity->getEntityID() : nullptr);
735 relyingParty = application.getRelyingParty(inlineEntity)->getString("entityID").second;
737 // Use a private holding area for filtering purposes.
738 ptr_vector<Attribute> holding2;
739 const vector<saml2::Attribute*>& attrs2 =
740 const_cast<const saml2::AttributeStatement*>(tokencopy->getAttributeStatements().front())->getAttributes();
742 make_indirect_iterator(attrs2.begin()), make_indirect_iterator(attrs2.end()),
743 boost::bind(extractV2Attr, this, boost::ref(application), request, inlineAssertingParty.get(), relyingParty, _1, boost::ref(holding2))
746 // Now we locally filter the attributes so that the actual issuer can be properly set.
747 // If we relied on outside filtering, the attributes couldn't be distinguished from the
748 // ones that come from the user's IdP.
749 if (m_filter && !holding2.empty()) {
751 // The filter API uses an unsafe container, so we have to transfer everything into one and back.
752 vector<Attribute*> unsafe_holding2;
754 // Use a local exception context since the container is unsafe.
756 while (!holding2.empty()) {
757 ptr_vector<Attribute>::auto_type ptr = holding2.pop_back();
758 unsafe_holding2.push_back(ptr.get());
761 BasicFilteringContext fc(application, unsafe_holding2, policy.getIssuerMetadata());
762 Locker filtlocker(m_filter.get());
763 m_filter->filterAttributes(fc, unsafe_holding2);
765 // Transfer back to safe container
766 while (!unsafe_holding2.empty()) {
767 auto_ptr<Attribute> ptr(unsafe_holding2.back());
768 unsafe_holding2.pop_back();
769 holding2.push_back(ptr.get());
773 catch (std::exception& ex) {
774 m_log.error("caught exception filtering attributes: %s", ex.what());
775 m_log.error("dumping extracted attributes due to filtering exception");
776 for_each(unsafe_holding2.begin(), unsafe_holding2.end(), xmltooling::cleanup<Attribute>());
777 holding2.clear(); // in case the exception was during transfer between containers
781 if (!holding2.empty()) {
782 // Copy them over to the main holding tank, which transfers ownership.
783 holding.transfer(holding.end(), holding2);
786 catch (std::exception& ex) {
787 // Known exceptions are handled gracefully by skipping the assertion.
788 if (m_log.isDebugEnabled()) {
789 auto_ptr_char tempid(assert->getID());
790 auto_ptr_char eid(entityID);
792 "exception authenticating assertion (%s) in metadata extension for entity (%s): %s",
803 if (!holding.empty()) {
805 locker.release(); // unguard to upgrade lock
806 m_attrLock->unlock();
807 m_attrLock->wrlock();
808 SharedLock locker2(m_attrLock, false); // pop the lock when we're done
809 if (cacheEntry->second.count(container) == 0) {
810 static void (vector<DDF>::* push_back)(DDF const &) = &vector<DDF>::push_back;
811 vector<DDF>& marshalled = cacheEntry->second[container];
813 holding.begin(), holding.end(),
814 boost::bind(push_back, boost::ref(marshalled), boost::bind(&Attribute::marshall, _1))
819 // Copy them to the output parameter, which transfers ownership.
820 attributes.transfer(attributes.end(), holding);
823 // If the lock is held, it's guarded.
825 break; // only process a single extension element
829 void XMLExtractor::extractAttributes(
830 const Application& application, const GenericRequest* request, const RoleDescriptor* issuer, const XMLObject& xmlObject, vector<Attribute*>& attributes
836 ptr_vector<Attribute> holding;
837 extractAttributes(application, request, issuer, xmlObject, holding);
839 // Transfer ownership from the ptr_vector to the unsafe vector for API compatibility.
840 // Any throws should leave each container in a consistent state. The holding container
841 // is freed by us, and the result container by the caller.
842 while (!holding.empty()) {
843 ptr_vector<Attribute>::auto_type ptr = holding.pop_back();
844 attributes.push_back(ptr.get());
849 void XMLExtractor::extractAttributes(
850 const Application& application, const GenericRequest* request, const RoleDescriptor* issuer, const XMLObject& xmlObject, ptr_vector<Attribute>& attributes
853 static void (XMLExtractor::* extractEncrypted)(
854 const Application&, const GenericRequest*, const RoleDescriptor*, const XMLObject&, ptr_vector<Attribute>&
855 ) const = &XMLExtractor::extractAttributes;
856 static void (XMLExtractorImpl::* extractV1Statement)(
857 const Application&, const GenericRequest*, const char*, const char*, const saml1::AttributeStatement&, ptr_vector<Attribute>&
858 ) const = &XMLExtractorImpl::extractAttributes;
860 const EntityDescriptor* entity = issuer ? dynamic_cast<const EntityDescriptor*>(issuer->getParent()) : nullptr;
861 const char* relyingParty = application.getRelyingParty(entity)->getString("entityID").second;
863 // Check for statements.
864 if (XMLString::equals(xmlObject.getElementQName().getLocalPart(), saml1::AttributeStatement::LOCAL_NAME)) {
865 const saml2::AttributeStatement* statement2 = dynamic_cast<const saml2::AttributeStatement*>(&xmlObject);
867 auto_ptr_char assertingParty(entity ? entity->getEntityID() : nullptr);
868 m_impl->extractAttributes(application, request, assertingParty.get(), relyingParty, *statement2, attributes);
869 // Handle EncryptedAttributes inline so we have access to the role descriptor.
870 const vector<saml2::EncryptedAttribute*>& encattrs = statement2->getEncryptedAttributes();
872 make_indirect_iterator(encattrs.begin()), make_indirect_iterator(encattrs.end()),
873 boost::bind(extractEncrypted, this, boost::ref(application), request, issuer, _1, boost::ref(attributes))
878 const saml1::AttributeStatement* statement1 = dynamic_cast<const saml1::AttributeStatement*>(&xmlObject);
880 auto_ptr_char assertingParty(entity ? entity->getEntityID() : nullptr);
881 m_impl->extractAttributes(application, request, assertingParty.get(), relyingParty, *statement1, attributes);
885 throw AttributeExtractionException("Unable to extract attributes, unknown object type.");
888 // Check for assertions.
889 if (XMLString::equals(xmlObject.getElementQName().getLocalPart(), saml1::Assertion::LOCAL_NAME)) {
890 const saml2::Assertion* token2 = dynamic_cast<const saml2::Assertion*>(&xmlObject);
892 auto_ptr_char assertingParty(entity ? entity->getEntityID() : nullptr);
893 const vector<saml2::AttributeStatement*>& statements = token2->getAttributeStatements();
894 for (indirect_iterator<vector<saml2::AttributeStatement*>::const_iterator> s = make_indirect_iterator(statements.begin());
895 s != make_indirect_iterator(statements.end()); ++s) {
896 m_impl->extractAttributes(application, request, assertingParty.get(), relyingParty, *s, attributes);
897 // Handle EncryptedAttributes inline so we have access to the role descriptor.
898 const vector<saml2::EncryptedAttribute*>& encattrs = const_cast<const saml2::AttributeStatement&>(*s).getEncryptedAttributes();
900 make_indirect_iterator(encattrs.begin()), make_indirect_iterator(encattrs.end()),
901 boost::bind(extractEncrypted, this, boost::ref(application), request, issuer, _1, boost::ref(attributes))
907 const saml1::Assertion* token1 = dynamic_cast<const saml1::Assertion*>(&xmlObject);
909 auto_ptr_char assertingParty(entity ? entity->getEntityID() : nullptr);
910 const vector<saml1::AttributeStatement*>& statements = token1->getAttributeStatements();
911 for_each(make_indirect_iterator(statements.begin()), make_indirect_iterator(statements.end()),
912 boost::bind(extractV1Statement, m_impl.get(), boost::ref(application), request, assertingParty.get(), relyingParty, _1, boost::ref(attributes))
917 throw AttributeExtractionException("Unable to extract attributes, unknown object type.");
920 // Check for metadata.
921 if (XMLString::equals(xmlObject.getElementQName().getNamespaceURI(), samlconstants::SAML20MD_NS)) {
922 const RoleDescriptor* roleToExtract = dynamic_cast<const RoleDescriptor*>(&xmlObject);
923 const EntityDescriptor* entityToExtract = roleToExtract ? dynamic_cast<const EntityDescriptor*>(roleToExtract->getParent()) : nullptr;
924 if (!entityToExtract)
925 throw AttributeExtractionException("Unable to extract attributes, unknown metadata object type.");
926 const Extensions* ext = entityToExtract->getExtensions();
928 m_impl->extractAttributes(
931 dynamic_cast<const ObservableMetadataProvider*>(application.getMetadataProvider(false)),
932 entityToExtract->getEntityID(),
938 const EntitiesDescriptor* group = dynamic_cast<const EntitiesDescriptor*>(entityToExtract->getParent());
940 ext = group->getExtensions();
942 m_impl->extractAttributes(
945 dynamic_cast<const ObservableMetadataProvider*>(application.getMetadataProvider(false)),
946 nullptr, // not an entity, so inline assertions won't be processed
952 group = dynamic_cast<const EntitiesDescriptor*>(group->getParent());
957 // Check for attributes.
958 if (XMLString::equals(xmlObject.getElementQName().getLocalPart(), saml1::Attribute::LOCAL_NAME)) {
959 auto_ptr_char assertingParty(entity ? entity->getEntityID() : nullptr);
960 const saml2::Attribute* attr2 = dynamic_cast<const saml2::Attribute*>(&xmlObject);
962 return m_impl->extractAttributes(application, request, assertingParty.get(), relyingParty, *attr2, attributes);
964 const saml1::Attribute* attr1 = dynamic_cast<const saml1::Attribute*>(&xmlObject);
966 return m_impl->extractAttributes(application, request, assertingParty.get(), relyingParty, *attr1, attributes);
968 throw AttributeExtractionException("Unable to extract attributes, unknown object type.");
971 if (XMLString::equals(xmlObject.getElementQName().getLocalPart(), EncryptedAttribute::LOCAL_NAME)) {
972 const EncryptedAttribute* encattr = dynamic_cast<const EncryptedAttribute*>(&xmlObject);
974 const XMLCh* recipient = application.getXMLString("entityID").second;
975 CredentialResolver* cr = application.getCredentialResolver();
977 m_log.warn("found encrypted attribute, but no CredentialResolver was available");
982 Locker credlocker(cr);
984 MetadataCredentialCriteria mcc(*issuer);
985 scoped_ptr<XMLObject> decrypted(encattr->decrypt(*cr, recipient, &mcc));
986 if (m_log.isDebugEnabled())
987 m_log.debugStream() << "decrypted Attribute: " << *decrypted << logging::eol;
988 return extractAttributes(application, request, issuer, *decrypted, attributes);
991 scoped_ptr<XMLObject> decrypted(encattr->decrypt(*cr, recipient));
992 if (m_log.isDebugEnabled())
993 m_log.debugStream() << "decrypted Attribute: " << *decrypted << logging::eol;
994 return extractAttributes(application, request, issuer, *decrypted, attributes);
997 catch (std::exception& ex) {
998 m_log.error("failed to decrypt Attribute: %s", ex.what());
1004 // Check for NameIDs.
1005 const NameID* name2 = dynamic_cast<const NameID*>(&xmlObject);
1007 auto_ptr_char assertingParty(entity ? entity->getEntityID() : nullptr);
1008 return m_impl->extractAttributes(application, assertingParty.get(), relyingParty, *name2, attributes);
1011 const NameIdentifier* name1 = dynamic_cast<const NameIdentifier*>(&xmlObject);
1013 auto_ptr_char assertingParty(entity ? entity->getEntityID() : nullptr);
1014 return m_impl->extractAttributes(application, assertingParty.get(), relyingParty, *name1, attributes);
1017 m_log.debug("unable to extract attributes, unknown XML object type: %s", xmlObject.getElementQName().toString().c_str());
1020 pair<bool,DOMElement*> XMLExtractor::background_load()
1022 // Load from source using base class.
1023 pair<bool,DOMElement*> raw = ReloadableXMLFile::load();
1025 // If we own it, wrap it.
1026 XercesJanitor<DOMDocument> docjanitor(raw.first ? raw.second->getOwnerDocument() : nullptr);
1028 scoped_ptr<XMLExtractorImpl> impl(new XMLExtractorImpl(raw.second, m_log));
1030 // If we held the document, transfer it to the impl. If we didn't, it's a no-op.
1031 impl->setDocument(docjanitor.release());
1033 // Perform the swap inside a lock.
1036 SharedLock locker(m_lock, false);
1039 return make_pair(false,(DOMElement*)nullptr);