2 * Copyright 2001-2010 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 * XMLAttributeExtractor.cpp
20 * AttributeExtractor based on an XML mapping file.
24 #include "exceptions.h"
25 #include "Application.h"
26 #include "ServiceProvider.h"
27 #include "attribute/Attribute.h"
28 #include "attribute/AttributeDecoder.h"
29 #include "attribute/filtering/AttributeFilter.h"
30 #include "attribute/filtering/BasicFilteringContext.h"
31 #include "attribute/resolver/AttributeExtractor.h"
32 #include "remoting/ddf.h"
33 #include "security/SecurityPolicy.h"
34 #include "util/SPConstants.h"
36 #include <saml/SAMLConfig.h>
37 #include <saml/saml1/core/Assertions.h>
38 #include <saml/saml2/core/Assertions.h>
39 #include <saml/saml2/metadata/Metadata.h>
40 #include <saml/saml2/metadata/MetadataCredentialCriteria.h>
41 #include <saml/saml2/metadata/ObservableMetadataProvider.h>
42 #include <xmltooling/XMLToolingConfig.h>
43 #include <xmltooling/security/TrustEngine.h>
44 #include <xmltooling/util/NDC.h>
45 #include <xmltooling/util/ReloadableXMLFile.h>
46 #include <xmltooling/util/Threads.h>
47 #include <xmltooling/util/XMLHelper.h>
48 #include <xercesc/util/XMLUniDefs.hpp>
50 using namespace shibsp;
51 using namespace opensaml::saml2md;
52 using namespace opensaml;
53 using namespace xmltooling;
55 using saml1::NameIdentifier;
57 using saml2::EncryptedAttribute;
61 #if defined (_MSC_VER)
62 #pragma warning( push )
63 #pragma warning( disable : 4250 )
66 class XMLExtractorImpl : public ObservableMetadataProvider::Observer
69 XMLExtractorImpl(const DOMElement* e, Category& log);
71 for (map<const ObservableMetadataProvider*,decoded_t>::iterator i=m_decodedMap.begin(); i!=m_decodedMap.end(); ++i) {
72 i->first->removeObserver(this);
73 for (decoded_t::iterator attrs = i->second.begin(); attrs!=i->second.end(); ++attrs)
74 for_each(attrs->second.begin(), attrs->second.end(), mem_fun_ref<DDF&,DDF>(&DDF::destroy));
80 for (attrmap_t::iterator j = m_attrMap.begin(); j!=m_attrMap.end(); ++j)
81 delete j->second.first;
83 m_document->release();
86 void setDocument(DOMDocument* doc) {
90 void onEvent(const ObservableMetadataProvider& metadata) const {
91 // Destroy attributes we cached from this provider.
93 decoded_t& d = m_decodedMap[&metadata];
94 for (decoded_t::iterator a = d.begin(); a!=d.end(); ++a)
95 for_each(a->second.begin(), a->second.end(), mem_fun_ref<DDF&,DDF>(&DDF::destroy));
100 void extractAttributes(
101 const Application& application,
102 const char* assertingParty,
103 const char* relyingParty,
104 const NameIdentifier& nameid,
105 vector<Attribute*>& attributes
107 void extractAttributes(
108 const Application& application,
109 const char* assertingParty,
110 const char* relyingParty,
111 const NameID& nameid,
112 vector<Attribute*>& attributes
114 void extractAttributes(
115 const Application& application,
116 const char* assertingParty,
117 const char* relyingParty,
118 const saml1::Attribute& attr,
119 vector<Attribute*>& attributes
121 void extractAttributes(
122 const Application& application,
123 const char* assertingParty,
124 const char* relyingParty,
125 const saml2::Attribute& attr,
126 vector<Attribute*>& attributes
128 void extractAttributes(
129 const Application& application,
130 const char* assertingParty,
131 const char* relyingParty,
132 const saml1::AttributeStatement& statement,
133 vector<Attribute*>& attributes
135 void extractAttributes(
136 const Application& application,
137 const char* assertingParty,
138 const char* relyingParty,
139 const saml2::AttributeStatement& statement,
140 vector<Attribute*>& attributes
142 void extractAttributes(
143 const Application& application,
144 const ObservableMetadataProvider* observable,
145 const XMLCh* entityID,
146 const char* relyingParty,
147 const Extensions& ext,
148 vector<Attribute*>& attributes
151 void getAttributeIds(vector<string>& attributes) const {
152 attributes.insert(attributes.end(), m_attributeIds.begin(), m_attributeIds.end());
157 DOMDocument* m_document;
159 typedef map< pair<xstring,xstring>,pair< AttributeDecoder*,vector<string> > > attrmap_t;
161 typedef map< pair<string,string>,pair< AttributeDecoder*,vector<string> > > attrmap_t;
164 vector<string> m_attributeIds;
166 // settings for embedded assertions in metadata
168 MetadataProvider* m_metadata;
169 TrustEngine* m_trust;
170 AttributeFilter* m_filter;
171 bool m_entityAssertions;
173 // manages caching of decoded Attributes
174 mutable RWLock* m_attrLock;
175 typedef map< const EntityAttributes*,vector<DDF> > decoded_t;
176 mutable map<const ObservableMetadataProvider*,decoded_t> m_decodedMap;
179 class XMLExtractor : public AttributeExtractor, public ReloadableXMLFile
182 XMLExtractor(const DOMElement* e) : ReloadableXMLFile(e, Category::getInstance(SHIBSP_LOGCAT".AttributeExtractor.XML")), m_impl(nullptr) {
190 void extractAttributes(
191 const Application& application, const RoleDescriptor* issuer, const XMLObject& xmlObject, vector<Attribute*>& attributes
194 void getAttributeIds(std::vector<std::string>& attributes) const {
196 m_impl->getAttributeIds(attributes);
200 pair<bool,DOMElement*> background_load();
203 XMLExtractorImpl* m_impl;
206 #if defined (_MSC_VER)
207 #pragma warning( pop )
210 AttributeExtractor* SHIBSP_DLLLOCAL XMLAttributeExtractorFactory(const DOMElement* const & e)
212 return new XMLExtractor(e);
215 static const XMLCh _aliases[] = UNICODE_LITERAL_7(a,l,i,a,s,e,s);
216 static const XMLCh _AttributeDecoder[] = UNICODE_LITERAL_16(A,t,t,r,i,b,u,t,e,D,e,c,o,d,e,r);
217 static const XMLCh _AttributeFilter[] = UNICODE_LITERAL_15(A,t,t,r,i,b,u,t,e,F,i,l,t,e,r);
218 static const XMLCh Attributes[] = UNICODE_LITERAL_10(A,t,t,r,i,b,u,t,e,s);
219 static const XMLCh _id[] = UNICODE_LITERAL_2(i,d);
220 static const XMLCh _MetadataProvider[] = UNICODE_LITERAL_16(M,e,t,a,d,a,t,a,P,r,o,v,i,d,e,r);
221 static const XMLCh _name[] = UNICODE_LITERAL_4(n,a,m,e);
222 static const XMLCh nameFormat[] = UNICODE_LITERAL_10(n,a,m,e,F,o,r,m,a,t);
223 static const XMLCh metadataPolicyId[] = UNICODE_LITERAL_16(m,e,t,a,d,a,t,a,P,o,l,i,c,y,I,d);
224 static const XMLCh _TrustEngine[] = UNICODE_LITERAL_11(T,r,u,s,t,E,n,g,i,n,e);
225 static const XMLCh _type[] = UNICODE_LITERAL_4(t,y,p,e);
228 XMLExtractorImpl::XMLExtractorImpl(const DOMElement* e, Category& log)
231 m_policyId(XMLHelper::getAttrString(e, nullptr, metadataPolicyId)),
235 m_entityAssertions(true),
239 xmltooling::NDC ndc("XMLExtractorImpl");
242 if (!XMLHelper::isNodeNamed(e, shibspconstants::SHIB2ATTRIBUTEMAP_NS, Attributes))
243 throw ConfigurationException("XML AttributeExtractor requires am:Attributes at root of configuration.");
245 DOMElement* child = XMLHelper::getFirstChildElement(e, shibspconstants::SHIB2ATTRIBUTEMAP_NS, _MetadataProvider);
248 string t(XMLHelper::getAttrString(child, nullptr, _type));
250 throw ConfigurationException("MetadataProvider element missing type attribute.");
251 m_log.info("building MetadataProvider of type %s...", t.c_str());
252 auto_ptr<MetadataProvider> mp(SAMLConfig::getConfig().MetadataProviderManager.newPlugin(t.c_str(), child));
254 m_metadata = mp.release();
256 catch (exception& ex) {
257 m_entityAssertions = false;
258 m_log.crit("error building/initializing dedicated MetadataProvider: %s", ex.what());
259 m_log.crit("disabling support for Assertions in EntityAttributes extension");
263 if (m_entityAssertions) {
264 child = XMLHelper::getFirstChildElement(e, shibspconstants::SHIB2ATTRIBUTEMAP_NS, _TrustEngine);
267 string t(XMLHelper::getAttrString(child, nullptr, _type));
269 throw ConfigurationException("TrustEngine element missing type attribute.");
270 m_log.info("building TrustEngine of type %s...", t.c_str());
271 m_trust = XMLToolingConfig::getConfig().TrustEngineManager.newPlugin(t.c_str(), child);
273 catch (exception& ex) {
274 m_entityAssertions = false;
275 m_log.crit("error building/initializing dedicated TrustEngine: %s", ex.what());
276 m_log.crit("disabling support for Assertions in EntityAttributes extension");
281 if (m_entityAssertions) {
282 child = XMLHelper::getFirstChildElement(e, shibspconstants::SHIB2ATTRIBUTEMAP_NS, _AttributeFilter);
285 string t(XMLHelper::getAttrString(child, nullptr, _type));
287 throw ConfigurationException("AttributeFilter element missing type attribute.");
288 m_log.info("building AttributeFilter of type %s...", t.c_str());
289 m_filter = SPConfig::getConfig().AttributeFilterManager.newPlugin(t.c_str(), child);
291 catch (exception& ex) {
292 m_entityAssertions = false;
293 m_log.crit("error building/initializing dedicated AttributeFilter: %s", ex.what());
294 m_log.crit("disabling support for Assertions in EntityAttributes extension");
299 child = XMLHelper::getFirstChildElement(e, shibspconstants::SHIB2ATTRIBUTEMAP_NS, saml1::Attribute::LOCAL_NAME);
301 // Check for missing name or id.
302 const XMLCh* name = child->getAttributeNS(nullptr, _name);
303 if (!name || !*name) {
304 m_log.warn("skipping Attribute with no name");
305 child = XMLHelper::getNextSiblingElement(child, shibspconstants::SHIB2ATTRIBUTEMAP_NS, saml1::Attribute::LOCAL_NAME);
309 auto_ptr_char id(child->getAttributeNS(nullptr, _id));
310 if (!id.get() || !*id.get()) {
311 m_log.warn("skipping Attribute with no id");
312 child = XMLHelper::getNextSiblingElement(child, shibspconstants::SHIB2ATTRIBUTEMAP_NS, saml1::Attribute::LOCAL_NAME);
315 else if (!strcmp(id.get(), "REMOTE_USER")) {
316 m_log.warn("skipping Attribute, id of REMOTE_USER is a reserved name");
317 child = XMLHelper::getNextSiblingElement(child, shibspconstants::SHIB2ATTRIBUTEMAP_NS, saml1::Attribute::LOCAL_NAME);
321 AttributeDecoder* decoder=nullptr;
323 DOMElement* dchild = XMLHelper::getFirstChildElement(child, shibspconstants::SHIB2ATTRIBUTEMAP_NS, _AttributeDecoder);
325 auto_ptr<xmltooling::QName> q(XMLHelper::getXSIType(dchild));
327 decoder = SPConfig::getConfig().AttributeDecoderManager.newPlugin(*q.get(), dchild);
330 decoder = SPConfig::getConfig().AttributeDecoderManager.newPlugin(StringAttributeDecoderType, nullptr);
332 catch (exception& ex) {
333 m_log.error("skipping Attribute (%s), error building AttributeDecoder: %s", id.get(), ex.what());
337 child = XMLHelper::getNextSiblingElement(child, shibspconstants::SHIB2ATTRIBUTEMAP_NS, saml1::Attribute::LOCAL_NAME);
341 // Empty NameFormat implies the usual Shib URI naming defaults.
342 const XMLCh* format = child->getAttributeNS(nullptr, nameFormat);
343 if (!format || XMLString::equals(format, shibspconstants::SHIB1_ATTRIBUTE_NAMESPACE_URI) ||
344 XMLString::equals(format, saml2::Attribute::URI_REFERENCE))
345 format = &chNull; // ignore default Format/Namespace values
347 // Fetch/create the map entry and see if it's a duplicate rule.
349 pair< AttributeDecoder*,vector<string> >& decl = m_attrMap[pair<xstring,xstring>(name,format)];
351 auto_ptr_char n(name);
352 auto_ptr_char f(format);
353 pair< AttributeDecoder*,vector<string> >& decl = m_attrMap[pair<string,string>(n.get(),f.get())];
356 m_log.warn("skipping duplicate Attribute mapping (same name and nameFormat)");
358 child = XMLHelper::getNextSiblingElement(child, shibspconstants::SHIB2ATTRIBUTEMAP_NS, saml1::Attribute::LOCAL_NAME);
362 if (m_log.isInfoEnabled()) {
364 auto_ptr_char n(name);
365 auto_ptr_char f(format);
367 m_log.info("creating mapping for Attribute %s%s%s", n.get(), *f.get() ? ", Format/Namespace:" : "", f.get());
370 decl.first = decoder;
371 decl.second.push_back(id.get());
372 m_attributeIds.push_back(id.get());
374 name = child->getAttributeNS(nullptr, _aliases);
376 auto_ptr_char aliases(name);
378 char* start = const_cast<char*>(aliases.get());
379 while (start && *start) {
380 while (*start && isspace(*start))
384 pos = strchr(start,' ');
387 if (strcmp(start, "REMOTE_USER")) {
388 decl.second.push_back(start);
389 m_attributeIds.push_back(start);
392 m_log.warn("skipping alias, REMOTE_USER is a reserved name");
394 start = pos ? pos+1 : nullptr;
398 child = XMLHelper::getNextSiblingElement(child, shibspconstants::SHIB2ATTRIBUTEMAP_NS, saml1::Attribute::LOCAL_NAME);
401 m_attrLock = RWLock::create();
404 void XMLExtractorImpl::extractAttributes(
405 const Application& application,
406 const char* assertingParty,
407 const char* relyingParty,
408 const NameIdentifier& nameid,
409 vector<Attribute*>& attributes
413 map< pair<xstring,xstring>,pair< AttributeDecoder*,vector<string> > >::const_iterator rule;
415 map< pair<string,string>,pair< AttributeDecoder*,vector<string> > >::const_iterator rule;
418 const XMLCh* format = nameid.getFormat();
419 if (!format || !*format)
420 format = NameIdentifier::UNSPECIFIED;
422 if ((rule=m_attrMap.find(pair<xstring,xstring>(format,xstring()))) != m_attrMap.end()) {
424 auto_ptr_char temp(format);
425 if ((rule=m_attrMap.find(pair<string,string>(temp.get(),string()))) != m_attrMap.end()) {
427 Attribute* a = rule->second.first->decode(rule->second.second, &nameid, assertingParty, relyingParty);
429 attributes.push_back(a);
431 else if (m_log.isDebugEnabled()) {
433 auto_ptr_char temp(format);
435 m_log.debug("skipping unmapped NameIdentifier with format (%s)", temp.get());
439 void XMLExtractorImpl::extractAttributes(
440 const Application& application,
441 const char* assertingParty,
442 const char* relyingParty,
443 const NameID& nameid,
444 vector<Attribute*>& attributes
448 map< pair<xstring,xstring>,pair< AttributeDecoder*,vector<string> > >::const_iterator rule;
450 map< pair<string,string>,pair< AttributeDecoder*,vector<string> > >::const_iterator rule;
453 const XMLCh* format = nameid.getFormat();
454 if (!format || !*format)
455 format = NameID::UNSPECIFIED;
457 if ((rule=m_attrMap.find(pair<xstring,xstring>(format,xstring()))) != m_attrMap.end()) {
459 auto_ptr_char temp(format);
460 if ((rule=m_attrMap.find(pair<string,string>(temp.get(),string()))) != m_attrMap.end()) {
462 Attribute* a = rule->second.first->decode(rule->second.second, &nameid, assertingParty, relyingParty);
464 attributes.push_back(a);
466 else if (m_log.isDebugEnabled()) {
468 auto_ptr_char temp(format);
470 m_log.debug("skipping unmapped NameID with format (%s)", temp.get());
474 void XMLExtractorImpl::extractAttributes(
475 const Application& application,
476 const char* assertingParty,
477 const char* relyingParty,
478 const saml1::Attribute& attr,
479 vector<Attribute*>& attributes
483 map< pair<xstring,xstring>,pair< AttributeDecoder*,vector<string> > >::const_iterator rule;
485 map< pair<string,string>,pair< AttributeDecoder*,vector<string> > >::const_iterator rule;
488 const XMLCh* name = attr.getAttributeName();
489 const XMLCh* format = attr.getAttributeNamespace();
492 if (!format || XMLString::equals(format, shibspconstants::SHIB1_ATTRIBUTE_NAMESPACE_URI))
495 if ((rule=m_attrMap.find(pair<xstring,xstring>(name,format))) != m_attrMap.end()) {
497 auto_ptr_char temp1(name);
498 auto_ptr_char temp2(format);
499 if ((rule=m_attrMap.find(pair<string,string>(temp1.get(),temp2.get()))) != m_attrMap.end()) {
501 Attribute* a = rule->second.first->decode(rule->second.second, &attr, assertingParty, relyingParty);
503 attributes.push_back(a);
505 else if (m_log.isInfoEnabled()) {
507 auto_ptr_char temp1(name);
508 auto_ptr_char temp2(format);
510 m_log.info("skipping unmapped SAML 1.x Attribute with Name: %s%s%s", temp1.get(), *temp2.get() ? ", Namespace:" : "", temp2.get());
514 void XMLExtractorImpl::extractAttributes(
515 const Application& application,
516 const char* assertingParty,
517 const char* relyingParty,
518 const saml2::Attribute& attr,
519 vector<Attribute*>& attributes
523 map< pair<xstring,xstring>,pair< AttributeDecoder*,vector<string> > >::const_iterator rule;
525 map< pair<string,string>,pair< AttributeDecoder*,vector<string> > >::const_iterator rule;
528 const XMLCh* name = attr.getName();
529 const XMLCh* format = attr.getNameFormat();
532 if (!format || !*format)
533 format = saml2::Attribute::UNSPECIFIED;
534 else if (XMLString::equals(format, saml2::Attribute::URI_REFERENCE))
538 if ((rule=m_attrMap.find(pair<xstring,xstring>(name,format))) != m_attrMap.end()) {
540 auto_ptr_char temp1(name);
541 auto_ptr_char temp2(format);
542 if ((rule=m_attrMap.find(pair<string,string>(temp1.get(),temp2.get()))) != m_attrMap.end()) {
544 Attribute* a = rule->second.first->decode(rule->second.second, &attr, assertingParty, relyingParty);
546 attributes.push_back(a);
550 else if (XMLString::equals(format, saml2::Attribute::UNSPECIFIED)) {
551 // As a fallback, if the format is "unspecified", null out the value and re-map.
553 if ((rule=m_attrMap.find(pair<xstring,xstring>(name,xstring()))) != m_attrMap.end()) {
555 if ((rule=m_attrMap.find(pair<string,string>(temp1.get(),string()))) != m_attrMap.end()) {
557 Attribute* a = rule->second.first->decode(rule->second.second, &attr, assertingParty, relyingParty);
559 attributes.push_back(a);
565 if (m_log.isInfoEnabled()) {
567 auto_ptr_char temp1(name);
568 auto_ptr_char temp2(format);
570 m_log.info("skipping unmapped SAML 2.0 Attribute with Name: %s%s%s", temp1.get(), *temp2.get() ? ", Format:" : "", temp2.get());
574 void XMLExtractorImpl::extractAttributes(
575 const Application& application,
576 const char* assertingParty,
577 const char* relyingParty,
578 const saml1::AttributeStatement& statement,
579 vector<Attribute*>& attributes
582 const vector<saml1::Attribute*>& attrs = statement.getAttributes();
583 for (vector<saml1::Attribute*>::const_iterator a = attrs.begin(); a!=attrs.end(); ++a)
584 extractAttributes(application, assertingParty, relyingParty, *(*a), attributes);
587 void XMLExtractorImpl::extractAttributes(
588 const Application& application,
589 const char* assertingParty,
590 const char* relyingParty,
591 const saml2::AttributeStatement& statement,
592 vector<Attribute*>& attributes
595 const vector<saml2::Attribute*>& attrs = statement.getAttributes();
596 for (vector<saml2::Attribute*>::const_iterator a = attrs.begin(); a!=attrs.end(); ++a)
597 extractAttributes(application, assertingParty, relyingParty, *(*a), attributes);
600 void XMLExtractorImpl::extractAttributes(
601 const Application& application,
602 const ObservableMetadataProvider* observable,
603 const XMLCh* entityID,
604 const char* relyingParty,
605 const Extensions& ext,
606 vector<Attribute*>& attributes
609 const vector<XMLObject*>& exts = ext.getUnknownXMLObjects();
610 for (vector<XMLObject*>::const_iterator i = exts.begin(); i!=exts.end(); ++i) {
611 const EntityAttributes* container = dynamic_cast<const EntityAttributes*>(*i);
615 bool useCache = false;
616 map<const ObservableMetadataProvider*,decoded_t>::iterator cacheEntry;
618 // Check for cached result.
620 m_attrLock->rdlock();
621 cacheEntry = m_decodedMap.find(observable);
622 if (cacheEntry == m_decodedMap.end()) {
623 // We need to elevate the lock and retry.
624 m_attrLock->unlock();
625 m_attrLock->wrlock();
626 cacheEntry = m_decodedMap.find(observable);
627 if (cacheEntry==m_decodedMap.end()) {
629 // It's still brand new, so hook it for cache activation.
630 observable->addObserver(this);
632 // Prime the map reference with an empty decoded map.
633 cacheEntry = m_decodedMap.insert(make_pair(observable,decoded_t())).first;
635 // Downgrade the lock.
636 // We don't have to recheck because we never erase the master map entry entirely, even on changes.
637 m_attrLock->unlock();
638 m_attrLock->rdlock();
645 // We're holding a read lock, so check the cache.
646 decoded_t::iterator d = cacheEntry->second.find(container);
647 if (d != cacheEntry->second.end()) {
648 SharedLock locker(m_attrLock, false); // pop the lock when we're done
649 for (vector<DDF>::iterator obj = d->second.begin(); obj != d->second.end(); ++obj) {
650 auto_ptr<Attribute> wrapper(Attribute::unmarshall(*obj));
651 m_log.debug("recovered cached metadata attribute (%s)", wrapper->getId());
652 attributes.push_back(wrapper.release());
658 // Use a holding area to support caching.
659 vector<Attribute*> holding;
661 const vector<saml2::Attribute*>& attrs = container->getAttributes();
662 for (vector<saml2::Attribute*>::const_iterator attr = attrs.begin(); attr != attrs.end(); ++attr) {
664 extractAttributes(application, nullptr, relyingParty, *(*attr), holding);
668 m_attrLock->unlock();
669 for_each(holding.begin(), holding.end(), xmltooling::cleanup<Attribute>());
674 if (entityID && m_entityAssertions) {
675 const vector<saml2::Assertion*>& asserts = container->getAssertions();
676 for (vector<saml2::Assertion*>::const_iterator assert = asserts.begin(); assert != asserts.end(); ++assert) {
677 if (!(*assert)->getSignature()) {
678 if (m_log.isDebugEnabled()) {
679 auto_ptr_char eid(entityID);
680 m_log.debug("skipping unsigned assertion in metadata extension for entity (%s)", eid.get());
684 else if ((*assert)->getAttributeStatements().empty()) {
685 if (m_log.isDebugEnabled()) {
686 auto_ptr_char eid(entityID);
687 m_log.debug("skipping assertion with no AttributeStatement in metadata extension for entity (%s)", eid.get());
693 const NameID* subject = (*assert)->getSubject() ? (*assert)->getSubject()->getNameID() : nullptr;
695 !XMLString::equals(subject->getFormat(), NameID::ENTITY) ||
696 !XMLString::equals(subject->getName(), entityID)) {
697 if (m_log.isDebugEnabled()) {
698 auto_ptr_char eid(entityID);
699 m_log.debug("skipping assertion with improper Subject in metadata extension for entity (%s)", eid.get());
705 // Use a private holding area for filtering purposes.
706 vector<Attribute*> holding2;
709 // Set up and evaluate a policy for an AA asserting attributes to us.
710 shibsp::SecurityPolicy policy(application, &AttributeAuthorityDescriptor::ELEMENT_QNAME, false, m_policyId.c_str());
711 Locker locker(m_metadata);
713 policy.setMetadataProvider(m_metadata);
715 policy.setTrustEngine(m_trust);
716 // Populate recipient as audience.
717 const XMLCh* issuer = (*assert)->getIssuer() ? (*assert)->getIssuer()->getName() : nullptr;
718 policy.getAudiences().push_back(application.getRelyingParty(issuer)->getXMLString("entityID").second);
720 // Extract assertion information for policy.
721 policy.setMessageID((*assert)->getID());
722 policy.setIssueInstant((*assert)->getIssueInstantEpoch());
723 policy.setIssuer((*assert)->getIssuer());
725 // Look up metadata for issuer.
726 if (policy.getIssuer() && policy.getMetadataProvider()) {
727 if (policy.getIssuer()->getFormat() && !XMLString::equals(policy.getIssuer()->getFormat(), saml2::NameIDType::ENTITY)) {
728 m_log.debug("non-system entity issuer, skipping metadata lookup");
731 m_log.debug("searching metadata for entity assertion issuer...");
732 pair<const EntityDescriptor*,const RoleDescriptor*> lookup;
733 MetadataProvider::Criteria& mc = policy.getMetadataProviderCriteria();
734 mc.entityID_unicode = policy.getIssuer()->getName();
735 mc.role = &AttributeAuthorityDescriptor::ELEMENT_QNAME;
736 mc.protocol = samlconstants::SAML20P_NS;
737 lookup = policy.getMetadataProvider()->getEntityDescriptor(mc);
739 auto_ptr_char iname(policy.getIssuer()->getName());
740 m_log.debug("no metadata found, can't establish identity of issuer (%s)", iname.get());
742 else if (!lookup.second) {
743 m_log.debug("unable to find compatible AA role in metadata");
746 policy.setIssuerMetadata(lookup.second);
751 // Authenticate the assertion. We have to clone and marshall it to establish the signature for verification.
752 auto_ptr<saml2::Assertion> tokencopy((*assert)->cloneAssertion());
753 tokencopy->marshall();
754 policy.evaluate(*tokencopy);
755 if (!policy.isAuthenticated()) {
756 if (m_log.isDebugEnabled()) {
757 auto_ptr_char tempid(tokencopy->getID());
758 auto_ptr_char eid(entityID);
760 "failed to authenticate assertion (%s) in metadata extension for entity (%s)", tempid.get(), eid.get()
766 // Override the asserting/relying party names based on this new issuer.
767 const EntityDescriptor* inlineEntity =
768 policy.getIssuerMetadata() ? dynamic_cast<const EntityDescriptor*>(policy.getIssuerMetadata()->getParent()) : nullptr;
769 auto_ptr_char inlineAssertingParty(inlineEntity ? inlineEntity->getEntityID() : nullptr);
770 relyingParty = application.getRelyingParty(inlineEntity)->getString("entityID").second;
771 const vector<saml2::Attribute*>& attrs2 =
772 const_cast<const saml2::AttributeStatement*>(tokencopy->getAttributeStatements().front())->getAttributes();
773 for (vector<saml2::Attribute*>::const_iterator a = attrs2.begin(); a!=attrs2.end(); ++a)
774 extractAttributes(application, inlineAssertingParty.get(), relyingParty, *(*a), holding2);
776 // Now we locally filter the attributes so that the actual issuer can be properly set.
777 // If we relied on outside filtering, the attributes couldn't be distinguished from the
778 // ones that come from the user's IdP.
779 if (m_filter && !holding2.empty()) {
780 BasicFilteringContext fc(application, holding2, policy.getIssuerMetadata());
781 Locker filtlocker(m_filter);
783 m_filter->filterAttributes(fc, holding2);
785 catch (exception& ex) {
786 m_log.error("caught exception filtering attributes: %s", ex.what());
787 m_log.error("dumping extracted attributes due to filtering exception");
788 for_each(holding2.begin(), holding2.end(), xmltooling::cleanup<Attribute>());
793 if (!holding2.empty()) {
794 // Copy them over to the main holding tank.
795 holding.insert(holding.end(), holding2.begin(), holding2.end());
798 catch (exception& ex) {
799 // Known exceptions are handled gracefully by skipping the assertion.
800 if (m_log.isDebugEnabled()) {
801 auto_ptr_char tempid((*assert)->getID());
802 auto_ptr_char eid(entityID);
804 "exception authenticating assertion (%s) in metadata extension for entity (%s): %s",
810 for_each(holding2.begin(), holding2.end(), xmltooling::cleanup<Attribute>());
814 // Unknown exceptions are fatal.
816 m_attrLock->unlock();
817 for_each(holding.begin(), holding.end(), xmltooling::cleanup<Attribute>());
818 for_each(holding2.begin(), holding2.end(), xmltooling::cleanup<Attribute>());
824 if (!holding.empty()) {
826 m_attrLock->unlock();
827 m_attrLock->wrlock();
828 SharedLock locker(m_attrLock, false); // pop the lock when we're done
829 if (cacheEntry->second.count(container) == 0) {
830 for (vector<Attribute*>::const_iterator held = holding.begin(); held != holding.end(); ++held)
831 cacheEntry->second[container].push_back((*held)->marshall());
834 attributes.insert(attributes.end(), holding.begin(), holding.end());
837 m_attrLock->unlock();
840 break; // only process a single extension element
844 void XMLExtractor::extractAttributes(
845 const Application& application, const RoleDescriptor* issuer, const XMLObject& xmlObject, vector<Attribute*>& attributes
851 const EntityDescriptor* entity = issuer ? dynamic_cast<const EntityDescriptor*>(issuer->getParent()) : nullptr;
852 const char* relyingParty = application.getRelyingParty(entity)->getString("entityID").second;
854 // Check for statements.
855 if (XMLString::equals(xmlObject.getElementQName().getLocalPart(), saml1::AttributeStatement::LOCAL_NAME)) {
856 const saml2::AttributeStatement* statement2 = dynamic_cast<const saml2::AttributeStatement*>(&xmlObject);
858 auto_ptr_char assertingParty(entity ? entity->getEntityID() : nullptr);
859 m_impl->extractAttributes(application, assertingParty.get(), relyingParty, *statement2, attributes);
860 // Handle EncryptedAttributes inline so we have access to the role descriptor.
861 const vector<saml2::EncryptedAttribute*>& encattrs = statement2->getEncryptedAttributes();
862 for (vector<saml2::EncryptedAttribute*>::const_iterator ea = encattrs.begin(); ea!=encattrs.end(); ++ea)
863 extractAttributes(application, issuer, *(*ea), attributes);
867 const saml1::AttributeStatement* statement1 = dynamic_cast<const saml1::AttributeStatement*>(&xmlObject);
869 auto_ptr_char assertingParty(entity ? entity->getEntityID() : nullptr);
870 m_impl->extractAttributes(application, assertingParty.get(), relyingParty, *statement1, attributes);
874 throw AttributeExtractionException("Unable to extract attributes, unknown object type.");
877 // Check for assertions.
878 if (XMLString::equals(xmlObject.getElementQName().getLocalPart(), saml1::Assertion::LOCAL_NAME)) {
879 const saml2::Assertion* token2 = dynamic_cast<const saml2::Assertion*>(&xmlObject);
881 auto_ptr_char assertingParty(entity ? entity->getEntityID() : nullptr);
882 const vector<saml2::AttributeStatement*>& statements = token2->getAttributeStatements();
883 for (vector<saml2::AttributeStatement*>::const_iterator s = statements.begin(); s!=statements.end(); ++s) {
884 m_impl->extractAttributes(application, assertingParty.get(), relyingParty, *(*s), attributes);
885 // Handle EncryptedAttributes inline so we have access to the role descriptor.
886 const vector<saml2::EncryptedAttribute*>& encattrs = const_cast<const saml2::AttributeStatement*>(*s)->getEncryptedAttributes();
887 for (vector<saml2::EncryptedAttribute*>::const_iterator ea = encattrs.begin(); ea!=encattrs.end(); ++ea)
888 extractAttributes(application, issuer, *(*ea), attributes);
893 const saml1::Assertion* token1 = dynamic_cast<const saml1::Assertion*>(&xmlObject);
895 auto_ptr_char assertingParty(entity ? entity->getEntityID() : nullptr);
896 const vector<saml1::AttributeStatement*>& statements = token1->getAttributeStatements();
897 for (vector<saml1::AttributeStatement*>::const_iterator s = statements.begin(); s!=statements.end(); ++s)
898 m_impl->extractAttributes(application, assertingParty.get(), relyingParty, *(*s), attributes);
902 throw AttributeExtractionException("Unable to extract attributes, unknown object type.");
905 // Check for metadata.
906 if (XMLString::equals(xmlObject.getElementQName().getNamespaceURI(), samlconstants::SAML20MD_NS)) {
907 const RoleDescriptor* roleToExtract = dynamic_cast<const RoleDescriptor*>(&xmlObject);
908 const EntityDescriptor* entityToExtract = roleToExtract ? dynamic_cast<const EntityDescriptor*>(roleToExtract->getParent()) : nullptr;
909 if (!entityToExtract)
910 throw AttributeExtractionException("Unable to extract attributes, unknown metadata object type.");
911 const Extensions* ext = entityToExtract->getExtensions();
913 m_impl->extractAttributes(
915 dynamic_cast<const ObservableMetadataProvider*>(application.getMetadataProvider(false)),
916 entityToExtract->getEntityID(),
922 const EntitiesDescriptor* group = dynamic_cast<const EntitiesDescriptor*>(entityToExtract->getParent());
924 ext = group->getExtensions();
926 m_impl->extractAttributes(
928 dynamic_cast<const ObservableMetadataProvider*>(application.getMetadataProvider(false)),
929 nullptr, // not an entity, so inline assertions won't be processed
935 group = dynamic_cast<const EntitiesDescriptor*>(group->getParent());
940 // Check for attributes.
941 if (XMLString::equals(xmlObject.getElementQName().getLocalPart(), saml1::Attribute::LOCAL_NAME)) {
942 auto_ptr_char assertingParty(entity ? entity->getEntityID() : nullptr);
943 const saml2::Attribute* attr2 = dynamic_cast<const saml2::Attribute*>(&xmlObject);
945 return m_impl->extractAttributes(application, assertingParty.get(), relyingParty, *attr2, attributes);
947 const saml1::Attribute* attr1 = dynamic_cast<const saml1::Attribute*>(&xmlObject);
949 return m_impl->extractAttributes(application, assertingParty.get(), relyingParty, *attr1, attributes);
951 throw AttributeExtractionException("Unable to extract attributes, unknown object type.");
954 if (XMLString::equals(xmlObject.getElementQName().getLocalPart(), EncryptedAttribute::LOCAL_NAME)) {
955 const EncryptedAttribute* encattr = dynamic_cast<const EncryptedAttribute*>(&xmlObject);
957 const XMLCh* recipient = application.getXMLString("entityID").second;
958 CredentialResolver* cr = application.getCredentialResolver();
960 m_log.warn("found encrypted attribute, but no CredentialResolver was available");
965 Locker credlocker(cr);
967 MetadataCredentialCriteria mcc(*issuer);
968 auto_ptr<XMLObject> decrypted(encattr->decrypt(*cr, recipient, &mcc));
969 if (m_log.isDebugEnabled())
970 m_log.debugStream() << "decrypted Attribute: " << *(decrypted.get()) << logging::eol;
971 return extractAttributes(application, issuer, *(decrypted.get()), attributes);
974 auto_ptr<XMLObject> decrypted(encattr->decrypt(*cr, recipient));
975 if (m_log.isDebugEnabled())
976 m_log.debugStream() << "decrypted Attribute: " << *(decrypted.get()) << logging::eol;
977 return extractAttributes(application, issuer, *(decrypted.get()), attributes);
980 catch (exception& ex) {
981 m_log.error("caught exception decrypting Attribute: %s", ex.what());
987 // Check for NameIDs.
988 const NameID* name2 = dynamic_cast<const NameID*>(&xmlObject);
990 auto_ptr_char assertingParty(entity ? entity->getEntityID() : nullptr);
991 return m_impl->extractAttributes(application, assertingParty.get(), relyingParty, *name2, attributes);
994 const NameIdentifier* name1 = dynamic_cast<const NameIdentifier*>(&xmlObject);
996 auto_ptr_char assertingParty(entity ? entity->getEntityID() : nullptr);
997 return m_impl->extractAttributes(application, assertingParty.get(), relyingParty, *name1, attributes);
1000 throw AttributeExtractionException("Unable to extract attributes, unknown object type.");
1003 pair<bool,DOMElement*> XMLExtractor::background_load()
1005 // Load from source using base class.
1006 pair<bool,DOMElement*> raw = ReloadableXMLFile::load();
1008 // If we own it, wrap it.
1009 XercesJanitor<DOMDocument> docjanitor(raw.first ? raw.second->getOwnerDocument() : nullptr);
1011 XMLExtractorImpl* impl = new XMLExtractorImpl(raw.second, m_log);
1013 // If we held the document, transfer it to the impl. If we didn't, it's a no-op.
1014 impl->setDocument(docjanitor.release());
1016 // Perform the swap inside a lock.
1019 SharedLock locker(m_lock, false);
1023 return make_pair(false,(DOMElement*)nullptr);