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/RequestMapper.h>
30 #include <shibsp/SPConfig.h>
31 #include <shibsp/TransactionLog.h>
32 #include <shibsp/security/PKIXTrustEngine.h>
33 #include <shibsp/util/DOMPropertySet.h>
34 #include <saml/SAMLConfig.h>
35 #include <saml/saml1/core/Assertions.h>
36 #include <saml/saml2/metadata/ChainingMetadataProvider.h>
37 #include <xmltooling/XMLToolingConfig.h>
38 #include <xmltooling/security/ChainingTrustEngine.h>
39 #include <xmltooling/util/ReloadableXMLFile.h>
41 using namespace shibsp;
42 using namespace shibtarget;
43 using namespace shibboleth;
45 using namespace opensaml::saml1;
46 using namespace opensaml::saml2md;
47 using namespace xmltooling;
48 using namespace log4cpp;
50 using xmlsignature::CredentialResolver;
54 vector<const Handler*> g_noHandlers;
56 // Application configuration wrapper
57 class XMLApplication : public virtual IApplication, public DOMPropertySet, public DOMNodeFilter
60 XMLApplication(const ServiceProvider*, const DOMElement* e, const XMLApplication* base=NULL);
61 ~XMLApplication() { cleanup(); }
64 pair<bool,bool> getBool(const char* name, const char* ns=NULL) const;
65 pair<bool,const char*> getString(const char* name, const char* ns=NULL) const;
66 pair<bool,const XMLCh*> getXMLString(const char* name, const char* ns=NULL) const;
67 pair<bool,unsigned int> getUnsignedInt(const char* name, const char* ns=NULL) const;
68 pair<bool,int> getInt(const char* name, const char* ns=NULL) const;
69 const PropertySet* getPropertySet(const char* name, const char* ns="urn:mace:shibboleth:target:config:1.0") const;
72 const char* getId() const {return getString("id").second;}
73 const char* getHash() const {return m_hash.c_str();}
74 Iterator<IAAP*> getAAPProviders() const;
75 MetadataProvider* getMetadataProvider() const;
76 TrustEngine* getTrustEngine() const;
77 const vector<const XMLCh*>& getAudiences() const;
78 const PropertySet* getCredentialUse(const EntityDescriptor* provider) const;
80 const SAMLBrowserProfile* getBrowserProfile() const {return m_profile;}
81 const SAMLBinding* getBinding(const XMLCh* binding) const
82 {return XMLString::compareString(SAMLBinding::SOAP,binding) ? NULL : m_binding;}
83 SAMLBrowserProfile::ArtifactMapper* getArtifactMapper() const {return new STArtifactMapper(this);}
87 const RoleDescriptor* role=NULL,
88 const TrustEngine* trust=NULL
90 const Handler* getDefaultSessionInitiator() const;
91 const Handler* getSessionInitiatorById(const char* id) const;
92 const Handler* getDefaultAssertionConsumerService() const;
93 const Handler* getAssertionConsumerServiceByIndex(unsigned short index) const;
94 const vector<const Handler*>& getAssertionConsumerServicesByBinding(const XMLCh* binding) const;
95 const Handler* getHandler(const char* path) const;
97 // Provides filter to exclude special config elements.
98 short acceptNode(const DOMNode* node) const;
102 const ServiceProvider* m_sp; // this is ok because its locking scope includes us
103 const XMLApplication* m_base;
105 vector<IAAP*> m_aaps;
106 MetadataProvider* m_metadata;
107 TrustEngine* m_trust;
108 vector<const XMLCh*> m_audiences;
109 ShibBrowserProfile* m_profile;
110 SAMLBinding* m_binding;
111 ShibHTTPHook* m_bindingHook;
113 // manage handler objects
114 vector<Handler*> m_handlers;
116 // maps location (path info) to applicable handlers
117 map<string,const Handler*> m_handlerMap;
119 // maps unique indexes to consumer services
120 map<unsigned int,const Handler*> m_acsIndexMap;
122 // pointer to default consumer service
123 const Handler* m_acsDefault;
125 // maps binding strings to supporting consumer service(s)
127 typedef map<xmltooling::xstring,vector<const Handler*> > ACSBindingMap;
129 typedef map<string,vector<const Handler*> > ACSBindingMap;
131 ACSBindingMap m_acsBindingMap;
133 // maps unique ID strings to session initiators
134 map<string,const Handler*> m_sessionInitMap;
136 // pointer to default session initiator
137 const Handler* 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 RequestMapper* m_requestMapper;
156 map<string,Application*> 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 ServiceProvider, public ReloadableXMLFile
182 XMLConfig(const DOMElement* e)
183 : ReloadableXMLFile(e), m_impl(NULL), m_listener(NULL), m_sessionCache(NULL) {
192 delete m_sessionCache;
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 TransactionLog* getTransactionLog() const {
210 throw ConfigurationException("No TransactionLog available.");
213 ListenerService* getListenerService(bool required=true) const {
214 if (required && !m_listener)
215 throw ConfigurationException("No ListenerService available.");
219 SessionCache* getSessionCache(bool required=true) const {
220 if (required && !m_sessionCache)
221 throw ConfigurationException("No SessionCache available.");
222 return m_sessionCache;
225 RequestMapper* getRequestMapper(bool required=true) const {
226 if (required && !m_impl->m_requestMapper)
227 throw ConfigurationException("No RequestMapper available.");
228 return m_impl->m_requestMapper;
231 const Application* getApplication(const char* applicationId) const {
232 map<string,Application*>::const_iterator i=m_impl->m_appmap.find(applicationId);
233 return (i!=m_impl->m_appmap.end()) ? i->second : NULL;
236 CredentialResolver* getCredentialResolver(const char* id) const {
238 map<string,CredentialResolver*>::const_iterator i=m_impl->m_credResolverMap.find(id);
239 if (i!=m_impl->m_credResolverMap.end())
246 pair<bool,DOMElement*> load();
249 friend class XMLConfigImpl;
250 XMLConfigImpl* m_impl;
251 mutable ListenerService* m_listener;
252 mutable SessionCache* m_sessionCache;
253 mutable TransactionLog* m_tranLog;
256 #if defined (_MSC_VER)
257 #pragma warning( pop )
260 static const XMLCh AAPProvider[] = UNICODE_LITERAL_11(A,A,P,P,r,o,v,i,d,e,r);
261 static const XMLCh _Application[] = UNICODE_LITERAL_11(A,p,p,l,i,c,a,t,i,o,n);
262 static const XMLCh Applications[] = UNICODE_LITERAL_12(A,p,p,l,i,c,a,t,i,o,n,s);
263 static const XMLCh AttributeFactory[] = UNICODE_LITERAL_16(A,t,t,r,i,b,u,t,e,F,a,c,t,o,r,y);
264 static const XMLCh Credentials[] = UNICODE_LITERAL_11(C,r,e,d,e,n,t,i,a,l,s);
265 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);
266 static const XMLCh CredentialUse[] = UNICODE_LITERAL_13(C,r,e,d,e,n,t,i,a,l,U,s,e);
267 static const XMLCh DiagnosticService[] = UNICODE_LITERAL_17(D,i,a,g,n,o,s,t,i,c,S,e,r,v,i,c,e);
268 static const XMLCh fatal[] = UNICODE_LITERAL_5(f,a,t,a,l);
269 static const XMLCh FileResolver[] = UNICODE_LITERAL_12(F,i,l,e,R,e,s,o,l,v,e,r);
270 static const XMLCh Global[] = UNICODE_LITERAL_6(G,l,o,b,a,l);
271 static const XMLCh Id[] = UNICODE_LITERAL_2(I,d);
272 static const XMLCh Implementation[] = UNICODE_LITERAL_14(I,m,p,l,e,m,e,n,t,a,t,i,o,n);
273 static const XMLCh InProcess[] = UNICODE_LITERAL_9(I,n,P,r,o,c,e,s,s);
274 static const XMLCh Library[] = UNICODE_LITERAL_7(L,i,b,r,a,r,y);
275 static const XMLCh Listener[] = UNICODE_LITERAL_8(L,i,s,t,e,n,e,r);
276 static const XMLCh Local[] = UNICODE_LITERAL_5(L,o,c,a,l);
277 static const XMLCh logger[] = UNICODE_LITERAL_6(l,o,g,g,e,r);
278 static const XMLCh MemoryListener[] = UNICODE_LITERAL_14(M,e,m,o,r,y,L,i,s,t,e,n,e,r);
279 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);
280 static const XMLCh RelyingParty[] = UNICODE_LITERAL_12(R,e,l,y,i,n,g,P,a,r,t,y);
281 static const XMLCh ReplayCache[] = UNICODE_LITERAL_11(R,e,p,l,a,y,C,a,c,h,e);
282 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);
283 static const XMLCh SessionCache[] = UNICODE_LITERAL_12(S,e,s,s,i,o,n,C,a,c,h,e);
284 static const XMLCh SessionInitiator[] = UNICODE_LITERAL_16(S,e,s,s,i,o,n,I,n,i,t,i,a,t,o,r);
285 static const XMLCh OutOfProcess[] = UNICODE_LITERAL_12(O,u,t,O,f,P,r,o,c,e,s,s);
286 static const XMLCh TCPListener[] = UNICODE_LITERAL_11(T,C,P,L,i,s,t,e,n,e,r);
287 static const XMLCh TrustProvider[] = UNICODE_LITERAL_13(T,r,u,s,t,P,r,o,v,i,d,e,r);
288 static const XMLCh UnixListener[] = UNICODE_LITERAL_12(U,n,i,x,L,i,s,t,e,n,e,r);
289 static const XMLCh _MetadataProvider[] = UNICODE_LITERAL_16(M,e,t,a,d,a,t,a,P,r,o,v,i,d,e,r);
290 static const XMLCh _path[] = UNICODE_LITERAL_4(p,a,t,h);
291 static const XMLCh _type[] = UNICODE_LITERAL_4(t,y,p,e);
295 ServiceProvider* shibtarget::XMLServiceProviderFactory(const DOMElement* const & e)
297 return new XMLConfig(e);
300 XMLApplication::XMLApplication(
301 const ServiceProvider* sp,
303 const XMLApplication* base
304 ) : m_sp(sp), m_base(base), m_metadata(NULL), m_trust(NULL), m_profile(NULL), m_binding(NULL), m_bindingHook(NULL),
305 m_credDefault(NULL), m_sessionInitDefault(NULL), m_acsDefault(NULL)
308 xmltooling::NDC ndc("XMLApplication");
310 Category& log=Category::getInstance(SHIBT_LOGCAT".Application");
313 // First load any property sets.
314 map<string,string> root_remap;
315 root_remap["shire"]="session";
316 root_remap["shireURL"]="handlerURL";
317 root_remap["shireSSL"]="handlerSSL";
318 load(e,log,this,&root_remap);
320 const PropertySet* propcheck=getPropertySet("Errors");
321 if (propcheck && !propcheck->getString("session").first)
322 throw ConfigurationException("<Errors> element requires 'session' (or deprecated 'shire') attribute");
323 propcheck=getPropertySet("Sessions");
324 if (propcheck && !propcheck->getString("handlerURL").first)
325 throw ConfigurationException("<Sessions> element requires 'handlerURL' (or deprecated 'shireURL') attribute");
327 SPConfig& conf=SPConfig::getConfig();
328 XMLToolingConfig& xmlConf=XMLToolingConfig::getConfig();
329 opensaml::SAMLConfig& samlConf=opensaml::SAMLConfig::getConfig();
330 SAMLConfig& shibConf=SAMLConfig::getConfig();
333 m_hash+=getString("providerId").second;
334 m_hash=samlConf.hashSHA1(m_hash.c_str(), true);
337 Handler* handler=NULL;
338 bool hardACS=false, hardSessionInit=false;
339 const DOMElement* child = XMLHelper::getFirstChildElement(propcheck->getElement());
341 xmltooling::auto_ptr_char bindprop(child->getAttributeNS(NULL,EndpointType::BINDING_ATTRIB_NAME));
342 if (!bindprop.get() || !*(bindprop.get())) {
343 log.warn("md:AssertionConsumerService element has no Binding attribute, skipping it...");
344 child = XMLHelper::getNextSiblingElement(child);
349 // A handler is based on the Binding property in conjunction with the element name.
350 // If it's an ACS or SI, also handle index/id mappings and defaulting.
351 if (XMLHelper::isNodeNamed(child,samlconstants::SAML20MD_NS,AssertionConsumerService::LOCAL_NAME)) {
352 handler=conf.AssertionConsumerServiceManager.newPlugin(bindprop.get(),child);
353 // Map by binding (may be > 1 per binding, e.g. SAML 1.0 vs 1.1)
355 m_acsBindingMap[handler->getXMLString("Binding").second].push_back(handler);
357 m_acsBindingMap[handler->getString("Binding").second].push_back(handler);
359 m_acsIndexMap[handler->getUnsignedInt("index").second]=handler;
362 pair<bool,bool> defprop=handler->getBool("isDefault");
364 if (defprop.second) {
366 m_acsDefault=handler;
369 else if (!m_acsDefault)
370 m_acsDefault=handler;
373 else if (XMLString::equals(child->getLocalName(),SessionInitiator)) {
374 handler=conf.SessionInitiatorManager.newPlugin(bindprop.get(),child);
375 pair<bool,const char*> si_id=handler->getString("id");
376 if (si_id.first && si_id.second)
377 m_sessionInitMap[si_id.second]=handler;
378 if (!hardSessionInit) {
379 pair<bool,bool> defprop=handler->getBool("isDefault");
381 if (defprop.second) {
382 hardSessionInit=true;
383 m_sessionInitDefault=handler;
386 else if (!m_sessionInitDefault)
387 m_sessionInitDefault=handler;
390 else if (XMLHelper::isNodeNamed(child,samlconstants::SAML20MD_NS,SingleLogoutService::LOCAL_NAME)) {
391 handler=conf.SingleLogoutServiceManager.newPlugin(bindprop.get(),child);
393 else if (XMLHelper::isNodeNamed(child,samlconstants::SAML20MD_NS,ManageNameIDService::LOCAL_NAME)) {
394 handler=conf.ManageNameIDServiceManager.newPlugin(bindprop.get(),child);
397 handler=conf.HandlerManager.newPlugin(bindprop.get(),child);
400 catch (exception& ex) {
401 log.error("caught exception processing md:AssertionConsumerService element: %s",ex.what());
404 // Save off the objects after giving the property set to the handler for its use.
405 m_handlers.push_back(handler);
407 // Insert into location map.
408 pair<bool,const char*> location=handler->getString("Location");
409 if (location.first && *location.second == '/')
410 m_handlerMap[location.second]=handler;
411 else if (location.first)
412 m_handlerMap[string("/") + location.second]=handler;
414 child = XMLHelper::getNextSiblingElement(child);
417 // If no handlers defined at the root, assume a legacy configuration.
418 if (!m_base && m_handlers.empty()) {
419 // A legacy config installs a SAML POST handler at the root handler location.
420 // We use the Sessions element itself as the PropertySet.
421 Handler* h1=conf.SessionInitiatorManager.newPlugin(
422 shibspconstants::SHIB1_SESSIONINIT_PROFILE_URI,propcheck->getElement()
424 m_handlers.push_back(h1);
425 m_sessionInitDefault=h1;
427 Handler* h2=conf.AssertionConsumerServiceManager.newPlugin(
428 samlconstants::SAML1_PROFILE_BROWSER_POST,propcheck->getElement()
430 m_handlers.push_back(h2);
431 m_handlerMap[""] = h2;
435 DOMNodeList* nlist=e->getElementsByTagNameNS(samlconstants::SAML1_NS,Audience::LOCAL_NAME);
436 for (XMLSize_t i=0; nlist && i<nlist->getLength(); i++)
437 if (nlist->item(i)->getParentNode()->isSameNode(e) && nlist->item(i)->hasChildNodes())
438 m_audiences.push_back(nlist->item(i)->getFirstChild()->getNodeValue());
440 // Always include our own providerId as an audience.
441 m_audiences.push_back(getXMLString("providerId").second);
443 if (conf.isEnabled(SPConfig::AAP)) {
444 child = XMLHelper::getFirstChildElement(e,AAPProvider);
446 xmltooling::auto_ptr_char type(child->getAttributeNS(NULL,_type));
447 log.info("building AAP provider of type %s...",type.get());
449 IPlugIn* plugin=shibConf.getPlugMgr().newPlugin(type.get(),child);
450 IAAP* aap=dynamic_cast<IAAP*>(plugin);
452 m_aaps.push_back(aap);
455 log.crit("plugin was not an AAP provider");
458 catch (exception& ex) {
459 log.crit("error building AAP provider: %s", ex.what());
462 child = XMLHelper::getNextSiblingElement(child,AAPProvider);
466 if (conf.isEnabled(SPConfig::Metadata)) {
467 vector<MetadataProvider*> os2providers;
468 child = XMLHelper::getFirstChildElement(e,_MetadataProvider);
470 xmltooling::auto_ptr_char type(child->getAttributeNS(NULL,_type));
471 log.info("building metadata provider of type %s...",type.get());
473 auto_ptr<MetadataProvider> mp(samlConf.MetadataProviderManager.newPlugin(type.get(),child));
475 os2providers.push_back(mp.release());
477 catch (exception& ex) {
478 log.crit("error building/initializing metadata provider: %s", ex.what());
481 child = XMLHelper::getNextSiblingElement(child,_MetadataProvider);
484 if (os2providers.size()==1)
485 m_metadata=os2providers.front();
486 else if (os2providers.size()>1) {
488 m_metadata = samlConf.MetadataProviderManager.newPlugin(CHAINING_METADATA_PROVIDER,NULL);
489 ChainingMetadataProvider* chainMeta = dynamic_cast<ChainingMetadataProvider*>(m_metadata);
490 while (!os2providers.empty()) {
491 chainMeta->addMetadataProvider(os2providers.back());
492 os2providers.pop_back();
495 catch (exception& ex) {
496 log.crit("error building chaining metadata provider wrapper: %s",ex.what());
497 for_each(os2providers.begin(), os2providers.end(), xmltooling::cleanup<MetadataProvider>());
502 if (conf.isEnabled(SPConfig::Trust)) {
503 ChainingTrustEngine* chainTrust = NULL;
504 child = XMLHelper::getFirstChildElement(e,TrustProvider);
506 xmltooling::auto_ptr_char type(child->getAttributeNS(NULL,_type));
507 log.info("building trust provider of type %s...",type.get());
510 // For compatibility with old engine types, we're assuming a Shib engine is likely,
511 // which requires chaining, so we'll build that regardless.
512 m_trust = xmlConf.TrustEngineManager.newPlugin(CHAINING_TRUSTENGINE,NULL);
513 chainTrust = dynamic_cast<ChainingTrustEngine*>(m_trust);
515 if (!strcmp(type.get(),"edu.internet2.middleware.shibboleth.common.provider.ShibbolethTrust")) {
516 chainTrust->addTrustEngine(xmlConf.TrustEngineManager.newPlugin(EXPLICIT_KEY_TRUSTENGINE,child));
517 chainTrust->addTrustEngine(xmlConf.TrustEngineManager.newPlugin(SHIBBOLETH_PKIX_TRUSTENGINE,child));
519 else if (!strcmp(type.get(),"edu.internet2.middleware.shibboleth.common.provider.BasicTrust")) {
520 chainTrust->addTrustEngine(xmlConf.TrustEngineManager.newPlugin(EXPLICIT_KEY_TRUSTENGINE,child));
523 chainTrust->addTrustEngine(xmlConf.TrustEngineManager.newPlugin(type.get(),child));
526 catch (exception& ex) {
527 log.crit("error building trust provider: %s",ex.what());
530 child = XMLHelper::getNextSiblingElement(child,TrustProvider);
534 // Finally, load credential mappings.
535 child = XMLHelper::getFirstChildElement(e,CredentialUse);
537 m_credDefault=new DOMPropertySet();
538 m_credDefault->load(child,log,this);
539 child = XMLHelper::getFirstChildElement(child,RelyingParty);
541 DOMPropertySet* rp=new DOMPropertySet();
542 rp->load(child,log,this);
543 m_credMap[child->getAttributeNS(NULL,opensaml::saml2::Attribute::NAME_ATTRIB_NAME)]=rp;
544 child = XMLHelper::getNextSiblingElement(child,RelyingParty);
548 if (conf.isEnabled(SPConfig::OutOfProcess)) {
549 // Really finally, build local browser profile and binding objects.
550 m_profile=new ShibBrowserProfile(this, getMetadataProvider(), getTrustEngine());
551 m_bindingHook=new ShibHTTPHook(getTrustEngine());
552 m_binding=SAMLBinding::getInstance(SAMLBinding::SOAP);
553 SAMLSOAPHTTPBinding* bptr=dynamic_cast<SAMLSOAPHTTPBinding*>(m_binding);
555 log.fatal("binding implementation was not SOAP over HTTP");
556 throw UnknownExtensionException("binding implementation was not SOAP over HTTP");
558 bptr->addHook(m_bindingHook,m_bindingHook); // the hook is its own global context
573 void XMLApplication::cleanup()
575 delete m_bindingHook;
578 for_each(m_handlers.begin(),m_handlers.end(),xmltooling::cleanup<Handler>());
580 delete m_credDefault;
582 for_each(m_credMap.begin(),m_credMap.end(),xmltooling::cleanup_pair<xmltooling::xstring,PropertySet>());
584 for_each(m_credMap.begin(),m_credMap.end(),xmltooling::cleanup_pair<const XMLCh*,PropertySet>());
586 for_each(m_aaps.begin(),m_aaps.end(),xmltooling::cleanup<IAAP>());
592 short XMLApplication::acceptNode(const DOMNode* node) const
594 if (XMLHelper::isNodeNamed(node,samlconstants::SAML1_NS,AttributeDesignator::LOCAL_NAME))
595 return FILTER_REJECT;
596 else if (XMLHelper::isNodeNamed(node,samlconstants::SAML20_NS,opensaml::saml1::Attribute::LOCAL_NAME))
597 return FILTER_REJECT;
598 else if (XMLHelper::isNodeNamed(node,samlconstants::SAML1_NS,Audience::LOCAL_NAME))
599 return FILTER_REJECT;
600 const XMLCh* name=node->getLocalName();
601 if (XMLString::equals(name,_Application) ||
602 XMLString::equals(name,AssertionConsumerService::LOCAL_NAME) ||
603 XMLString::equals(name,SingleLogoutService::LOCAL_NAME) ||
604 XMLString::equals(name,DiagnosticService) ||
605 XMLString::equals(name,SessionInitiator) ||
606 XMLString::equals(name,AAPProvider) ||
607 XMLString::equals(name,CredentialUse) ||
608 XMLString::equals(name,RelyingParty) ||
609 XMLString::equals(name,_MetadataProvider) ||
610 XMLString::equals(name,TrustProvider))
611 return FILTER_REJECT;
613 return FILTER_ACCEPT;
616 pair<bool,bool> XMLApplication::getBool(const char* name, const char* ns) const
618 pair<bool,bool> ret=DOMPropertySet::getBool(name,ns);
621 return m_base ? m_base->getBool(name,ns) : ret;
624 pair<bool,const char*> XMLApplication::getString(const char* name, const char* ns) const
626 pair<bool,const char*> ret=DOMPropertySet::getString(name,ns);
629 return m_base ? m_base->getString(name,ns) : ret;
632 pair<bool,const XMLCh*> XMLApplication::getXMLString(const char* name, const char* ns) const
634 pair<bool,const XMLCh*> ret=DOMPropertySet::getXMLString(name,ns);
637 return m_base ? m_base->getXMLString(name,ns) : ret;
640 pair<bool,unsigned int> XMLApplication::getUnsignedInt(const char* name, const char* ns) const
642 pair<bool,unsigned int> ret=DOMPropertySet::getUnsignedInt(name,ns);
645 return m_base ? m_base->getUnsignedInt(name,ns) : ret;
648 pair<bool,int> XMLApplication::getInt(const char* name, const char* ns) const
650 pair<bool,int> ret=DOMPropertySet::getInt(name,ns);
653 return m_base ? m_base->getInt(name,ns) : ret;
656 const PropertySet* XMLApplication::getPropertySet(const char* name, const char* ns) const
658 const PropertySet* ret=DOMPropertySet::getPropertySet(name,ns);
661 return m_base->getPropertySet(name,ns);
664 Iterator<IAAP*> XMLApplication::getAAPProviders() const
666 return (m_aaps.empty() && m_base) ? m_base->getAAPProviders() : m_aaps;
669 MetadataProvider* XMLApplication::getMetadataProvider() const
671 return (!m_metadata && m_base) ? m_base->getMetadataProvider() : m_metadata;
674 TrustEngine* XMLApplication::getTrustEngine() const
676 return (!m_trust && m_base) ? m_base->getTrustEngine() : m_trust;
679 const vector<const XMLCh*>& XMLApplication::getAudiences() const
681 return (m_audiences.empty() && m_base) ? m_base->getAudiences() : m_audiences;
684 const PropertySet* XMLApplication::getCredentialUse(const EntityDescriptor* provider) const
686 if (!m_credDefault && m_base)
687 return m_base->getCredentialUse(provider);
690 map<xmltooling::xstring,PropertySet*>::const_iterator i=m_credMap.find(provider->getEntityID());
691 if (i!=m_credMap.end())
693 const EntitiesDescriptor* group=dynamic_cast<const EntitiesDescriptor*>(provider->getParent());
695 if (group->getName()) {
696 i=m_credMap.find(group->getName());
697 if (i!=m_credMap.end())
700 group=dynamic_cast<const EntitiesDescriptor*>(group->getParent());
703 map<const XMLCh*,PropertySet*>::const_iterator i=m_credMap.begin();
704 for (; i!=m_credMap.end(); i++) {
705 if (XMLString::equals(i->first,provider->getId()))
707 const EntitiesDescriptor* group=dynamic_cast<const EntitiesDescriptor*>(provider->getParent());
709 if (XMLString::equals(i->first,group->getName()))
711 group=dynamic_cast<const EntitiesDescriptor*>(group->getParent());
715 return m_credDefault;
718 void XMLApplication::validateToken(SAMLAssertion* token, time_t ts, const RoleDescriptor* role, const TrustEngine* trust) const
721 xmltooling::NDC ndc("validateToken");
723 Category& log=Category::getInstance(SHIBT_LOGCAT".Application");
725 // First we verify the time conditions, using the specified timestamp, if non-zero.
726 SAMLConfig& config=SAMLConfig::getConfig();
728 const SAMLDateTime* notBefore=token->getNotBefore();
729 if (notBefore && ts+config.clock_skew_secs < notBefore->getEpoch())
730 throw opensaml::FatalProfileException("Assertion is not yet valid.");
731 const SAMLDateTime* notOnOrAfter=token->getNotOnOrAfter();
732 if (notOnOrAfter && notOnOrAfter->getEpoch() <= ts-config.clock_skew_secs)
733 throw opensaml::FatalProfileException("Assertion is no longer valid.");
736 // Now we process conditions. Only audience restrictions at the moment.
737 Iterator<SAMLCondition*> conditions=token->getConditions();
738 while (conditions.hasNext()) {
739 SAMLCondition* cond=conditions.next();
740 const SAMLAudienceRestrictionCondition* ac=dynamic_cast<const SAMLAudienceRestrictionCondition*>(cond);
744 log.error("unrecognized Condition in assertion (%s)",os.str().c_str());
745 throw xmltooling::UnknownExtensionException("Assertion contains an unrecognized condition.");
747 else if (!ac->eval(getAudiences())) {
750 log.error("unacceptable AudienceRestrictionCondition in assertion (%s)",os.str().c_str());
751 throw opensaml::FatalProfileException("Assertion contains an unacceptable AudienceRestrictionCondition.");
755 if (!role || !trust) {
756 log.warn("no metadata provided, so no signature validation was performed");
760 const PropertySet* credUse=getCredentialUse(dynamic_cast<const EntityDescriptor*>(role->getParent()));
761 pair<bool,bool> signedAssertions=credUse ? credUse->getBool("signedAssertions") : make_pair(false,false);
763 if (token->isSigned()) {
765 // This will all change, but for fun, we'll port the object from OS1->OS2 for validation.
768 DOMDocument* doc = XMLToolingConfig::getConfig().getValidatingParser().parse(s);
769 XercesJanitor<DOMDocument> jdoc(doc);
770 auto_ptr<Assertion> os2ass(AssertionBuilder::buildAssertion());
771 os2ass->unmarshall(doc->getDocumentElement(),true);
774 if (!trust->validate(*(os2ass->getSignature()),*role))
775 throw xmltooling::XMLSecurityException("Assertion signature did not validate.");
777 else if (signedAssertions.first && signedAssertions.second)
778 throw xmltooling::XMLSecurityException("Assertion was unsigned, violating policy based on the issuer.");
781 const Handler* XMLApplication::getDefaultSessionInitiator() const
783 if (m_sessionInitDefault) return m_sessionInitDefault;
784 return m_base ? m_base->getDefaultSessionInitiator() : NULL;
787 const Handler* XMLApplication::getSessionInitiatorById(const char* id) const
789 map<string,const Handler*>::const_iterator i=m_sessionInitMap.find(id);
790 if (i!=m_sessionInitMap.end()) return i->second;
791 return m_base ? m_base->getSessionInitiatorById(id) : NULL;
794 const Handler* XMLApplication::getDefaultAssertionConsumerService() const
796 if (m_acsDefault) return m_acsDefault;
797 return m_base ? m_base->getDefaultAssertionConsumerService() : NULL;
800 const Handler* XMLApplication::getAssertionConsumerServiceByIndex(unsigned short index) const
802 map<unsigned int,const Handler*>::const_iterator i=m_acsIndexMap.find(index);
803 if (i!=m_acsIndexMap.end()) return i->second;
804 return m_base ? m_base->getAssertionConsumerServiceByIndex(index) : NULL;
807 const vector<const Handler*>& XMLApplication::getAssertionConsumerServicesByBinding(const XMLCh* binding) const
810 ACSBindingMap::const_iterator i=m_acsBindingMap.find(binding);
812 xmltooling::auto_ptr_char temp(binding);
813 ACSBindingMap::const_iterator i=m_acsBindingMap.find(temp.get());
815 if (i!=m_acsBindingMap.end())
817 return m_base ? m_base->getAssertionConsumerServicesByBinding(binding) : g_noHandlers;
820 const Handler* XMLApplication::getHandler(const char* path) const
823 map<string,const Handler*>::const_iterator i=m_handlerMap.find(wrap.substr(0,wrap.find('?')));
824 if (i!=m_handlerMap.end())
826 return m_base ? m_base->getHandler(path) : NULL;
829 short XMLConfigImpl::acceptNode(const DOMNode* node) const
831 if (!XMLString::equals(node->getNamespaceURI(),shibspconstants::SHIB1SPCONFIG_NS))
832 return FILTER_ACCEPT;
833 const XMLCh* name=node->getLocalName();
834 if (XMLString::equals(name,Applications) ||
835 XMLString::equals(name,AttributeFactory) ||
836 XMLString::equals(name,Credentials) ||
837 XMLString::equals(name,CredentialsProvider) ||
838 XMLString::equals(name,Extensions::LOCAL_NAME) ||
839 XMLString::equals(name,Implementation) ||
840 XMLString::equals(name,Listener) ||
841 XMLString::equals(name,MemoryListener) ||
842 XMLString::equals(name,MemorySessionCache) ||
843 XMLString::equals(name,RequestMapProvider) ||
844 XMLString::equals(name,ReplayCache) ||
845 XMLString::equals(name,SessionCache) ||
846 XMLString::equals(name,TCPListener) ||
847 XMLString::equals(name,UnixListener))
848 return FILTER_REJECT;
850 return FILTER_ACCEPT;
853 void XMLConfigImpl::doExtensions(const DOMElement* e, const char* label, Category& log)
855 const DOMElement* exts=XMLHelper::getFirstChildElement(e,Extensions::LOCAL_NAME);
857 exts=XMLHelper::getFirstChildElement(exts,Library);
859 xmltooling::auto_ptr_char path(exts->getAttributeNS(NULL,_path));
862 // TODO: replace with xmltooling extension load...
863 SAMLConfig::getConfig().saml_register_extension(path.get(),(void*)exts);
864 log.debug("loaded %s extension library (%s)", label, path.get());
867 catch (exception& e) {
868 const XMLCh* fatal=exts->getAttributeNS(NULL,fatal);
869 if (fatal && (*fatal==chLatin_t || *fatal==chDigit_1)) {
870 log.fatal("unable to load mandatory %s extension library %s: %s", label, path.get(), e.what());
874 log.crit("unable to load optional %s extension library %s: %s", label, path.get(), e.what());
877 exts=XMLHelper::getNextSiblingElement(exts,Library);
882 XMLConfigImpl::XMLConfigImpl(const DOMElement* e, bool first, const XMLConfig* outer) : m_outer(outer), m_requestMapper(NULL)
885 xmltooling::NDC ndc("XMLConfigImpl");
887 Category& log=Category::getInstance(SHIBT_LOGCAT".Config");
890 SAMLConfig& shibConf=SAMLConfig::getConfig();
891 SPConfig& conf=SPConfig::getConfig();
892 const DOMElement* SHAR=XMLHelper::getFirstChildElement(e,OutOfProcess);
894 SHAR=XMLHelper::getFirstChildElement(e,Global);
895 const DOMElement* SHIRE=XMLHelper::getFirstChildElement(e,InProcess);
897 SHIRE=XMLHelper::getFirstChildElement(e,Local);
899 // Initialize log4cpp manually in order to redirect log messages as soon as possible.
900 if (conf.isEnabled(SPConfig::Logging)) {
901 const XMLCh* logconf=NULL;
902 if (conf.isEnabled(SPConfig::OutOfProcess))
903 logconf=SHAR->getAttributeNS(NULL,logger);
904 else if (conf.isEnabled(SPConfig::InProcess))
905 logconf=SHIRE->getAttributeNS(NULL,logger);
906 if (!logconf || !*logconf)
907 logconf=e->getAttributeNS(NULL,logger);
908 if (logconf && *logconf) {
909 xmltooling::auto_ptr_char logpath(logconf);
910 log.debug("loading new logging configuration from (%s), check log destination for status of configuration",logpath.get());
911 XMLToolingConfig::getConfig().log_config(logpath.get());
915 m_outer->m_tranLog = new TransactionLog();
918 // First load any property sets.
919 map<string,string> root_remap;
920 root_remap["Global"]="OutOfProcess";
921 root_remap["Local"]="InProcess";
922 load(e,log,this,&root_remap);
924 const DOMElement* child;
927 // Much of the processing can only occur on the first instantiation.
931 doExtensions(e, "global", log);
932 if (conf.isEnabled(SPConfig::OutOfProcess))
933 doExtensions(SHAR, "out of process", log);
935 if (conf.isEnabled(SPConfig::InProcess))
936 doExtensions(SHIRE, "in process", log);
938 // Instantiate the ListenerService and SessionCache objects.
939 if (conf.isEnabled(SPConfig::Listener)) {
940 child=XMLHelper::getFirstChildElement(SHAR,UnixListener);
942 plugtype=UNIX_LISTENER_SERVICE;
944 child=XMLHelper::getFirstChildElement(SHAR,TCPListener);
946 plugtype=TCP_LISTENER_SERVICE;
948 child=XMLHelper::getFirstChildElement(SHAR,MemoryListener);
950 plugtype=MEMORY_LISTENER_SERVICE;
952 child=XMLHelper::getFirstChildElement(SHAR,Listener);
954 xmltooling::auto_ptr_char type(child->getAttributeNS(NULL,_type));
962 log.info("building ListenerService of type %s...", plugtype.c_str());
963 m_outer->m_listener = conf.ListenerServiceManager.newPlugin(plugtype.c_str(),child);
966 log.fatal("can't build ListenerService, missing conf:Listener element?");
967 throw ConfigurationException("Can't build ListenerService, missing conf:Listener element?");
971 if (conf.isEnabled(SPConfig::Caching)) {
972 // TODO: This code's a mess, due to a very bad config layout for the caches...
973 // Needs rework with the new config file.
974 const DOMElement* container=conf.isEnabled(SPConfig::OutOfProcess) ? SHAR : SHIRE;
975 child=XMLHelper::getFirstChildElement(container,MemorySessionCache);
977 log.info("building Session Cache of type %s...",STORAGESERVICE_SESSION_CACHE);
978 m_outer->m_sessionCache=conf.SessionCacheManager.newPlugin(STORAGESERVICE_SESSION_CACHE,child);
981 child=XMLHelper::getFirstChildElement(container,SessionCache);
983 xmltooling::auto_ptr_char type(child->getAttributeNS(NULL,_type));
984 log.info("building Session Cache of type %s...",type.get());
985 m_outer->m_sessionCache=conf.SessionCacheManager.newPlugin(type.get(),child);
988 log.info("custom SessionCache unspecified or no longer supported, building SessionCache of type %s...",STORAGESERVICE_SESSION_CACHE);
989 m_outer->m_sessionCache=conf.SessionCacheManager.newPlugin(STORAGESERVICE_SESSION_CACHE,child);
994 // TODO: switch to new cache interface
996 child=XMLHelper::getFirstChildElement(container,ReplayCache);
998 xmltooling::auto_ptr_char type(child->getAttributeNS(NULL,_type));
999 log.info("building ReplayCache of type %s...",type.get());
1000 m_outer->m_replayCache=IReplayCache::getInstance(type.get(),child);
1003 // OpenSAML default provider.
1004 log.info("custom ReplayCache unspecified or no longer supported, building default ReplayCache...");
1005 m_outer->m_replayCache=IReplayCache::getInstance();
1009 } // end of first-time-only stuff
1011 // Back to the fully dynamic stuff...next up is the RequestMapper.
1012 if (conf.isEnabled(SPConfig::RequestMapping)) {
1013 child=XMLHelper::getFirstChildElement(SHIRE,RequestMapProvider);
1015 xmltooling::auto_ptr_char type(child->getAttributeNS(NULL,_type));
1016 log.info("building RequestMapper of type %s...",type.get());
1017 m_requestMapper=conf.RequestMapperManager.newPlugin(type.get(),child);
1020 log.fatal("can't build RequestMapper, missing conf:RequestMapProvider element?");
1021 throw ConfigurationException("can't build RequestMapper, missing conf:RequestMapProvider element?");
1025 // Now we load the credentials map.
1026 if (conf.isEnabled(SPConfig::Credentials)) {
1027 // Old format was to wrap it in a CredentialsProvider plugin, we're inlining that...
1028 child = XMLHelper::getFirstChildElement(e,CredentialsProvider);
1029 child = XMLHelper::getFirstChildElement(child ? child : e,Credentials);
1031 // Step down and process resolvers.
1032 child=XMLHelper::getFirstChildElement(child);
1034 xmltooling::auto_ptr_char id(child->getAttributeNS(NULL,Id));
1035 if (!id.get() || !*(id.get())) {
1036 log.warn("skipping CredentialsResolver with no Id attribute");
1037 child = XMLHelper::getNextSiblingElement(child);
1041 if (XMLString::equals(child->getLocalName(),FileResolver))
1042 plugtype=FILESYSTEM_CREDENTIAL_RESOLVER;
1044 xmltooling::auto_ptr_char c(child->getAttributeNS(NULL,_type));
1048 if (!plugtype.empty()) {
1050 CredentialResolver* cr=
1051 XMLToolingConfig::getConfig().CredentialResolverManager.newPlugin(plugtype.c_str(),child);
1052 m_credResolverMap[id.get()] = cr;
1054 catch (exception& ex) {
1055 log.crit("failed to instantiate CredentialResolver (%s): %s", id.get(), ex.what());
1059 log.error("unknown type of CredentialResolver with Id (%s)", id.get());
1062 child = XMLHelper::getNextSiblingElement(child);
1067 // Now we load any attribute factories
1068 child = XMLHelper::getFirstChildElement(e,AttributeFactory);
1070 xmltooling::auto_ptr_char type(child->getAttributeNS(NULL,_type));
1071 log.info("building Attribute factory of type %s...",type.get());
1073 IPlugIn* plugin=shibConf.getPlugMgr().newPlugin(type.get(),child);
1075 IAttributeFactory* fact=dynamic_cast<IAttributeFactory*>(plugin);
1077 m_attrFactories.push_back(fact);
1078 ShibConfig::getConfig().regAttributeMapping(
1079 child->getAttributeNS(NULL,opensaml::saml1::Attribute::ATTRIBUTENAME_ATTRIB_NAME), fact
1084 log.crit("plugin was not an Attribute factory");
1088 catch (exception& ex) {
1089 log.crit("error building Attribute factory: %s", ex.what());
1092 child = XMLHelper::getNextSiblingElement(child,AttributeFactory);
1095 // Load the default application. This actually has a fixed ID of "default". ;-)
1096 child=XMLHelper::getFirstChildElement(e,Applications);
1098 log.fatal("can't build default Application object, missing conf:Applications element?");
1099 throw ConfigurationException("can't build default Application object, missing conf:Applications element?");
1101 XMLApplication* defapp=new XMLApplication(m_outer,child);
1102 m_appmap[defapp->getId()]=defapp;
1104 // Load any overrides.
1105 child = XMLHelper::getFirstChildElement(child,_Application);
1107 auto_ptr<XMLApplication> iapp(new XMLApplication(m_outer,child,defapp));
1108 if (m_appmap.find(iapp->getId())!=m_appmap.end())
1109 log.crit("found conf:Application element with duplicate Id attribute (%s), skipping it", iapp->getId());
1111 m_appmap[iapp->getId()]=iapp.release();
1113 child = XMLHelper::getNextSiblingElement(child,_Application);
1116 catch (exception&) {
1117 this->~XMLConfigImpl();
1122 this->~XMLConfigImpl();
1128 XMLConfigImpl::~XMLConfigImpl()
1130 for_each(m_appmap.begin(),m_appmap.end(),xmltooling::cleanup_pair<string,Application>());
1131 ShibConfig::getConfig().clearAttributeMappings();
1132 for_each(m_attrFactories.begin(),m_attrFactories.end(),xmltooling::cleanup<IAttributeFactory>());
1133 for_each(m_credResolverMap.begin(),m_credResolverMap.end(),xmltooling::cleanup_pair<string,CredentialResolver>());
1134 delete m_requestMapper;
1136 m_document->release();
1139 pair<bool,DOMElement*> XMLConfig::load()
1141 // Load from source using base class.
1142 pair<bool,DOMElement*> raw = ReloadableXMLFile::load();
1144 // If we own it, wrap it.
1145 XercesJanitor<DOMDocument> docjanitor(raw.first ? raw.second->getOwnerDocument() : NULL);
1147 XMLConfigImpl* impl = new XMLConfigImpl(raw.second,(m_impl==NULL),this);
1149 // If we held the document, transfer it to the impl. If we didn't, it's a no-op.
1150 impl->setDocument(docjanitor.release());
1155 return make_pair(false,(DOMElement*)NULL);