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/security/PKIXTrustEngine.h>
32 #include <shibsp/util/DOMPropertySet.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 vector<const Handler*> g_noHandlers;
55 // Application configuration wrapper
56 class XMLApplication : public virtual IApplication, public DOMPropertySet, public DOMNodeFilter
59 XMLApplication(const IConfig*, const DOMElement* e, const XMLApplication* base=NULL);
60 ~XMLApplication() { cleanup(); }
63 pair<bool,bool> getBool(const char* name, const char* ns=NULL) const;
64 pair<bool,const char*> getString(const char* name, const char* ns=NULL) const;
65 pair<bool,const XMLCh*> getXMLString(const char* name, const char* ns=NULL) const;
66 pair<bool,unsigned int> getUnsignedInt(const char* name, const char* ns=NULL) const;
67 pair<bool,int> getInt(const char* name, const char* ns=NULL) const;
68 const PropertySet* getPropertySet(const char* name, const char* ns="urn:mace:shibboleth:target:config:1.0") const;
71 const char* getId() const {return getString("id").second;}
72 const char* getHash() const {return m_hash.c_str();}
73 Iterator<IAAP*> getAAPProviders() const;
74 MetadataProvider* getMetadataProvider() const;
75 TrustEngine* getTrustEngine() const;
76 const vector<const XMLCh*>& getAudiences() const;
77 const PropertySet* getCredentialUse(const EntityDescriptor* provider) const;
79 const SAMLBrowserProfile* getBrowserProfile() const {return m_profile;}
80 const SAMLBinding* getBinding(const XMLCh* binding) const
81 {return XMLString::compareString(SAMLBinding::SOAP,binding) ? NULL : m_binding;}
82 SAMLBrowserProfile::ArtifactMapper* getArtifactMapper() const {return new STArtifactMapper(this);}
86 const RoleDescriptor* role=NULL,
87 const TrustEngine* trust=NULL
89 const Handler* getDefaultSessionInitiator() const;
90 const Handler* getSessionInitiatorById(const char* id) const;
91 const Handler* getDefaultAssertionConsumerService() const;
92 const Handler* getAssertionConsumerServiceByIndex(unsigned short index) const;
93 const vector<const Handler*>& getAssertionConsumerServicesByBinding(const XMLCh* binding) const;
94 const Handler* getHandler(const char* path) const;
96 // Provides filter to exclude special config elements.
97 short acceptNode(const DOMNode* node) const;
101 const IConfig* m_ini; // this is ok because its locking scope includes us
102 const XMLApplication* m_base;
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 // 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 IConfig, public ReloadableXMLFile
181 XMLConfig(const DOMElement* e)
182 : ReloadableXMLFile(e), m_impl(NULL), m_listener(NULL), m_sessionCache(NULL), m_replayCache(NULL) {
191 delete m_sessionCache;
192 delete m_replayCache;
197 pair<bool,bool> getBool(const char* name, const char* ns=NULL) const {return m_impl->getBool(name,ns);}
198 pair<bool,const char*> getString(const char* name, const char* ns=NULL) const {return m_impl->getString(name,ns);}
199 pair<bool,const XMLCh*> getXMLString(const char* name, const char* ns=NULL) const {return m_impl->getXMLString(name,ns);}
200 pair<bool,unsigned int> getUnsignedInt(const char* name, const char* ns=NULL) const {return m_impl->getUnsignedInt(name,ns);}
201 pair<bool,int> getInt(const char* name, const char* ns=NULL) const {return m_impl->getInt(name,ns);}
202 const PropertySet* getPropertySet(const char* name, const char* ns="urn:mace:shibboleth:target:config:1.0") const {return m_impl->getPropertySet(name,ns);}
203 const DOMElement* getElement() const {return m_impl->getElement();}
206 ListenerService* getListenerService(bool required=true) const {
207 if (required && !m_listener)
208 throw ConfigurationException("No ListenerService available.");
212 ISessionCache* getSessionCache() const {return m_sessionCache;}
213 IReplayCache* getReplayCache() const {return m_replayCache;}
214 RequestMapper* getRequestMapper() const {return m_impl->m_requestMapper;}
215 const Application* getApplication(const char* applicationId) const {
216 map<string,Application*>::const_iterator i=m_impl->m_appmap.find(applicationId);
217 return (i!=m_impl->m_appmap.end()) ? i->second : NULL;
220 CredentialResolver* getCredentialResolver(const char* id) const {
222 map<string,CredentialResolver*>::const_iterator i=m_impl->m_credResolverMap.find(id);
223 if (i!=m_impl->m_credResolverMap.end())
230 pair<bool,DOMElement*> load();
233 friend class XMLConfigImpl;
234 XMLConfigImpl* m_impl;
235 mutable ListenerService* m_listener;
236 mutable ISessionCache* m_sessionCache;
237 mutable IReplayCache* m_replayCache;
240 #if defined (_MSC_VER)
241 #pragma warning( pop )
244 static const XMLCh AAPProvider[] = UNICODE_LITERAL_11(A,A,P,P,r,o,v,i,d,e,r);
245 static const XMLCh _Application[] = UNICODE_LITERAL_11(A,p,p,l,i,c,a,t,i,o,n);
246 static const XMLCh Applications[] = UNICODE_LITERAL_12(A,p,p,l,i,c,a,t,i,o,n,s);
247 static const XMLCh AttributeFactory[] = UNICODE_LITERAL_16(A,t,t,r,i,b,u,t,e,F,a,c,t,o,r,y);
248 static const XMLCh Credentials[] = UNICODE_LITERAL_11(C,r,e,d,e,n,t,i,a,l,s);
249 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);
250 static const XMLCh CredentialUse[] = UNICODE_LITERAL_13(C,r,e,d,e,n,t,i,a,l,U,s,e);
251 static const XMLCh DiagnosticService[] = UNICODE_LITERAL_17(D,i,a,g,n,o,s,t,i,c,S,e,r,v,i,c,e);
252 static const XMLCh fatal[] = UNICODE_LITERAL_5(f,a,t,a,l);
253 static const XMLCh FileResolver[] = UNICODE_LITERAL_12(F,i,l,e,R,e,s,o,l,v,e,r);
254 static const XMLCh Global[] = UNICODE_LITERAL_6(G,l,o,b,a,l);
255 static const XMLCh Id[] = UNICODE_LITERAL_2(I,d);
256 static const XMLCh Implementation[] = UNICODE_LITERAL_14(I,m,p,l,e,m,e,n,t,a,t,i,o,n);
257 static const XMLCh InProcess[] = UNICODE_LITERAL_9(I,n,P,r,o,c,e,s,s);
258 static const XMLCh Library[] = UNICODE_LITERAL_7(L,i,b,r,a,r,y);
259 static const XMLCh Listener[] = UNICODE_LITERAL_8(L,i,s,t,e,n,e,r);
260 static const XMLCh Local[] = UNICODE_LITERAL_5(L,o,c,a,l);
261 static const XMLCh logger[] = UNICODE_LITERAL_6(l,o,g,g,e,r);
262 static const XMLCh MemoryListener[] = UNICODE_LITERAL_14(M,e,m,o,r,y,L,i,s,t,e,n,e,r);
263 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);
264 static const XMLCh RelyingParty[] = UNICODE_LITERAL_12(R,e,l,y,i,n,g,P,a,r,t,y);
265 static const XMLCh ReplayCache[] = UNICODE_LITERAL_11(R,e,p,l,a,y,C,a,c,h,e);
266 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);
267 static const XMLCh SessionCache[] = UNICODE_LITERAL_12(S,e,s,s,i,o,n,C,a,c,h,e);
268 static const XMLCh SessionInitiator[] = UNICODE_LITERAL_16(S,e,s,s,i,o,n,I,n,i,t,i,a,t,o,r);
269 static const XMLCh OutOfProcess[] = UNICODE_LITERAL_12(O,u,t,O,f,P,r,o,c,e,s,s);
270 static const XMLCh TCPListener[] = UNICODE_LITERAL_11(T,C,P,L,i,s,t,e,n,e,r);
271 static const XMLCh TrustProvider[] = UNICODE_LITERAL_13(T,r,u,s,t,P,r,o,v,i,d,e,r);
272 static const XMLCh UnixListener[] = UNICODE_LITERAL_12(U,n,i,x,L,i,s,t,e,n,e,r);
273 static const XMLCh _MetadataProvider[] = UNICODE_LITERAL_16(M,e,t,a,d,a,t,a,P,r,o,v,i,d,e,r);
274 static const XMLCh _path[] = UNICODE_LITERAL_4(p,a,t,h);
275 static const XMLCh _type[] = UNICODE_LITERAL_4(t,y,p,e);
279 ServiceProvider* shibtarget::XMLServiceProviderFactory(const DOMElement* const & e)
281 return new XMLConfig(e);
284 XMLApplication::XMLApplication(
287 const XMLApplication* base
288 ) : m_ini(ini), m_base(base), m_metadata(NULL), m_trust(NULL), m_profile(NULL), m_binding(NULL), m_bindingHook(NULL),
289 m_credDefault(NULL), m_sessionInitDefault(NULL), m_acsDefault(NULL)
292 xmltooling::NDC ndc("XMLApplication");
294 Category& log=Category::getInstance(SHIBT_LOGCAT".Application");
297 // First load any property sets.
298 map<string,string> root_remap;
299 root_remap["shire"]="session";
300 root_remap["shireURL"]="handlerURL";
301 root_remap["shireSSL"]="handlerSSL";
302 load(e,log,this,&root_remap);
304 const PropertySet* propcheck=getPropertySet("Errors");
305 if (propcheck && !propcheck->getString("session").first)
306 throw ConfigurationException("<Errors> element requires 'session' (or deprecated 'shire') attribute");
307 propcheck=getPropertySet("Sessions");
308 if (propcheck && !propcheck->getString("handlerURL").first)
309 throw ConfigurationException("<Sessions> element requires 'handlerURL' (or deprecated 'shireURL') attribute");
311 SPConfig& conf=SPConfig::getConfig();
312 XMLToolingConfig& xmlConf=XMLToolingConfig::getConfig();
313 opensaml::SAMLConfig& samlConf=opensaml::SAMLConfig::getConfig();
314 SAMLConfig& shibConf=SAMLConfig::getConfig();
317 m_hash+=getString("providerId").second;
318 m_hash=samlConf.hashSHA1(m_hash.c_str(), true);
321 Handler* handler=NULL;
322 bool hardACS=false, hardSessionInit=false;
323 const DOMElement* child = XMLHelper::getFirstChildElement(propcheck->getElement());
325 xmltooling::auto_ptr_char bindprop(child->getAttributeNS(NULL,EndpointType::BINDING_ATTRIB_NAME));
326 if (!bindprop.get() || !*(bindprop.get())) {
327 log.warn("md:AssertionConsumerService element has no Binding attribute, skipping it...");
328 child = XMLHelper::getNextSiblingElement(child);
333 // A handler is based on the Binding property in conjunction with the element name.
334 // If it's an ACS or SI, also handle index/id mappings and defaulting.
335 if (XMLHelper::isNodeNamed(child,samlconstants::SAML20MD_NS,AssertionConsumerService::LOCAL_NAME)) {
336 handler=conf.AssertionConsumerServiceManager.newPlugin(bindprop.get(),child);
337 // Map by binding (may be > 1 per binding, e.g. SAML 1.0 vs 1.1)
339 m_acsBindingMap[handler->getXMLString("Binding").second].push_back(handler);
341 m_acsBindingMap[handler->getString("Binding").second].push_back(handler);
343 m_acsIndexMap[handler->getUnsignedInt("index").second]=handler;
346 pair<bool,bool> defprop=handler->getBool("isDefault");
348 if (defprop.second) {
350 m_acsDefault=handler;
353 else if (!m_acsDefault)
354 m_acsDefault=handler;
357 else if (XMLString::equals(child->getLocalName(),SessionInitiator)) {
358 handler=conf.SessionInitiatorManager.newPlugin(bindprop.get(),child);
359 pair<bool,const char*> si_id=handler->getString("id");
360 if (si_id.first && si_id.second)
361 m_sessionInitMap[si_id.second]=handler;
362 if (!hardSessionInit) {
363 pair<bool,bool> defprop=handler->getBool("isDefault");
365 if (defprop.second) {
366 hardSessionInit=true;
367 m_sessionInitDefault=handler;
370 else if (!m_sessionInitDefault)
371 m_sessionInitDefault=handler;
374 else if (XMLHelper::isNodeNamed(child,samlconstants::SAML20MD_NS,SingleLogoutService::LOCAL_NAME)) {
375 handler=conf.SingleLogoutServiceManager.newPlugin(bindprop.get(),child);
377 else if (XMLHelper::isNodeNamed(child,samlconstants::SAML20MD_NS,ManageNameIDService::LOCAL_NAME)) {
378 handler=conf.ManageNameIDServiceManager.newPlugin(bindprop.get(),child);
381 handler=conf.HandlerManager.newPlugin(bindprop.get(),child);
384 catch (exception& ex) {
385 log.error("caught exception processing md:AssertionConsumerService element: %s",ex.what());
388 // Save off the objects after giving the property set to the handler for its use.
389 m_handlers.push_back(handler);
391 // Insert into location map.
392 pair<bool,const char*> location=handler->getString("Location");
393 if (location.first && *location.second == '/')
394 m_handlerMap[location.second]=handler;
395 else if (location.first)
396 m_handlerMap[string("/") + location.second]=handler;
398 child = XMLHelper::getNextSiblingElement(child);
401 // If no handlers defined at the root, assume a legacy configuration.
402 if (!m_base && m_handlers.empty()) {
403 // A legacy config installs a SAML POST handler at the root handler location.
404 // We use the Sessions element itself as the PropertySet.
405 Handler* h1=conf.SessionInitiatorManager.newPlugin(
406 shibspconstants::SHIB1_SESSIONINIT_PROFILE_URI,propcheck->getElement()
408 m_handlers.push_back(h1);
409 m_sessionInitDefault=h1;
411 Handler* h2=conf.AssertionConsumerServiceManager.newPlugin(
412 samlconstants::SAML1_PROFILE_BROWSER_POST,propcheck->getElement()
414 m_handlers.push_back(h2);
415 m_handlerMap[""] = h2;
419 DOMNodeList* nlist=e->getElementsByTagNameNS(samlconstants::SAML1_NS,Audience::LOCAL_NAME);
420 for (XMLSize_t i=0; nlist && i<nlist->getLength(); i++)
421 if (nlist->item(i)->getParentNode()->isSameNode(e) && nlist->item(i)->hasChildNodes())
422 m_audiences.push_back(nlist->item(i)->getFirstChild()->getNodeValue());
424 // Always include our own providerId as an audience.
425 m_audiences.push_back(getXMLString("providerId").second);
427 if (conf.isEnabled(SPConfig::AAP)) {
428 child = XMLHelper::getFirstChildElement(e,AAPProvider);
430 xmltooling::auto_ptr_char type(child->getAttributeNS(NULL,_type));
431 log.info("building AAP provider of type %s...",type.get());
433 IPlugIn* plugin=shibConf.getPlugMgr().newPlugin(type.get(),child);
434 IAAP* aap=dynamic_cast<IAAP*>(plugin);
436 m_aaps.push_back(aap);
439 log.crit("plugin was not an AAP provider");
442 catch (exception& ex) {
443 log.crit("error building AAP provider: %s", ex.what());
446 child = XMLHelper::getNextSiblingElement(child,AAPProvider);
450 if (conf.isEnabled(SPConfig::Metadata)) {
451 vector<MetadataProvider*> os2providers;
452 child = XMLHelper::getFirstChildElement(e,_MetadataProvider);
454 xmltooling::auto_ptr_char type(child->getAttributeNS(NULL,_type));
455 log.info("building metadata provider of type %s...",type.get());
457 auto_ptr<MetadataProvider> mp(samlConf.MetadataProviderManager.newPlugin(type.get(),child));
459 os2providers.push_back(mp.release());
461 catch (exception& ex) {
462 log.crit("error building/initializing metadata provider: %s", ex.what());
465 child = XMLHelper::getNextSiblingElement(child,_MetadataProvider);
468 if (os2providers.size()==1)
469 m_metadata=os2providers.front();
470 else if (os2providers.size()>1) {
472 m_metadata = samlConf.MetadataProviderManager.newPlugin(CHAINING_METADATA_PROVIDER,NULL);
473 ChainingMetadataProvider* chainMeta = dynamic_cast<ChainingMetadataProvider*>(m_metadata);
474 while (!os2providers.empty()) {
475 chainMeta->addMetadataProvider(os2providers.back());
476 os2providers.pop_back();
479 catch (exception& ex) {
480 log.crit("error building chaining metadata provider wrapper: %s",ex.what());
481 for_each(os2providers.begin(), os2providers.end(), xmltooling::cleanup<MetadataProvider>());
486 if (conf.isEnabled(SPConfig::Trust)) {
487 ChainingTrustEngine* chainTrust = NULL;
488 child = XMLHelper::getFirstChildElement(e,TrustProvider);
490 xmltooling::auto_ptr_char type(child->getAttributeNS(NULL,_type));
491 log.info("building trust provider of type %s...",type.get());
494 // For compatibility with old engine types, we're assuming a Shib engine is likely,
495 // which requires chaining, so we'll build that regardless.
496 m_trust = xmlConf.TrustEngineManager.newPlugin(CHAINING_TRUSTENGINE,NULL);
497 chainTrust = dynamic_cast<ChainingTrustEngine*>(m_trust);
499 if (!strcmp(type.get(),"edu.internet2.middleware.shibboleth.common.provider.ShibbolethTrust")) {
500 chainTrust->addTrustEngine(xmlConf.TrustEngineManager.newPlugin(EXPLICIT_KEY_TRUSTENGINE,child));
501 chainTrust->addTrustEngine(xmlConf.TrustEngineManager.newPlugin(SHIBBOLETH_PKIX_TRUSTENGINE,child));
503 else if (!strcmp(type.get(),"edu.internet2.middleware.shibboleth.common.provider.BasicTrust")) {
504 chainTrust->addTrustEngine(xmlConf.TrustEngineManager.newPlugin(EXPLICIT_KEY_TRUSTENGINE,child));
507 chainTrust->addTrustEngine(xmlConf.TrustEngineManager.newPlugin(type.get(),child));
510 catch (exception& ex) {
511 log.crit("error building trust provider: %s",ex.what());
514 child = XMLHelper::getNextSiblingElement(child,TrustProvider);
518 // Finally, load credential mappings.
519 child = XMLHelper::getFirstChildElement(e,CredentialUse);
521 m_credDefault=new DOMPropertySet();
522 m_credDefault->load(child,log,this);
523 child = XMLHelper::getFirstChildElement(child,RelyingParty);
525 DOMPropertySet* rp=new DOMPropertySet();
526 rp->load(child,log,this);
527 m_credMap[child->getAttributeNS(NULL,opensaml::saml2::Attribute::NAME_ATTRIB_NAME)]=rp;
528 child = XMLHelper::getNextSiblingElement(child,RelyingParty);
532 if (conf.isEnabled(SPConfig::OutOfProcess)) {
533 // Really finally, build local browser profile and binding objects.
534 m_profile=new ShibBrowserProfile(this, getMetadataProvider(), getTrustEngine());
535 m_bindingHook=new ShibHTTPHook(getTrustEngine());
536 m_binding=SAMLBinding::getInstance(SAMLBinding::SOAP);
537 SAMLSOAPHTTPBinding* bptr=dynamic_cast<SAMLSOAPHTTPBinding*>(m_binding);
539 log.fatal("binding implementation was not SOAP over HTTP");
540 throw UnknownExtensionException("binding implementation was not SOAP over HTTP");
542 bptr->addHook(m_bindingHook,m_bindingHook); // the hook is its own global context
557 void XMLApplication::cleanup()
559 delete m_bindingHook;
562 for_each(m_handlers.begin(),m_handlers.end(),xmltooling::cleanup<Handler>());
564 delete m_credDefault;
566 for_each(m_credMap.begin(),m_credMap.end(),xmltooling::cleanup_pair<xmltooling::xstring,PropertySet>());
568 for_each(m_credMap.begin(),m_credMap.end(),xmltooling::cleanup_pair<const XMLCh*,PropertySet>());
570 for_each(m_aaps.begin(),m_aaps.end(),xmltooling::cleanup<IAAP>());
576 short XMLApplication::acceptNode(const DOMNode* node) const
578 if (XMLHelper::isNodeNamed(node,samlconstants::SAML1_NS,AttributeDesignator::LOCAL_NAME))
579 return FILTER_REJECT;
580 else if (XMLHelper::isNodeNamed(node,samlconstants::SAML20_NS,Attribute::LOCAL_NAME))
581 return FILTER_REJECT;
582 else if (XMLHelper::isNodeNamed(node,samlconstants::SAML1_NS,Audience::LOCAL_NAME))
583 return FILTER_REJECT;
584 const XMLCh* name=node->getLocalName();
585 if (XMLString::equals(name,_Application) ||
586 XMLString::equals(name,AssertionConsumerService::LOCAL_NAME) ||
587 XMLString::equals(name,SingleLogoutService::LOCAL_NAME) ||
588 XMLString::equals(name,DiagnosticService) ||
589 XMLString::equals(name,SessionInitiator) ||
590 XMLString::equals(name,AAPProvider) ||
591 XMLString::equals(name,CredentialUse) ||
592 XMLString::equals(name,RelyingParty) ||
593 XMLString::equals(name,_MetadataProvider) ||
594 XMLString::equals(name,TrustProvider))
595 return FILTER_REJECT;
597 return FILTER_ACCEPT;
600 pair<bool,bool> XMLApplication::getBool(const char* name, const char* ns) const
602 pair<bool,bool> ret=DOMPropertySet::getBool(name,ns);
605 return m_base ? m_base->getBool(name,ns) : ret;
608 pair<bool,const char*> XMLApplication::getString(const char* name, const char* ns) const
610 pair<bool,const char*> ret=DOMPropertySet::getString(name,ns);
613 return m_base ? m_base->getString(name,ns) : ret;
616 pair<bool,const XMLCh*> XMLApplication::getXMLString(const char* name, const char* ns) const
618 pair<bool,const XMLCh*> ret=DOMPropertySet::getXMLString(name,ns);
621 return m_base ? m_base->getXMLString(name,ns) : ret;
624 pair<bool,unsigned int> XMLApplication::getUnsignedInt(const char* name, const char* ns) const
626 pair<bool,unsigned int> ret=DOMPropertySet::getUnsignedInt(name,ns);
629 return m_base ? m_base->getUnsignedInt(name,ns) : ret;
632 pair<bool,int> XMLApplication::getInt(const char* name, const char* ns) const
634 pair<bool,int> ret=DOMPropertySet::getInt(name,ns);
637 return m_base ? m_base->getInt(name,ns) : ret;
640 const PropertySet* XMLApplication::getPropertySet(const char* name, const char* ns) const
642 const PropertySet* ret=DOMPropertySet::getPropertySet(name,ns);
645 return m_base->getPropertySet(name,ns);
648 Iterator<IAAP*> XMLApplication::getAAPProviders() const
650 return (m_aaps.empty() && m_base) ? m_base->getAAPProviders() : m_aaps;
653 MetadataProvider* XMLApplication::getMetadataProvider() const
655 return (!m_metadata && m_base) ? m_base->getMetadataProvider() : m_metadata;
658 TrustEngine* XMLApplication::getTrustEngine() const
660 return (!m_trust && m_base) ? m_base->getTrustEngine() : m_trust;
663 const vector<const XMLCh*>& XMLApplication::getAudiences() const
665 return (m_audiences.empty() && m_base) ? m_base->getAudiences() : m_audiences;
668 const PropertySet* XMLApplication::getCredentialUse(const EntityDescriptor* provider) const
670 if (!m_credDefault && m_base)
671 return m_base->getCredentialUse(provider);
674 map<xmltooling::xstring,PropertySet*>::const_iterator i=m_credMap.find(provider->getEntityID());
675 if (i!=m_credMap.end())
677 const EntitiesDescriptor* group=dynamic_cast<const EntitiesDescriptor*>(provider->getParent());
679 if (group->getName()) {
680 i=m_credMap.find(group->getName());
681 if (i!=m_credMap.end())
684 group=dynamic_cast<const EntitiesDescriptor*>(group->getParent());
687 map<const XMLCh*,PropertySet*>::const_iterator i=m_credMap.begin();
688 for (; i!=m_credMap.end(); i++) {
689 if (XMLString::equals(i->first,provider->getId()))
691 const EntitiesDescriptor* group=dynamic_cast<const EntitiesDescriptor*>(provider->getParent());
693 if (XMLString::equals(i->first,group->getName()))
695 group=dynamic_cast<const EntitiesDescriptor*>(group->getParent());
699 return m_credDefault;
702 void XMLApplication::validateToken(SAMLAssertion* token, time_t ts, const RoleDescriptor* role, const TrustEngine* trust) const
705 xmltooling::NDC ndc("validateToken");
707 Category& log=Category::getInstance(SHIBT_LOGCAT".Application");
709 // First we verify the time conditions, using the specified timestamp, if non-zero.
710 SAMLConfig& config=SAMLConfig::getConfig();
712 const SAMLDateTime* notBefore=token->getNotBefore();
713 if (notBefore && ts+config.clock_skew_secs < notBefore->getEpoch())
714 throw opensaml::FatalProfileException("Assertion is not yet valid.");
715 const SAMLDateTime* notOnOrAfter=token->getNotOnOrAfter();
716 if (notOnOrAfter && notOnOrAfter->getEpoch() <= ts-config.clock_skew_secs)
717 throw opensaml::FatalProfileException("Assertion is no longer valid.");
720 // Now we process conditions. Only audience restrictions at the moment.
721 Iterator<SAMLCondition*> conditions=token->getConditions();
722 while (conditions.hasNext()) {
723 SAMLCondition* cond=conditions.next();
724 const SAMLAudienceRestrictionCondition* ac=dynamic_cast<const SAMLAudienceRestrictionCondition*>(cond);
728 log.error("unrecognized Condition in assertion (%s)",os.str().c_str());
729 throw xmltooling::UnknownExtensionException("Assertion contains an unrecognized condition.");
731 else if (!ac->eval(getAudiences())) {
734 log.error("unacceptable AudienceRestrictionCondition in assertion (%s)",os.str().c_str());
735 throw opensaml::FatalProfileException("Assertion contains an unacceptable AudienceRestrictionCondition.");
739 if (!role || !trust) {
740 log.warn("no metadata provided, so no signature validation was performed");
744 const PropertySet* credUse=getCredentialUse(dynamic_cast<const EntityDescriptor*>(role->getParent()));
745 pair<bool,bool> signedAssertions=credUse ? credUse->getBool("signedAssertions") : make_pair(false,false);
747 if (token->isSigned()) {
749 // This will all change, but for fun, we'll port the object from OS1->OS2 for validation.
752 DOMDocument* doc = XMLToolingConfig::getConfig().getValidatingParser().parse(s);
753 XercesJanitor<DOMDocument> jdoc(doc);
754 auto_ptr<Assertion> os2ass(AssertionBuilder::buildAssertion());
755 os2ass->unmarshall(doc->getDocumentElement(),true);
758 if (!trust->validate(*(os2ass->getSignature()),*role))
759 throw xmltooling::XMLSecurityException("Assertion signature did not validate.");
761 else if (signedAssertions.first && signedAssertions.second)
762 throw xmltooling::XMLSecurityException("Assertion was unsigned, violating policy based on the issuer.");
765 const Handler* XMLApplication::getDefaultSessionInitiator() const
767 if (m_sessionInitDefault) return m_sessionInitDefault;
768 return m_base ? m_base->getDefaultSessionInitiator() : NULL;
771 const Handler* XMLApplication::getSessionInitiatorById(const char* id) const
773 map<string,const Handler*>::const_iterator i=m_sessionInitMap.find(id);
774 if (i!=m_sessionInitMap.end()) return i->second;
775 return m_base ? m_base->getSessionInitiatorById(id) : NULL;
778 const Handler* XMLApplication::getDefaultAssertionConsumerService() const
780 if (m_acsDefault) return m_acsDefault;
781 return m_base ? m_base->getDefaultAssertionConsumerService() : NULL;
784 const Handler* XMLApplication::getAssertionConsumerServiceByIndex(unsigned short index) const
786 map<unsigned int,const Handler*>::const_iterator i=m_acsIndexMap.find(index);
787 if (i!=m_acsIndexMap.end()) return i->second;
788 return m_base ? m_base->getAssertionConsumerServiceByIndex(index) : NULL;
791 const vector<const Handler*>& XMLApplication::getAssertionConsumerServicesByBinding(const XMLCh* binding) const
794 ACSBindingMap::const_iterator i=m_acsBindingMap.find(binding);
796 xmltooling::auto_ptr_char temp(binding);
797 ACSBindingMap::const_iterator i=m_acsBindingMap.find(temp.get());
799 if (i!=m_acsBindingMap.end())
801 return m_base ? m_base->getAssertionConsumerServicesByBinding(binding) : g_noHandlers;
804 const Handler* XMLApplication::getHandler(const char* path) const
807 map<string,const Handler*>::const_iterator i=m_handlerMap.find(wrap.substr(0,wrap.find('?')));
808 if (i!=m_handlerMap.end())
810 return m_base ? m_base->getHandler(path) : NULL;
813 short XMLConfigImpl::acceptNode(const DOMNode* node) const
815 if (!XMLString::equals(node->getNamespaceURI(),shibspconstants::SHIB1SPCONFIG_NS))
816 return FILTER_ACCEPT;
817 const XMLCh* name=node->getLocalName();
818 if (XMLString::equals(name,Applications) ||
819 XMLString::equals(name,AttributeFactory) ||
820 XMLString::equals(name,Credentials) ||
821 XMLString::equals(name,CredentialsProvider) ||
822 XMLString::equals(name,Extensions::LOCAL_NAME) ||
823 XMLString::equals(name,Implementation) ||
824 XMLString::equals(name,Listener) ||
825 XMLString::equals(name,MemoryListener) ||
826 XMLString::equals(name,MemorySessionCache) ||
827 XMLString::equals(name,RequestMapProvider) ||
828 XMLString::equals(name,ReplayCache) ||
829 XMLString::equals(name,SessionCache) ||
830 XMLString::equals(name,TCPListener) ||
831 XMLString::equals(name,UnixListener))
832 return FILTER_REJECT;
834 return FILTER_ACCEPT;
837 void XMLConfigImpl::doExtensions(const DOMElement* e, const char* label, Category& log)
839 const DOMElement* exts=XMLHelper::getFirstChildElement(e,Extensions::LOCAL_NAME);
841 exts=XMLHelper::getFirstChildElement(exts,Library);
843 xmltooling::auto_ptr_char path(exts->getAttributeNS(NULL,_path));
846 // TODO: replace with xmltooling extension load...
847 SAMLConfig::getConfig().saml_register_extension(path.get(),(void*)exts);
848 log.debug("loaded %s extension library (%s)", label, path.get());
851 catch (exception& e) {
852 const XMLCh* fatal=exts->getAttributeNS(NULL,fatal);
853 if (fatal && (*fatal==chLatin_t || *fatal==chDigit_1)) {
854 log.fatal("unable to load mandatory %s extension library %s: %s", label, path.get(), e.what());
858 log.crit("unable to load optional %s extension library %s: %s", label, path.get(), e.what());
861 exts=XMLHelper::getNextSiblingElement(exts,Library);
866 XMLConfigImpl::XMLConfigImpl(const DOMElement* e, bool first, const XMLConfig* outer) : m_outer(outer), m_requestMapper(NULL)
869 xmltooling::NDC ndc("XMLConfigImpl");
871 Category& log=Category::getInstance(SHIBT_LOGCAT".Config");
874 SAMLConfig& shibConf=SAMLConfig::getConfig();
875 SPConfig& conf=SPConfig::getConfig();
876 const DOMElement* SHAR=XMLHelper::getFirstChildElement(e,OutOfProcess);
878 SHAR=XMLHelper::getFirstChildElement(e,Global);
879 const DOMElement* SHIRE=XMLHelper::getFirstChildElement(e,InProcess);
881 SHIRE=XMLHelper::getFirstChildElement(e,Local);
883 // Initialize log4cpp manually in order to redirect log messages as soon as possible.
884 if (conf.isEnabled(SPConfig::Logging)) {
885 const XMLCh* logconf=NULL;
886 if (conf.isEnabled(SPConfig::OutOfProcess))
887 logconf=SHAR->getAttributeNS(NULL,logger);
888 else if (conf.isEnabled(SPConfig::InProcess))
889 logconf=SHIRE->getAttributeNS(NULL,logger);
890 if (!logconf || !*logconf)
891 logconf=e->getAttributeNS(NULL,logger);
892 if (logconf && *logconf) {
893 xmltooling::auto_ptr_char logpath(logconf);
894 log.debug("loading new logging configuration from (%s), check log destination for status of configuration",logpath.get());
895 XMLToolingConfig::getConfig().log_config(logpath.get());
899 // First load any property sets.
900 map<string,string> root_remap;
901 root_remap["Global"]="OutOfProcess";
902 root_remap["Local"]="InProcess";
903 load(e,log,this,&root_remap);
905 const DOMElement* child;
906 IPlugIn* plugin=NULL;
909 // Much of the processing can only occur on the first instantiation.
913 doExtensions(e, "global", log);
914 if (conf.isEnabled(SPConfig::OutOfProcess))
915 doExtensions(SHAR, "out of process", log);
917 if (conf.isEnabled(SPConfig::InProcess))
918 doExtensions(SHIRE, "in process", log);
920 // Instantiate the ListenerService and SessionCache objects.
921 if (conf.isEnabled(SPConfig::Listener)) {
922 child=XMLHelper::getFirstChildElement(SHAR,UnixListener);
924 plugtype=UNIX_LISTENER_SERVICE;
926 child=XMLHelper::getFirstChildElement(SHAR,TCPListener);
928 plugtype=TCP_LISTENER_SERVICE;
930 child=XMLHelper::getFirstChildElement(SHAR,MemoryListener);
932 plugtype=MEMORY_LISTENER_SERVICE;
934 child=XMLHelper::getFirstChildElement(SHAR,Listener);
936 xmltooling::auto_ptr_char type(child->getAttributeNS(NULL,_type));
944 log.info("building ListenerService of type %s...", plugtype.c_str());
945 m_outer->m_listener = conf.ListenerServiceManager.newPlugin(plugtype.c_str(),child);
948 log.fatal("can't build ListenerService, missing conf:Listener element?");
949 throw ConfigurationException("Can't build ListenerService, missing conf:Listener element?");
953 if (conf.isEnabled(SPConfig::Caching)) {
954 // TODO: This code's a mess, due to a very bad config layout for the caches...
955 // Needs rework with the new config file.
956 const DOMElement* container=conf.isEnabled(SPConfig::OutOfProcess) ? SHAR : SHIRE;
957 child=XMLHelper::getFirstChildElement(container,MemorySessionCache);
959 log.info("building Session Cache of type %s...",MEMORY_SESSIONCACHE);
960 plugin=shibConf.getPlugMgr().newPlugin(MEMORY_SESSIONCACHE,child);
963 child=XMLHelper::getFirstChildElement(container,SessionCache);
965 xmltooling::auto_ptr_char type(child->getAttributeNS(NULL,_type));
966 log.info("building Session Cache of type %s...",type.get());
967 plugin=shibConf.getPlugMgr().newPlugin(type.get(),child);
970 log.info("custom SessionCache unspecified or no longer supported, building SessionCache of type %s...",MEMORY_SESSIONCACHE);
971 plugin=shibConf.getPlugMgr().newPlugin(MEMORY_SESSIONCACHE,child);
975 ISessionCache* cache=dynamic_cast<ISessionCache*>(plugin);
977 m_outer->m_sessionCache=cache;
980 log.fatal("plugin was not a Session Cache object");
981 throw UnknownExtensionException("plugin was not a Session Cache object");
986 // TODO: switch to new cache interface
987 child=XMLHelper::getFirstChildElement(container,ReplayCache);
989 xmltooling::auto_ptr_char type(child->getAttributeNS(NULL,_type));
990 log.info("building ReplayCache of type %s...",type.get());
991 m_outer->m_replayCache=IReplayCache::getInstance(type.get(),child);
994 // OpenSAML default provider.
995 log.info("custom ReplayCache unspecified or no longer supported, building default ReplayCache...");
996 m_outer->m_replayCache=IReplayCache::getInstance();
999 } // end of first-time-only stuff
1001 // Back to the fully dynamic stuff...next up is the RequestMapper.
1002 if (conf.isEnabled(SPConfig::RequestMapping)) {
1003 child=XMLHelper::getFirstChildElement(SHIRE,RequestMapProvider);
1005 xmltooling::auto_ptr_char type(child->getAttributeNS(NULL,_type));
1006 log.info("building RequestMapper of type %s...",type.get());
1007 m_requestMapper=conf.RequestMapperManager.newPlugin(type.get(),child);
1010 log.fatal("can't build RequestMapper, missing conf:RequestMapProvider element?");
1011 throw ConfigurationException("can't build RequestMapper, missing conf:RequestMapProvider element?");
1015 // Now we load the credentials map.
1016 if (conf.isEnabled(SPConfig::Credentials)) {
1017 // Old format was to wrap it in a CredentialsProvider plugin, we're inlining that...
1018 child = XMLHelper::getFirstChildElement(e,CredentialsProvider);
1019 child = XMLHelper::getFirstChildElement(child ? child : e,Credentials);
1021 // Step down and process resolvers.
1022 child=XMLHelper::getFirstChildElement(child);
1024 xmltooling::auto_ptr_char id(child->getAttributeNS(NULL,Id));
1025 if (!id.get() || !*(id.get())) {
1026 log.warn("skipping CredentialsResolver with no Id attribute");
1027 child = XMLHelper::getNextSiblingElement(child);
1031 if (XMLString::equals(child->getLocalName(),FileResolver))
1032 plugtype=FILESYSTEM_CREDENTIAL_RESOLVER;
1034 xmltooling::auto_ptr_char c(child->getAttributeNS(NULL,_type));
1038 if (!plugtype.empty()) {
1040 CredentialResolver* cr=
1041 XMLToolingConfig::getConfig().CredentialResolverManager.newPlugin(plugtype.c_str(),child);
1042 m_credResolverMap[id.get()] = cr;
1044 catch (exception& ex) {
1045 log.crit("failed to instantiate CredentialResolver (%s): %s", id.get(), ex.what());
1049 log.error("unknown type of CredentialResolver with Id (%s)", id.get());
1052 child = XMLHelper::getNextSiblingElement(child);
1057 // Now we load any attribute factories
1058 child = XMLHelper::getFirstChildElement(e,AttributeFactory);
1060 xmltooling::auto_ptr_char type(child->getAttributeNS(NULL,_type));
1061 log.info("building Attribute factory of type %s...",type.get());
1063 plugin=shibConf.getPlugMgr().newPlugin(type.get(),child);
1065 IAttributeFactory* fact=dynamic_cast<IAttributeFactory*>(plugin);
1067 m_attrFactories.push_back(fact);
1068 ShibConfig::getConfig().regAttributeMapping(
1069 child->getAttributeNS(NULL,Attribute::ATTRIBUTENAME_ATTRIB_NAME), fact
1074 log.crit("plugin was not an Attribute factory");
1078 catch (exception& ex) {
1079 log.crit("error building Attribute factory: %s", ex.what());
1082 child = XMLHelper::getNextSiblingElement(child,AttributeFactory);
1085 // Load the default application. This actually has a fixed ID of "default". ;-)
1086 child=XMLHelper::getFirstChildElement(e,Applications);
1088 log.fatal("can't build default Application object, missing conf:Applications element?");
1089 throw ConfigurationException("can't build default Application object, missing conf:Applications element?");
1091 XMLApplication* defapp=new XMLApplication(m_outer,child);
1092 m_appmap[defapp->getId()]=defapp;
1094 // Load any overrides.
1095 child = XMLHelper::getFirstChildElement(child,_Application);
1097 auto_ptr<XMLApplication> iapp(new XMLApplication(m_outer,child,defapp));
1098 if (m_appmap.find(iapp->getId())!=m_appmap.end())
1099 log.crit("found conf:Application element with duplicate Id attribute (%s), skipping it", iapp->getId());
1101 m_appmap[iapp->getId()]=iapp.release();
1103 child = XMLHelper::getNextSiblingElement(child,_Application);
1106 catch (exception&) {
1107 this->~XMLConfigImpl();
1112 this->~XMLConfigImpl();
1118 XMLConfigImpl::~XMLConfigImpl()
1120 for_each(m_appmap.begin(),m_appmap.end(),xmltooling::cleanup_pair<string,Application>());
1121 ShibConfig::getConfig().clearAttributeMappings();
1122 for_each(m_attrFactories.begin(),m_attrFactories.end(),xmltooling::cleanup<IAttributeFactory>());
1123 for_each(m_credResolverMap.begin(),m_credResolverMap.end(),xmltooling::cleanup_pair<string,CredentialResolver>());
1124 delete m_requestMapper;
1126 m_document->release();
1129 pair<bool,DOMElement*> XMLConfig::load()
1131 // Load from source using base class.
1132 pair<bool,DOMElement*> raw = ReloadableXMLFile::load();
1134 // If we own it, wrap it.
1135 XercesJanitor<DOMDocument> docjanitor(raw.first ? raw.second->getOwnerDocument() : NULL);
1137 XMLConfigImpl* impl = new XMLConfigImpl(raw.second,(m_impl==NULL),this);
1139 // If we held the document, transfer it to the impl. If we didn't, it's a no-op.
1140 impl->setDocument(docjanitor.release());
1145 return make_pair(false,(DOMElement*)NULL);