2 * Copyright 2001-2009 Internet2
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
18 * 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/XMLHelper.h>
47 #include <xercesc/util/XMLUniDefs.hpp>
49 using namespace shibsp;
50 using namespace opensaml::saml2md;
51 using namespace opensaml;
52 using namespace xmltooling;
54 using saml1::NameIdentifier;
56 using saml2::EncryptedAttribute;
60 #if defined (_MSC_VER)
61 #pragma warning( push )
62 #pragma warning( disable : 4250 )
65 class XMLExtractorImpl : public ObservableMetadataProvider::Observer
68 XMLExtractorImpl(const DOMElement* e, Category& log);
70 for (map<const ObservableMetadataProvider*,decoded_t>::iterator i=m_decodedMap.begin(); i!=m_decodedMap.end(); ++i) {
71 i->first->removeObserver(this);
72 for (decoded_t::iterator attrs = i->second.begin(); attrs!=i->second.end(); ++attrs)
73 for_each(attrs->second.begin(), attrs->second.end(), mem_fun_ref<DDF&,DDF>(&DDF::destroy));
79 for (attrmap_t::iterator j = m_attrMap.begin(); j!=m_attrMap.end(); ++j)
80 delete j->second.first;
82 m_document->release();
85 void setDocument(DOMDocument* doc) {
89 void onEvent(const ObservableMetadataProvider& metadata) const {
90 // Destroy attributes we cached from this provider.
92 decoded_t& d = m_decodedMap[&metadata];
93 for (decoded_t::iterator a = d.begin(); a!=d.end(); ++a)
94 for_each(a->second.begin(), a->second.end(), mem_fun_ref<DDF&,DDF>(&DDF::destroy));
99 void extractAttributes(
100 const Application& application,
101 const char* assertingParty,
102 const char* relyingParty,
103 const NameIdentifier& nameid,
104 vector<Attribute*>& attributes
106 void extractAttributes(
107 const Application& application,
108 const char* assertingParty,
109 const char* relyingParty,
110 const NameID& nameid,
111 vector<Attribute*>& attributes
113 void extractAttributes(
114 const Application& application,
115 const char* assertingParty,
116 const char* relyingParty,
117 const saml1::Attribute& attr,
118 vector<Attribute*>& attributes
120 void extractAttributes(
121 const Application& application,
122 const char* assertingParty,
123 const char* relyingParty,
124 const saml2::Attribute& attr,
125 vector<Attribute*>& attributes
127 void extractAttributes(
128 const Application& application,
129 const ObservableMetadataProvider* observable,
130 const XMLCh* entityID,
131 const char* relyingParty,
132 const Extensions& ext,
133 vector<Attribute*>& attributes
136 void getAttributeIds(vector<string>& attributes) const {
137 attributes.insert(attributes.end(), m_attributeIds.begin(), m_attributeIds.end());
142 DOMDocument* m_document;
144 typedef map< pair<xstring,xstring>,pair< AttributeDecoder*,vector<string> > > attrmap_t;
146 typedef map< pair<string,string>,pair< AttributeDecoder*,vector<string> > > attrmap_t;
149 vector<string> m_attributeIds;
151 // settings for embedded assertions in metadata
152 auto_ptr_char m_policyId;
153 MetadataProvider* m_metadata;
154 TrustEngine* m_trust;
155 AttributeFilter* m_filter;
156 bool m_entityAssertions;
158 // manages caching of decoded Attributes
159 mutable RWLock* m_attrLock;
160 typedef map< const EntityAttributes*,vector<DDF> > decoded_t;
161 mutable map<const ObservableMetadataProvider*,decoded_t> m_decodedMap;
164 class XMLExtractor : public AttributeExtractor, public ReloadableXMLFile
167 XMLExtractor(const DOMElement* e) : ReloadableXMLFile(e, Category::getInstance(SHIBSP_LOGCAT".AttributeExtractor.XML")), m_impl(NULL) {
174 void extractAttributes(
175 const Application& application, const RoleDescriptor* issuer, const XMLObject& xmlObject, vector<Attribute*>& attributes
178 void getAttributeIds(std::vector<std::string>& attributes) const {
180 m_impl->getAttributeIds(attributes);
184 pair<bool,DOMElement*> load();
187 XMLExtractorImpl* m_impl;
190 #if defined (_MSC_VER)
191 #pragma warning( pop )
194 AttributeExtractor* SHIBSP_DLLLOCAL XMLAttributeExtractorFactory(const DOMElement* const & e)
196 return new XMLExtractor(e);
199 static const XMLCh _aliases[] = UNICODE_LITERAL_7(a,l,i,a,s,e,s);
200 static const XMLCh _AttributeDecoder[] = UNICODE_LITERAL_16(A,t,t,r,i,b,u,t,e,D,e,c,o,d,e,r);
201 static const XMLCh _AttributeFilter[] = UNICODE_LITERAL_15(A,t,t,r,i,b,u,t,e,F,i,l,t,e,r);
202 static const XMLCh Attributes[] = UNICODE_LITERAL_10(A,t,t,r,i,b,u,t,e,s);
203 static const XMLCh _id[] = UNICODE_LITERAL_2(i,d);
204 static const XMLCh _MetadataProvider[] = UNICODE_LITERAL_16(M,e,t,a,d,a,t,a,P,r,o,v,i,d,e,r);
205 static const XMLCh _name[] = UNICODE_LITERAL_4(n,a,m,e);
206 static const XMLCh nameFormat[] = UNICODE_LITERAL_10(n,a,m,e,F,o,r,m,a,t);
207 static const XMLCh metadataPolicyId[] = UNICODE_LITERAL_16(m,e,t,a,d,a,t,a,P,o,l,i,c,y,I,d);
208 static const XMLCh _TrustEngine[] = UNICODE_LITERAL_11(T,r,u,s,t,E,n,g,i,n,e);
209 static const XMLCh _type[] = UNICODE_LITERAL_4(t,y,p,e);
212 XMLExtractorImpl::XMLExtractorImpl(const DOMElement* e, Category& log)
215 m_policyId(e ? e->getAttributeNS(NULL, metadataPolicyId) : NULL),
219 m_entityAssertions(true),
223 xmltooling::NDC ndc("XMLExtractorImpl");
226 if (!XMLHelper::isNodeNamed(e, shibspconstants::SHIB2ATTRIBUTEMAP_NS, Attributes))
227 throw ConfigurationException("XML AttributeExtractor requires am:Attributes at root of configuration.");
229 DOMElement* child = XMLHelper::getFirstChildElement(e, shibspconstants::SHIB2ATTRIBUTEMAP_NS, _MetadataProvider);
232 auto_ptr_char type(child->getAttributeNS(NULL, _type));
233 if (!type.get() || !*type.get())
234 throw ConfigurationException("MetadataProvider element missing type attribute.");
235 m_log.info("building MetadataProvider of type %s...", type.get());
236 auto_ptr<MetadataProvider> mp(SAMLConfig::getConfig().MetadataProviderManager.newPlugin(type.get(), child));
238 m_metadata = mp.release();
240 catch (exception& ex) {
241 m_entityAssertions = false;
242 m_log.crit("error building/initializing dedicated MetadataProvider: %s", ex.what());
243 m_log.crit("disabling support for Assertions in EntityAttributes extension");
247 if (m_entityAssertions) {
248 child = XMLHelper::getFirstChildElement(e, shibspconstants::SHIB2ATTRIBUTEMAP_NS, _TrustEngine);
251 auto_ptr_char type(child->getAttributeNS(NULL, _type));
252 if (!type.get() || !*type.get())
253 throw ConfigurationException("TrustEngine element missing type attribute.");
254 m_log.info("building TrustEngine of type %s...", type.get());
255 m_trust = XMLToolingConfig::getConfig().TrustEngineManager.newPlugin(type.get(), child);
257 catch (exception& ex) {
258 m_entityAssertions = false;
259 m_log.crit("error building/initializing dedicated TrustEngine: %s", ex.what());
260 m_log.crit("disabling support for Assertions in EntityAttributes extension");
265 if (m_entityAssertions) {
266 child = XMLHelper::getFirstChildElement(e, shibspconstants::SHIB2ATTRIBUTEMAP_NS, _AttributeFilter);
269 auto_ptr_char type(child->getAttributeNS(NULL, _type));
270 if (!type.get() || !*type.get())
271 throw ConfigurationException("AttributeFilter element missing type attribute.");
272 m_log.info("building AttributeFilter of type %s...", type.get());
273 m_filter = SPConfig::getConfig().AttributeFilterManager.newPlugin(type.get(), child);
275 catch (exception& ex) {
276 m_entityAssertions = false;
277 m_log.crit("error building/initializing dedicated AttributeFilter: %s", ex.what());
278 m_log.crit("disabling support for Assertions in EntityAttributes extension");
283 child = XMLHelper::getFirstChildElement(e, shibspconstants::SHIB2ATTRIBUTEMAP_NS, saml1::Attribute::LOCAL_NAME);
285 // Check for missing name or id.
286 const XMLCh* name = child->getAttributeNS(NULL, _name);
287 if (!name || !*name) {
288 m_log.warn("skipping Attribute with no name");
289 child = XMLHelper::getNextSiblingElement(child, shibspconstants::SHIB2ATTRIBUTEMAP_NS, saml1::Attribute::LOCAL_NAME);
293 auto_ptr_char id(child->getAttributeNS(NULL, _id));
294 if (!id.get() || !*id.get()) {
295 m_log.warn("skipping Attribute with no id");
296 child = XMLHelper::getNextSiblingElement(child, shibspconstants::SHIB2ATTRIBUTEMAP_NS, saml1::Attribute::LOCAL_NAME);
299 else if (!strcmp(id.get(), "REMOTE_USER")) {
300 m_log.warn("skipping Attribute, id of REMOTE_USER is a reserved name");
301 child = XMLHelper::getNextSiblingElement(child, shibspconstants::SHIB2ATTRIBUTEMAP_NS, saml1::Attribute::LOCAL_NAME);
305 AttributeDecoder* decoder=NULL;
307 DOMElement* dchild = XMLHelper::getFirstChildElement(child, shibspconstants::SHIB2ATTRIBUTEMAP_NS, _AttributeDecoder);
309 auto_ptr<xmltooling::QName> q(XMLHelper::getXSIType(dchild));
311 decoder = SPConfig::getConfig().AttributeDecoderManager.newPlugin(*q.get(), dchild);
314 decoder = SPConfig::getConfig().AttributeDecoderManager.newPlugin(StringAttributeDecoderType, NULL);
316 catch (exception& ex) {
317 m_log.error("skipping Attribute (%s), error building AttributeDecoder: %s", id.get(), ex.what());
321 child = XMLHelper::getNextSiblingElement(child, shibspconstants::SHIB2ATTRIBUTEMAP_NS, saml1::Attribute::LOCAL_NAME);
325 // Empty NameFormat implies the usual Shib URI naming defaults.
326 const XMLCh* format = child->getAttributeNS(NULL, nameFormat);
327 if (!format || XMLString::equals(format, shibspconstants::SHIB1_ATTRIBUTE_NAMESPACE_URI) ||
328 XMLString::equals(format, saml2::Attribute::URI_REFERENCE))
329 format = &chNull; // ignore default Format/Namespace values
331 // Fetch/create the map entry and see if it's a duplicate rule.
333 pair< AttributeDecoder*,vector<string> >& decl = m_attrMap[pair<xstring,xstring>(name,format)];
335 auto_ptr_char n(name);
336 auto_ptr_char f(format);
337 pair< AttributeDecoder*,vector<string> >& decl = m_attrMap[pair<string,string>(n.get(),f.get())];
340 m_log.warn("skipping duplicate Attribute mapping (same name and nameFormat)");
342 child = XMLHelper::getNextSiblingElement(child, shibspconstants::SHIB2ATTRIBUTEMAP_NS, saml1::Attribute::LOCAL_NAME);
346 if (m_log.isInfoEnabled()) {
348 auto_ptr_char n(name);
349 auto_ptr_char f(format);
351 m_log.info("creating mapping for Attribute %s%s%s", n.get(), *f.get() ? ", Format/Namespace:" : "", f.get());
354 decl.first = decoder;
355 decl.second.push_back(id.get());
356 m_attributeIds.push_back(id.get());
358 name = child->getAttributeNS(NULL, _aliases);
360 auto_ptr_char aliases(name);
362 char* start = const_cast<char*>(aliases.get());
363 while (start && *start) {
364 while (*start && isspace(*start))
368 pos = strchr(start,' ');
371 if (strcmp(start, "REMOTE_USER")) {
372 decl.second.push_back(start);
373 m_attributeIds.push_back(start);
376 m_log.warn("skipping alias, REMOTE_USER is a reserved name");
378 start = pos ? pos+1 : NULL;
382 child = XMLHelper::getNextSiblingElement(child, shibspconstants::SHIB2ATTRIBUTEMAP_NS, saml1::Attribute::LOCAL_NAME);
385 m_attrLock = RWLock::create();
388 void XMLExtractorImpl::extractAttributes(
389 const Application& application,
390 const char* assertingParty,
391 const char* relyingParty,
392 const NameIdentifier& nameid,
393 vector<Attribute*>& attributes
397 map< pair<xstring,xstring>,pair< AttributeDecoder*,vector<string> > >::const_iterator rule;
399 map< pair<string,string>,pair< AttributeDecoder*,vector<string> > >::const_iterator rule;
402 const XMLCh* format = nameid.getFormat();
403 if (!format || !*format)
404 format = NameIdentifier::UNSPECIFIED;
406 if ((rule=m_attrMap.find(pair<xstring,xstring>(format,xstring()))) != m_attrMap.end()) {
408 auto_ptr_char temp(format);
409 if ((rule=m_attrMap.find(pair<string,string>(temp.get(),string()))) != m_attrMap.end()) {
411 Attribute* a = rule->second.first->decode(rule->second.second, &nameid, assertingParty, relyingParty);
413 attributes.push_back(a);
415 else if (m_log.isDebugEnabled()) {
417 auto_ptr_char temp(format);
419 m_log.debug("skipping unmapped NameIdentifier with format (%s)", temp.get());
423 void XMLExtractorImpl::extractAttributes(
424 const Application& application,
425 const char* assertingParty,
426 const char* relyingParty,
427 const NameID& nameid,
428 vector<Attribute*>& attributes
432 map< pair<xstring,xstring>,pair< AttributeDecoder*,vector<string> > >::const_iterator rule;
434 map< pair<string,string>,pair< AttributeDecoder*,vector<string> > >::const_iterator rule;
437 const XMLCh* format = nameid.getFormat();
438 if (!format || !*format)
439 format = NameID::UNSPECIFIED;
441 if ((rule=m_attrMap.find(pair<xstring,xstring>(format,xstring()))) != m_attrMap.end()) {
443 auto_ptr_char temp(format);
444 if ((rule=m_attrMap.find(pair<string,string>(temp.get(),string()))) != m_attrMap.end()) {
446 Attribute* a = rule->second.first->decode(rule->second.second, &nameid, assertingParty, relyingParty);
448 attributes.push_back(a);
450 else if (m_log.isDebugEnabled()) {
452 auto_ptr_char temp(format);
454 m_log.debug("skipping unmapped NameID with format (%s)", temp.get());
458 void XMLExtractorImpl::extractAttributes(
459 const Application& application,
460 const char* assertingParty,
461 const char* relyingParty,
462 const saml1::Attribute& attr,
463 vector<Attribute*>& attributes
467 map< pair<xstring,xstring>,pair< AttributeDecoder*,vector<string> > >::const_iterator rule;
469 map< pair<string,string>,pair< AttributeDecoder*,vector<string> > >::const_iterator rule;
472 const XMLCh* name = attr.getAttributeName();
473 const XMLCh* format = attr.getAttributeNamespace();
476 if (!format || XMLString::equals(format, shibspconstants::SHIB1_ATTRIBUTE_NAMESPACE_URI))
479 if ((rule=m_attrMap.find(pair<xstring,xstring>(name,format))) != m_attrMap.end()) {
481 auto_ptr_char temp1(name);
482 auto_ptr_char temp2(format);
483 if ((rule=m_attrMap.find(pair<string,string>(temp1.get(),temp2.get()))) != m_attrMap.end()) {
485 Attribute* a = rule->second.first->decode(rule->second.second, &attr, assertingParty, relyingParty);
487 attributes.push_back(a);
489 else if (m_log.isInfoEnabled()) {
491 auto_ptr_char temp1(name);
492 auto_ptr_char temp2(format);
494 m_log.info("skipping unmapped SAML 1.x Attribute with Name: %s%s%s", temp1.get(), *temp2.get() ? ", Namespace:" : "", temp2.get());
498 void XMLExtractorImpl::extractAttributes(
499 const Application& application,
500 const char* assertingParty,
501 const char* relyingParty,
502 const saml2::Attribute& attr,
503 vector<Attribute*>& attributes
507 map< pair<xstring,xstring>,pair< AttributeDecoder*,vector<string> > >::const_iterator rule;
509 map< pair<string,string>,pair< AttributeDecoder*,vector<string> > >::const_iterator rule;
512 const XMLCh* name = attr.getName();
513 const XMLCh* format = attr.getNameFormat();
516 if (!format || !*format)
517 format = saml2::Attribute::UNSPECIFIED;
518 else if (XMLString::equals(format, saml2::Attribute::URI_REFERENCE))
521 if ((rule=m_attrMap.find(pair<xstring,xstring>(name,format))) != m_attrMap.end()) {
523 auto_ptr_char temp1(name);
524 auto_ptr_char temp2(format);
525 if ((rule=m_attrMap.find(pair<string,string>(temp1.get(),temp2.get()))) != m_attrMap.end()) {
527 Attribute* a = rule->second.first->decode(rule->second.second, &attr, assertingParty, relyingParty);
529 attributes.push_back(a);
531 else if (m_log.isInfoEnabled()) {
533 auto_ptr_char temp1(name);
534 auto_ptr_char temp2(format);
536 m_log.info("skipping unmapped SAML 2.0 Attribute with Name: %s%s%s", temp1.get(), *temp2.get() ? ", Format:" : "", temp2.get());
540 void XMLExtractorImpl::extractAttributes(
541 const Application& application,
542 const ObservableMetadataProvider* observable,
543 const XMLCh* entityID,
544 const char* relyingParty,
545 const Extensions& ext,
546 vector<Attribute*>& attributes
549 const vector<XMLObject*>& exts = ext.getUnknownXMLObjects();
550 for (vector<XMLObject*>::const_iterator i = exts.begin(); i!=exts.end(); ++i) {
551 const EntityAttributes* container = dynamic_cast<const EntityAttributes*>(*i);
555 bool useCache = false;
556 map<const ObservableMetadataProvider*,decoded_t>::iterator cacheEntry;
558 // Check for cached result.
560 m_attrLock->rdlock();
561 cacheEntry = m_decodedMap.find(observable);
562 if (cacheEntry == m_decodedMap.end()) {
563 // We need to elevate the lock and retry.
564 m_attrLock->unlock();
565 m_attrLock->wrlock();
566 cacheEntry = m_decodedMap.find(observable);
567 if (cacheEntry==m_decodedMap.end()) {
569 // It's still brand new, so hook it for cache activation.
570 observable->addObserver(this);
572 // Prime the map reference with an empty decoded map.
573 cacheEntry = m_decodedMap.insert(make_pair(observable,decoded_t())).first;
575 // Downgrade the lock.
576 // We don't have to recheck because we never erase the master map entry entirely, even on changes.
577 m_attrLock->unlock();
578 m_attrLock->rdlock();
585 // We're holding a read lock, so check the cache.
586 decoded_t::iterator d = cacheEntry->second.find(container);
587 if (d != cacheEntry->second.end()) {
588 SharedLock locker(m_attrLock, false); // pop the lock when we're done
589 for (vector<DDF>::iterator obj = d->second.begin(); obj != d->second.end(); ++obj) {
590 auto_ptr<Attribute> wrapper(Attribute::unmarshall(*obj));
591 m_log.debug("recovered cached metadata attribute (%s)", wrapper->getId());
592 attributes.push_back(wrapper.release());
598 // Use a holding area to support caching.
599 vector<Attribute*> holding;
601 const vector<saml2::Attribute*>& attrs = container->getAttributes();
602 for (vector<saml2::Attribute*>::const_iterator attr = attrs.begin(); attr != attrs.end(); ++attr) {
604 extractAttributes(application, NULL, relyingParty, *(*attr), holding);
608 m_attrLock->unlock();
609 for_each(holding.begin(), holding.end(), xmltooling::cleanup<Attribute>());
614 if (entityID && m_entityAssertions) {
615 const vector<saml2::Assertion*>& asserts = container->getAssertions();
616 for (vector<saml2::Assertion*>::const_iterator assert = asserts.begin(); assert != asserts.end(); ++assert) {
617 if (!(*assert)->getSignature()) {
618 if (m_log.isDebugEnabled()) {
619 auto_ptr_char eid(entityID);
620 m_log.debug("skipping unsigned assertion in metadata extension for entity (%s)", eid.get());
624 else if ((*assert)->getAttributeStatements().empty()) {
625 if (m_log.isDebugEnabled()) {
626 auto_ptr_char eid(entityID);
627 m_log.debug("skipping assertion with no AttributeStatement in metadata extension for entity (%s)", eid.get());
633 const NameID* subject = (*assert)->getSubject() ? (*assert)->getSubject()->getNameID() : NULL;
635 !XMLString::equals(subject->getFormat(), NameID::ENTITY) ||
636 !XMLString::equals(subject->getName(), entityID)) {
637 if (m_log.isDebugEnabled()) {
638 auto_ptr_char eid(entityID);
639 m_log.debug("skipping assertion with improper Subject in metadata extension for entity (%s)", eid.get());
645 // Use a private holding area for filtering purposes.
646 vector<Attribute*> holding2;
649 // Set up and evaluate a policy for an AA asserting attributes to us.
650 shibsp::SecurityPolicy policy(application, &AttributeAuthorityDescriptor::ELEMENT_QNAME, false, m_policyId.get());
651 Locker locker(m_metadata);
653 policy.setMetadataProvider(m_metadata);
655 policy.setTrustEngine(m_trust);
656 // Populate recipient as audience.
657 const XMLCh* issuer = (*assert)->getIssuer() ? (*assert)->getIssuer()->getName() : NULL;
658 policy.getAudiences().push_back(application.getRelyingParty(issuer)->getXMLString("entityID").second);
660 // Extract assertion information for policy.
661 policy.setMessageID((*assert)->getID());
662 policy.setIssueInstant((*assert)->getIssueInstantEpoch());
663 policy.setIssuer((*assert)->getIssuer());
665 // Look up metadata for issuer.
666 if (policy.getIssuer() && policy.getMetadataProvider()) {
667 if (policy.getIssuer()->getFormat() && !XMLString::equals(policy.getIssuer()->getFormat(), saml2::NameIDType::ENTITY)) {
668 m_log.debug("non-system entity issuer, skipping metadata lookup");
671 m_log.debug("searching metadata for entity assertion issuer...");
672 pair<const EntityDescriptor*,const RoleDescriptor*> lookup;
673 MetadataProvider::Criteria& mc = policy.getMetadataProviderCriteria();
674 mc.entityID_unicode = policy.getIssuer()->getName();
675 mc.role = &AttributeAuthorityDescriptor::ELEMENT_QNAME;
676 mc.protocol = samlconstants::SAML20P_NS;
677 lookup = policy.getMetadataProvider()->getEntityDescriptor(mc);
679 auto_ptr_char iname(policy.getIssuer()->getName());
680 m_log.debug("no metadata found, can't establish identity of issuer (%s)", iname.get());
682 else if (!lookup.second) {
683 m_log.debug("unable to find compatible AA role in metadata");
686 policy.setIssuerMetadata(lookup.second);
691 // Authenticate the assertion. We have to clone and marshall it to establish the signature for verification.
692 auto_ptr<saml2::Assertion> tokencopy((*assert)->cloneAssertion());
693 tokencopy->marshall();
694 policy.evaluate(*tokencopy);
695 if (!policy.isAuthenticated()) {
696 if (m_log.isDebugEnabled()) {
697 auto_ptr_char tempid(tokencopy->getID());
698 auto_ptr_char eid(entityID);
700 "failed to authenticate assertion (%s) in metadata extension for entity (%s)", tempid.get(), eid.get()
706 // Override the asserting/relying party names based on this new issuer.
707 const EntityDescriptor* inlineEntity =
708 policy.getIssuerMetadata() ? dynamic_cast<const EntityDescriptor*>(policy.getIssuerMetadata()->getParent()) : NULL;
709 auto_ptr_char inlineAssertingParty(inlineEntity ? inlineEntity->getEntityID() : NULL);
710 relyingParty = application.getRelyingParty(inlineEntity)->getString("entityID").second;
711 const vector<saml2::Attribute*>& attrs2 =
712 const_cast<const saml2::AttributeStatement*>(tokencopy->getAttributeStatements().front())->getAttributes();
713 for (vector<saml2::Attribute*>::const_iterator a = attrs2.begin(); a!=attrs2.end(); ++a)
714 extractAttributes(application, inlineAssertingParty.get(), relyingParty, *(*a), holding2);
716 // Now we locally filter the attributes so that the actual issuer can be properly set.
717 // If we relied on outside filtering, the attributes couldn't be distinguished from the
718 // ones that come from the user's IdP.
719 if (m_filter && !holding2.empty()) {
720 BasicFilteringContext fc(application, holding2, policy.getIssuerMetadata());
721 Locker filtlocker(m_filter);
723 m_filter->filterAttributes(fc, holding2);
725 catch (exception& ex) {
726 m_log.error("caught exception filtering attributes: %s", ex.what());
727 m_log.error("dumping extracted attributes due to filtering exception");
728 for_each(holding2.begin(), holding2.end(), xmltooling::cleanup<Attribute>());
733 if (!holding2.empty()) {
734 // Copy them over to the main holding tank.
735 holding.insert(holding.end(), holding2.begin(), holding2.end());
738 catch (exception& ex) {
739 // Known exceptions are handled gracefully by skipping the assertion.
740 if (m_log.isDebugEnabled()) {
741 auto_ptr_char tempid((*assert)->getID());
742 auto_ptr_char eid(entityID);
744 "exception authenticating assertion (%s) in metadata extension for entity (%s): %s",
750 for_each(holding2.begin(), holding2.end(), xmltooling::cleanup<Attribute>());
754 // Unknown exceptions are fatal.
756 m_attrLock->unlock();
757 for_each(holding.begin(), holding.end(), xmltooling::cleanup<Attribute>());
758 for_each(holding2.begin(), holding2.end(), xmltooling::cleanup<Attribute>());
764 if (!holding.empty()) {
766 m_attrLock->unlock();
767 m_attrLock->wrlock();
768 SharedLock locker(m_attrLock, false); // pop the lock when we're done
769 if (cacheEntry->second.count(container) == 0) {
770 for (vector<Attribute*>::const_iterator held = holding.begin(); held != holding.end(); ++held)
771 cacheEntry->second[container].push_back((*held)->marshall());
774 attributes.insert(attributes.end(), holding.begin(), holding.end());
777 m_attrLock->unlock();
780 break; // only process a single extension element
784 void XMLExtractor::extractAttributes(
785 const Application& application, const RoleDescriptor* issuer, const XMLObject& xmlObject, vector<Attribute*>& attributes
791 const EntityDescriptor* entity = issuer ? dynamic_cast<const EntityDescriptor*>(issuer->getParent()) : NULL;
792 const char* relyingParty = application.getRelyingParty(entity)->getString("entityID").second;
794 // Check for assertions.
795 if (XMLString::equals(xmlObject.getElementQName().getLocalPart(), saml1::Assertion::LOCAL_NAME)) {
796 const saml2::Assertion* token2 = dynamic_cast<const saml2::Assertion*>(&xmlObject);
798 auto_ptr_char assertingParty(entity ? entity->getEntityID() : NULL);
799 const vector<saml2::AttributeStatement*>& statements = token2->getAttributeStatements();
800 for (vector<saml2::AttributeStatement*>::const_iterator s = statements.begin(); s!=statements.end(); ++s) {
801 const vector<saml2::Attribute*>& attrs = const_cast<const saml2::AttributeStatement*>(*s)->getAttributes();
802 for (vector<saml2::Attribute*>::const_iterator a = attrs.begin(); a!=attrs.end(); ++a)
803 m_impl->extractAttributes(application, assertingParty.get(), relyingParty, *(*a), attributes);
805 const vector<saml2::EncryptedAttribute*>& encattrs = const_cast<const saml2::AttributeStatement*>(*s)->getEncryptedAttributes();
806 for (vector<saml2::EncryptedAttribute*>::const_iterator ea = encattrs.begin(); ea!=encattrs.end(); ++ea)
807 extractAttributes(application, issuer, *(*ea), attributes);
812 const saml1::Assertion* token1 = dynamic_cast<const saml1::Assertion*>(&xmlObject);
814 auto_ptr_char assertingParty(entity ? entity->getEntityID() : NULL);
815 const vector<saml1::AttributeStatement*>& statements = token1->getAttributeStatements();
816 for (vector<saml1::AttributeStatement*>::const_iterator s = statements.begin(); s!=statements.end(); ++s) {
817 const vector<saml1::Attribute*>& attrs = const_cast<const saml1::AttributeStatement*>(*s)->getAttributes();
818 for (vector<saml1::Attribute*>::const_iterator a = attrs.begin(); a!=attrs.end(); ++a)
819 m_impl->extractAttributes(application, assertingParty.get(), relyingParty, *(*a), attributes);
824 throw AttributeExtractionException("Unable to extract attributes, unknown object type.");
827 // Check for metadata.
828 if (XMLString::equals(xmlObject.getElementQName().getNamespaceURI(), samlconstants::SAML20MD_NS)) {
829 const RoleDescriptor* roleToExtract = dynamic_cast<const RoleDescriptor*>(&xmlObject);
830 const EntityDescriptor* entityToExtract = roleToExtract ? dynamic_cast<const EntityDescriptor*>(roleToExtract->getParent()) : NULL;
831 if (!entityToExtract)
832 throw AttributeExtractionException("Unable to extract attributes, unknown metadata object type.");
833 const Extensions* ext = entityToExtract->getExtensions();
835 m_impl->extractAttributes(
837 dynamic_cast<const ObservableMetadataProvider*>(application.getMetadataProvider(false)),
838 entityToExtract->getEntityID(),
844 const EntitiesDescriptor* group = dynamic_cast<const EntitiesDescriptor*>(entityToExtract->getParent());
846 ext = group->getExtensions();
848 m_impl->extractAttributes(
850 dynamic_cast<const ObservableMetadataProvider*>(application.getMetadataProvider(false)),
851 NULL, // not an entity, so inline assertions won't be processed
857 group = dynamic_cast<const EntitiesDescriptor*>(group->getParent());
862 // Check for attributes.
863 if (XMLString::equals(xmlObject.getElementQName().getLocalPart(), saml1::Attribute::LOCAL_NAME)) {
864 auto_ptr_char assertingParty(entity ? entity->getEntityID() : NULL);
865 const saml2::Attribute* attr2 = dynamic_cast<const saml2::Attribute*>(&xmlObject);
867 return m_impl->extractAttributes(application, assertingParty.get(), relyingParty, *attr2, attributes);
869 const saml1::Attribute* attr1 = dynamic_cast<const saml1::Attribute*>(&xmlObject);
871 return m_impl->extractAttributes(application, assertingParty.get(), relyingParty, *attr1, attributes);
873 throw AttributeExtractionException("Unable to extract attributes, unknown object type.");
876 if (XMLString::equals(xmlObject.getElementQName().getLocalPart(), EncryptedAttribute::LOCAL_NAME)) {
877 const EncryptedAttribute* encattr = dynamic_cast<const EncryptedAttribute*>(&xmlObject);
879 const XMLCh* recipient = application.getXMLString("entityID").second;
880 CredentialResolver* cr = application.getCredentialResolver();
882 m_log.warn("found encrypted attribute, but no CredentialResolver was available");
887 Locker credlocker(cr);
889 MetadataCredentialCriteria mcc(*issuer);
890 auto_ptr<XMLObject> decrypted(encattr->decrypt(*cr, recipient, &mcc));
891 if (m_log.isDebugEnabled())
892 m_log.debugStream() << "decrypted Attribute: " << *(decrypted.get()) << logging::eol;
893 return extractAttributes(application, issuer, *(decrypted.get()), attributes);
896 auto_ptr<XMLObject> decrypted(encattr->decrypt(*cr, recipient));
897 if (m_log.isDebugEnabled())
898 m_log.debugStream() << "decrypted Attribute: " << *(decrypted.get()) << logging::eol;
899 return extractAttributes(application, issuer, *(decrypted.get()), attributes);
902 catch (exception& ex) {
903 m_log.error("caught exception decrypting Attribute: %s", ex.what());
909 // Check for NameIDs.
910 const NameID* name2 = dynamic_cast<const NameID*>(&xmlObject);
912 auto_ptr_char assertingParty(entity ? entity->getEntityID() : NULL);
913 return m_impl->extractAttributes(application, assertingParty.get(), relyingParty, *name2, attributes);
916 const NameIdentifier* name1 = dynamic_cast<const NameIdentifier*>(&xmlObject);
918 auto_ptr_char assertingParty(entity ? entity->getEntityID() : NULL);
919 return m_impl->extractAttributes(application, assertingParty.get(), relyingParty, *name1, attributes);
922 throw AttributeExtractionException("Unable to extract attributes, unknown object type.");
925 pair<bool,DOMElement*> XMLExtractor::load()
927 // Load from source using base class.
928 pair<bool,DOMElement*> raw = ReloadableXMLFile::load();
930 // If we own it, wrap it.
931 XercesJanitor<DOMDocument> docjanitor(raw.first ? raw.second->getOwnerDocument() : NULL);
933 XMLExtractorImpl* impl = new XMLExtractorImpl(raw.second, m_log);
935 // If we held the document, transfer it to the impl. If we didn't, it's a no-op.
936 impl->setDocument(docjanitor.release());
941 return make_pair(false,(DOMElement*)NULL);