2 * Copyright 2001-2005 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 * shib-ini.h -- config file handling, now XML-based
25 #include <sys/types.h>
27 #include <log4cpp/Category.hh>
28 #include <log4cpp/PropertyConfigurator.hh>
29 #include <shibsp/DOMPropertySet.h>
30 #include <shibsp/PKIXTrustEngine.h>
31 #include <shibsp/SPConfig.h>
32 #include <shibsp/SPConstants.h>
33 #include <saml/SAMLConfig.h>
34 #include <saml/saml1/core/Assertions.h>
35 #include <saml/saml2/metadata/ChainingMetadataProvider.h>
36 #include <xmltooling/XMLToolingConfig.h>
37 #include <xmltooling/security/ChainingTrustEngine.h>
38 #include <xmltooling/util/ReloadableXMLFile.h>
40 using namespace shibsp;
41 using namespace shibtarget;
42 using namespace shibboleth;
44 using namespace opensaml::saml1;
45 using namespace opensaml::saml2md;
46 using namespace xmltooling;
47 using namespace log4cpp;
49 using xmlsignature::CredentialResolver;
53 // Application configuration wrapper
54 class XMLApplication : public virtual IApplication, public DOMPropertySet, public DOMNodeFilter
57 XMLApplication(const IConfig*, const DOMElement* e, const XMLApplication* base=NULL);
58 ~XMLApplication() { cleanup(); }
61 pair<bool,bool> getBool(const char* name, const char* ns=NULL) const;
62 pair<bool,const char*> getString(const char* name, const char* ns=NULL) const;
63 pair<bool,const XMLCh*> getXMLString(const char* name, const char* ns=NULL) const;
64 pair<bool,unsigned int> getUnsignedInt(const char* name, const char* ns=NULL) const;
65 pair<bool,int> getInt(const char* name, const char* ns=NULL) const;
66 const PropertySet* getPropertySet(const char* name, const char* ns="urn:mace:shibboleth:target:config:1.0") const;
69 const char* getId() const {return getString("id").second;}
70 const char* getHash() const {return m_hash.c_str();}
71 Iterator<SAMLAttributeDesignator*> getAttributeDesignators() const;
72 Iterator<IAAP*> getAAPProviders() const;
73 MetadataProvider* getMetadataProvider() const;
74 TrustEngine* getTrustEngine() const;
75 Iterator<const XMLCh*> getAudiences() const;
76 const PropertySet* getCredentialUse(const EntityDescriptor* provider) const;
78 const SAMLBrowserProfile* getBrowserProfile() const {return m_profile;}
79 const SAMLBinding* getBinding(const XMLCh* binding) const
80 {return XMLString::compareString(SAMLBinding::SOAP,binding) ? NULL : m_binding;}
81 SAMLBrowserProfile::ArtifactMapper* getArtifactMapper() const {return new STArtifactMapper(this);}
85 const RoleDescriptor* role=NULL,
86 const TrustEngine* trust=NULL
88 const IHandler* getDefaultSessionInitiator() const;
89 const IHandler* getSessionInitiatorById(const char* id) const;
90 const IHandler* getDefaultAssertionConsumerService() const;
91 const IHandler* getAssertionConsumerServiceByIndex(unsigned short index) const;
92 Iterator<const IHandler*> getAssertionConsumerServicesByBinding(const XMLCh* binding) const;
93 const IHandler* getHandler(const char* path) const;
95 // Provides filter to exclude special config elements.
96 short acceptNode(const DOMNode* node) const;
100 const IConfig* m_ini; // this is ok because its locking scope includes us
101 const XMLApplication* m_base;
103 vector<SAMLAttributeDesignator*> m_designators;
104 vector<IAAP*> m_aaps;
105 MetadataProvider* m_metadata;
106 TrustEngine* m_trust;
107 vector<const XMLCh*> m_audiences;
108 ShibBrowserProfile* m_profile;
109 SAMLBinding* m_binding;
110 ShibHTTPHook* m_bindingHook;
112 // vectors manage object life for handlers and their property sets
113 vector<IHandler*> m_handlers;
114 vector<PropertySet*> m_handlerProps;
116 // maps location (path info) to applicable handlers
117 map<string,const IHandler*> m_handlerMap;
119 // maps unique indexes to consumer services
120 map<unsigned int,const IHandler*> m_acsIndexMap;
122 // pointer to default consumer service
123 const IHandler* m_acsDefault;
125 // maps binding strings to supporting consumer service(s)
127 typedef map<xmltooling::xstring,vector<const IHandler*> > ACSBindingMap;
129 typedef map<string,vector<const IHandler*> > ACSBindingMap;
131 ACSBindingMap m_acsBindingMap;
133 // maps unique ID strings to session initiators
134 map<string,const IHandler*> m_sessionInitMap;
136 // pointer to default session initiator
137 const IHandler* m_sessionInitDefault;
139 DOMPropertySet* m_credDefault;
141 map<xmltooling::xstring,PropertySet*> m_credMap;
143 map<const XMLCh*,PropertySet*> m_credMap;
147 // Top-level configuration implementation
149 class XMLConfigImpl : public DOMPropertySet, public DOMNodeFilter
152 XMLConfigImpl(const DOMElement* e, bool first, const XMLConfig* outer);
155 IRequestMapper* m_requestMapper;
156 map<string,IApplication*> m_appmap;
157 map<string,CredentialResolver*> m_credResolverMap;
158 vector<IAttributeFactory*> m_attrFactories;
160 // Provides filter to exclude special config elements.
161 short acceptNode(const DOMNode* node) const;
163 void setDocument(DOMDocument* doc) {
168 void doExtensions(const DOMElement* e, const char* label, Category& log);
170 const XMLConfig* m_outer;
171 DOMDocument* m_document;
174 #if defined (_MSC_VER)
175 #pragma warning( push )
176 #pragma warning( disable : 4250 )
179 class XMLConfig : public IConfig, public ReloadableXMLFile
182 XMLConfig(const DOMElement* e)
183 : ReloadableXMLFile(e), m_impl(NULL), m_listener(NULL), m_sessionCache(NULL), m_replayCache(NULL) {
192 delete m_sessionCache;
193 delete m_replayCache;
198 pair<bool,bool> getBool(const char* name, const char* ns=NULL) const {return m_impl->getBool(name,ns);}
199 pair<bool,const char*> getString(const char* name, const char* ns=NULL) const {return m_impl->getString(name,ns);}
200 pair<bool,const XMLCh*> getXMLString(const char* name, const char* ns=NULL) const {return m_impl->getXMLString(name,ns);}
201 pair<bool,unsigned int> getUnsignedInt(const char* name, const char* ns=NULL) const {return m_impl->getUnsignedInt(name,ns);}
202 pair<bool,int> getInt(const char* name, const char* ns=NULL) const {return m_impl->getInt(name,ns);}
203 const PropertySet* getPropertySet(const char* name, const char* ns="urn:mace:shibboleth:target:config:1.0") const {return m_impl->getPropertySet(name,ns);}
204 const DOMElement* getElement() const {return m_impl->getElement();}
207 ListenerService* getListenerService(bool required=true) const {
208 if (required && !m_listener)
209 throw ConfigurationException("No ListenerService available.");
213 ISessionCache* getSessionCache() const {return m_sessionCache;}
214 IReplayCache* getReplayCache() const {return m_replayCache;}
215 IRequestMapper* getRequestMapper() const {return m_impl->m_requestMapper;}
216 const IApplication* getApplication(const char* applicationId) const {
217 map<string,IApplication*>::const_iterator i=m_impl->m_appmap.find(applicationId);
218 return (i!=m_impl->m_appmap.end()) ? i->second : NULL;
221 CredentialResolver* getCredentialResolver(const char* id) const {
223 map<string,CredentialResolver*>::const_iterator i=m_impl->m_credResolverMap.find(id);
224 if (i!=m_impl->m_credResolverMap.end())
231 pair<bool,DOMElement*> load();
234 friend class XMLConfigImpl;
235 XMLConfigImpl* m_impl;
236 mutable ListenerService* m_listener;
237 mutable ISessionCache* m_sessionCache;
238 mutable IReplayCache* m_replayCache;
241 #if defined (_MSC_VER)
242 #pragma warning( pop )
245 static const XMLCh AAPProvider[] = UNICODE_LITERAL_11(A,A,P,P,r,o,v,i,d,e,r);
246 static const XMLCh Application[] = UNICODE_LITERAL_11(A,p,p,l,i,c,a,t,i,o,n);
247 static const XMLCh Applications[] = UNICODE_LITERAL_12(A,p,p,l,i,c,a,t,i,o,n,s);
248 static const XMLCh AttributeFactory[] = UNICODE_LITERAL_16(A,t,t,r,i,b,u,t,e,F,a,c,t,o,r,y);
249 static const XMLCh Credentials[] = UNICODE_LITERAL_11(C,r,e,d,e,n,t,i,a,l,s);
250 static const XMLCh CredentialsProvider[] = UNICODE_LITERAL_19(C,r,e,d,e,n,t,i,a,l,s,P,r,o,v,i,d,e,r);
251 static const XMLCh CredentialUse[] = UNICODE_LITERAL_13(C,r,e,d,e,n,t,i,a,l,U,s,e);
252 static const XMLCh DiagnosticService[] = UNICODE_LITERAL_17(D,i,a,g,n,o,s,t,i,c,S,e,r,v,i,c,e);
253 static const XMLCh fatal[] = UNICODE_LITERAL_5(f,a,t,a,l);
254 static const XMLCh FileResolver[] = UNICODE_LITERAL_12(F,i,l,e,R,e,s,o,l,v,e,r);
255 static const XMLCh Global[] = UNICODE_LITERAL_6(G,l,o,b,a,l);
256 static const XMLCh Id[] = UNICODE_LITERAL_2(I,d);
257 static const XMLCh Implementation[] = UNICODE_LITERAL_14(I,m,p,l,e,m,e,n,t,a,t,i,o,n);
258 static const XMLCh InProcess[] = UNICODE_LITERAL_9(I,n,P,r,o,c,e,s,s);
259 static const XMLCh Library[] = UNICODE_LITERAL_7(L,i,b,r,a,r,y);
260 static const XMLCh Listener[] = UNICODE_LITERAL_8(L,i,s,t,e,n,e,r);
261 static const XMLCh Local[] = UNICODE_LITERAL_5(L,o,c,a,l);
262 static const XMLCh logger[] = UNICODE_LITERAL_6(l,o,g,g,e,r);
263 static const XMLCh MemoryListener[] = UNICODE_LITERAL_14(M,e,m,o,r,y,L,i,s,t,e,n,e,r);
264 static const XMLCh MemorySessionCache[] = UNICODE_LITERAL_18(M,e,m,o,r,y,S,e,s,s,i,o,n,C,a,c,h,e);
265 static const XMLCh RelyingParty[] = UNICODE_LITERAL_12(R,e,l,y,i,n,g,P,a,r,t,y);
266 static const XMLCh ReplayCache[] = UNICODE_LITERAL_11(R,e,p,l,a,y,C,a,c,h,e);
267 static const XMLCh RequestMapProvider[] = UNICODE_LITERAL_18(R,e,q,u,e,s,t,M,a,p,P,r,o,v,i,d,e,r);
268 static const XMLCh SessionCache[] = UNICODE_LITERAL_12(S,e,s,s,i,o,n,C,a,c,h,e);
269 static const XMLCh SessionInitiator[] = UNICODE_LITERAL_16(S,e,s,s,i,o,n,I,n,i,t,i,a,t,o,r);
270 static const XMLCh OutOfProcess[] = UNICODE_LITERAL_12(O,u,t,O,f,P,r,o,c,e,s,s);
271 static const XMLCh TCPListener[] = UNICODE_LITERAL_11(T,C,P,L,i,s,t,e,n,e,r);
272 static const XMLCh TrustProvider[] = UNICODE_LITERAL_13(T,r,u,s,t,P,r,o,v,i,d,e,r);
273 static const XMLCh UnixListener[] = UNICODE_LITERAL_12(U,n,i,x,L,i,s,t,e,n,e,r);
274 static const XMLCh _MetadataProvider[] = UNICODE_LITERAL_16(M,e,t,a,d,a,t,a,P,r,o,v,i,d,e,r);
275 static const XMLCh _path[] = UNICODE_LITERAL_4(p,a,t,h);
276 static const XMLCh _type[] = UNICODE_LITERAL_4(t,y,p,e);
280 ServiceProvider* shibtarget::XMLServiceProviderFactory(const DOMElement* const & e)
282 return new XMLConfig(e);
285 XMLApplication::XMLApplication(
288 const XMLApplication* base
289 ) : m_ini(ini), m_base(base), m_metadata(NULL), m_trust(NULL), m_profile(NULL), m_binding(NULL), m_bindingHook(NULL),
290 m_credDefault(NULL), m_sessionInitDefault(NULL), m_acsDefault(NULL)
293 xmltooling::NDC ndc("XMLApplication");
295 Category& log=Category::getInstance(SHIBT_LOGCAT".Application");
298 // First load any property sets.
299 map<string,string> root_remap;
300 root_remap["shire"]="session";
301 root_remap["shireURL"]="handlerURL";
302 root_remap["shireSSL"]="handlerSSL";
303 load(e,log,this,&root_remap);
305 const PropertySet* propcheck=getPropertySet("Errors");
306 if (propcheck && !propcheck->getString("session").first)
307 throw ConfigurationException("<Errors> element requires 'session' (or deprecated 'shire') attribute");
308 propcheck=getPropertySet("Sessions");
309 if (propcheck && !propcheck->getString("handlerURL").first)
310 throw ConfigurationException("<Sessions> element requires 'handlerURL' (or deprecated 'shireURL') attribute");
312 SPConfig& conf=SPConfig::getConfig();
313 XMLToolingConfig& xmlConf=XMLToolingConfig::getConfig();
314 opensaml::SAMLConfig& samlConf=opensaml::SAMLConfig::getConfig();
315 SAMLConfig& shibConf=SAMLConfig::getConfig();
318 m_hash+=getString("providerId").second;
319 m_hash=samlConf.hashSHA1(m_hash.c_str(), true);
321 const DOMElement* child;
322 IPlugIn* plugin=NULL;
325 bool hardACS=false, hardSessionInit=false;
326 child = XMLHelper::getFirstChildElement(propcheck->getElement());
328 // A handler is split across a property set and the plugin itself, which is based on the Binding property.
329 // We build both objects first and then insert them into various structures for lookup.
331 DOMPropertySet* hprops=new DOMPropertySet();
333 hprops->load(child,log,this); // filter irrelevant for now, no embedded elements expected
334 const char* bindprop=hprops->getString("Binding").second;
336 throw ConfigurationException("Handler element has no Binding attribute, skipping it...");
337 plugin=shibConf.getPlugMgr().newPlugin(bindprop,child);
338 hobj=dynamic_cast<IHandler*>(plugin);
341 throw UnknownExtensionException(
342 "Plugin for binding ($1) does not implement IHandler interface.",xmltooling::params(1,bindprop)
346 catch (exception& ex) {
347 // If we get here, the handler's not built, so dispose of the property set.
348 log.error("caught exception processing a handler element: %s",ex.what());
353 const char* location=hprops ? hprops->getString("Location").second : NULL;
356 child = XMLHelper::getNextSiblingElement(child);
360 // Save off the objects after giving the property set to the handler for its use.
361 hobj->setProperties(hprops);
362 m_handlers.push_back(hobj);
363 m_handlerProps.push_back(hprops);
365 // Insert into location map.
366 if (*location == '/')
367 m_handlerMap[location]=hobj;
369 m_handlerMap[string("/") + location]=hobj;
371 // If it's an ACS or SI, handle index/id mappings and defaulting.
372 if (XMLHelper::isNodeNamed(child,samlconstants::SAML20MD_NS,AssertionConsumerService::LOCAL_NAME)) {
375 const XMLCh* binding=hprops->getXMLString("Binding").second;
377 const char* binding=hprops->getString("Binding").second;
379 if (m_acsBindingMap.count(binding)==0)
380 m_acsBindingMap[binding]=vector<const IHandler*>(1,hobj);
382 m_acsBindingMap[binding].push_back(hobj);
383 m_acsIndexMap[hprops->getUnsignedInt("index").second]=hobj;
386 pair<bool,bool> defprop=hprops->getBool("isDefault");
388 if (defprop.second) {
393 else if (!m_acsDefault)
397 else if (XMLString::equals(child->getLocalName(),SessionInitiator)) {
398 pair<bool,const char*> si_id=hprops->getString("id");
399 if (si_id.first && si_id.second)
400 m_sessionInitMap[si_id.second]=hobj;
401 if (!hardSessionInit) {
402 pair<bool,bool> defprop=hprops->getBool("isDefault");
404 if (defprop.second) {
405 hardSessionInit=true;
406 m_sessionInitDefault=hobj;
409 else if (!m_sessionInitDefault)
410 m_sessionInitDefault=hobj;
413 child = XMLHelper::getNextSiblingElement(child);
416 // If no handlers defined at the root, assume a legacy configuration.
417 if (!m_base && m_handlers.empty()) {
418 // A legacy config installs a SAML POST handler at the root handler location.
419 // We use the Sessions element itself as the PropertySet.
421 xmltooling::auto_ptr_char b1(shibspconstants::SHIB1_SESSIONINIT_PROFILE_URI);
422 plugin=shibConf.getPlugMgr().newPlugin(b1.get(),propcheck->getElement());
423 IHandler* h1=dynamic_cast<IHandler*>(plugin);
426 throw UnknownExtensionException(
427 "Plugin for binding ($1) does not implement IHandler interface.",xmltooling::params(1,b1.get())
430 h1->setProperties(propcheck);
431 m_handlers.push_back(h1);
432 m_sessionInitDefault=h1;
434 xmltooling::auto_ptr_char b2(samlconstants::SAML1_PROFILE_BROWSER_POST);
435 plugin=shibConf.getPlugMgr().newPlugin(b2.get(),propcheck->getElement());
436 IHandler* h2=dynamic_cast<IHandler*>(plugin);
439 throw UnknownExtensionException(
440 "Plugin for binding ($1) does not implement IHandler interface.",xmltooling::params(1,b2.get())
443 h2->setProperties(propcheck);
444 m_handlers.push_back(h2);
445 m_handlerMap[""] = h2;
449 // Process general configuration elements.
451 DOMNodeList* nlist=e->getElementsByTagNameNS(samlconstants::SAML1_NS,AttributeDesignator::LOCAL_NAME);
452 for (i=0; nlist && i<nlist->getLength(); i++)
453 if (nlist->item(i)->getParentNode()->isSameNode(e))
454 m_designators.push_back(new SAMLAttributeDesignator(static_cast<DOMElement*>(nlist->item(i))));
456 nlist=e->getElementsByTagNameNS(samlconstants::SAML1_NS,Audience::LOCAL_NAME);
457 for (i=0; nlist && i<nlist->getLength(); i++)
458 if (nlist->item(i)->getParentNode()->isSameNode(e) && nlist->item(i)->hasChildNodes())
459 m_audiences.push_back(nlist->item(i)->getFirstChild()->getNodeValue());
461 // Always include our own providerId as an audience.
462 m_audiences.push_back(getXMLString("providerId").second);
464 if (conf.isEnabled(SPConfig::AAP)) {
465 child = XMLHelper::getFirstChildElement(e,AAPProvider);
467 xmltooling::auto_ptr_char type(child->getAttributeNS(NULL,_type));
468 log.info("building AAP provider of type %s...",type.get());
470 plugin=shibConf.getPlugMgr().newPlugin(type.get(),child);
471 IAAP* aap=dynamic_cast<IAAP*>(plugin);
473 m_aaps.push_back(aap);
476 log.crit("plugin was not an AAP provider");
479 catch (exception& ex) {
480 log.crit("error building AAP provider: %s", ex.what());
483 child = XMLHelper::getNextSiblingElement(child,AAPProvider);
487 if (conf.isEnabled(SPConfig::Metadata)) {
488 vector<MetadataProvider*> os2providers;
489 child = XMLHelper::getFirstChildElement(e,_MetadataProvider);
491 xmltooling::auto_ptr_char type(child->getAttributeNS(NULL,_type));
492 log.info("building metadata provider of type %s...",type.get());
494 auto_ptr<MetadataProvider> mp(samlConf.MetadataProviderManager.newPlugin(type.get(),child));
496 os2providers.push_back(mp.release());
498 catch (exception& ex) {
499 log.crit("error building/initializing metadata provider: %s", ex.what());
502 child = XMLHelper::getNextSiblingElement(child,_MetadataProvider);
505 if (os2providers.size()==1)
506 m_metadata=os2providers.front();
507 else if (os2providers.size()>1) {
509 m_metadata = samlConf.MetadataProviderManager.newPlugin(CHAINING_METADATA_PROVIDER,NULL);
510 ChainingMetadataProvider* chainMeta = dynamic_cast<ChainingMetadataProvider*>(m_metadata);
511 while (!os2providers.empty()) {
512 chainMeta->addMetadataProvider(os2providers.back());
513 os2providers.pop_back();
516 catch (exception& ex) {
517 log.crit("error building chaining metadata provider wrapper: %s",ex.what());
518 for_each(os2providers.begin(), os2providers.end(), xmltooling::cleanup<MetadataProvider>());
523 if (conf.isEnabled(SPConfig::Trust)) {
524 ChainingTrustEngine* chainTrust = NULL;
525 child = XMLHelper::getFirstChildElement(e,TrustProvider);
527 xmltooling::auto_ptr_char type(child->getAttributeNS(NULL,_type));
528 log.info("building trust provider of type %s...",type.get());
531 // For compatibility with old engine types, we're assuming a Shib engine is likely,
532 // which requires chaining, so we'll build that regardless.
533 m_trust = xmlConf.TrustEngineManager.newPlugin(CHAINING_TRUSTENGINE,NULL);
534 chainTrust = dynamic_cast<ChainingTrustEngine*>(m_trust);
536 if (!strcmp(type.get(),"edu.internet2.middleware.shibboleth.common.provider.ShibbolethTrust")) {
537 chainTrust->addTrustEngine(xmlConf.TrustEngineManager.newPlugin(EXPLICIT_KEY_TRUSTENGINE,child));
538 chainTrust->addTrustEngine(xmlConf.TrustEngineManager.newPlugin(SHIBBOLETH_PKIX_TRUSTENGINE,child));
540 else if (!strcmp(type.get(),"edu.internet2.middleware.shibboleth.common.provider.BasicTrust")) {
541 chainTrust->addTrustEngine(xmlConf.TrustEngineManager.newPlugin(EXPLICIT_KEY_TRUSTENGINE,child));
544 chainTrust->addTrustEngine(xmlConf.TrustEngineManager.newPlugin(type.get(),child));
547 catch (exception& ex) {
548 log.crit("error building trust provider: %s",ex.what());
551 child = XMLHelper::getNextSiblingElement(child,TrustProvider);
555 // Finally, load credential mappings.
556 child = XMLHelper::getFirstChildElement(e,CredentialUse);
558 m_credDefault=new DOMPropertySet();
559 m_credDefault->load(child,log,this);
560 child = XMLHelper::getFirstChildElement(child,RelyingParty);
562 DOMPropertySet* rp=new DOMPropertySet();
563 rp->load(child,log,this);
564 m_credMap[child->getAttributeNS(NULL,opensaml::saml2::Attribute::NAME_ATTRIB_NAME)]=rp;
565 child = XMLHelper::getNextSiblingElement(child,RelyingParty);
569 if (conf.isEnabled(SPConfig::OutOfProcess)) {
570 // Really finally, build local browser profile and binding objects.
571 m_profile=new ShibBrowserProfile(this, getMetadataProvider(), getTrustEngine());
572 m_bindingHook=new ShibHTTPHook(getTrustEngine());
573 m_binding=SAMLBinding::getInstance(SAMLBinding::SOAP);
574 SAMLSOAPHTTPBinding* bptr=dynamic_cast<SAMLSOAPHTTPBinding*>(m_binding);
576 log.fatal("binding implementation was not SOAP over HTTP");
577 throw UnknownExtensionException("binding implementation was not SOAP over HTTP");
579 bptr->addHook(m_bindingHook,m_bindingHook); // the hook is its own global context
594 void XMLApplication::cleanup()
596 delete m_bindingHook;
599 for_each(m_handlers.begin(),m_handlers.end(),xmltooling::cleanup<IHandler>());
601 delete m_credDefault;
603 for_each(m_credMap.begin(),m_credMap.end(),xmltooling::cleanup_pair<xmltooling::xstring,PropertySet>());
605 for_each(m_credMap.begin(),m_credMap.end(),xmltooling::cleanup_pair<const XMLCh*,PropertySet>());
607 for_each(m_designators.begin(),m_designators.end(),xmltooling::cleanup<SAMLAttributeDesignator>());
608 for_each(m_aaps.begin(),m_aaps.end(),xmltooling::cleanup<IAAP>());
614 short XMLApplication::acceptNode(const DOMNode* node) const
616 if (XMLHelper::isNodeNamed(node,samlconstants::SAML1_NS,AttributeDesignator::LOCAL_NAME))
617 return FILTER_REJECT;
618 else if (XMLHelper::isNodeNamed(node,samlconstants::SAML1_NS,Audience::LOCAL_NAME))
619 return FILTER_REJECT;
620 const XMLCh* name=node->getLocalName();
621 if (XMLString::equals(name,Application) ||
622 XMLString::equals(name,AssertionConsumerService::LOCAL_NAME) ||
623 XMLString::equals(name,SingleLogoutService::LOCAL_NAME) ||
624 XMLString::equals(name,DiagnosticService) ||
625 XMLString::equals(name,SessionInitiator) ||
626 XMLString::equals(name,AAPProvider) ||
627 XMLString::equals(name,CredentialUse) ||
628 XMLString::equals(name,RelyingParty) ||
629 XMLString::equals(name,_MetadataProvider) ||
630 XMLString::equals(name,TrustProvider))
631 return FILTER_REJECT;
633 return FILTER_ACCEPT;
636 pair<bool,bool> XMLApplication::getBool(const char* name, const char* ns) const
638 pair<bool,bool> ret=DOMPropertySet::getBool(name,ns);
641 return m_base ? m_base->getBool(name,ns) : ret;
644 pair<bool,const char*> XMLApplication::getString(const char* name, const char* ns) const
646 pair<bool,const char*> ret=DOMPropertySet::getString(name,ns);
649 return m_base ? m_base->getString(name,ns) : ret;
652 pair<bool,const XMLCh*> XMLApplication::getXMLString(const char* name, const char* ns) const
654 pair<bool,const XMLCh*> ret=DOMPropertySet::getXMLString(name,ns);
657 return m_base ? m_base->getXMLString(name,ns) : ret;
660 pair<bool,unsigned int> XMLApplication::getUnsignedInt(const char* name, const char* ns) const
662 pair<bool,unsigned int> ret=DOMPropertySet::getUnsignedInt(name,ns);
665 return m_base ? m_base->getUnsignedInt(name,ns) : ret;
668 pair<bool,int> XMLApplication::getInt(const char* name, const char* ns) const
670 pair<bool,int> ret=DOMPropertySet::getInt(name,ns);
673 return m_base ? m_base->getInt(name,ns) : ret;
676 const PropertySet* XMLApplication::getPropertySet(const char* name, const char* ns) const
678 const PropertySet* ret=DOMPropertySet::getPropertySet(name,ns);
681 return m_base->getPropertySet(name,ns);
684 Iterator<SAMLAttributeDesignator*> XMLApplication::getAttributeDesignators() const
686 if (!m_designators.empty() || !m_base)
687 return m_designators;
688 return m_base->getAttributeDesignators();
691 Iterator<IAAP*> XMLApplication::getAAPProviders() const
693 return (m_aaps.empty() && m_base) ? m_base->getAAPProviders() : m_aaps;
696 MetadataProvider* XMLApplication::getMetadataProvider() const
698 return (!m_metadata && m_base) ? m_base->getMetadataProvider() : m_metadata;
701 TrustEngine* XMLApplication::getTrustEngine() const
703 return (!m_trust && m_base) ? m_base->getTrustEngine() : m_trust;
706 Iterator<const XMLCh*> XMLApplication::getAudiences() const
708 return (m_audiences.empty() && m_base) ? m_base->getAudiences() : m_audiences;
711 const PropertySet* XMLApplication::getCredentialUse(const EntityDescriptor* provider) const
713 if (!m_credDefault && m_base)
714 return m_base->getCredentialUse(provider);
717 map<xmltooling::xstring,PropertySet*>::const_iterator i=m_credMap.find(provider->getEntityID());
718 if (i!=m_credMap.end())
720 const EntitiesDescriptor* group=dynamic_cast<const EntitiesDescriptor*>(provider->getParent());
722 if (group->getName()) {
723 i=m_credMap.find(group->getName());
724 if (i!=m_credMap.end())
727 group=dynamic_cast<const EntitiesDescriptor*>(group->getParent());
730 map<const XMLCh*,PropertySet*>::const_iterator i=m_credMap.begin();
731 for (; i!=m_credMap.end(); i++) {
732 if (XMLString::equals(i->first,provider->getId()))
734 const EntitiesDescriptor* group=dynamic_cast<const EntitiesDescriptor*>(provider->getParent());
736 if (XMLString::equals(i->first,group->getName()))
738 group=dynamic_cast<const EntitiesDescriptor*>(group->getParent());
742 return m_credDefault;
745 void XMLApplication::validateToken(SAMLAssertion* token, time_t ts, const RoleDescriptor* role, const TrustEngine* trust) const
748 xmltooling::NDC ndc("validateToken");
750 Category& log=Category::getInstance(SHIBT_LOGCAT".Application");
752 // First we verify the time conditions, using the specified timestamp, if non-zero.
753 SAMLConfig& config=SAMLConfig::getConfig();
755 const SAMLDateTime* notBefore=token->getNotBefore();
756 if (notBefore && ts+config.clock_skew_secs < notBefore->getEpoch())
757 throw opensaml::FatalProfileException("Assertion is not yet valid.");
758 const SAMLDateTime* notOnOrAfter=token->getNotOnOrAfter();
759 if (notOnOrAfter && notOnOrAfter->getEpoch() <= ts-config.clock_skew_secs)
760 throw opensaml::FatalProfileException("Assertion is no longer valid.");
763 // Now we process conditions. Only audience restrictions at the moment.
764 Iterator<SAMLCondition*> conditions=token->getConditions();
765 while (conditions.hasNext()) {
766 SAMLCondition* cond=conditions.next();
767 const SAMLAudienceRestrictionCondition* ac=dynamic_cast<const SAMLAudienceRestrictionCondition*>(cond);
771 log.error("unrecognized Condition in assertion (%s)",os.str().c_str());
772 throw xmltooling::UnknownExtensionException("Assertion contains an unrecognized condition.");
774 else if (!ac->eval(getAudiences())) {
777 log.error("unacceptable AudienceRestrictionCondition in assertion (%s)",os.str().c_str());
778 throw opensaml::FatalProfileException("Assertion contains an unacceptable AudienceRestrictionCondition.");
782 if (!role || !trust) {
783 log.warn("no metadata provided, so no signature validation was performed");
787 const PropertySet* credUse=getCredentialUse(dynamic_cast<const EntityDescriptor*>(role->getParent()));
788 pair<bool,bool> signedAssertions=credUse ? credUse->getBool("signedAssertions") : make_pair(false,false);
790 if (token->isSigned()) {
792 // This will all change, but for fun, we'll port the object from OS1->OS2 for validation.
795 DOMDocument* doc = XMLToolingConfig::getConfig().getValidatingParser().parse(s);
796 XercesJanitor<DOMDocument> jdoc(doc);
797 auto_ptr<Assertion> os2ass(AssertionBuilder::buildAssertion());
798 os2ass->unmarshall(doc->getDocumentElement(),true);
801 if (!trust->validate(*(os2ass->getSignature()),*role))
802 throw xmltooling::XMLSecurityException("Assertion signature did not validate.");
804 else if (signedAssertions.first && signedAssertions.second)
805 throw xmltooling::XMLSecurityException("Assertion was unsigned, violating policy based on the issuer.");
808 const IHandler* XMLApplication::getDefaultSessionInitiator() const
810 if (m_sessionInitDefault) return m_sessionInitDefault;
811 return m_base ? m_base->getDefaultSessionInitiator() : NULL;
814 const IHandler* XMLApplication::getSessionInitiatorById(const char* id) const
816 map<string,const IHandler*>::const_iterator i=m_sessionInitMap.find(id);
817 if (i!=m_sessionInitMap.end()) return i->second;
818 return m_base ? m_base->getSessionInitiatorById(id) : NULL;
821 const IHandler* XMLApplication::getDefaultAssertionConsumerService() const
823 if (m_acsDefault) return m_acsDefault;
824 return m_base ? m_base->getDefaultAssertionConsumerService() : NULL;
827 const IHandler* XMLApplication::getAssertionConsumerServiceByIndex(unsigned short index) const
829 map<unsigned int,const IHandler*>::const_iterator i=m_acsIndexMap.find(index);
830 if (i!=m_acsIndexMap.end()) return i->second;
831 return m_base ? m_base->getAssertionConsumerServiceByIndex(index) : NULL;
834 Iterator<const IHandler*> XMLApplication::getAssertionConsumerServicesByBinding(const XMLCh* binding) const
837 ACSBindingMap::const_iterator i=m_acsBindingMap.find(binding);
839 xmltooling::auto_ptr_char temp(binding);
840 ACSBindingMap::const_iterator i=m_acsBindingMap.find(temp.get());
842 if (i!=m_acsBindingMap.end())
844 return m_base ? m_base->getAssertionConsumerServicesByBinding(binding) : EMPTY(const IHandler*);
847 const IHandler* XMLApplication::getHandler(const char* path) const
850 map<string,const IHandler*>::const_iterator i=m_handlerMap.find(wrap.substr(0,wrap.find('?')));
851 if (i!=m_handlerMap.end())
853 return m_base ? m_base->getHandler(path) : NULL;
856 short XMLConfigImpl::acceptNode(const DOMNode* node) const
858 if (!XMLString::equals(node->getNamespaceURI(),shibspconstants::SHIB1SPCONFIG_NS))
859 return FILTER_ACCEPT;
860 const XMLCh* name=node->getLocalName();
861 if (XMLString::equals(name,Applications) ||
862 XMLString::equals(name,AttributeFactory) ||
863 XMLString::equals(name,Credentials) ||
864 XMLString::equals(name,CredentialsProvider) ||
865 XMLString::equals(name,Extensions::LOCAL_NAME) ||
866 XMLString::equals(name,Implementation) ||
867 XMLString::equals(name,Listener) ||
868 XMLString::equals(name,MemoryListener) ||
869 XMLString::equals(name,MemorySessionCache) ||
870 XMLString::equals(name,RequestMapProvider) ||
871 XMLString::equals(name,ReplayCache) ||
872 XMLString::equals(name,SessionCache) ||
873 XMLString::equals(name,TCPListener) ||
874 XMLString::equals(name,UnixListener))
875 return FILTER_REJECT;
877 return FILTER_ACCEPT;
880 void XMLConfigImpl::doExtensions(const DOMElement* e, const char* label, Category& log)
882 const DOMElement* exts=XMLHelper::getFirstChildElement(e,Extensions::LOCAL_NAME);
884 exts=XMLHelper::getFirstChildElement(exts,Library);
886 xmltooling::auto_ptr_char path(exts->getAttributeNS(NULL,_path));
889 // TODO: replace with xmltooling extension load...
890 SAMLConfig::getConfig().saml_register_extension(path.get(),(void*)exts);
891 log.debug("loaded %s extension library (%s)", label, path.get());
894 catch (exception& e) {
895 const XMLCh* fatal=exts->getAttributeNS(NULL,fatal);
896 if (fatal && (*fatal==chLatin_t || *fatal==chDigit_1)) {
897 log.fatal("unable to load mandatory %s extension library %s: %s", label, path.get(), e.what());
901 log.crit("unable to load optional %s extension library %s: %s", label, path.get(), e.what());
904 exts=XMLHelper::getNextSiblingElement(exts,Library);
909 XMLConfigImpl::XMLConfigImpl(const DOMElement* e, bool first, const XMLConfig* outer) : m_outer(outer), m_requestMapper(NULL)
912 xmltooling::NDC ndc("XMLConfigImpl");
914 Category& log=Category::getInstance(SHIBT_LOGCAT".Config");
917 SAMLConfig& shibConf=SAMLConfig::getConfig();
918 SPConfig& conf=SPConfig::getConfig();
919 const DOMElement* SHAR=XMLHelper::getFirstChildElement(e,OutOfProcess);
921 SHAR=XMLHelper::getFirstChildElement(e,Global);
922 const DOMElement* SHIRE=XMLHelper::getFirstChildElement(e,InProcess);
924 SHIRE=XMLHelper::getFirstChildElement(e,Local);
926 // Initialize log4cpp manually in order to redirect log messages as soon as possible.
927 if (conf.isEnabled(SPConfig::Logging)) {
928 const XMLCh* logconf=NULL;
929 if (conf.isEnabled(SPConfig::OutOfProcess))
930 logconf=SHAR->getAttributeNS(NULL,logger);
931 else if (conf.isEnabled(SPConfig::InProcess))
932 logconf=SHIRE->getAttributeNS(NULL,logger);
933 if (!logconf || !*logconf)
934 logconf=e->getAttributeNS(NULL,logger);
935 if (logconf && *logconf) {
936 xmltooling::auto_ptr_char logpath(logconf);
937 log.debug("loading new logging configuration from (%s), check log destination for status of configuration",logpath.get());
938 XMLToolingConfig::getConfig().log_config(logpath.get());
942 // First load any property sets.
943 map<string,string> root_remap;
944 root_remap["Global"]="OutOfProcess";
945 root_remap["Local"]="InProcess";
946 load(e,log,this,&root_remap);
948 const DOMElement* child;
949 IPlugIn* plugin=NULL;
952 // Much of the processing can only occur on the first instantiation.
956 doExtensions(e, "global", log);
957 if (conf.isEnabled(SPConfig::OutOfProcess))
958 doExtensions(SHAR, "out of process", log);
960 if (conf.isEnabled(SPConfig::InProcess))
961 doExtensions(SHIRE, "in process", log);
963 // Instantiate the ListenerService and SessionCache objects.
964 if (conf.isEnabled(SPConfig::Listener)) {
965 child=XMLHelper::getFirstChildElement(SHAR,UnixListener);
967 plugtype=UNIX_LISTENER_SERVICE;
969 child=XMLHelper::getFirstChildElement(SHAR,TCPListener);
971 plugtype=TCP_LISTENER_SERVICE;
973 child=XMLHelper::getFirstChildElement(SHAR,MemoryListener);
975 plugtype=MEMORY_LISTENER_SERVICE;
977 child=XMLHelper::getFirstChildElement(SHAR,Listener);
979 xmltooling::auto_ptr_char type(child->getAttributeNS(NULL,_type));
987 log.info("building ListenerService of type %s...", plugtype.c_str());
988 m_outer->m_listener = conf.ListenerServiceManager.newPlugin(plugtype.c_str(),child);
991 log.fatal("can't build ListenerService, missing conf:Listener element?");
992 throw ConfigurationException("Can't build ListenerService, missing conf:Listener element?");
996 if (conf.isEnabled(SPConfig::Caching)) {
997 // TODO: This code's a mess, due to a very bad config layout for the caches...
998 // Needs rework with the new config file.
999 const DOMElement* container=conf.isEnabled(SPConfig::OutOfProcess) ? SHAR : SHIRE;
1000 child=XMLHelper::getFirstChildElement(container,MemorySessionCache);
1002 log.info("building Session Cache of type %s...",MEMORY_SESSIONCACHE);
1003 plugin=shibConf.getPlugMgr().newPlugin(MEMORY_SESSIONCACHE,child);
1006 child=XMLHelper::getFirstChildElement(container,SessionCache);
1008 xmltooling::auto_ptr_char type(child->getAttributeNS(NULL,_type));
1009 log.info("building Session Cache of type %s...",type.get());
1010 plugin=shibConf.getPlugMgr().newPlugin(type.get(),child);
1013 log.info("custom SessionCache unspecified or no longer supported, building SessionCache of type %s...",MEMORY_SESSIONCACHE);
1014 plugin=shibConf.getPlugMgr().newPlugin(MEMORY_SESSIONCACHE,child);
1018 ISessionCache* cache=dynamic_cast<ISessionCache*>(plugin);
1020 m_outer->m_sessionCache=cache;
1023 log.fatal("plugin was not a Session Cache object");
1024 throw UnknownExtensionException("plugin was not a Session Cache object");
1029 // TODO: switch to new cache interface
1030 child=XMLHelper::getFirstChildElement(container,ReplayCache);
1032 xmltooling::auto_ptr_char type(child->getAttributeNS(NULL,_type));
1033 log.info("building ReplayCache of type %s...",type.get());
1034 m_outer->m_replayCache=IReplayCache::getInstance(type.get(),child);
1037 // OpenSAML default provider.
1038 log.info("custom ReplayCache unspecified or no longer supported, building default ReplayCache...");
1039 m_outer->m_replayCache=IReplayCache::getInstance();
1042 } // end of first-time-only stuff
1044 // Back to the fully dynamic stuff...next up is the RequestMapper.
1045 if (conf.isEnabled(SPConfig::RequestMapper)) {
1046 child=XMLHelper::getFirstChildElement(SHIRE,RequestMapProvider);
1048 xmltooling::auto_ptr_char type(child->getAttributeNS(NULL,_type));
1049 log.info("building RequestMapper of type %s...",type.get());
1050 plugin=shibConf.getPlugMgr().newPlugin(type.get(),child);
1052 IRequestMapper* reqmap=dynamic_cast<IRequestMapper*>(plugin);
1054 m_requestMapper=reqmap;
1057 log.fatal("plugin was not a RequestMapper object");
1058 throw UnknownExtensionException("plugin was not a RequestMapper object");
1063 log.fatal("can't build RequestMapper, missing conf:RequestMapProvider element?");
1064 throw ConfigurationException("can't build RequestMapper, missing conf:RequestMapProvider element?");
1068 // Now we load the credentials map.
1069 if (conf.isEnabled(SPConfig::Credentials)) {
1070 // Old format was to wrap it in a CredentialsProvider plugin, we're inlining that...
1071 child = XMLHelper::getFirstChildElement(e,CredentialsProvider);
1072 child = XMLHelper::getFirstChildElement(child ? child : e,Credentials);
1074 // Step down and process resolvers.
1075 child=XMLHelper::getFirstChildElement(child);
1077 xmltooling::auto_ptr_char id(child->getAttributeNS(NULL,Id));
1078 if (!id.get() || !*(id.get())) {
1079 log.warn("skipping CredentialsResolver with no Id attribute");
1080 child = XMLHelper::getNextSiblingElement(child);
1084 if (XMLString::equals(child->getLocalName(),FileResolver))
1085 plugtype=FILESYSTEM_CREDENTIAL_RESOLVER;
1087 xmltooling::auto_ptr_char c(child->getAttributeNS(NULL,_type));
1091 if (!plugtype.empty()) {
1093 CredentialResolver* cr=
1094 XMLToolingConfig::getConfig().CredentialResolverManager.newPlugin(plugtype.c_str(),child);
1095 m_credResolverMap[id.get()] = cr;
1097 catch (exception& ex) {
1098 log.crit("failed to instantiate CredentialResolver (%s): %s", id.get(), ex.what());
1102 log.error("unknown type of CredentialResolver with Id (%s)", id.get());
1105 child = XMLHelper::getNextSiblingElement(child);
1110 // Now we load any attribute factories
1111 child = XMLHelper::getFirstChildElement(e,AttributeFactory);
1113 xmltooling::auto_ptr_char type(child->getAttributeNS(NULL,_type));
1114 log.info("building Attribute factory of type %s...",type.get());
1116 plugin=shibConf.getPlugMgr().newPlugin(type.get(),child);
1118 IAttributeFactory* fact=dynamic_cast<IAttributeFactory*>(plugin);
1120 m_attrFactories.push_back(fact);
1121 ShibConfig::getConfig().regAttributeMapping(
1122 child->getAttributeNS(NULL,Attribute::ATTRIBUTENAME_ATTRIB_NAME), fact
1127 log.crit("plugin was not an Attribute factory");
1131 catch (exception& ex) {
1132 log.crit("error building Attribute factory: %s", ex.what());
1135 child = XMLHelper::getNextSiblingElement(child,AttributeFactory);
1138 // Load the default application. This actually has a fixed ID of "default". ;-)
1139 child=XMLHelper::getFirstChildElement(e,Applications);
1141 log.fatal("can't build default Application object, missing conf:Applications element?");
1142 throw ConfigurationException("can't build default Application object, missing conf:Applications element?");
1144 XMLApplication* defapp=new XMLApplication(m_outer,child);
1145 m_appmap[defapp->getId()]=defapp;
1147 // Load any overrides.
1148 child = XMLHelper::getFirstChildElement(child,Application);
1150 auto_ptr<XMLApplication> iapp(new XMLApplication(m_outer,child,defapp));
1151 if (m_appmap.find(iapp->getId())!=m_appmap.end())
1152 log.crit("found conf:Application element with duplicate Id attribute (%s), skipping it", iapp->getId());
1154 m_appmap[iapp->getId()]=iapp.release();
1156 child = XMLHelper::getNextSiblingElement(child,Application);
1159 catch (exception&) {
1160 this->~XMLConfigImpl();
1165 this->~XMLConfigImpl();
1171 XMLConfigImpl::~XMLConfigImpl()
1173 for_each(m_appmap.begin(),m_appmap.end(),xmltooling::cleanup_pair<string,IApplication>());
1174 ShibConfig::getConfig().clearAttributeMappings();
1175 for_each(m_attrFactories.begin(),m_attrFactories.end(),xmltooling::cleanup<IAttributeFactory>());
1176 for_each(m_credResolverMap.begin(),m_credResolverMap.end(),xmltooling::cleanup_pair<string,CredentialResolver>());
1177 delete m_requestMapper;
1179 m_document->release();
1182 pair<bool,DOMElement*> XMLConfig::load()
1184 // Load from source using base class.
1185 pair<bool,DOMElement*> raw = ReloadableXMLFile::load();
1187 // If we own it, wrap it.
1188 XercesJanitor<DOMDocument> docjanitor(raw.first ? raw.second->getOwnerDocument() : NULL);
1190 XMLConfigImpl* impl = new XMLConfigImpl(raw.second,(m_impl==NULL),this);
1192 // If we held the document, transfer it to the impl. If we didn't, it's a no-op.
1193 impl->setDocument(docjanitor.release());
1198 return make_pair(false,(DOMElement*)NULL);