2 * Copyright 2001-2009 Internet2
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
18 * XMLServiceProvider.cpp
20 * XML-based SP configuration and mgmt.
24 #include "exceptions.h"
26 #include "AccessControl.h"
27 #include "Application.h"
28 #include "RequestMapper.h"
29 #include "ServiceProvider.h"
30 #include "SessionCache.h"
32 #include "SPRequest.h"
33 #include "handler/SessionInitiator.h"
34 #include "remoting/ListenerService.h"
35 #include "util/DOMPropertySet.h"
36 #include "util/SPConstants.h"
38 #if defined(XMLTOOLING_LOG4SHIB)
39 # include <log4shib/PropertyConfigurator.hh>
40 #elif defined(XMLTOOLING_LOG4CPP)
41 # include <log4cpp/PropertyConfigurator.hh>
43 # error "Supported logging library not available."
46 #include <xercesc/util/XMLUniDefs.hpp>
47 #include <xmltooling/XMLToolingConfig.h>
48 #include <xmltooling/version.h>
49 #include <xmltooling/util/NDC.h>
50 #include <xmltooling/util/ReloadableXMLFile.h>
51 #include <xmltooling/util/TemplateEngine.h>
52 #include <xmltooling/util/XMLHelper.h>
55 # include "TransactionLog.h"
56 # include "attribute/filtering/AttributeFilter.h"
57 # include "attribute/resolver/AttributeExtractor.h"
58 # include "attribute/resolver/AttributeResolver.h"
59 # include "security/PKIXTrustEngine.h"
60 # include <saml/SAMLConfig.h>
61 # include <saml/version.h>
62 # include <saml/binding/ArtifactMap.h>
63 # include <saml/binding/SAMLArtifact.h>
64 # include <saml/saml1/core/Assertions.h>
65 # include <saml/saml2/binding/SAML2ArtifactType0004.h>
66 # include <xmltooling/util/ReplayCache.h>
67 using namespace opensaml::saml2;
68 using namespace opensaml::saml2p;
69 using namespace opensaml::saml2md;
70 using namespace opensaml;
73 using namespace shibsp;
74 using namespace xmltooling;
78 # define min(a,b) (((a) < (b)) ? (a) : (b))
83 #if defined (_MSC_VER)
84 #pragma warning( push )
85 #pragma warning( disable : 4250 )
88 static vector<const Handler*> g_noHandlers;
90 // Application configuration wrapper
91 class SHIBSP_DLLLOCAL XMLApplication : public Application, public Remoted, public DOMPropertySet, public DOMNodeFilter
94 XMLApplication(const ServiceProvider*, const DOMElement* e, const XMLApplication* base=NULL);
95 ~XMLApplication() { cleanup(); }
97 const char* getHash() const {return m_hash.c_str();}
100 SAMLArtifact* generateSAML1Artifact(const EntityDescriptor* relyingParty) const {
101 throw ConfigurationException("No support for SAML 1.x artifact generation.");
103 SAML2Artifact* generateSAML2Artifact(const EntityDescriptor* relyingParty) const {
104 pair<bool,int> index = make_pair(false,0);
105 const PropertySet* props = getRelyingParty(relyingParty);
106 index = props->getInt("artifactEndpointIndex");
108 index = getArtifactEndpointIndex();
109 return new SAML2ArtifactType0004(SAMLConfig::getConfig().hashSHA1(props->getString("entityID").second),index.first ? index.second : 1);
112 MetadataProvider* getMetadataProvider(bool required=true) const {
113 if (required && !m_base && !m_metadata)
114 throw ConfigurationException("No MetadataProvider available.");
115 return (!m_metadata && m_base) ? m_base->getMetadataProvider() : m_metadata;
117 TrustEngine* getTrustEngine(bool required=true) const {
118 if (required && !m_base && !m_trust)
119 throw ConfigurationException("No TrustEngine available.");
120 return (!m_trust && m_base) ? m_base->getTrustEngine() : m_trust;
122 AttributeExtractor* getAttributeExtractor() const {
123 return (!m_attrExtractor && m_base) ? m_base->getAttributeExtractor() : m_attrExtractor;
125 AttributeFilter* getAttributeFilter() const {
126 return (!m_attrFilter && m_base) ? m_base->getAttributeFilter() : m_attrFilter;
128 AttributeResolver* getAttributeResolver() const {
129 return (!m_attrResolver && m_base) ? m_base->getAttributeResolver() : m_attrResolver;
131 CredentialResolver* getCredentialResolver() const {
132 return (!m_credResolver && m_base) ? m_base->getCredentialResolver() : m_credResolver;
134 const PropertySet* getRelyingParty(const EntityDescriptor* provider) const;
135 const PropertySet* getRelyingParty(const XMLCh* entityID) const;
136 const vector<const XMLCh*>* getAudiences() const {
137 return (m_audiences.empty() && m_base) ? m_base->getAudiences() : &m_audiences;
140 string getNotificationURL(const char* resource, bool front, unsigned int index) const;
142 const vector<string>& getRemoteUserAttributeIds() const {
143 return (m_remoteUsers.empty() && m_base) ? m_base->getRemoteUserAttributeIds() : m_remoteUsers;
146 void clearHeader(SPRequest& request, const char* rawname, const char* cginame) const;
147 void setHeader(SPRequest& request, const char* name, const char* value) const;
148 string getSecureHeader(const SPRequest& request, const char* name) const;
150 const SessionInitiator* getDefaultSessionInitiator() const;
151 const SessionInitiator* getSessionInitiatorById(const char* id) const;
152 const Handler* getDefaultAssertionConsumerService() const;
153 const Handler* getAssertionConsumerServiceByIndex(unsigned short index) const;
154 const vector<const Handler*>& getAssertionConsumerServicesByBinding(const XMLCh* binding) const;
155 const Handler* getHandler(const char* path) const;
156 void getHandlers(vector<const Handler*>& handlers) const;
158 void receive(DDF& in, ostream& out) {
159 // Only current function is to return the headers to clear.
161 DDF ret=DDF(NULL).list();
162 DDFJanitor jret(ret);
163 for (vector< pair<string,string> >::const_iterator i = m_unsetHeaders.begin(); i!=m_unsetHeaders.end(); ++i) {
164 header = DDF(i->first.c_str()).string(i->second.c_str());
170 // Provides filter to exclude special config elements.
171 #ifdef SHIBSP_XERCESC_SHORT_ACCEPTNODE
176 acceptNode(const DOMNode* node) const;
180 const XMLApplication* m_base;
182 std::pair<std::string,std::string> m_attributePrefix;
184 MetadataProvider* m_metadata;
185 TrustEngine* m_trust;
186 AttributeExtractor* m_attrExtractor;
187 AttributeFilter* m_attrFilter;
188 AttributeResolver* m_attrResolver;
189 CredentialResolver* m_credResolver;
190 vector<const XMLCh*> m_audiences;
192 // RelyingParty properties
193 map<xstring,PropertySet*> m_partyMap;
195 vector<string> m_remoteUsers,m_frontLogout,m_backLogout;
197 // manage handler objects
198 vector<Handler*> m_handlers;
200 // maps location (path info) to applicable handlers
201 map<string,const Handler*> m_handlerMap;
203 // maps unique indexes to consumer services
204 map<unsigned int,const Handler*> m_acsIndexMap;
206 // pointer to default consumer service
207 const Handler* m_acsDefault;
209 // maps binding strings to supporting consumer service(s)
210 typedef map<xstring,vector<const Handler*> > ACSBindingMap;
211 ACSBindingMap m_acsBindingMap;
213 // pointer to default session initiator
214 const SessionInitiator* m_sessionInitDefault;
216 // maps unique ID strings to session initiators
217 map<string,const SessionInitiator*> m_sessionInitMap;
219 // pointer to default artifact resolution service
220 const Handler* m_artifactResolutionDefault;
222 pair<bool,int> getArtifactEndpointIndex() const {
223 if (m_artifactResolutionDefault) return m_artifactResolutionDefault->getInt("index");
224 return m_base ? m_base->getArtifactEndpointIndex() : make_pair(false,0);
228 // Top-level configuration implementation
229 class SHIBSP_DLLLOCAL XMLConfig;
230 class SHIBSP_DLLLOCAL XMLConfigImpl : public DOMPropertySet, public DOMNodeFilter
233 XMLConfigImpl(const DOMElement* e, bool first, const XMLConfig* outer, Category& log);
236 RequestMapper* m_requestMapper;
237 map<string,Application*> m_appmap;
239 map< string,pair< PropertySet*,vector<const SecurityPolicyRule*> > > m_policyMap;
240 vector< pair< string, pair<string,string> > > m_transportOptions;
243 // Provides filter to exclude special config elements.
244 #ifdef SHIBSP_XERCESC_SHORT_ACCEPTNODE
249 acceptNode(const DOMNode* node) const;
251 void setDocument(DOMDocument* doc) {
256 void doExtensions(const DOMElement* e, const char* label, Category& log);
259 const XMLConfig* m_outer;
260 DOMDocument* m_document;
263 class SHIBSP_DLLLOCAL XMLConfig : public ServiceProvider, public ReloadableXMLFile
269 XMLConfig(const DOMElement* e) : ReloadableXMLFile(e, Category::getInstance(SHIBSP_LOGCAT".Config")),
270 m_impl(NULL), m_listener(NULL), m_sessionCache(NULL)
283 delete m_sessionCache;
287 SAMLConfig::getConfig().setArtifactMap(NULL);
288 XMLToolingConfig::getConfig().setReplayCache(NULL);
289 for_each(m_storage.begin(), m_storage.end(), cleanup_pair<string,StorageService>());
294 const PropertySet* getParent() const { return m_impl->getParent(); }
295 void setParent(const PropertySet* parent) {return m_impl->setParent(parent);}
296 pair<bool,bool> getBool(const char* name, const char* ns=NULL) const {return m_impl->getBool(name,ns);}
297 pair<bool,const char*> getString(const char* name, const char* ns=NULL) const {return m_impl->getString(name,ns);}
298 pair<bool,const XMLCh*> getXMLString(const char* name, const char* ns=NULL) const {return m_impl->getXMLString(name,ns);}
299 pair<bool,unsigned int> getUnsignedInt(const char* name, const char* ns=NULL) const {return m_impl->getUnsignedInt(name,ns);}
300 pair<bool,int> getInt(const char* name, const char* ns=NULL) const {return m_impl->getInt(name,ns);}
301 void getAll(map<string,const char*>& properties) const {return m_impl->getAll(properties);}
302 const PropertySet* getPropertySet(const char* name, const char* ns="urn:mace:shibboleth:2.0:native:sp:config") const {return m_impl->getPropertySet(name,ns);}
303 const DOMElement* getElement() const {return m_impl->getElement();}
308 void receive(DDF& in, ostream& out);
310 TransactionLog* getTransactionLog() const {
313 throw ConfigurationException("No TransactionLog available.");
316 StorageService* getStorageService(const char* id) const {
318 map<string,StorageService*>::const_iterator i=m_storage.find(id);
319 if (i!=m_storage.end())
326 ListenerService* getListenerService(bool required=true) const {
327 if (required && !m_listener)
328 throw ConfigurationException("No ListenerService available.");
332 SessionCache* getSessionCache(bool required=true) const {
333 if (required && !m_sessionCache)
334 throw ConfigurationException("No SessionCache available.");
335 return m_sessionCache;
338 RequestMapper* getRequestMapper(bool required=true) const {
339 if (required && !m_impl->m_requestMapper)
340 throw ConfigurationException("No RequestMapper available.");
341 return m_impl->m_requestMapper;
344 const Application* getApplication(const char* applicationId) const {
345 map<string,Application*>::const_iterator i=m_impl->m_appmap.find(applicationId);
346 return (i!=m_impl->m_appmap.end()) ? i->second : NULL;
350 const PropertySet* getPolicySettings(const char* id) const {
351 map<string,pair<PropertySet*,vector<const SecurityPolicyRule*> > >::const_iterator i = m_impl->m_policyMap.find(id);
352 if (i!=m_impl->m_policyMap.end())
353 return i->second.first;
354 throw ConfigurationException("Security Policy ($1) not found, check <SecurityPolicies> element.", params(1,id));
357 const vector<const SecurityPolicyRule*>& getPolicyRules(const char* id) const {
358 map<string,pair<PropertySet*,vector<const SecurityPolicyRule*> > >::const_iterator i = m_impl->m_policyMap.find(id);
359 if (i!=m_impl->m_policyMap.end())
360 return i->second.second;
361 throw ConfigurationException("Security Policy ($1) not found, check <SecurityPolicies> element.", params(1,id));
364 bool setTransportOptions(SOAPTransport& transport) const {
366 vector< pair< string, pair<string,string> > >::const_iterator opt;
367 for (opt = m_impl->m_transportOptions.begin(); opt != m_impl->m_transportOptions.end(); ++opt) {
368 if (!transport.setProviderOption(opt->first.c_str(), opt->second.first.c_str(), opt->second.second.c_str())) {
369 m_log.error("failed to set SOAPTransport option (%s)", opt->second.first.c_str());
378 pair<bool,DOMElement*> load();
381 friend class XMLConfigImpl;
382 XMLConfigImpl* m_impl;
383 mutable ListenerService* m_listener;
384 mutable SessionCache* m_sessionCache;
386 mutable TransactionLog* m_tranLog;
387 mutable map<string,StorageService*> m_storage;
391 #if defined (_MSC_VER)
392 #pragma warning( pop )
395 static const XMLCh ApplicationOverride[] = UNICODE_LITERAL_19(A,p,p,l,i,c,a,t,i,o,n,O,v,e,r,r,i,d,e);
396 static const XMLCh ApplicationDefaults[] = UNICODE_LITERAL_19(A,p,p,l,i,c,a,t,i,o,n,D,e,f,a,u,l,t,s);
397 static const XMLCh _ArtifactMap[] = UNICODE_LITERAL_11(A,r,t,i,f,a,c,t,M,a,p);
398 static const XMLCh _AttributeExtractor[] = UNICODE_LITERAL_18(A,t,t,r,i,b,u,t,e,E,x,t,r,a,c,t,o,r);
399 static const XMLCh _AttributeFilter[] = UNICODE_LITERAL_15(A,t,t,r,i,b,u,t,e,F,i,l,t,e,r);
400 static const XMLCh _AttributeResolver[] = UNICODE_LITERAL_17(A,t,t,r,i,b,u,t,e,R,e,s,o,l,v,e,r);
401 static const XMLCh _AssertionConsumerService[] = UNICODE_LITERAL_24(A,s,s,e,r,t,i,o,n,C,o,n,s,u,m,e,r,S,e,r,v,i,c,e);
402 static const XMLCh _ArtifactResolutionService[] =UNICODE_LITERAL_25(A,r,t,i,f,a,c,t,R,e,s,o,l,u,t,i,o,n,S,e,r,v,i,c,e);
403 static const XMLCh _Audience[] = UNICODE_LITERAL_8(A,u,d,i,e,n,c,e);
404 static const XMLCh Binding[] = UNICODE_LITERAL_7(B,i,n,d,i,n,g);
405 static const XMLCh Channel[]= UNICODE_LITERAL_7(C,h,a,n,n,e,l);
406 static const XMLCh _CredentialResolver[] = UNICODE_LITERAL_18(C,r,e,d,e,n,t,i,a,l,R,e,s,o,l,v,e,r);
407 static const XMLCh _Extensions[] = UNICODE_LITERAL_10(E,x,t,e,n,s,i,o,n,s);
408 static const XMLCh _fatal[] = UNICODE_LITERAL_5(f,a,t,a,l);
409 static const XMLCh _Handler[] = UNICODE_LITERAL_7(H,a,n,d,l,e,r);
410 static const XMLCh _id[] = UNICODE_LITERAL_2(i,d);
411 static const XMLCh InProcess[] = UNICODE_LITERAL_9(I,n,P,r,o,c,e,s,s);
412 static const XMLCh Library[] = UNICODE_LITERAL_7(L,i,b,r,a,r,y);
413 static const XMLCh Listener[] = UNICODE_LITERAL_8(L,i,s,t,e,n,e,r);
414 static const XMLCh Location[] = UNICODE_LITERAL_8(L,o,c,a,t,i,o,n);
415 static const XMLCh logger[] = UNICODE_LITERAL_6(l,o,g,g,e,r);
416 static const XMLCh _LogoutInitiator[] = UNICODE_LITERAL_15(L,o,g,o,u,t,I,n,i,t,i,a,t,o,r);
417 static const XMLCh _ManageNameIDService[] = UNICODE_LITERAL_19(M,a,n,a,g,e,N,a,m,e,I,D,S,e,r,v,i,c,e);
418 static const XMLCh _MetadataProvider[] = UNICODE_LITERAL_16(M,e,t,a,d,a,t,a,P,r,o,v,i,d,e,r);
419 static const XMLCh Notify[] = UNICODE_LITERAL_6(N,o,t,i,f,y);
420 static const XMLCh _option[] = UNICODE_LITERAL_6(o,p,t,i,o,n);
421 static const XMLCh OutOfProcess[] = UNICODE_LITERAL_12(O,u,t,O,f,P,r,o,c,e,s,s);
422 static const XMLCh _path[] = UNICODE_LITERAL_4(p,a,t,h);
423 static const XMLCh Policy[] = UNICODE_LITERAL_6(P,o,l,i,c,y);
424 static const XMLCh PolicyRule[] = UNICODE_LITERAL_10(P,o,l,i,c,y,R,u,l,e);
425 static const XMLCh _provider[] = UNICODE_LITERAL_8(p,r,o,v,i,d,e,r);
426 static const XMLCh RelyingParty[] = UNICODE_LITERAL_12(R,e,l,y,i,n,g,P,a,r,t,y);
427 static const XMLCh _ReplayCache[] = UNICODE_LITERAL_11(R,e,p,l,a,y,C,a,c,h,e);
428 static const XMLCh _RequestMapper[] = UNICODE_LITERAL_13(R,e,q,u,e,s,t,M,a,p,p,e,r);
429 static const XMLCh Rule[] = UNICODE_LITERAL_4(R,u,l,e);
430 static const XMLCh SecurityPolicies[] = UNICODE_LITERAL_16(S,e,c,u,r,i,t,y,P,o,l,i,c,i,e,s);
431 static const XMLCh _SessionCache[] = UNICODE_LITERAL_12(S,e,s,s,i,o,n,C,a,c,h,e);
432 static const XMLCh _SessionInitiator[] = UNICODE_LITERAL_16(S,e,s,s,i,o,n,I,n,i,t,i,a,t,o,r);
433 static const XMLCh _SingleLogoutService[] = UNICODE_LITERAL_19(S,i,n,g,l,e,L,o,g,o,u,t,S,e,r,v,i,c,e);
434 static const XMLCh Site[] = UNICODE_LITERAL_4(S,i,t,e);
435 static const XMLCh _StorageService[] = UNICODE_LITERAL_14(S,t,o,r,a,g,e,S,e,r,v,i,c,e);
436 static const XMLCh TCPListener[] = UNICODE_LITERAL_11(T,C,P,L,i,s,t,e,n,e,r);
437 static const XMLCh TransportOption[] = UNICODE_LITERAL_15(T,r,a,n,s,p,o,r,t,O,p,t,i,o,n);
438 static const XMLCh _TrustEngine[] = UNICODE_LITERAL_11(T,r,u,s,t,E,n,g,i,n,e);
439 static const XMLCh _type[] = UNICODE_LITERAL_4(t,y,p,e);
440 static const XMLCh UnixListener[] = UNICODE_LITERAL_12(U,n,i,x,L,i,s,t,e,n,e,r);
443 class SHIBSP_DLLLOCAL PolicyNodeFilter : public DOMNodeFilter
446 #ifdef SHIBSP_XERCESC_SHORT_ACCEPTNODE
451 acceptNode(const DOMNode* node) const {
452 return FILTER_REJECT;
459 ServiceProvider* XMLServiceProviderFactory(const DOMElement* const & e)
461 return new XMLConfig(e);
465 XMLApplication::XMLApplication(
466 const ServiceProvider* sp,
468 const XMLApplication* base
469 ) : Application(sp), m_base(base),
471 m_metadata(NULL), m_trust(NULL),
472 m_attrExtractor(NULL), m_attrFilter(NULL), m_attrResolver(NULL),
473 m_credResolver(NULL),
475 m_acsDefault(NULL), m_sessionInitDefault(NULL), m_artifactResolutionDefault(NULL)
478 xmltooling::NDC ndc("XMLApplication");
480 Category& log=Category::getInstance(SHIBSP_LOGCAT".Application");
483 // First load any property sets.
488 SPConfig& conf=SPConfig::getConfig();
490 SAMLConfig& samlConf=SAMLConfig::getConfig();
491 XMLToolingConfig& xmlConf=XMLToolingConfig::getConfig();
494 // This used to be an actual hash, but now it's just a hex-encode to avoid xmlsec.
495 static char DIGITS[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
496 string tohash=getId();
497 tohash+=getString("entityID").second;
498 for (const char* ch = tohash.c_str(); *ch; ++ch) {
499 m_hash += (DIGITS[((unsigned char)(0xF0 & *ch)) >> 4 ]);
500 m_hash += (DIGITS[0x0F & *ch]);
503 // Populate prefix pair.
504 m_attributePrefix.second = "HTTP_";
505 pair<bool,const char*> prefix = getString("attributePrefix");
507 m_attributePrefix.first = prefix.second;
508 const char* pch = prefix.second;
510 m_attributePrefix.second += (isalnum(*pch) ? toupper(*pch) : '_');
515 // Load attribute ID lists for REMOTE_USER and header clearing.
516 if (conf.isEnabled(SPConfig::InProcess)) {
517 pair<bool,const char*> attributes = getString("REMOTE_USER");
518 if (attributes.first) {
519 char* dup = strdup(attributes.second);
522 while (start && *start) {
523 while (*start && isspace(*start))
527 pos = strchr(start,' ');
530 m_remoteUsers.push_back(start);
531 start = pos ? pos+1 : NULL;
536 attributes = getString("unsetHeaders");
537 if (attributes.first) {
538 string transformedprefix(m_attributePrefix.second);
540 prefix = getString("metadataAttributePrefix");
544 transformedprefix += (isalnum(*pch) ? toupper(*pch) : '_');
548 char* dup = strdup(attributes.second);
551 while (start && *start) {
552 while (*start && isspace(*start))
556 pos = strchr(start,' ');
563 transformed += (isalnum(*pch) ? toupper(*pch) : '_');
567 m_unsetHeaders.push_back(pair<string,string>(m_attributePrefix.first + start, m_attributePrefix.second + transformed));
569 m_unsetHeaders.push_back(pair<string,string>(m_attributePrefix.first + prefix.second + start, transformedprefix + transformed));
570 start = pos ? pos+1 : NULL;
573 m_unsetHeaders.push_back(pair<string,string>(m_attributePrefix.first + "Shib-Application-ID", m_attributePrefix.second + "SHIB_APPLICATION_ID"));
577 Handler* handler=NULL;
578 const PropertySet* sessions = getPropertySet("Sessions");
580 // Process assertion export handler.
581 pair<bool,const char*> location = sessions ? sessions->getString("exportLocation") : pair<bool,const char*>(false,NULL);
582 if (location.first) {
584 DOMElement* exportElement = e->getOwnerDocument()->createElementNS(shibspconstants::SHIB2SPCONFIG_NS,_Handler);
585 exportElement->setAttributeNS(NULL,Location,sessions->getXMLString("exportLocation").second);
586 pair<bool,const XMLCh*> exportACL = sessions->getXMLString("exportACL");
587 if (exportACL.first) {
588 static const XMLCh _acl[] = UNICODE_LITERAL_9(e,x,p,o,r,t,A,C,L);
589 exportElement->setAttributeNS(NULL,_acl,exportACL.second);
591 handler = conf.HandlerManager.newPlugin(
592 samlconstants::SAML20_BINDING_URI, pair<const DOMElement*,const char*>(exportElement, getId())
594 m_handlers.push_back(handler);
596 // Insert into location map. If it contains the handlerURL, we skip past that part.
597 const char* pch = strstr(location.second, sessions->getString("handlerURL").second);
599 location.second = pch + strlen(sessions->getString("handlerURL").second);
600 if (*location.second == '/')
601 m_handlerMap[location.second]=handler;
603 m_handlerMap[string("/") + location.second]=handler;
605 catch (exception& ex) {
606 log.error("caught exception installing assertion lookup handler: %s", ex.what());
610 // Process other handlers.
611 bool hardACS=false, hardSessionInit=false, hardArt=false;
612 const DOMElement* child = sessions ? XMLHelper::getFirstChildElement(sessions->getElement()) : NULL;
615 // A handler is based on the Binding property in conjunction with the element name.
616 // If it's an ACS or SI, also handle index/id mappings and defaulting.
617 if (XMLString::equals(child->getLocalName(),_AssertionConsumerService)) {
618 auto_ptr_char bindprop(child->getAttributeNS(NULL,Binding));
619 if (!bindprop.get() || !*(bindprop.get())) {
620 log.warn("md:AssertionConsumerService element has no Binding attribute, skipping it...");
621 child = XMLHelper::getNextSiblingElement(child);
624 handler=conf.AssertionConsumerServiceManager.newPlugin(bindprop.get(),make_pair(child, getId()));
625 // Map by binding (may be > 1 per binding, e.g. SAML 1.0 vs 1.1)
626 m_acsBindingMap[handler->getXMLString("Binding").second].push_back(handler);
627 m_acsIndexMap[handler->getUnsignedInt("index").second]=handler;
630 pair<bool,bool> defprop=handler->getBool("isDefault");
632 if (defprop.second) {
634 m_acsDefault=handler;
637 else if (!m_acsDefault)
638 m_acsDefault=handler;
641 else if (XMLString::equals(child->getLocalName(),_SessionInitiator)) {
642 auto_ptr_char type(child->getAttributeNS(NULL,_type));
643 if (!type.get() || !*(type.get())) {
644 log.warn("SessionInitiator element has no type attribute, skipping it...");
645 child = XMLHelper::getNextSiblingElement(child);
648 SessionInitiator* sihandler=conf.SessionInitiatorManager.newPlugin(type.get(),make_pair(child, getId()));
650 pair<bool,const char*> si_id=handler->getString("id");
651 if (si_id.first && si_id.second)
652 m_sessionInitMap[si_id.second]=sihandler;
653 if (!hardSessionInit) {
654 pair<bool,bool> defprop=handler->getBool("isDefault");
656 if (defprop.second) {
657 hardSessionInit=true;
658 m_sessionInitDefault=sihandler;
661 else if (!m_sessionInitDefault)
662 m_sessionInitDefault=sihandler;
665 else if (XMLString::equals(child->getLocalName(),_LogoutInitiator)) {
666 auto_ptr_char type(child->getAttributeNS(NULL,_type));
667 if (!type.get() || !*(type.get())) {
668 log.warn("LogoutInitiator element has no type attribute, skipping it...");
669 child = XMLHelper::getNextSiblingElement(child);
672 handler=conf.LogoutInitiatorManager.newPlugin(type.get(),make_pair(child, getId()));
674 else if (XMLString::equals(child->getLocalName(),_ArtifactResolutionService)) {
675 auto_ptr_char bindprop(child->getAttributeNS(NULL,Binding));
676 if (!bindprop.get() || !*(bindprop.get())) {
677 log.warn("md:ArtifactResolutionService element has no Binding attribute, skipping it...");
678 child = XMLHelper::getNextSiblingElement(child);
681 handler=conf.ArtifactResolutionServiceManager.newPlugin(bindprop.get(),make_pair(child, getId()));
684 pair<bool,bool> defprop=handler->getBool("isDefault");
686 if (defprop.second) {
688 m_artifactResolutionDefault=handler;
691 else if (!m_artifactResolutionDefault)
692 m_artifactResolutionDefault=handler;
695 else if (XMLString::equals(child->getLocalName(),_SingleLogoutService)) {
696 auto_ptr_char bindprop(child->getAttributeNS(NULL,Binding));
697 if (!bindprop.get() || !*(bindprop.get())) {
698 log.warn("md:SingleLogoutService element has no Binding attribute, skipping it...");
699 child = XMLHelper::getNextSiblingElement(child);
702 handler=conf.SingleLogoutServiceManager.newPlugin(bindprop.get(),make_pair(child, getId()));
704 else if (XMLString::equals(child->getLocalName(),_ManageNameIDService)) {
705 auto_ptr_char bindprop(child->getAttributeNS(NULL,Binding));
706 if (!bindprop.get() || !*(bindprop.get())) {
707 log.warn("md:ManageNameIDService element has no Binding attribute, skipping it...");
708 child = XMLHelper::getNextSiblingElement(child);
711 handler=conf.ManageNameIDServiceManager.newPlugin(bindprop.get(),make_pair(child, getId()));
714 auto_ptr_char type(child->getAttributeNS(NULL,_type));
715 if (!type.get() || !*(type.get())) {
716 log.warn("Handler element has no type attribute, skipping it...");
717 child = XMLHelper::getNextSiblingElement(child);
720 handler=conf.HandlerManager.newPlugin(type.get(),make_pair(child, getId()));
723 m_handlers.push_back(handler);
725 // Insert into location map.
726 location=handler->getString("Location");
727 if (location.first && *location.second == '/')
728 m_handlerMap[location.second]=handler;
729 else if (location.first)
730 m_handlerMap[string("/") + location.second]=handler;
733 catch (exception& ex) {
734 log.error("caught exception processing handler element: %s", ex.what());
737 child = XMLHelper::getNextSiblingElement(child);
741 DOMNodeList* nlist=e->getElementsByTagNameNS(shibspconstants::SHIB2SPCONFIG_NS,Notify);
742 for (XMLSize_t i=0; nlist && i<nlist->getLength(); i++) {
743 if (nlist->item(i)->getParentNode()->isSameNode(e)) {
744 const XMLCh* channel = static_cast<DOMElement*>(nlist->item(i))->getAttributeNS(NULL,Channel);
745 auto_ptr_char loc(static_cast<DOMElement*>(nlist->item(i))->getAttributeNS(NULL,Location));
746 if (loc.get() && *loc.get()) {
747 if (channel && *channel == chLatin_f)
748 m_frontLogout.push_back(loc.get());
750 m_backLogout.push_back(loc.get());
756 nlist=e->getElementsByTagNameNS(samlconstants::SAML20_NS,Audience::LOCAL_NAME);
757 if (nlist && nlist->getLength()) {
758 log.warn("use of <saml:Audience> elements outside of a Security Policy Rule is deprecated");
759 for (XMLSize_t i=0; i<nlist->getLength(); i++)
760 if (nlist->item(i)->getParentNode()->isSameNode(e) && nlist->item(i)->hasChildNodes())
761 m_audiences.push_back(nlist->item(i)->getFirstChild()->getNodeValue());
764 if (conf.isEnabled(SPConfig::Metadata)) {
765 child = XMLHelper::getFirstChildElement(e,_MetadataProvider);
767 auto_ptr_char type(child->getAttributeNS(NULL,_type));
768 log.info("building MetadataProvider of type %s...",type.get());
770 auto_ptr<MetadataProvider> mp(samlConf.MetadataProviderManager.newPlugin(type.get(),child));
772 m_metadata = mp.release();
774 catch (exception& ex) {
775 log.crit("error building/initializing MetadataProvider: %s", ex.what());
780 if (conf.isEnabled(SPConfig::Trust)) {
781 child = XMLHelper::getFirstChildElement(e,_TrustEngine);
783 auto_ptr_char type(child->getAttributeNS(NULL,_type));
784 log.info("building TrustEngine of type %s...",type.get());
786 m_trust = xmlConf.TrustEngineManager.newPlugin(type.get(),child);
788 catch (exception& ex) {
789 log.crit("error building TrustEngine: %s", ex.what());
794 if (conf.isEnabled(SPConfig::AttributeResolution)) {
795 child = XMLHelper::getFirstChildElement(e,_AttributeExtractor);
797 auto_ptr_char type(child->getAttributeNS(NULL,_type));
798 log.info("building AttributeExtractor of type %s...",type.get());
800 m_attrExtractor = conf.AttributeExtractorManager.newPlugin(type.get(),child);
802 catch (exception& ex) {
803 log.crit("error building AttributeExtractor: %s", ex.what());
807 child = XMLHelper::getFirstChildElement(e,_AttributeFilter);
809 auto_ptr_char type(child->getAttributeNS(NULL,_type));
810 log.info("building AttributeFilter of type %s...",type.get());
812 m_attrFilter = conf.AttributeFilterManager.newPlugin(type.get(),child);
814 catch (exception& ex) {
815 log.crit("error building AttributeFilter: %s", ex.what());
819 child = XMLHelper::getFirstChildElement(e,_AttributeResolver);
821 auto_ptr_char type(child->getAttributeNS(NULL,_type));
822 log.info("building AttributeResolver of type %s...",type.get());
824 m_attrResolver = conf.AttributeResolverManager.newPlugin(type.get(),child);
826 catch (exception& ex) {
827 log.crit("error building AttributeResolver: %s", ex.what());
831 if (m_unsetHeaders.empty()) {
832 vector<string> unsetHeaders;
833 if (m_attrExtractor) {
834 Locker extlock(m_attrExtractor);
835 m_attrExtractor->getAttributeIds(unsetHeaders);
837 else if (m_base && m_base->m_attrExtractor) {
838 Locker extlock(m_base->m_attrExtractor);
839 m_base->m_attrExtractor->getAttributeIds(unsetHeaders);
841 if (m_attrResolver) {
842 Locker reslock(m_attrResolver);
843 m_attrResolver->getAttributeIds(unsetHeaders);
845 else if (m_base && m_base->m_attrResolver) {
846 Locker extlock(m_base->m_attrResolver);
847 m_base->m_attrResolver->getAttributeIds(unsetHeaders);
849 if (!unsetHeaders.empty()) {
850 string transformedprefix(m_attributePrefix.second);
852 pair<bool,const char*> prefix = getString("metadataAttributePrefix");
856 transformedprefix += (isalnum(*pch) ? toupper(*pch) : '_');
860 for (vector<string>::const_iterator hdr = unsetHeaders.begin(); hdr!=unsetHeaders.end(); ++hdr) {
864 transformed += (isalnum(*pch) ? toupper(*pch) : '_');
867 m_unsetHeaders.push_back(pair<string,string>(m_attributePrefix.first + *hdr, m_attributePrefix.second + transformed));
869 m_unsetHeaders.push_back(pair<string,string>(m_attributePrefix.first + prefix.second + *hdr, transformedprefix + transformed));
872 m_unsetHeaders.push_back(pair<string,string>(m_attributePrefix.first + "Shib-Application-ID", m_attributePrefix.second + "SHIB_APPLICATION_ID"));
876 if (conf.isEnabled(SPConfig::Credentials)) {
877 child = XMLHelper::getFirstChildElement(e,_CredentialResolver);
879 auto_ptr_char type(child->getAttributeNS(NULL,_type));
880 log.info("building CredentialResolver of type %s...",type.get());
882 m_credResolver = xmlConf.CredentialResolverManager.newPlugin(type.get(),child);
884 catch (exception& ex) {
885 log.crit("error building CredentialResolver: %s", ex.what());
890 // Finally, load relying parties.
891 child = XMLHelper::getFirstChildElement(e,RelyingParty);
893 auto_ptr<DOMPropertySet> rp(new DOMPropertySet());
894 rp->load(child,NULL,this);
896 m_partyMap[child->getAttributeNS(NULL,saml2::Attribute::NAME_ATTRIB_NAME)]=rp.release();
897 child = XMLHelper::getNextSiblingElement(child,RelyingParty);
901 // Out of process only, we register a listener endpoint.
902 if (!conf.isEnabled(SPConfig::InProcess)) {
903 ListenerService* listener = sp->getListenerService(false);
905 string addr=string(getId()) + "::getHeaders::Application";
906 listener->regListener(addr.c_str(),this);
909 log.info("no ListenerService available, Application remoting disabled");
924 void XMLApplication::cleanup()
926 ListenerService* listener=getServiceProvider().getListenerService(false);
927 if (listener && SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess) && !SPConfig::getConfig().isEnabled(SPConfig::InProcess)) {
928 string addr=string(getId()) + "::getHeaders::Application";
929 listener->unregListener(addr.c_str(),this);
931 for_each(m_handlers.begin(),m_handlers.end(),xmltooling::cleanup<Handler>());
934 for_each(m_partyMap.begin(),m_partyMap.end(),cleanup_pair<xstring,PropertySet>());
936 delete m_credResolver;
937 m_credResolver = NULL;
938 delete m_attrResolver;
939 m_attrResolver = NULL;
942 delete m_attrExtractor;
943 m_attrExtractor = NULL;
951 #ifdef SHIBSP_XERCESC_SHORT_ACCEPTNODE
954 DOMNodeFilter::FilterAction
956 XMLApplication::acceptNode(const DOMNode* node) const
958 const XMLCh* name=node->getLocalName();
959 if (XMLString::equals(name,ApplicationOverride) ||
960 XMLString::equals(name,_Audience) ||
961 XMLString::equals(name,Notify) ||
962 XMLString::equals(name,_Handler) ||
963 XMLString::equals(name,_AssertionConsumerService) ||
964 XMLString::equals(name,_ArtifactResolutionService) ||
965 XMLString::equals(name,_LogoutInitiator) ||
966 XMLString::equals(name,_ManageNameIDService) ||
967 XMLString::equals(name,_SessionInitiator) ||
968 XMLString::equals(name,_SingleLogoutService) ||
969 XMLString::equals(name,RelyingParty) ||
970 XMLString::equals(name,_MetadataProvider) ||
971 XMLString::equals(name,_TrustEngine) ||
972 XMLString::equals(name,_CredentialResolver) ||
973 XMLString::equals(name,_AttributeFilter) ||
974 XMLString::equals(name,_AttributeExtractor) ||
975 XMLString::equals(name,_AttributeResolver))
976 return FILTER_REJECT;
978 return FILTER_ACCEPT;
983 const PropertySet* XMLApplication::getRelyingParty(const EntityDescriptor* provider) const
988 map<xstring,PropertySet*>::const_iterator i=m_partyMap.find(provider->getEntityID());
989 if (i!=m_partyMap.end())
991 const EntitiesDescriptor* group=dynamic_cast<const EntitiesDescriptor*>(provider->getParent());
993 if (group->getName()) {
994 i=m_partyMap.find(group->getName());
995 if (i!=m_partyMap.end())
998 group=dynamic_cast<const EntitiesDescriptor*>(group->getParent());
1003 const PropertySet* XMLApplication::getRelyingParty(const XMLCh* entityID) const
1008 map<xstring,PropertySet*>::const_iterator i=m_partyMap.find(entityID);
1009 if (i!=m_partyMap.end())
1016 string XMLApplication::getNotificationURL(const char* resource, bool front, unsigned int index) const
1018 const vector<string>& locs = front ? m_frontLogout : m_backLogout;
1020 return m_base ? m_base->getNotificationURL(resource, front, index) : string();
1021 else if (index >= locs.size())
1024 #ifdef HAVE_STRCASECMP
1025 if (!resource || (strncasecmp(resource,"http://",7) && strncasecmp(resource,"https://",8)))
1027 if (!resource || (strnicmp(resource,"http://",7) && strnicmp(resource,"https://",8)))
1029 throw ConfigurationException("Request URL was not absolute.");
1031 const char* handler=locs[index].c_str();
1033 // Should never happen...
1034 if (!handler || (*handler!='/' && strncmp(handler,"http:",5) && strncmp(handler,"https:",6)))
1035 throw ConfigurationException(
1036 "Invalid Location property ($1) in Notify element for Application ($2)",
1037 params(2, handler ? handler : "null", getId())
1040 // The "Location" property can be in one of three formats:
1042 // 1) a full URI: http://host/foo/bar
1043 // 2) a hostless URI: http:///foo/bar
1044 // 3) a relative path: /foo/bar
1046 // # Protocol Host Path
1047 // 1 handler handler handler
1048 // 2 handler resource handler
1049 // 3 resource resource handler
1051 const char* path = NULL;
1053 // Decide whether to use the handler or the resource for the "protocol"
1055 if (*handler != '/') {
1063 // break apart the "protocol" string into protocol, host, and "the rest"
1064 const char* colon=strchr(prot,':');
1066 const char* slash=strchr(colon,'/');
1070 // Compute the actual protocol and store.
1071 string notifyURL(prot, colon-prot);
1073 // create the "host" from either the colon/slash or from the target string
1074 // If prot == handler then we're in either #1 or #2, else #3.
1075 // If slash == colon then we're in #2.
1076 if (prot != handler || slash == colon) {
1077 colon = strchr(resource, ':');
1078 colon += 3; // Get past the ://
1079 slash = strchr(colon, '/');
1081 string host(colon, (slash ? slash-colon : strlen(colon)));
1084 notifyURL += host + path;
1088 void XMLApplication::clearHeader(SPRequest& request, const char* rawname, const char* cginame) const
1090 if (!m_attributePrefix.first.empty()) {
1091 string temp = m_attributePrefix.first + rawname;
1092 string temp2 = m_attributePrefix.second + (cginame + 5);
1093 request.clearHeader(temp.c_str(), temp2.c_str());
1096 m_base->clearHeader(request, rawname, cginame);
1099 request.clearHeader(rawname, cginame);
1103 void XMLApplication::setHeader(SPRequest& request, const char* name, const char* value) const
1105 if (!m_attributePrefix.first.empty()) {
1106 string temp = m_attributePrefix.first + name;
1107 request.setHeader(temp.c_str(), value);
1110 m_base->setHeader(request, name, value);
1113 request.setHeader(name, value);
1117 string XMLApplication::getSecureHeader(const SPRequest& request, const char* name) const
1119 if (!m_attributePrefix.first.empty()) {
1120 string temp = m_attributePrefix.first + name;
1121 return request.getSecureHeader(temp.c_str());
1124 return m_base->getSecureHeader(request,name);
1127 return request.getSecureHeader(name);
1131 const SessionInitiator* XMLApplication::getDefaultSessionInitiator() const
1133 if (m_sessionInitDefault) return m_sessionInitDefault;
1134 return m_base ? m_base->getDefaultSessionInitiator() : NULL;
1137 const SessionInitiator* XMLApplication::getSessionInitiatorById(const char* id) const
1139 map<string,const SessionInitiator*>::const_iterator i=m_sessionInitMap.find(id);
1140 if (i!=m_sessionInitMap.end()) return i->second;
1141 return m_base ? m_base->getSessionInitiatorById(id) : NULL;
1144 const Handler* XMLApplication::getDefaultAssertionConsumerService() const
1146 if (m_acsDefault) return m_acsDefault;
1147 return m_base ? m_base->getDefaultAssertionConsumerService() : NULL;
1150 const Handler* XMLApplication::getAssertionConsumerServiceByIndex(unsigned short index) const
1152 map<unsigned int,const Handler*>::const_iterator i=m_acsIndexMap.find(index);
1153 if (i!=m_acsIndexMap.end()) return i->second;
1154 return m_base ? m_base->getAssertionConsumerServiceByIndex(index) : NULL;
1157 const vector<const Handler*>& XMLApplication::getAssertionConsumerServicesByBinding(const XMLCh* binding) const
1159 ACSBindingMap::const_iterator i=m_acsBindingMap.find(binding);
1160 if (i!=m_acsBindingMap.end())
1162 return m_base ? m_base->getAssertionConsumerServicesByBinding(binding) : g_noHandlers;
1165 const Handler* XMLApplication::getHandler(const char* path) const
1168 wrap = wrap.substr(0,wrap.find(';'));
1169 map<string,const Handler*>::const_iterator i=m_handlerMap.find(wrap.substr(0,wrap.find('?')));
1170 if (i!=m_handlerMap.end())
1172 return m_base ? m_base->getHandler(path) : NULL;
1175 void XMLApplication::getHandlers(vector<const Handler*>& handlers) const
1177 handlers.insert(handlers.end(), m_handlers.begin(), m_handlers.end());
1179 for (map<string,const Handler*>::const_iterator h = m_base->m_handlerMap.begin(); h != m_base->m_handlerMap.end(); ++h) {
1180 if (m_handlerMap.count(h->first) == 0)
1181 handlers.push_back(h->second);
1186 #ifdef SHIBSP_XERCESC_SHORT_ACCEPTNODE
1189 DOMNodeFilter::FilterAction
1191 XMLConfigImpl::acceptNode(const DOMNode* node) const
1193 if (!XMLString::equals(node->getNamespaceURI(),shibspconstants::SHIB2SPCONFIG_NS))
1194 return FILTER_ACCEPT;
1195 const XMLCh* name=node->getLocalName();
1196 if (XMLString::equals(name,ApplicationDefaults) ||
1197 XMLString::equals(name,_ArtifactMap) ||
1198 XMLString::equals(name,_Extensions) ||
1199 XMLString::equals(name,Listener) ||
1200 XMLString::equals(name,_RequestMapper) ||
1201 XMLString::equals(name,_ReplayCache) ||
1202 XMLString::equals(name,SecurityPolicies) ||
1203 XMLString::equals(name,_SessionCache) ||
1204 XMLString::equals(name,Site) ||
1205 XMLString::equals(name,_StorageService) ||
1206 XMLString::equals(name,TCPListener) ||
1207 XMLString::equals(name,TransportOption) ||
1208 XMLString::equals(name,UnixListener))
1209 return FILTER_REJECT;
1211 return FILTER_ACCEPT;
1214 void XMLConfigImpl::doExtensions(const DOMElement* e, const char* label, Category& log)
1216 const DOMElement* exts=XMLHelper::getFirstChildElement(e,_Extensions);
1218 exts=XMLHelper::getFirstChildElement(exts,Library);
1220 auto_ptr_char path(exts->getAttributeNS(NULL,_path));
1223 if (!XMLToolingConfig::getConfig().load_library(path.get(),(void*)exts))
1224 throw ConfigurationException("XMLToolingConfig::load_library failed.");
1225 log.debug("loaded %s extension library (%s)", label, path.get());
1228 catch (exception& e) {
1229 const XMLCh* fatal=exts->getAttributeNS(NULL,_fatal);
1230 if (fatal && (*fatal==chLatin_t || *fatal==chDigit_1)) {
1231 log.fatal("unable to load mandatory %s extension library %s: %s", label, path.get(), e.what());
1235 log.crit("unable to load optional %s extension library %s: %s", label, path.get(), e.what());
1238 exts=XMLHelper::getNextSiblingElement(exts,Library);
1243 XMLConfigImpl::XMLConfigImpl(const DOMElement* e, bool first, const XMLConfig* outer, Category& log)
1244 : m_requestMapper(NULL), m_outer(outer), m_document(NULL)
1247 xmltooling::NDC ndc("XMLConfigImpl");
1251 SPConfig& conf=SPConfig::getConfig();
1253 SAMLConfig& samlConf=SAMLConfig::getConfig();
1255 XMLToolingConfig& xmlConf=XMLToolingConfig::getConfig();
1256 const DOMElement* SHAR=XMLHelper::getFirstChildElement(e,OutOfProcess);
1257 const DOMElement* SHIRE=XMLHelper::getFirstChildElement(e,InProcess);
1259 // Initialize log4cpp manually in order to redirect log messages as soon as possible.
1260 if (conf.isEnabled(SPConfig::Logging)) {
1261 const XMLCh* logconf=NULL;
1262 if (conf.isEnabled(SPConfig::OutOfProcess))
1263 logconf=SHAR->getAttributeNS(NULL,logger);
1264 else if (conf.isEnabled(SPConfig::InProcess))
1265 logconf=SHIRE->getAttributeNS(NULL,logger);
1266 if (!logconf || !*logconf)
1267 logconf=e->getAttributeNS(NULL,logger);
1268 if (logconf && *logconf) {
1269 auto_ptr_char logpath(logconf);
1270 log.debug("loading new logging configuration from (%s), check log destination for status of configuration",logpath.get());
1271 if (!XMLToolingConfig::getConfig().log_config(logpath.get()))
1272 log.crit("failed to load new logging configuration from (%s)", logpath.get());
1277 m_outer->m_tranLog = new TransactionLog();
1281 // Re-log library versions now that logging is set up.
1284 "Library versions: Xerces-C %s, XML-Security-C %s, XMLTooling-C %s, OpenSAML-C %s, Shibboleth %s",
1285 XERCES_FULLVERSIONDOT, XSEC_FULLVERSIONDOT, XMLTOOLING_FULLVERSIONDOT, OPENSAML_FULLVERSIONDOT, SHIBSP_FULLVERSIONDOT
1289 "Library versions: Xerces-C %s, XMLTooling-C %s, Shibboleth %s",
1290 XERCES_FULLVERSIONDOT, XMLTOOLING_FULLVERSIONDOT, SHIBSP_FULLVERSIONDOT
1294 // First load any property sets.
1297 const DOMElement* child;
1300 // Much of the processing can only occur on the first instantiation.
1303 pair<bool,unsigned int> skew=getUnsignedInt("clockSkew");
1305 xmlConf.clock_skew_secs=min(skew.second,(60*60*24*7*28));
1307 pair<bool,const char*> unsafe = getString("unsafeChars");
1309 TemplateEngine::unsafe_chars = unsafe.second;
1312 doExtensions(e, "global", log);
1313 if (conf.isEnabled(SPConfig::OutOfProcess))
1314 doExtensions(SHAR, "out of process", log);
1316 if (conf.isEnabled(SPConfig::InProcess))
1317 doExtensions(SHIRE, "in process", log);
1319 // Instantiate the ListenerService and SessionCache objects.
1320 if (conf.isEnabled(SPConfig::Listener)) {
1321 child=XMLHelper::getFirstChildElement(e,UnixListener);
1323 plugtype=UNIX_LISTENER_SERVICE;
1325 child=XMLHelper::getFirstChildElement(e,TCPListener);
1327 plugtype=TCP_LISTENER_SERVICE;
1329 child=XMLHelper::getFirstChildElement(e,Listener);
1331 auto_ptr_char type(child->getAttributeNS(NULL,_type));
1333 plugtype=type.get();
1338 log.info("building ListenerService of type %s...", plugtype.c_str());
1339 m_outer->m_listener = conf.ListenerServiceManager.newPlugin(plugtype.c_str(), child);
1342 log.fatal("can't build ListenerService, missing conf:Listener element?");
1343 throw ConfigurationException("Can't build ListenerService, missing conf:Listener element?");
1348 if (m_outer->m_listener && conf.isEnabled(SPConfig::OutOfProcess) && !conf.isEnabled(SPConfig::InProcess)) {
1349 m_outer->m_listener->regListener("set::RelayState", const_cast<XMLConfig*>(m_outer));
1350 m_outer->m_listener->regListener("get::RelayState", const_cast<XMLConfig*>(m_outer));
1351 m_outer->m_listener->regListener("set::PostData", const_cast<XMLConfig*>(m_outer));
1352 m_outer->m_listener->regListener("get::PostData", const_cast<XMLConfig*>(m_outer));
1356 if (conf.isEnabled(SPConfig::Caching)) {
1357 if (conf.isEnabled(SPConfig::OutOfProcess)) {
1359 // First build any StorageServices.
1360 child=XMLHelper::getFirstChildElement(e,_StorageService);
1362 auto_ptr_char id(child->getAttributeNS(NULL,_id));
1363 auto_ptr_char type(child->getAttributeNS(NULL,_type));
1365 log.info("building StorageService (%s) of type %s...", id.get(), type.get());
1366 m_outer->m_storage[id.get()] = xmlConf.StorageServiceManager.newPlugin(type.get(),child);
1368 catch (exception& ex) {
1369 log.crit("failed to instantiate StorageService (%s): %s", id.get(), ex.what());
1371 child=XMLHelper::getNextSiblingElement(child,_StorageService);
1375 StorageService* replaySS=NULL;
1376 child=XMLHelper::getFirstChildElement(e,_ReplayCache);
1378 auto_ptr_char ssid(child->getAttributeNS(NULL,_StorageService));
1379 if (ssid.get() && *ssid.get()) {
1380 if (m_outer->m_storage.count(ssid.get()))
1381 replaySS = m_outer->m_storage[ssid.get()];
1383 log.info("building ReplayCache on top of StorageService (%s)...", ssid.get());
1385 log.warn("unable to locate StorageService (%s) for ReplayCache, using dedicated in-memory instance", ssid.get());
1387 xmlConf.setReplayCache(new ReplayCache(replaySS));
1390 log.warn("no ReplayCache built, missing conf:ReplayCache element?");
1394 child=XMLHelper::getFirstChildElement(e,_ArtifactMap);
1396 auto_ptr_char ssid(child->getAttributeNS(NULL,_StorageService));
1397 if (ssid.get() && *ssid.get() && m_outer->m_storage.count(ssid.get())) {
1398 log.info("building ArtifactMap on top of StorageService (%s)...", ssid.get());
1399 samlConf.setArtifactMap(new ArtifactMap(child, m_outer->m_storage[ssid.get()]));
1402 if (samlConf.getArtifactMap()==NULL) {
1403 log.info("building in-memory ArtifactMap...");
1404 samlConf.setArtifactMap(new ArtifactMap(child));
1408 child=XMLHelper::getFirstChildElement(e,_SessionCache);
1410 auto_ptr_char type(child->getAttributeNS(NULL,_type));
1411 log.info("building SessionCache of type %s...",type.get());
1412 m_outer->m_sessionCache=conf.SessionCacheManager.newPlugin(type.get(), child);
1415 log.fatal("can't build SessionCache, missing conf:SessionCache element?");
1416 throw ConfigurationException("Can't build SessionCache, missing conf:SessionCache element?");
1419 } // end of first-time-only stuff
1421 // Back to the fully dynamic stuff...next up is the RequestMapper.
1422 if (conf.isEnabled(SPConfig::RequestMapping)) {
1423 child=XMLHelper::getFirstChildElement(e,_RequestMapper);
1425 auto_ptr_char type(child->getAttributeNS(NULL,_type));
1426 log.info("building RequestMapper of type %s...",type.get());
1427 m_requestMapper=conf.RequestMapperManager.newPlugin(type.get(),child);
1430 log.fatal("can't build RequestMapper, missing conf:RequestMapper element?");
1431 throw ConfigurationException("Can't build RequestMapper, missing conf:RequestMapper element?");
1436 // Load security policies.
1437 child = XMLHelper::getLastChildElement(e,SecurityPolicies);
1439 PolicyNodeFilter filter;
1440 child = XMLHelper::getFirstChildElement(child,Policy);
1442 auto_ptr_char id(child->getAttributeNS(NULL,_id));
1443 pair< PropertySet*,vector<const SecurityPolicyRule*> >& rules = m_policyMap[id.get()];
1445 auto_ptr<DOMPropertySet> settings(new DOMPropertySet());
1446 settings->load(child, NULL, &filter);
1447 rules.first = settings.release();
1449 // Process PolicyRule elements.
1450 const DOMElement* rule = XMLHelper::getFirstChildElement(child,PolicyRule);
1452 auto_ptr_char type(rule->getAttributeNS(NULL,_type));
1454 rules.second.push_back(samlConf.SecurityPolicyRuleManager.newPlugin(type.get(),rule));
1456 catch (exception& ex) {
1457 log.crit("error instantiating policy rule (%s) in policy (%s): %s", type.get(), id.get(), ex.what());
1459 rule = XMLHelper::getNextSiblingElement(rule,PolicyRule);
1462 if (rules.second.size() == 0) {
1463 // Process Rule elements.
1464 log.warn("detected legacy Policy configuration, please convert to new PolicyRule syntax");
1465 rule = XMLHelper::getFirstChildElement(child,Rule);
1467 auto_ptr_char type(rule->getAttributeNS(NULL,_type));
1469 rules.second.push_back(samlConf.SecurityPolicyRuleManager.newPlugin(type.get(),rule));
1471 catch (exception& ex) {
1472 log.crit("error instantiating policy rule (%s) in policy (%s): %s", type.get(), id.get(), ex.what());
1474 rule = XMLHelper::getNextSiblingElement(rule,Rule);
1477 // Manually add a basic Conditions rule.
1478 log.info("installing a default Conditions rule in policy (%s) for compatibility with legacy configuration", id.get());
1479 rules.second.push_back(samlConf.SecurityPolicyRuleManager.newPlugin(CONDITIONS_POLICY_RULE, NULL));
1482 child = XMLHelper::getNextSiblingElement(child,Policy);
1486 // Process TransportOption elements.
1487 child = XMLHelper::getLastChildElement(e,TransportOption);
1489 if (child->hasChildNodes()) {
1490 auto_ptr_char provider(child->getAttributeNS(NULL,_provider));
1491 auto_ptr_char option(child->getAttributeNS(NULL,_option));
1492 auto_ptr_char value(child->getFirstChild()->getNodeValue());
1493 if (provider.get() && *provider.get() && option.get() && *option.get() && value.get() && *value.get()) {
1494 m_transportOptions.push_back(make_pair(string(provider.get()), make_pair(string(option.get()), string(value.get()))));
1497 child = XMLHelper::getPreviousSiblingElement(child,TransportOption);
1501 // Load the default application. This actually has a fixed ID of "default". ;-)
1502 child=XMLHelper::getLastChildElement(e,ApplicationDefaults);
1504 log.fatal("can't build default Application object, missing conf:ApplicationDefaults element?");
1505 throw ConfigurationException("can't build default Application object, missing conf:ApplicationDefaults element?");
1507 XMLApplication* defapp=new XMLApplication(m_outer,child);
1508 m_appmap[defapp->getId()]=defapp;
1510 // Load any overrides.
1511 child = XMLHelper::getFirstChildElement(child,ApplicationOverride);
1513 auto_ptr<XMLApplication> iapp(new XMLApplication(m_outer,child,defapp));
1514 if (m_appmap.count(iapp->getId()))
1515 log.crit("found conf:ApplicationOverride element with duplicate id attribute (%s), skipping it", iapp->getId());
1517 const char* iappid=iapp->getId();
1518 m_appmap[iappid]=iapp.release();
1521 child = XMLHelper::getNextSiblingElement(child,ApplicationOverride);
1524 catch (exception&) {
1530 XMLConfigImpl::~XMLConfigImpl()
1535 void XMLConfigImpl::cleanup()
1537 for_each(m_appmap.begin(),m_appmap.end(),cleanup_pair<string,Application>());
1540 for (map< string,pair<PropertySet*,vector<const SecurityPolicyRule*> > >::iterator i=m_policyMap.begin(); i!=m_policyMap.end(); ++i) {
1541 delete i->second.first;
1542 for_each(i->second.second.begin(), i->second.second.end(), xmltooling::cleanup<SecurityPolicyRule>());
1544 m_policyMap.clear();
1546 delete m_requestMapper;
1547 m_requestMapper = NULL;
1549 m_document->release();
1554 void XMLConfig::receive(DDF& in, ostream& out)
1556 if (!strcmp(in.name(), "get::RelayState")) {
1557 const char* id = in["id"].string();
1558 const char* key = in["key"].string();
1560 throw ListenerException("Required parameters missing for RelayState recovery.");
1563 StorageService* storage = getStorageService(id);
1565 if (storage->readString("RelayState",key,&relayState)>0) {
1566 if (in["clear"].integer())
1567 storage->deleteString("RelayState",key);
1571 Category::getInstance(SHIBSP_LOGCAT".ServiceProvider").error(
1572 "Storage-backed RelayState with invalid StorageService ID (%s)", id
1576 // Repack for return to caller.
1577 DDF ret=DDF(NULL).unsafe_string(relayState.c_str());
1578 DDFJanitor jret(ret);
1581 else if (!strcmp(in.name(), "set::RelayState")) {
1582 const char* id = in["id"].string();
1583 const char* value = in["value"].string();
1585 throw ListenerException("Required parameters missing for RelayState creation.");
1588 StorageService* storage = getStorageService(id);
1590 SAMLConfig::getConfig().generateRandomBytes(rsKey,20);
1591 rsKey = SAMLArtifact::toHex(rsKey);
1592 storage->createString("RelayState", rsKey.c_str(), value, time(NULL) + 600);
1595 Category::getInstance(SHIBSP_LOGCAT".ServiceProvider").error(
1596 "Storage-backed RelayState with invalid StorageService ID (%s)", id
1600 // Repack for return to caller.
1601 DDF ret=DDF(NULL).string(rsKey.c_str());
1602 DDFJanitor jret(ret);
1605 else if (!strcmp(in.name(), "get::PostData")) {
1606 const char* id = in["id"].string();
1607 const char* key = in["key"].string();
1609 throw ListenerException("Required parameters missing for PostData recovery.");
1612 StorageService* storage = getStorageService(id);
1614 if (storage->readString("PostData",key,&postData) > 0) {
1615 storage->deleteString("PostData",key);
1619 Category::getInstance(SHIBSP_LOGCAT".ServiceProvider").error(
1620 "Storage-backed PostData with invalid StorageService ID (%s)", id
1623 // If the data's empty, we'll send nothing back.
1624 // If not, we don't need to round trip it, just send back the serialized DDF list.
1625 if (postData.empty()) {
1627 DDFJanitor jret(ret);
1634 else if (!strcmp(in.name(), "set::PostData")) {
1635 const char* id = in["id"].string();
1636 if (!id || !in["parameters"].islist())
1637 throw ListenerException("Required parameters missing for PostData creation.");
1640 StorageService* storage = getStorageService(id);
1642 SAMLConfig::getConfig().generateRandomBytes(rsKey,20);
1643 rsKey = SAMLArtifact::toHex(rsKey);
1644 ostringstream params;
1645 params << in["parameters"];
1646 storage->createString("PostData", rsKey.c_str(), params.str().c_str(), time(NULL) + 600);
1649 Category::getInstance(SHIBSP_LOGCAT".ServiceProvider").error(
1650 "Storage-backed PostData with invalid StorageService ID (%s)", id
1654 // Repack for return to caller.
1655 DDF ret=DDF(NULL).string(rsKey.c_str());
1656 DDFJanitor jret(ret);
1662 pair<bool,DOMElement*> XMLConfig::load()
1664 // Load from source using base class.
1665 pair<bool,DOMElement*> raw = ReloadableXMLFile::load();
1667 // If we own it, wrap it.
1668 XercesJanitor<DOMDocument> docjanitor(raw.first ? raw.second->getOwnerDocument() : NULL);
1670 XMLConfigImpl* impl = new XMLConfigImpl(raw.second,(m_impl==NULL),this,m_log);
1672 // If we held the document, transfer it to the impl. If we didn't, it's a no-op.
1673 impl->setDocument(docjanitor.release());
1678 return make_pair(false,(DOMElement*)NULL);