2 * Copyright 2001-2007 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>
40 #include <xmltooling/util/ReplayCache.h>
42 using namespace shibsp;
43 using namespace shibtarget;
44 using namespace shibboleth;
46 using namespace opensaml::saml1;
47 using namespace opensaml::saml2md;
48 using namespace xmltooling;
49 using namespace log4cpp;
51 using xmlsignature::CredentialResolver;
55 vector<const Handler*> g_noHandlers;
57 // Application configuration wrapper
58 class XMLApplication : public virtual IApplication, public DOMPropertySet, public DOMNodeFilter
61 XMLApplication(const ServiceProvider*, const DOMElement* e, const XMLApplication* base=NULL);
62 ~XMLApplication() { cleanup(); }
65 pair<bool,bool> getBool(const char* name, const char* ns=NULL) const;
66 pair<bool,const char*> getString(const char* name, const char* ns=NULL) const;
67 pair<bool,const XMLCh*> getXMLString(const char* name, const char* ns=NULL) const;
68 pair<bool,unsigned int> getUnsignedInt(const char* name, const char* ns=NULL) const;
69 pair<bool,int> getInt(const char* name, const char* ns=NULL) const;
70 const PropertySet* getPropertySet(const char* name, const char* ns="urn:mace:shibboleth:target:config:1.0") const;
73 const char* getId() const {return getString("id").second;}
74 const char* getHash() const {return m_hash.c_str();}
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 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 // manage handler objects
113 vector<Handler*> m_handlers;
115 // maps location (path info) to applicable handlers
116 map<string,const Handler*> m_handlerMap;
118 // maps unique indexes to consumer services
119 map<unsigned int,const Handler*> m_acsIndexMap;
121 // pointer to default consumer service
122 const Handler* m_acsDefault;
124 // maps binding strings to supporting consumer service(s)
126 typedef map<xmltooling::xstring,vector<const Handler*> > ACSBindingMap;
128 typedef map<string,vector<const Handler*> > ACSBindingMap;
130 ACSBindingMap m_acsBindingMap;
132 // maps unique ID strings to session initiators
133 map<string,const Handler*> m_sessionInitMap;
135 // pointer to default session initiator
136 const Handler* m_sessionInitDefault;
138 DOMPropertySet* m_credDefault;
140 map<xmltooling::xstring,PropertySet*> m_credMap;
142 map<const XMLCh*,PropertySet*> m_credMap;
146 // Top-level configuration implementation
148 class XMLConfigImpl : public DOMPropertySet, public DOMNodeFilter
151 XMLConfigImpl(const DOMElement* e, bool first, const XMLConfig* outer);
154 RequestMapper* m_requestMapper;
155 map<string,Application*> m_appmap;
156 map<string,CredentialResolver*> m_credResolverMap;
157 vector<IAttributeFactory*> m_attrFactories;
159 // Provides filter to exclude special config elements.
160 short acceptNode(const DOMNode* node) const;
162 void setDocument(DOMDocument* doc) {
167 void doExtensions(const DOMElement* e, const char* label, Category& log);
169 const XMLConfig* m_outer;
170 DOMDocument* m_document;
173 #if defined (_MSC_VER)
174 #pragma warning( push )
175 #pragma warning( disable : 4250 )
178 class XMLConfig : public ServiceProvider, public ReloadableXMLFile
181 XMLConfig(const DOMElement* e)
182 : ReloadableXMLFile(e), m_impl(NULL), m_listener(NULL), m_sessionCache(NULL) {
191 delete m_sessionCache;
194 XMLToolingConfig::getConfig().setReplayCache(NULL);
195 for_each(m_storage.begin(), m_storage.end(), xmltooling::cleanup_pair<string,StorageService>());
199 pair<bool,bool> getBool(const char* name, const char* ns=NULL) const {return m_impl->getBool(name,ns);}
200 pair<bool,const char*> getString(const char* name, const char* ns=NULL) const {return m_impl->getString(name,ns);}
201 pair<bool,const XMLCh*> getXMLString(const char* name, const char* ns=NULL) const {return m_impl->getXMLString(name,ns);}
202 pair<bool,unsigned int> getUnsignedInt(const char* name, const char* ns=NULL) const {return m_impl->getUnsignedInt(name,ns);}
203 pair<bool,int> getInt(const char* name, const char* ns=NULL) const {return m_impl->getInt(name,ns);}
204 const PropertySet* getPropertySet(const char* name, const char* ns="urn:mace:shibboleth:target:config:1.0") const {return m_impl->getPropertySet(name,ns);}
205 const DOMElement* getElement() const {return m_impl->getElement();}
208 TransactionLog* getTransactionLog() const {
211 throw ConfigurationException("No TransactionLog available.");
214 StorageService* getStorageService(const char* id) const {
216 map<string,StorageService*>::const_iterator i=m_storage.find(id);
217 if (i!=m_storage.end())
223 ListenerService* getListenerService(bool required=true) const {
224 if (required && !m_listener)
225 throw ConfigurationException("No ListenerService available.");
229 SessionCache* getSessionCache(bool required=true) const {
230 if (required && !m_sessionCache)
231 throw ConfigurationException("No SessionCache available.");
232 return m_sessionCache;
235 RequestMapper* getRequestMapper(bool required=true) const {
236 if (required && !m_impl->m_requestMapper)
237 throw ConfigurationException("No RequestMapper available.");
238 return m_impl->m_requestMapper;
241 const Application* getApplication(const char* applicationId) const {
242 map<string,Application*>::const_iterator i=m_impl->m_appmap.find(applicationId);
243 return (i!=m_impl->m_appmap.end()) ? i->second : NULL;
246 CredentialResolver* getCredentialResolver(const char* id) const {
248 map<string,CredentialResolver*>::const_iterator i=m_impl->m_credResolverMap.find(id);
249 if (i!=m_impl->m_credResolverMap.end())
256 pair<bool,DOMElement*> load();
259 friend class XMLConfigImpl;
260 XMLConfigImpl* m_impl;
261 mutable ListenerService* m_listener;
262 mutable SessionCache* m_sessionCache;
263 mutable TransactionLog* m_tranLog;
264 mutable map<string,StorageService*> m_storage;
267 #if defined (_MSC_VER)
268 #pragma warning( pop )
271 static const XMLCh AAPProvider[] = UNICODE_LITERAL_11(A,A,P,P,r,o,v,i,d,e,r);
272 static const XMLCh _Application[] = UNICODE_LITERAL_11(A,p,p,l,i,c,a,t,i,o,n);
273 static const XMLCh Applications[] = UNICODE_LITERAL_12(A,p,p,l,i,c,a,t,i,o,n,s);
274 static const XMLCh AttributeFactory[] = UNICODE_LITERAL_16(A,t,t,r,i,b,u,t,e,F,a,c,t,o,r,y);
275 static const XMLCh Credentials[] = UNICODE_LITERAL_11(C,r,e,d,e,n,t,i,a,l,s);
276 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);
277 static const XMLCh CredentialUse[] = UNICODE_LITERAL_13(C,r,e,d,e,n,t,i,a,l,U,s,e);
278 static const XMLCh DiagnosticService[] = UNICODE_LITERAL_17(D,i,a,g,n,o,s,t,i,c,S,e,r,v,i,c,e);
279 static const XMLCh fatal[] = UNICODE_LITERAL_5(f,a,t,a,l);
280 static const XMLCh FileResolver[] = UNICODE_LITERAL_12(F,i,l,e,R,e,s,o,l,v,e,r);
281 static const XMLCh Global[] = UNICODE_LITERAL_6(G,l,o,b,a,l);
282 static const XMLCh Id[] = UNICODE_LITERAL_2(I,d);
283 static const XMLCh Implementation[] = UNICODE_LITERAL_14(I,m,p,l,e,m,e,n,t,a,t,i,o,n);
284 static const XMLCh InProcess[] = UNICODE_LITERAL_9(I,n,P,r,o,c,e,s,s);
285 static const XMLCh Library[] = UNICODE_LITERAL_7(L,i,b,r,a,r,y);
286 static const XMLCh Listener[] = UNICODE_LITERAL_8(L,i,s,t,e,n,e,r);
287 static const XMLCh Local[] = UNICODE_LITERAL_5(L,o,c,a,l);
288 static const XMLCh logger[] = UNICODE_LITERAL_6(l,o,g,g,e,r);
289 static const XMLCh MemoryListener[] = UNICODE_LITERAL_14(M,e,m,o,r,y,L,i,s,t,e,n,e,r);
290 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);
291 static const XMLCh RelyingParty[] = UNICODE_LITERAL_12(R,e,l,y,i,n,g,P,a,r,t,y);
292 static const XMLCh _ReplayCache[] = UNICODE_LITERAL_11(R,e,p,l,a,y,C,a,c,h,e);
293 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);
294 static const XMLCh _SessionCache[] = UNICODE_LITERAL_12(S,e,s,s,i,o,n,C,a,c,h,e);
295 static const XMLCh SessionInitiator[] = UNICODE_LITERAL_16(S,e,s,s,i,o,n,I,n,i,t,i,a,t,o,r);
296 static const XMLCh _StorageService[] = UNICODE_LITERAL_14(S,t,o,r,a,g,e,S,e,r,v,i,c,e);
297 static const XMLCh OutOfProcess[] = UNICODE_LITERAL_12(O,u,t,O,f,P,r,o,c,e,s,s);
298 static const XMLCh TCPListener[] = UNICODE_LITERAL_11(T,C,P,L,i,s,t,e,n,e,r);
299 static const XMLCh TrustProvider[] = UNICODE_LITERAL_13(T,r,u,s,t,P,r,o,v,i,d,e,r);
300 static const XMLCh UnixListener[] = UNICODE_LITERAL_12(U,n,i,x,L,i,s,t,e,n,e,r);
301 static const XMLCh _MetadataProvider[] = UNICODE_LITERAL_16(M,e,t,a,d,a,t,a,P,r,o,v,i,d,e,r);
302 static const XMLCh _path[] = UNICODE_LITERAL_4(p,a,t,h);
303 static const XMLCh _type[] = UNICODE_LITERAL_4(t,y,p,e);
307 ServiceProvider* shibtarget::XMLServiceProviderFactory(const DOMElement* const & e)
309 return new XMLConfig(e);
312 XMLApplication::XMLApplication(
313 const ServiceProvider* sp,
315 const XMLApplication* base
316 ) : m_sp(sp), m_base(base), m_metadata(NULL), m_trust(NULL), m_profile(NULL), m_binding(NULL), m_bindingHook(NULL),
317 m_credDefault(NULL), m_sessionInitDefault(NULL), m_acsDefault(NULL)
320 xmltooling::NDC ndc("XMLApplication");
322 Category& log=Category::getInstance(SHIBT_LOGCAT".Application");
325 // First load any property sets.
326 map<string,string> root_remap;
327 root_remap["shire"]="session";
328 root_remap["shireURL"]="handlerURL";
329 root_remap["shireSSL"]="handlerSSL";
330 load(e,log,this,&root_remap);
332 const PropertySet* propcheck=getPropertySet("Errors");
333 if (propcheck && !propcheck->getString("session").first)
334 throw ConfigurationException("<Errors> element requires 'session' (or deprecated 'shire') attribute");
335 propcheck=getPropertySet("Sessions");
336 if (propcheck && !propcheck->getString("handlerURL").first)
337 throw ConfigurationException("<Sessions> element requires 'handlerURL' (or deprecated 'shireURL') attribute");
339 SPConfig& conf=SPConfig::getConfig();
340 XMLToolingConfig& xmlConf=XMLToolingConfig::getConfig();
341 opensaml::SAMLConfig& samlConf=opensaml::SAMLConfig::getConfig();
342 SAMLConfig& shibConf=SAMLConfig::getConfig();
345 m_hash+=getString("providerId").second;
346 m_hash=samlConf.hashSHA1(m_hash.c_str(), true);
349 Handler* handler=NULL;
350 bool hardACS=false, hardSessionInit=false;
351 const DOMElement* child = XMLHelper::getFirstChildElement(propcheck->getElement());
353 xmltooling::auto_ptr_char bindprop(child->getAttributeNS(NULL,EndpointType::BINDING_ATTRIB_NAME));
354 if (!bindprop.get() || !*(bindprop.get())) {
355 log.warn("md:AssertionConsumerService element has no Binding attribute, skipping it...");
356 child = XMLHelper::getNextSiblingElement(child);
361 // A handler is based on the Binding property in conjunction with the element name.
362 // If it's an ACS or SI, also handle index/id mappings and defaulting.
363 if (XMLHelper::isNodeNamed(child,samlconstants::SAML20MD_NS,AssertionConsumerService::LOCAL_NAME)) {
364 handler=conf.AssertionConsumerServiceManager.newPlugin(bindprop.get(),child);
365 // Map by binding (may be > 1 per binding, e.g. SAML 1.0 vs 1.1)
367 m_acsBindingMap[handler->getXMLString("Binding").second].push_back(handler);
369 m_acsBindingMap[handler->getString("Binding").second].push_back(handler);
371 m_acsIndexMap[handler->getUnsignedInt("index").second]=handler;
374 pair<bool,bool> defprop=handler->getBool("isDefault");
376 if (defprop.second) {
378 m_acsDefault=handler;
381 else if (!m_acsDefault)
382 m_acsDefault=handler;
385 else if (XMLString::equals(child->getLocalName(),SessionInitiator)) {
386 handler=conf.SessionInitiatorManager.newPlugin(bindprop.get(),child);
387 pair<bool,const char*> si_id=handler->getString("id");
388 if (si_id.first && si_id.second)
389 m_sessionInitMap[si_id.second]=handler;
390 if (!hardSessionInit) {
391 pair<bool,bool> defprop=handler->getBool("isDefault");
393 if (defprop.second) {
394 hardSessionInit=true;
395 m_sessionInitDefault=handler;
398 else if (!m_sessionInitDefault)
399 m_sessionInitDefault=handler;
402 else if (XMLHelper::isNodeNamed(child,samlconstants::SAML20MD_NS,SingleLogoutService::LOCAL_NAME)) {
403 handler=conf.SingleLogoutServiceManager.newPlugin(bindprop.get(),child);
405 else if (XMLHelper::isNodeNamed(child,samlconstants::SAML20MD_NS,ManageNameIDService::LOCAL_NAME)) {
406 handler=conf.ManageNameIDServiceManager.newPlugin(bindprop.get(),child);
409 handler=conf.HandlerManager.newPlugin(bindprop.get(),child);
412 catch (exception& ex) {
413 log.error("caught exception processing md:AssertionConsumerService element: %s",ex.what());
416 // Save off the objects after giving the property set to the handler for its use.
417 m_handlers.push_back(handler);
419 // Insert into location map.
420 pair<bool,const char*> location=handler->getString("Location");
421 if (location.first && *location.second == '/')
422 m_handlerMap[location.second]=handler;
423 else if (location.first)
424 m_handlerMap[string("/") + location.second]=handler;
426 child = XMLHelper::getNextSiblingElement(child);
429 // If no handlers defined at the root, assume a legacy configuration.
430 if (!m_base && m_handlers.empty()) {
431 // A legacy config installs a SAML POST handler at the root handler location.
432 // We use the Sessions element itself as the PropertySet.
433 Handler* h1=conf.SessionInitiatorManager.newPlugin(
434 shibspconstants::SHIB1_SESSIONINIT_PROFILE_URI,propcheck->getElement()
436 m_handlers.push_back(h1);
437 m_sessionInitDefault=h1;
439 Handler* h2=conf.AssertionConsumerServiceManager.newPlugin(
440 samlconstants::SAML1_PROFILE_BROWSER_POST,propcheck->getElement()
442 m_handlers.push_back(h2);
443 m_handlerMap[""] = h2;
447 DOMNodeList* nlist=e->getElementsByTagNameNS(samlconstants::SAML1_NS,Audience::LOCAL_NAME);
448 for (XMLSize_t i=0; nlist && i<nlist->getLength(); i++)
449 if (nlist->item(i)->getParentNode()->isSameNode(e) && nlist->item(i)->hasChildNodes())
450 m_audiences.push_back(nlist->item(i)->getFirstChild()->getNodeValue());
452 // Always include our own providerId as an audience.
453 m_audiences.push_back(getXMLString("providerId").second);
455 if (conf.isEnabled(SPConfig::AAP)) {
456 child = XMLHelper::getFirstChildElement(e,AAPProvider);
458 // TODO: some kind of compatibility
459 child = XMLHelper::getNextSiblingElement(child,AAPProvider);
463 if (conf.isEnabled(SPConfig::Metadata)) {
464 vector<MetadataProvider*> os2providers;
465 child = XMLHelper::getFirstChildElement(e,_MetadataProvider);
467 xmltooling::auto_ptr_char type(child->getAttributeNS(NULL,_type));
468 log.info("building metadata provider of type %s...",type.get());
470 auto_ptr<MetadataProvider> mp(samlConf.MetadataProviderManager.newPlugin(type.get(),child));
472 os2providers.push_back(mp.release());
474 catch (exception& ex) {
475 log.crit("error building/initializing metadata provider: %s", ex.what());
478 child = XMLHelper::getNextSiblingElement(child,_MetadataProvider);
481 if (os2providers.size()==1)
482 m_metadata=os2providers.front();
483 else if (os2providers.size()>1) {
485 m_metadata = samlConf.MetadataProviderManager.newPlugin(CHAINING_METADATA_PROVIDER,NULL);
486 ChainingMetadataProvider* chainMeta = dynamic_cast<ChainingMetadataProvider*>(m_metadata);
487 while (!os2providers.empty()) {
488 chainMeta->addMetadataProvider(os2providers.back());
489 os2providers.pop_back();
492 catch (exception& ex) {
493 log.crit("error building chaining metadata provider wrapper: %s",ex.what());
494 for_each(os2providers.begin(), os2providers.end(), xmltooling::cleanup<MetadataProvider>());
499 if (conf.isEnabled(SPConfig::Trust)) {
500 ChainingTrustEngine* chainTrust = NULL;
501 child = XMLHelper::getFirstChildElement(e,TrustProvider);
503 xmltooling::auto_ptr_char type(child->getAttributeNS(NULL,_type));
504 log.info("building trust provider of type %s...",type.get());
507 // For compatibility with old engine types, we're assuming a Shib engine is likely,
508 // which requires chaining, so we'll build that regardless.
509 m_trust = xmlConf.TrustEngineManager.newPlugin(CHAINING_TRUSTENGINE,NULL);
510 chainTrust = dynamic_cast<ChainingTrustEngine*>(m_trust);
512 if (!strcmp(type.get(),"edu.internet2.middleware.shibboleth.common.provider.ShibbolethTrust")) {
513 chainTrust->addTrustEngine(xmlConf.TrustEngineManager.newPlugin(EXPLICIT_KEY_TRUSTENGINE,child));
514 chainTrust->addTrustEngine(xmlConf.TrustEngineManager.newPlugin(SHIBBOLETH_PKIX_TRUSTENGINE,child));
516 else if (!strcmp(type.get(),"edu.internet2.middleware.shibboleth.common.provider.BasicTrust")) {
517 chainTrust->addTrustEngine(xmlConf.TrustEngineManager.newPlugin(EXPLICIT_KEY_TRUSTENGINE,child));
520 chainTrust->addTrustEngine(xmlConf.TrustEngineManager.newPlugin(type.get(),child));
523 catch (exception& ex) {
524 log.crit("error building trust provider: %s",ex.what());
527 child = XMLHelper::getNextSiblingElement(child,TrustProvider);
531 // Finally, load credential mappings.
532 child = XMLHelper::getFirstChildElement(e,CredentialUse);
534 m_credDefault=new DOMPropertySet();
535 m_credDefault->load(child,log,this);
536 child = XMLHelper::getFirstChildElement(child,RelyingParty);
538 DOMPropertySet* rp=new DOMPropertySet();
539 rp->load(child,log,this);
540 m_credMap[child->getAttributeNS(NULL,opensaml::saml2::Attribute::NAME_ATTRIB_NAME)]=rp;
541 child = XMLHelper::getNextSiblingElement(child,RelyingParty);
545 if (conf.isEnabled(SPConfig::OutOfProcess)) {
546 // Really finally, build local browser profile and binding objects.
547 m_profile=new ShibBrowserProfile(this, getMetadataProvider(), getTrustEngine());
548 m_bindingHook=new ShibHTTPHook(getTrustEngine());
549 m_binding=SAMLBinding::getInstance(SAMLBinding::SOAP);
550 SAMLSOAPHTTPBinding* bptr=dynamic_cast<SAMLSOAPHTTPBinding*>(m_binding);
552 log.fatal("binding implementation was not SOAP over HTTP");
553 throw UnknownExtensionException("binding implementation was not SOAP over HTTP");
555 bptr->addHook(m_bindingHook,m_bindingHook); // the hook is its own global context
570 void XMLApplication::cleanup()
572 delete m_bindingHook;
575 for_each(m_handlers.begin(),m_handlers.end(),xmltooling::cleanup<Handler>());
577 delete m_credDefault;
579 for_each(m_credMap.begin(),m_credMap.end(),xmltooling::cleanup_pair<xmltooling::xstring,PropertySet>());
581 for_each(m_credMap.begin(),m_credMap.end(),xmltooling::cleanup_pair<const XMLCh*,PropertySet>());
588 short XMLApplication::acceptNode(const DOMNode* node) const
590 if (XMLHelper::isNodeNamed(node,samlconstants::SAML1_NS,AttributeDesignator::LOCAL_NAME))
591 return FILTER_REJECT;
592 else if (XMLHelper::isNodeNamed(node,samlconstants::SAML20_NS,opensaml::saml1::Attribute::LOCAL_NAME))
593 return FILTER_REJECT;
594 else if (XMLHelper::isNodeNamed(node,samlconstants::SAML1_NS,Audience::LOCAL_NAME))
595 return FILTER_REJECT;
596 const XMLCh* name=node->getLocalName();
597 if (XMLString::equals(name,_Application) ||
598 XMLString::equals(name,AssertionConsumerService::LOCAL_NAME) ||
599 XMLString::equals(name,SingleLogoutService::LOCAL_NAME) ||
600 XMLString::equals(name,DiagnosticService) ||
601 XMLString::equals(name,SessionInitiator) ||
602 XMLString::equals(name,AAPProvider) ||
603 XMLString::equals(name,CredentialUse) ||
604 XMLString::equals(name,RelyingParty) ||
605 XMLString::equals(name,_MetadataProvider) ||
606 XMLString::equals(name,TrustProvider))
607 return FILTER_REJECT;
609 return FILTER_ACCEPT;
612 pair<bool,bool> XMLApplication::getBool(const char* name, const char* ns) const
614 pair<bool,bool> ret=DOMPropertySet::getBool(name,ns);
617 return m_base ? m_base->getBool(name,ns) : ret;
620 pair<bool,const char*> XMLApplication::getString(const char* name, const char* ns) const
622 pair<bool,const char*> ret=DOMPropertySet::getString(name,ns);
625 return m_base ? m_base->getString(name,ns) : ret;
628 pair<bool,const XMLCh*> XMLApplication::getXMLString(const char* name, const char* ns) const
630 pair<bool,const XMLCh*> ret=DOMPropertySet::getXMLString(name,ns);
633 return m_base ? m_base->getXMLString(name,ns) : ret;
636 pair<bool,unsigned int> XMLApplication::getUnsignedInt(const char* name, const char* ns) const
638 pair<bool,unsigned int> ret=DOMPropertySet::getUnsignedInt(name,ns);
641 return m_base ? m_base->getUnsignedInt(name,ns) : ret;
644 pair<bool,int> XMLApplication::getInt(const char* name, const char* ns) const
646 pair<bool,int> ret=DOMPropertySet::getInt(name,ns);
649 return m_base ? m_base->getInt(name,ns) : ret;
652 const PropertySet* XMLApplication::getPropertySet(const char* name, const char* ns) const
654 const PropertySet* ret=DOMPropertySet::getPropertySet(name,ns);
657 return m_base->getPropertySet(name,ns);
660 MetadataProvider* XMLApplication::getMetadataProvider() const
662 return (!m_metadata && m_base) ? m_base->getMetadataProvider() : m_metadata;
665 TrustEngine* XMLApplication::getTrustEngine() const
667 return (!m_trust && m_base) ? m_base->getTrustEngine() : m_trust;
670 const vector<const XMLCh*>& XMLApplication::getAudiences() const
672 return (m_audiences.empty() && m_base) ? m_base->getAudiences() : m_audiences;
675 const PropertySet* XMLApplication::getCredentialUse(const EntityDescriptor* provider) const
677 if (!m_credDefault && m_base)
678 return m_base->getCredentialUse(provider);
681 map<xmltooling::xstring,PropertySet*>::const_iterator i=m_credMap.find(provider->getEntityID());
682 if (i!=m_credMap.end())
684 const EntitiesDescriptor* group=dynamic_cast<const EntitiesDescriptor*>(provider->getParent());
686 if (group->getName()) {
687 i=m_credMap.find(group->getName());
688 if (i!=m_credMap.end())
691 group=dynamic_cast<const EntitiesDescriptor*>(group->getParent());
694 map<const XMLCh*,PropertySet*>::const_iterator i=m_credMap.begin();
695 for (; i!=m_credMap.end(); i++) {
696 if (XMLString::equals(i->first,provider->getId()))
698 const EntitiesDescriptor* group=dynamic_cast<const EntitiesDescriptor*>(provider->getParent());
700 if (XMLString::equals(i->first,group->getName()))
702 group=dynamic_cast<const EntitiesDescriptor*>(group->getParent());
706 return m_credDefault;
709 void XMLApplication::validateToken(SAMLAssertion* token, time_t ts, const RoleDescriptor* role, const TrustEngine* trust) const
712 xmltooling::NDC ndc("validateToken");
714 Category& log=Category::getInstance(SHIBT_LOGCAT".Application");
716 // First we verify the time conditions, using the specified timestamp, if non-zero.
717 SAMLConfig& config=SAMLConfig::getConfig();
719 const SAMLDateTime* notBefore=token->getNotBefore();
720 if (notBefore && ts+config.clock_skew_secs < notBefore->getEpoch())
721 throw opensaml::FatalProfileException("Assertion is not yet valid.");
722 const SAMLDateTime* notOnOrAfter=token->getNotOnOrAfter();
723 if (notOnOrAfter && notOnOrAfter->getEpoch() <= ts-config.clock_skew_secs)
724 throw opensaml::FatalProfileException("Assertion is no longer valid.");
727 // Now we process conditions. Only audience restrictions at the moment.
728 Iterator<SAMLCondition*> conditions=token->getConditions();
729 while (conditions.hasNext()) {
730 SAMLCondition* cond=conditions.next();
731 const SAMLAudienceRestrictionCondition* ac=dynamic_cast<const SAMLAudienceRestrictionCondition*>(cond);
735 log.error("unrecognized Condition in assertion (%s)",os.str().c_str());
736 throw xmltooling::UnknownExtensionException("Assertion contains an unrecognized condition.");
738 else if (!ac->eval(getAudiences())) {
741 log.error("unacceptable AudienceRestrictionCondition in assertion (%s)",os.str().c_str());
742 throw opensaml::FatalProfileException("Assertion contains an unacceptable AudienceRestrictionCondition.");
746 if (!role || !trust) {
747 log.warn("no metadata provided, so no signature validation was performed");
751 const PropertySet* credUse=getCredentialUse(dynamic_cast<const EntityDescriptor*>(role->getParent()));
752 pair<bool,bool> signedAssertions=credUse ? credUse->getBool("signedAssertions") : make_pair(false,false);
754 if (token->isSigned()) {
756 // This will all change, but for fun, we'll port the object from OS1->OS2 for validation.
759 DOMDocument* doc = XMLToolingConfig::getConfig().getValidatingParser().parse(s);
760 XercesJanitor<DOMDocument> jdoc(doc);
761 auto_ptr<Assertion> os2ass(AssertionBuilder::buildAssertion());
762 os2ass->unmarshall(doc->getDocumentElement(),true);
765 if (!trust->validate(*(os2ass->getSignature()),*role))
766 throw xmltooling::XMLSecurityException("Assertion signature did not validate.");
768 else if (signedAssertions.first && signedAssertions.second)
769 throw xmltooling::XMLSecurityException("Assertion was unsigned, violating policy based on the issuer.");
772 const Handler* XMLApplication::getDefaultSessionInitiator() const
774 if (m_sessionInitDefault) return m_sessionInitDefault;
775 return m_base ? m_base->getDefaultSessionInitiator() : NULL;
778 const Handler* XMLApplication::getSessionInitiatorById(const char* id) const
780 map<string,const Handler*>::const_iterator i=m_sessionInitMap.find(id);
781 if (i!=m_sessionInitMap.end()) return i->second;
782 return m_base ? m_base->getSessionInitiatorById(id) : NULL;
785 const Handler* XMLApplication::getDefaultAssertionConsumerService() const
787 if (m_acsDefault) return m_acsDefault;
788 return m_base ? m_base->getDefaultAssertionConsumerService() : NULL;
791 const Handler* XMLApplication::getAssertionConsumerServiceByIndex(unsigned short index) const
793 map<unsigned int,const Handler*>::const_iterator i=m_acsIndexMap.find(index);
794 if (i!=m_acsIndexMap.end()) return i->second;
795 return m_base ? m_base->getAssertionConsumerServiceByIndex(index) : NULL;
798 const vector<const Handler*>& XMLApplication::getAssertionConsumerServicesByBinding(const XMLCh* binding) const
801 ACSBindingMap::const_iterator i=m_acsBindingMap.find(binding);
803 xmltooling::auto_ptr_char temp(binding);
804 ACSBindingMap::const_iterator i=m_acsBindingMap.find(temp.get());
806 if (i!=m_acsBindingMap.end())
808 return m_base ? m_base->getAssertionConsumerServicesByBinding(binding) : g_noHandlers;
811 const Handler* XMLApplication::getHandler(const char* path) const
814 map<string,const Handler*>::const_iterator i=m_handlerMap.find(wrap.substr(0,wrap.find('?')));
815 if (i!=m_handlerMap.end())
817 return m_base ? m_base->getHandler(path) : NULL;
820 short XMLConfigImpl::acceptNode(const DOMNode* node) const
822 if (!XMLString::equals(node->getNamespaceURI(),shibspconstants::SHIB1SPCONFIG_NS))
823 return FILTER_ACCEPT;
824 const XMLCh* name=node->getLocalName();
825 if (XMLString::equals(name,Applications) ||
826 XMLString::equals(name,AttributeFactory) ||
827 XMLString::equals(name,Credentials) ||
828 XMLString::equals(name,CredentialsProvider) ||
829 XMLString::equals(name,Extensions::LOCAL_NAME) ||
830 XMLString::equals(name,Implementation) ||
831 XMLString::equals(name,Listener) ||
832 XMLString::equals(name,MemoryListener) ||
833 XMLString::equals(name,MemorySessionCache) ||
834 XMLString::equals(name,RequestMapProvider) ||
835 XMLString::equals(name,_ReplayCache) ||
836 XMLString::equals(name,_SessionCache) ||
837 XMLString::equals(name,_StorageService) ||
838 XMLString::equals(name,TCPListener) ||
839 XMLString::equals(name,UnixListener))
840 return FILTER_REJECT;
842 return FILTER_ACCEPT;
845 void XMLConfigImpl::doExtensions(const DOMElement* e, const char* label, Category& log)
847 const DOMElement* exts=XMLHelper::getFirstChildElement(e,Extensions::LOCAL_NAME);
849 exts=XMLHelper::getFirstChildElement(exts,Library);
851 xmltooling::auto_ptr_char path(exts->getAttributeNS(NULL,_path));
854 // TODO: replace with xmltooling extension load...
855 SAMLConfig::getConfig().saml_register_extension(path.get(),(void*)exts);
856 log.debug("loaded %s extension library (%s)", label, path.get());
859 catch (exception& e) {
860 const XMLCh* fatal=exts->getAttributeNS(NULL,fatal);
861 if (fatal && (*fatal==chLatin_t || *fatal==chDigit_1)) {
862 log.fatal("unable to load mandatory %s extension library %s: %s", label, path.get(), e.what());
866 log.crit("unable to load optional %s extension library %s: %s", label, path.get(), e.what());
869 exts=XMLHelper::getNextSiblingElement(exts,Library);
874 XMLConfigImpl::XMLConfigImpl(const DOMElement* e, bool first, const XMLConfig* outer) : m_outer(outer), m_requestMapper(NULL)
877 xmltooling::NDC ndc("XMLConfigImpl");
879 Category& log=Category::getInstance(SHIBT_LOGCAT".Config");
882 SPConfig& conf=SPConfig::getConfig();
883 SAMLConfig& shibConf=SAMLConfig::getConfig();
884 XMLToolingConfig& xmlConf=XMLToolingConfig::getConfig();
885 const DOMElement* SHAR=XMLHelper::getFirstChildElement(e,OutOfProcess);
887 SHAR=XMLHelper::getFirstChildElement(e,Global);
888 const DOMElement* SHIRE=XMLHelper::getFirstChildElement(e,InProcess);
890 SHIRE=XMLHelper::getFirstChildElement(e,Local);
892 // Initialize log4cpp manually in order to redirect log messages as soon as possible.
893 if (conf.isEnabled(SPConfig::Logging)) {
894 const XMLCh* logconf=NULL;
895 if (conf.isEnabled(SPConfig::OutOfProcess))
896 logconf=SHAR->getAttributeNS(NULL,logger);
897 else if (conf.isEnabled(SPConfig::InProcess))
898 logconf=SHIRE->getAttributeNS(NULL,logger);
899 if (!logconf || !*logconf)
900 logconf=e->getAttributeNS(NULL,logger);
901 if (logconf && *logconf) {
902 xmltooling::auto_ptr_char logpath(logconf);
903 log.debug("loading new logging configuration from (%s), check log destination for status of configuration",logpath.get());
904 XMLToolingConfig::getConfig().log_config(logpath.get());
908 m_outer->m_tranLog = new TransactionLog();
911 // First load any property sets.
912 map<string,string> root_remap;
913 root_remap["Global"]="OutOfProcess";
914 root_remap["Local"]="InProcess";
915 load(e,log,this,&root_remap);
917 const DOMElement* child;
920 // Much of the processing can only occur on the first instantiation.
924 doExtensions(e, "global", log);
925 if (conf.isEnabled(SPConfig::OutOfProcess))
926 doExtensions(SHAR, "out of process", log);
928 if (conf.isEnabled(SPConfig::InProcess))
929 doExtensions(SHIRE, "in process", log);
931 // Instantiate the ListenerService and SessionCache objects.
932 if (conf.isEnabled(SPConfig::Listener)) {
933 child=XMLHelper::getFirstChildElement(SHAR,UnixListener);
935 plugtype=UNIX_LISTENER_SERVICE;
937 child=XMLHelper::getFirstChildElement(SHAR,TCPListener);
939 plugtype=TCP_LISTENER_SERVICE;
941 child=XMLHelper::getFirstChildElement(SHAR,MemoryListener);
943 plugtype=MEMORY_LISTENER_SERVICE;
945 child=XMLHelper::getFirstChildElement(SHAR,Listener);
947 xmltooling::auto_ptr_char type(child->getAttributeNS(NULL,_type));
955 log.info("building ListenerService of type %s...", plugtype.c_str());
956 m_outer->m_listener = conf.ListenerServiceManager.newPlugin(plugtype.c_str(),child);
959 log.fatal("can't build ListenerService, missing conf:Listener element?");
960 throw ConfigurationException("Can't build ListenerService, missing conf:Listener element?");
964 if (conf.isEnabled(SPConfig::Caching)) {
965 // TODO: This code's a mess, due to a very bad config layout for the caches...
966 // Needs rework with the new config file.
967 const DOMElement* container=conf.isEnabled(SPConfig::OutOfProcess) ? SHAR : SHIRE;
969 // First build any StorageServices.
971 child=XMLHelper::getFirstChildElement(container,_StorageService);
973 xmltooling::auto_ptr_char id(child->getAttributeNS(NULL,Id));
974 xmltooling::auto_ptr_char type(child->getAttributeNS(NULL,_type));
975 if (id.get() && type.get()) {
977 log.info("building StorageService (%s) of type %s...", id.get(), type.get());
978 m_outer->m_storage[id.get()] = xmlConf.StorageServiceManager.newPlugin(type.get(),child);
979 if (!strcmp(type.get(),MEMORY_STORAGE_SERVICE))
982 catch (exception& ex) {
983 log.crit("failed to instantiate StorageService (%s): %s", id.get(), ex.what());
986 child=XMLHelper::getNextSiblingElement(container,_StorageService);
989 child=XMLHelper::getFirstChildElement(container,_SessionCache);
991 xmltooling::auto_ptr_char type(child->getAttributeNS(NULL,_type));
992 log.info("building Session Cache of type %s...",type.get());
993 m_outer->m_sessionCache=conf.SessionCacheManager.newPlugin(type.get(),child);
995 else if (conf.isEnabled(SPConfig::OutOfProcess)) {
996 log.warn("custom SessionCache unspecified or no longer supported, building SessionCache of type %s...",STORAGESERVICE_SESSION_CACHE);
997 if (inmemID.empty()) {
999 log.info("no StorageServices configured, providing in-memory version for legacy config");
1000 m_outer->m_storage[inmemID] = xmlConf.StorageServiceManager.newPlugin(MEMORY_STORAGE_SERVICE,NULL);
1002 child = container->getOwnerDocument()->createElementNS(NULL,_SessionCache);
1003 xmltooling::auto_ptr_XMLCh ssid(inmemID.c_str());
1004 const_cast<DOMElement*>(child)->setAttributeNS(NULL,_StorageService,ssid.get());
1005 m_outer->m_sessionCache=conf.SessionCacheManager.newPlugin(STORAGESERVICE_SESSION_CACHE,child);
1008 log.warn("custom SessionCache unspecified or no longer supported, building SessionCache of type %s...",REMOTED_SESSION_CACHE);
1009 m_outer->m_sessionCache=conf.SessionCacheManager.newPlugin(REMOTED_SESSION_CACHE,NULL);
1013 StorageService* replaySS=NULL;
1014 child=XMLHelper::getFirstChildElement(container,_ReplayCache);
1016 xmltooling::auto_ptr_char ssid(child->getAttributeNS(NULL,_StorageService));
1017 if (ssid.get() && *ssid.get()) {
1018 replaySS = m_outer->m_storage[ssid.get()];
1020 log.info("building ReplayCache on top of StorageService (%s)...", ssid.get());
1022 log.crit("unable to locate StorageService (%s) in configuration", ssid.get());
1026 log.info("building ReplayCache using in-memory StorageService...");
1027 if (inmemID.empty()) {
1029 log.info("no StorageServices configured, providing in-memory version for legacy config");
1030 m_outer->m_storage[inmemID] = xmlConf.StorageServiceManager.newPlugin(MEMORY_STORAGE_SERVICE,NULL);
1032 replaySS = m_outer->m_storage[inmemID];
1034 xmlConf.setReplayCache(new ReplayCache(replaySS));
1036 } // end of first-time-only stuff
1038 // Back to the fully dynamic stuff...next up is the RequestMapper.
1039 if (conf.isEnabled(SPConfig::RequestMapping)) {
1040 child=XMLHelper::getFirstChildElement(SHIRE,RequestMapProvider);
1042 xmltooling::auto_ptr_char type(child->getAttributeNS(NULL,_type));
1043 log.info("building RequestMapper of type %s...",type.get());
1044 m_requestMapper=conf.RequestMapperManager.newPlugin(type.get(),child);
1047 log.fatal("can't build RequestMapper, missing conf:RequestMapProvider element?");
1048 throw ConfigurationException("can't build RequestMapper, missing conf:RequestMapProvider element?");
1052 // Now we load the credentials map.
1053 if (conf.isEnabled(SPConfig::Credentials)) {
1054 // Old format was to wrap it in a CredentialsProvider plugin, we're inlining that...
1055 child = XMLHelper::getFirstChildElement(e,CredentialsProvider);
1056 child = XMLHelper::getFirstChildElement(child ? child : e,Credentials);
1058 // Step down and process resolvers.
1059 child=XMLHelper::getFirstChildElement(child);
1061 xmltooling::auto_ptr_char id(child->getAttributeNS(NULL,Id));
1062 if (!id.get() || !*(id.get())) {
1063 log.warn("skipping CredentialsResolver with no Id attribute");
1064 child = XMLHelper::getNextSiblingElement(child);
1068 if (XMLString::equals(child->getLocalName(),FileResolver))
1069 plugtype=FILESYSTEM_CREDENTIAL_RESOLVER;
1071 xmltooling::auto_ptr_char c(child->getAttributeNS(NULL,_type));
1075 if (!plugtype.empty()) {
1077 CredentialResolver* cr=
1078 XMLToolingConfig::getConfig().CredentialResolverManager.newPlugin(plugtype.c_str(),child);
1079 m_credResolverMap[id.get()] = cr;
1081 catch (exception& ex) {
1082 log.crit("failed to instantiate CredentialResolver (%s): %s", id.get(), ex.what());
1086 log.error("unknown type of CredentialResolver with Id (%s)", id.get());
1089 child = XMLHelper::getNextSiblingElement(child);
1094 // Now we load any attribute factories
1095 child = XMLHelper::getFirstChildElement(e,AttributeFactory);
1097 xmltooling::auto_ptr_char type(child->getAttributeNS(NULL,_type));
1098 log.info("building Attribute factory of type %s...",type.get());
1100 IPlugIn* plugin=shibConf.getPlugMgr().newPlugin(type.get(),child);
1102 IAttributeFactory* fact=dynamic_cast<IAttributeFactory*>(plugin);
1104 m_attrFactories.push_back(fact);
1105 ShibConfig::getConfig().regAttributeMapping(
1106 child->getAttributeNS(NULL,opensaml::saml1::Attribute::ATTRIBUTENAME_ATTRIB_NAME), fact
1111 log.crit("plugin was not an Attribute factory");
1115 catch (exception& ex) {
1116 log.crit("error building Attribute factory: %s", ex.what());
1119 child = XMLHelper::getNextSiblingElement(child,AttributeFactory);
1122 // Load the default application. This actually has a fixed ID of "default". ;-)
1123 child=XMLHelper::getFirstChildElement(e,Applications);
1125 log.fatal("can't build default Application object, missing conf:Applications element?");
1126 throw ConfigurationException("can't build default Application object, missing conf:Applications element?");
1128 XMLApplication* defapp=new XMLApplication(m_outer,child);
1129 m_appmap[defapp->getId()]=defapp;
1131 // Load any overrides.
1132 child = XMLHelper::getFirstChildElement(child,_Application);
1134 auto_ptr<XMLApplication> iapp(new XMLApplication(m_outer,child,defapp));
1135 if (m_appmap.find(iapp->getId())!=m_appmap.end())
1136 log.crit("found conf:Application element with duplicate Id attribute (%s), skipping it", iapp->getId());
1138 m_appmap[iapp->getId()]=iapp.release();
1140 child = XMLHelper::getNextSiblingElement(child,_Application);
1143 catch (exception&) {
1144 this->~XMLConfigImpl();
1149 this->~XMLConfigImpl();
1155 XMLConfigImpl::~XMLConfigImpl()
1157 for_each(m_appmap.begin(),m_appmap.end(),xmltooling::cleanup_pair<string,Application>());
1158 ShibConfig::getConfig().clearAttributeMappings();
1159 for_each(m_attrFactories.begin(),m_attrFactories.end(),xmltooling::cleanup<IAttributeFactory>());
1160 for_each(m_credResolverMap.begin(),m_credResolverMap.end(),xmltooling::cleanup_pair<string,CredentialResolver>());
1161 delete m_requestMapper;
1163 m_document->release();
1166 pair<bool,DOMElement*> XMLConfig::load()
1168 // Load from source using base class.
1169 pair<bool,DOMElement*> raw = ReloadableXMLFile::load();
1171 // If we own it, wrap it.
1172 XercesJanitor<DOMDocument> docjanitor(raw.first ? raw.second->getOwnerDocument() : NULL);
1174 XMLConfigImpl* impl = new XMLConfigImpl(raw.second,(m_impl==NULL),this);
1176 // If we held the document, transfer it to the impl. If we didn't, it's a no-op.
1177 impl->setDocument(docjanitor.release());
1182 return make_pair(false,(DOMElement*)NULL);