2 * Copyright 2001-2010 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/Threads.h>
53 #include <xmltooling/util/XMLHelper.h>
56 # include "TransactionLog.h"
57 # include "attribute/filtering/AttributeFilter.h"
58 # include "attribute/resolver/AttributeExtractor.h"
59 # include "attribute/resolver/AttributeResolver.h"
60 # include "security/PKIXTrustEngine.h"
61 # include <saml/SAMLConfig.h>
62 # include <saml/version.h>
63 # include <saml/binding/ArtifactMap.h>
64 # include <saml/binding/SAMLArtifact.h>
65 # include <saml/binding/SecurityPolicyRule.h>
66 # include <saml/saml1/core/Assertions.h>
67 # include <saml/saml2/core/Assertions.h>
68 # include <saml/saml2/binding/SAML2ArtifactType0004.h>
69 # include <saml/saml2/metadata/Metadata.h>
70 # include <saml/saml2/metadata/MetadataProvider.h>
71 # include <saml/util/SAMLConstants.h>
72 # include <xmltooling/security/CredentialResolver.h>
73 # include <xmltooling/security/SecurityHelper.h>
74 # include <xmltooling/security/TrustEngine.h>
75 # include <xmltooling/util/ReplayCache.h>
76 # include <xmltooling/util/StorageService.h>
77 # include <xercesc/util/XMLStringTokenizer.hpp>
78 # include <xsec/utils/XSECPlatformUtils.hpp>
79 using namespace opensaml::saml2;
80 using namespace opensaml::saml2p;
81 using namespace opensaml::saml2md;
82 using namespace opensaml;
84 # include "lite/SAMLConstants.h"
87 using namespace shibsp;
88 using namespace xmltooling;
92 # define min(a,b) (((a) < (b)) ? (a) : (b))
97 #if defined (_MSC_VER)
98 #pragma warning( push )
99 #pragma warning( disable : 4250 )
102 static vector<const Handler*> g_noHandlers;
104 // Application configuration wrapper
105 class SHIBSP_DLLLOCAL XMLApplication : public Application, public Remoted, public DOMPropertySet, public DOMNodeFilter
108 XMLApplication(const ServiceProvider*, const DOMElement* e, const XMLApplication* base=nullptr);
109 ~XMLApplication() { cleanup(); }
111 const char* getHash() const {return m_hash.c_str();}
114 SAMLArtifact* generateSAML1Artifact(const EntityDescriptor* relyingParty) const {
115 throw ConfigurationException("No support for SAML 1.x artifact generation.");
117 SAML2Artifact* generateSAML2Artifact(const EntityDescriptor* relyingParty) const {
118 pair<bool,int> index = make_pair(false,0);
119 const PropertySet* props = getRelyingParty(relyingParty);
120 index = props->getInt("artifactEndpointIndex");
122 index = getArtifactEndpointIndex();
123 pair<bool,const char*> entityID = props->getString("entityID");
124 return new SAML2ArtifactType0004(
125 SecurityHelper::doHash("SHA1", entityID.second, strlen(entityID.second), false),
126 index.first ? index.second : 1
130 MetadataProvider* getMetadataProvider(bool required=true) const {
131 if (required && !m_base && !m_metadata)
132 throw ConfigurationException("No MetadataProvider available.");
133 return (!m_metadata && m_base) ? m_base->getMetadataProvider() : m_metadata;
135 TrustEngine* getTrustEngine(bool required=true) const {
136 if (required && !m_base && !m_trust)
137 throw ConfigurationException("No TrustEngine available.");
138 return (!m_trust && m_base) ? m_base->getTrustEngine() : m_trust;
140 AttributeExtractor* getAttributeExtractor() const {
141 return (!m_attrExtractor && m_base) ? m_base->getAttributeExtractor() : m_attrExtractor;
143 AttributeFilter* getAttributeFilter() const {
144 return (!m_attrFilter && m_base) ? m_base->getAttributeFilter() : m_attrFilter;
146 AttributeResolver* getAttributeResolver() const {
147 return (!m_attrResolver && m_base) ? m_base->getAttributeResolver() : m_attrResolver;
149 CredentialResolver* getCredentialResolver() const {
150 return (!m_credResolver && m_base) ? m_base->getCredentialResolver() : m_credResolver;
152 const PropertySet* getRelyingParty(const EntityDescriptor* provider) const;
153 const PropertySet* getRelyingParty(const XMLCh* entityID) const;
154 const vector<const XMLCh*>* getAudiences() const {
155 return (m_audiences.empty() && m_base) ? m_base->getAudiences() : &m_audiences;
158 string getNotificationURL(const char* resource, bool front, unsigned int index) const;
160 const vector<string>& getRemoteUserAttributeIds() const {
161 return (m_remoteUsers.empty() && m_base) ? m_base->getRemoteUserAttributeIds() : m_remoteUsers;
164 void clearHeader(SPRequest& request, const char* rawname, const char* cginame) const;
165 void setHeader(SPRequest& request, const char* name, const char* value) const;
166 string getSecureHeader(const SPRequest& request, const char* name) const;
168 const SessionInitiator* getDefaultSessionInitiator() const;
169 const SessionInitiator* getSessionInitiatorById(const char* id) const;
170 const Handler* getDefaultAssertionConsumerService() const;
171 const Handler* getAssertionConsumerServiceByIndex(unsigned short index) const;
172 const vector<const Handler*>& getAssertionConsumerServicesByBinding(const XMLCh* binding) const;
173 const Handler* getHandler(const char* path) const;
174 void getHandlers(vector<const Handler*>& handlers) const;
176 void receive(DDF& in, ostream& out) {
177 // Only current function is to return the headers to clear.
179 DDF ret=DDF(nullptr).list();
180 DDFJanitor jret(ret);
181 for (vector< pair<string,string> >::const_iterator i = m_unsetHeaders.begin(); i!=m_unsetHeaders.end(); ++i) {
182 header = DDF(i->first.c_str()).string(i->second.c_str());
188 // Provides filter to exclude special config elements.
189 #ifdef SHIBSP_XERCESC_SHORT_ACCEPTNODE
194 acceptNode(const DOMNode* node) const;
198 const XMLApplication* m_base;
200 std::pair<std::string,std::string> m_attributePrefix;
202 MetadataProvider* m_metadata;
203 TrustEngine* m_trust;
204 AttributeExtractor* m_attrExtractor;
205 AttributeFilter* m_attrFilter;
206 AttributeResolver* m_attrResolver;
207 CredentialResolver* m_credResolver;
208 vector<const XMLCh*> m_audiences;
210 // RelyingParty properties
211 map<xstring,PropertySet*> m_partyMap;
213 vector<string> m_remoteUsers,m_frontLogout,m_backLogout;
215 // manage handler objects
216 vector<Handler*> m_handlers;
218 // maps location (path info) to applicable handlers
219 map<string,const Handler*> m_handlerMap;
221 // maps unique indexes to consumer services
222 map<unsigned int,const Handler*> m_acsIndexMap;
224 // pointer to default consumer service
225 const Handler* m_acsDefault;
227 // maps binding strings to supporting consumer service(s)
228 typedef map<xstring,vector<const Handler*> > ACSBindingMap;
229 ACSBindingMap m_acsBindingMap;
231 // pointer to default session initiator
232 const SessionInitiator* m_sessionInitDefault;
234 // maps unique ID strings to session initiators
235 map<string,const SessionInitiator*> m_sessionInitMap;
237 // pointer to default artifact resolution service
238 const Handler* m_artifactResolutionDefault;
240 pair<bool,int> getArtifactEndpointIndex() const {
241 if (m_artifactResolutionDefault) return m_artifactResolutionDefault->getInt("index");
242 return m_base ? m_base->getArtifactEndpointIndex() : make_pair(false,0);
246 // Top-level configuration implementation
247 class SHIBSP_DLLLOCAL XMLConfig;
248 class SHIBSP_DLLLOCAL XMLConfigImpl : public DOMPropertySet, public DOMNodeFilter
251 XMLConfigImpl(const DOMElement* e, bool first, const XMLConfig* outer, Category& log);
254 RequestMapper* m_requestMapper;
255 map<string,Application*> m_appmap;
257 map< string,pair< PropertySet*,vector<const SecurityPolicyRule*> > > m_policyMap;
258 vector< pair< string, pair<string,string> > > m_transportOptions;
261 // Provides filter to exclude special config elements.
262 #ifdef SHIBSP_XERCESC_SHORT_ACCEPTNODE
267 acceptNode(const DOMNode* node) const;
269 void setDocument(DOMDocument* doc) {
274 void doExtensions(const DOMElement* e, const char* label, Category& log);
277 const XMLConfig* m_outer;
278 DOMDocument* m_document;
281 class SHIBSP_DLLLOCAL XMLConfig : public ServiceProvider, public ReloadableXMLFile
287 XMLConfig(const DOMElement* e) : ReloadableXMLFile(e, Category::getInstance(SHIBSP_LOGCAT".Config")),
288 m_impl(nullptr), m_listener(nullptr), m_sessionCache(nullptr)
302 delete m_sessionCache;
306 SAMLConfig::getConfig().setArtifactMap(nullptr);
307 XMLToolingConfig::getConfig().setReplayCache(nullptr);
308 for_each(m_storage.begin(), m_storage.end(), cleanup_pair<string,StorageService>());
313 const PropertySet* getParent() const { return m_impl->getParent(); }
314 void setParent(const PropertySet* parent) {return m_impl->setParent(parent);}
315 pair<bool,bool> getBool(const char* name, const char* ns=nullptr) const {return m_impl->getBool(name,ns);}
316 pair<bool,const char*> getString(const char* name, const char* ns=nullptr) const {return m_impl->getString(name,ns);}
317 pair<bool,const XMLCh*> getXMLString(const char* name, const char* ns=nullptr) const {return m_impl->getXMLString(name,ns);}
318 pair<bool,unsigned int> getUnsignedInt(const char* name, const char* ns=nullptr) const {return m_impl->getUnsignedInt(name,ns);}
319 pair<bool,int> getInt(const char* name, const char* ns=nullptr) const {return m_impl->getInt(name,ns);}
320 void getAll(map<string,const char*>& properties) const {return m_impl->getAll(properties);}
321 const PropertySet* getPropertySet(const char* name, const char* ns="urn:mace:shibboleth:2.0:native:sp:config") const {return m_impl->getPropertySet(name,ns);}
322 const DOMElement* getElement() const {return m_impl->getElement();}
327 void receive(DDF& in, ostream& out);
329 TransactionLog* getTransactionLog() const {
332 throw ConfigurationException("No TransactionLog available.");
335 StorageService* getStorageService(const char* id) const {
337 map<string,StorageService*>::const_iterator i=m_storage.find(id);
338 if (i!=m_storage.end())
345 ListenerService* getListenerService(bool required=true) const {
346 if (required && !m_listener)
347 throw ConfigurationException("No ListenerService available.");
351 SessionCache* getSessionCache(bool required=true) const {
352 if (required && !m_sessionCache)
353 throw ConfigurationException("No SessionCache available.");
354 return m_sessionCache;
357 RequestMapper* getRequestMapper(bool required=true) const {
358 if (required && !m_impl->m_requestMapper)
359 throw ConfigurationException("No RequestMapper available.");
360 return m_impl->m_requestMapper;
363 const Application* getApplication(const char* applicationId) const {
364 map<string,Application*>::const_iterator i=m_impl->m_appmap.find(applicationId);
365 return (i!=m_impl->m_appmap.end()) ? i->second : nullptr;
369 const PropertySet* getPolicySettings(const char* id) const {
370 map<string,pair<PropertySet*,vector<const SecurityPolicyRule*> > >::const_iterator i = m_impl->m_policyMap.find(id);
371 if (i!=m_impl->m_policyMap.end())
372 return i->second.first;
373 throw ConfigurationException("Security Policy ($1) not found, check <SecurityPolicies> element.", params(1,id));
376 const vector<const SecurityPolicyRule*>& getPolicyRules(const char* id) const {
377 map<string,pair<PropertySet*,vector<const SecurityPolicyRule*> > >::const_iterator i = m_impl->m_policyMap.find(id);
378 if (i!=m_impl->m_policyMap.end())
379 return i->second.second;
380 throw ConfigurationException("Security Policy ($1) not found, check <SecurityPolicies> element.", params(1,id));
383 bool setTransportOptions(SOAPTransport& transport) const {
385 vector< pair< string, pair<string,string> > >::const_iterator opt;
386 for (opt = m_impl->m_transportOptions.begin(); opt != m_impl->m_transportOptions.end(); ++opt) {
387 if (!transport.setProviderOption(opt->first.c_str(), opt->second.first.c_str(), opt->second.second.c_str())) {
388 m_log.error("failed to set SOAPTransport option (%s)", opt->second.first.c_str());
397 pair<bool,DOMElement*> background_load();
400 friend class XMLConfigImpl;
401 XMLConfigImpl* m_impl;
402 mutable ListenerService* m_listener;
403 mutable SessionCache* m_sessionCache;
405 mutable TransactionLog* m_tranLog;
406 mutable map<string,StorageService*> m_storage;
410 #if defined (_MSC_VER)
411 #pragma warning( pop )
414 static const XMLCh AlgorithmBlacklist[] = UNICODE_LITERAL_18(A,l,g,o,r,i,t,h,m,B,l,a,c,k,l,i,s,t);
415 static const XMLCh AlgorithmWhitelist[] = UNICODE_LITERAL_18(A,l,g,o,r,i,t,h,m,W,h,i,t,e,l,i,s,t);
416 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);
417 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);
418 static const XMLCh _ArtifactMap[] = UNICODE_LITERAL_11(A,r,t,i,f,a,c,t,M,a,p);
419 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);
420 static const XMLCh _AttributeFilter[] = UNICODE_LITERAL_15(A,t,t,r,i,b,u,t,e,F,i,l,t,e,r);
421 static const XMLCh _AttributeResolver[] = UNICODE_LITERAL_17(A,t,t,r,i,b,u,t,e,R,e,s,o,l,v,e,r);
422 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);
423 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);
424 static const XMLCh _Audience[] = UNICODE_LITERAL_8(A,u,d,i,e,n,c,e);
425 static const XMLCh Binding[] = UNICODE_LITERAL_7(B,i,n,d,i,n,g);
426 static const XMLCh Channel[]= UNICODE_LITERAL_7(C,h,a,n,n,e,l);
427 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);
428 static const XMLCh _Extensions[] = UNICODE_LITERAL_10(E,x,t,e,n,s,i,o,n,s);
429 static const XMLCh _fatal[] = UNICODE_LITERAL_5(f,a,t,a,l);
430 static const XMLCh _Handler[] = UNICODE_LITERAL_7(H,a,n,d,l,e,r);
431 static const XMLCh _id[] = UNICODE_LITERAL_2(i,d);
432 static const XMLCh InProcess[] = UNICODE_LITERAL_9(I,n,P,r,o,c,e,s,s);
433 static const XMLCh Library[] = UNICODE_LITERAL_7(L,i,b,r,a,r,y);
434 static const XMLCh Listener[] = UNICODE_LITERAL_8(L,i,s,t,e,n,e,r);
435 static const XMLCh Location[] = UNICODE_LITERAL_8(L,o,c,a,t,i,o,n);
436 static const XMLCh logger[] = UNICODE_LITERAL_6(l,o,g,g,e,r);
437 static const XMLCh _LogoutInitiator[] = UNICODE_LITERAL_15(L,o,g,o,u,t,I,n,i,t,i,a,t,o,r);
438 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);
439 static const XMLCh _MetadataProvider[] = UNICODE_LITERAL_16(M,e,t,a,d,a,t,a,P,r,o,v,i,d,e,r);
440 static const XMLCh Notify[] = UNICODE_LITERAL_6(N,o,t,i,f,y);
441 static const XMLCh _option[] = UNICODE_LITERAL_6(o,p,t,i,o,n);
442 static const XMLCh OutOfProcess[] = UNICODE_LITERAL_12(O,u,t,O,f,P,r,o,c,e,s,s);
443 static const XMLCh _path[] = UNICODE_LITERAL_4(p,a,t,h);
444 static const XMLCh Policy[] = UNICODE_LITERAL_6(P,o,l,i,c,y);
445 static const XMLCh PolicyRule[] = UNICODE_LITERAL_10(P,o,l,i,c,y,R,u,l,e);
446 static const XMLCh _provider[] = UNICODE_LITERAL_8(p,r,o,v,i,d,e,r);
447 static const XMLCh RelyingParty[] = UNICODE_LITERAL_12(R,e,l,y,i,n,g,P,a,r,t,y);
448 static const XMLCh _ReplayCache[] = UNICODE_LITERAL_11(R,e,p,l,a,y,C,a,c,h,e);
449 static const XMLCh _RequestMapper[] = UNICODE_LITERAL_13(R,e,q,u,e,s,t,M,a,p,p,e,r);
450 static const XMLCh Rule[] = UNICODE_LITERAL_4(R,u,l,e);
451 static const XMLCh SecurityPolicies[] = UNICODE_LITERAL_16(S,e,c,u,r,i,t,y,P,o,l,i,c,i,e,s);
452 static const XMLCh _SessionCache[] = UNICODE_LITERAL_12(S,e,s,s,i,o,n,C,a,c,h,e);
453 static const XMLCh _SessionInitiator[] = UNICODE_LITERAL_16(S,e,s,s,i,o,n,I,n,i,t,i,a,t,o,r);
454 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);
455 static const XMLCh Site[] = UNICODE_LITERAL_4(S,i,t,e);
456 static const XMLCh _StorageService[] = UNICODE_LITERAL_14(S,t,o,r,a,g,e,S,e,r,v,i,c,e);
457 static const XMLCh TCPListener[] = UNICODE_LITERAL_11(T,C,P,L,i,s,t,e,n,e,r);
458 static const XMLCh TransportOption[] = UNICODE_LITERAL_15(T,r,a,n,s,p,o,r,t,O,p,t,i,o,n);
459 static const XMLCh _TrustEngine[] = UNICODE_LITERAL_11(T,r,u,s,t,E,n,g,i,n,e);
460 static const XMLCh _type[] = UNICODE_LITERAL_4(t,y,p,e);
461 static const XMLCh UnixListener[] = UNICODE_LITERAL_12(U,n,i,x,L,i,s,t,e,n,e,r);
464 class SHIBSP_DLLLOCAL PolicyNodeFilter : public DOMNodeFilter
467 #ifdef SHIBSP_XERCESC_SHORT_ACCEPTNODE
472 acceptNode(const DOMNode* node) const {
473 return FILTER_REJECT;
480 ServiceProvider* XMLServiceProviderFactory(const DOMElement* const & e)
482 return new XMLConfig(e);
486 XMLApplication::XMLApplication(
487 const ServiceProvider* sp,
489 const XMLApplication* base
490 ) : Application(sp), m_base(base),
492 m_metadata(nullptr), m_trust(nullptr),
493 m_attrExtractor(nullptr), m_attrFilter(nullptr), m_attrResolver(nullptr),
494 m_credResolver(nullptr),
496 m_acsDefault(nullptr), m_sessionInitDefault(nullptr), m_artifactResolutionDefault(nullptr)
499 xmltooling::NDC ndc("XMLApplication");
501 Category& log=Category::getInstance(SHIBSP_LOGCAT".Application");
504 // First load any property sets.
505 load(e,nullptr,this);
509 SPConfig& conf=SPConfig::getConfig();
511 SAMLConfig& samlConf=SAMLConfig::getConfig();
512 XMLToolingConfig& xmlConf=XMLToolingConfig::getConfig();
515 // This used to be an actual hash, but now it's just a hex-encode to avoid xmlsec.
516 static char DIGITS[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
517 string tohash=getId();
518 tohash+=getString("entityID").second;
519 for (const char* ch = tohash.c_str(); *ch; ++ch) {
520 m_hash += (DIGITS[((unsigned char)(0xF0 & *ch)) >> 4 ]);
521 m_hash += (DIGITS[0x0F & *ch]);
524 // Populate prefix pair.
525 m_attributePrefix.second = "HTTP_";
526 pair<bool,const char*> prefix = getString("attributePrefix");
528 m_attributePrefix.first = prefix.second;
529 const char* pch = prefix.second;
531 m_attributePrefix.second += (isalnum(*pch) ? toupper(*pch) : '_');
536 // Load attribute ID lists for REMOTE_USER and header clearing.
537 if (conf.isEnabled(SPConfig::InProcess)) {
538 pair<bool,const char*> attributes = getString("REMOTE_USER");
539 if (attributes.first) {
540 char* dup = strdup(attributes.second);
543 while (start && *start) {
544 while (*start && isspace(*start))
548 pos = strchr(start,' ');
551 m_remoteUsers.push_back(start);
552 start = pos ? pos+1 : nullptr;
557 attributes = getString("unsetHeaders");
558 if (attributes.first) {
559 string transformedprefix(m_attributePrefix.second);
561 prefix = getString("metadataAttributePrefix");
565 transformedprefix += (isalnum(*pch) ? toupper(*pch) : '_');
569 char* dup = strdup(attributes.second);
572 while (start && *start) {
573 while (*start && isspace(*start))
577 pos = strchr(start,' ');
584 transformed += (isalnum(*pch) ? toupper(*pch) : '_');
588 m_unsetHeaders.push_back(pair<string,string>(m_attributePrefix.first + start, m_attributePrefix.second + transformed));
590 m_unsetHeaders.push_back(pair<string,string>(m_attributePrefix.first + prefix.second + start, transformedprefix + transformed));
591 start = pos ? pos+1 : nullptr;
594 m_unsetHeaders.push_back(pair<string,string>(m_attributePrefix.first + "Shib-Application-ID", m_attributePrefix.second + "SHIB_APPLICATION_ID"));
598 Handler* handler=nullptr;
599 const PropertySet* sessions = getPropertySet("Sessions");
601 // Process assertion export handler.
602 pair<bool,const char*> location = sessions ? sessions->getString("exportLocation") : pair<bool,const char*>(false,nullptr);
603 if (location.first) {
605 DOMElement* exportElement = e->getOwnerDocument()->createElementNS(shibspconstants::SHIB2SPCONFIG_NS,_Handler);
606 exportElement->setAttributeNS(nullptr,Location,sessions->getXMLString("exportLocation").second);
607 pair<bool,const XMLCh*> exportACL = sessions->getXMLString("exportACL");
608 if (exportACL.first) {
609 static const XMLCh _acl[] = UNICODE_LITERAL_9(e,x,p,o,r,t,A,C,L);
610 exportElement->setAttributeNS(nullptr,_acl,exportACL.second);
612 handler = conf.HandlerManager.newPlugin(
613 samlconstants::SAML20_BINDING_URI, pair<const DOMElement*,const char*>(exportElement, getId())
615 m_handlers.push_back(handler);
617 // Insert into location map. If it contains the handlerURL, we skip past that part.
618 const char* pch = strstr(location.second, sessions->getString("handlerURL").second);
620 location.second = pch + strlen(sessions->getString("handlerURL").second);
621 if (*location.second == '/')
622 m_handlerMap[location.second]=handler;
624 m_handlerMap[string("/") + location.second]=handler;
626 catch (exception& ex) {
627 log.error("caught exception installing assertion lookup handler: %s", ex.what());
631 // Process other handlers.
632 bool hardACS=false, hardSessionInit=false, hardArt=false;
633 const DOMElement* child = sessions ? XMLHelper::getFirstChildElement(sessions->getElement()) : nullptr;
635 if (!child->hasAttributeNS(nullptr, Location)) {
636 auto_ptr_char hclass(child->getLocalName());
637 log.error("%s handler with no Location property cannot be processed", hclass.get());
638 child = XMLHelper::getNextSiblingElement(child);
642 if (XMLString::equals(child->getLocalName(),_AssertionConsumerService)) {
643 auto_ptr_char bindprop(child->getAttributeNS(nullptr,Binding));
644 if (!bindprop.get() || !*(bindprop.get())) {
645 log.warn("md:AssertionConsumerService element has no Binding attribute, skipping it...");
646 child = XMLHelper::getNextSiblingElement(child);
649 handler=conf.AssertionConsumerServiceManager.newPlugin(bindprop.get(),make_pair(child, getId()));
650 // Map by binding (may be > 1 per binding, e.g. SAML 1.0 vs 1.1)
651 m_acsBindingMap[handler->getXMLString("Binding").second].push_back(handler);
652 m_acsIndexMap[handler->getUnsignedInt("index").second]=handler;
655 pair<bool,bool> defprop=handler->getBool("isDefault");
657 if (defprop.second) {
659 m_acsDefault=handler;
662 else if (!m_acsDefault)
663 m_acsDefault=handler;
666 else if (XMLString::equals(child->getLocalName(),_SessionInitiator)) {
667 auto_ptr_char type(child->getAttributeNS(nullptr,_type));
668 if (!type.get() || !*(type.get())) {
669 log.warn("SessionInitiator element has no type attribute, skipping it...");
670 child = XMLHelper::getNextSiblingElement(child);
673 SessionInitiator* sihandler=conf.SessionInitiatorManager.newPlugin(type.get(),make_pair(child, getId()));
675 pair<bool,const char*> si_id=handler->getString("id");
676 if (si_id.first && si_id.second)
677 m_sessionInitMap[si_id.second]=sihandler;
678 if (!hardSessionInit) {
679 pair<bool,bool> defprop=handler->getBool("isDefault");
681 if (defprop.second) {
682 hardSessionInit=true;
683 m_sessionInitDefault=sihandler;
686 else if (!m_sessionInitDefault)
687 m_sessionInitDefault=sihandler;
690 else if (XMLString::equals(child->getLocalName(),_LogoutInitiator)) {
691 auto_ptr_char type(child->getAttributeNS(nullptr,_type));
692 if (!type.get() || !*(type.get())) {
693 log.warn("LogoutInitiator element has no type attribute, skipping it...");
694 child = XMLHelper::getNextSiblingElement(child);
697 handler=conf.LogoutInitiatorManager.newPlugin(type.get(),make_pair(child, getId()));
699 else if (XMLString::equals(child->getLocalName(),_ArtifactResolutionService)) {
700 auto_ptr_char bindprop(child->getAttributeNS(nullptr,Binding));
701 if (!bindprop.get() || !*(bindprop.get())) {
702 log.warn("md:ArtifactResolutionService element has no Binding attribute, skipping it...");
703 child = XMLHelper::getNextSiblingElement(child);
706 handler=conf.ArtifactResolutionServiceManager.newPlugin(bindprop.get(),make_pair(child, getId()));
709 pair<bool,bool> defprop=handler->getBool("isDefault");
711 if (defprop.second) {
713 m_artifactResolutionDefault=handler;
716 else if (!m_artifactResolutionDefault)
717 m_artifactResolutionDefault=handler;
720 else if (XMLString::equals(child->getLocalName(),_SingleLogoutService)) {
721 auto_ptr_char bindprop(child->getAttributeNS(nullptr,Binding));
722 if (!bindprop.get() || !*(bindprop.get())) {
723 log.warn("md:SingleLogoutService element has no Binding attribute, skipping it...");
724 child = XMLHelper::getNextSiblingElement(child);
727 handler=conf.SingleLogoutServiceManager.newPlugin(bindprop.get(),make_pair(child, getId()));
729 else if (XMLString::equals(child->getLocalName(),_ManageNameIDService)) {
730 auto_ptr_char bindprop(child->getAttributeNS(nullptr,Binding));
731 if (!bindprop.get() || !*(bindprop.get())) {
732 log.warn("md:ManageNameIDService element has no Binding attribute, skipping it...");
733 child = XMLHelper::getNextSiblingElement(child);
736 handler=conf.ManageNameIDServiceManager.newPlugin(bindprop.get(),make_pair(child, getId()));
739 auto_ptr_char type(child->getAttributeNS(nullptr,_type));
740 if (!type.get() || !*(type.get())) {
741 log.warn("Handler element has no type attribute, skipping it...");
742 child = XMLHelper::getNextSiblingElement(child);
745 handler=conf.HandlerManager.newPlugin(type.get(),make_pair(child, getId()));
748 m_handlers.push_back(handler);
750 // Insert into location map.
751 location=handler->getString("Location");
752 if (location.first && *location.second == '/')
753 m_handlerMap[location.second]=handler;
754 else if (location.first)
755 m_handlerMap[string("/") + location.second]=handler;
758 catch (exception& ex) {
759 log.error("caught exception processing handler element: %s", ex.what());
762 child = XMLHelper::getNextSiblingElement(child);
766 DOMNodeList* nlist=e->getElementsByTagNameNS(shibspconstants::SHIB2SPCONFIG_NS,Notify);
767 for (XMLSize_t i=0; nlist && i<nlist->getLength(); i++) {
768 if (nlist->item(i)->getParentNode()->isSameNode(e)) {
769 const XMLCh* channel = static_cast<DOMElement*>(nlist->item(i))->getAttributeNS(nullptr,Channel);
770 auto_ptr_char loc(static_cast<DOMElement*>(nlist->item(i))->getAttributeNS(nullptr,Location));
771 if (loc.get() && *loc.get()) {
772 if (channel && *channel == chLatin_f)
773 m_frontLogout.push_back(loc.get());
775 m_backLogout.push_back(loc.get());
781 nlist=e->getElementsByTagNameNS(samlconstants::SAML20_NS,Audience::LOCAL_NAME);
782 if (nlist && nlist->getLength()) {
783 log.warn("use of <saml:Audience> elements outside of a Security Policy Rule is deprecated");
784 for (XMLSize_t i=0; i<nlist->getLength(); i++)
785 if (nlist->item(i)->getParentNode()->isSameNode(e) && nlist->item(i)->hasChildNodes())
786 m_audiences.push_back(nlist->item(i)->getFirstChild()->getNodeValue());
789 if (conf.isEnabled(SPConfig::Metadata)) {
790 child = XMLHelper::getFirstChildElement(e,_MetadataProvider);
792 auto_ptr_char type(child->getAttributeNS(nullptr,_type));
793 log.info("building MetadataProvider of type %s...",type.get());
795 auto_ptr<MetadataProvider> mp(samlConf.MetadataProviderManager.newPlugin(type.get(),child));
797 m_metadata = mp.release();
799 catch (exception& ex) {
800 log.crit("error building/initializing MetadataProvider: %s", ex.what());
805 if (conf.isEnabled(SPConfig::Trust)) {
806 child = XMLHelper::getFirstChildElement(e,_TrustEngine);
808 auto_ptr_char type(child->getAttributeNS(nullptr,_type));
809 log.info("building TrustEngine of type %s...",type.get());
811 m_trust = xmlConf.TrustEngineManager.newPlugin(type.get(),child);
813 catch (exception& ex) {
814 log.crit("error building TrustEngine: %s", ex.what());
819 if (conf.isEnabled(SPConfig::AttributeResolution)) {
820 child = XMLHelper::getFirstChildElement(e,_AttributeExtractor);
822 auto_ptr_char type(child->getAttributeNS(nullptr,_type));
823 log.info("building AttributeExtractor of type %s...",type.get());
825 m_attrExtractor = conf.AttributeExtractorManager.newPlugin(type.get(),child);
827 catch (exception& ex) {
828 log.crit("error building AttributeExtractor: %s", ex.what());
832 child = XMLHelper::getFirstChildElement(e,_AttributeFilter);
834 auto_ptr_char type(child->getAttributeNS(nullptr,_type));
835 log.info("building AttributeFilter of type %s...",type.get());
837 m_attrFilter = conf.AttributeFilterManager.newPlugin(type.get(),child);
839 catch (exception& ex) {
840 log.crit("error building AttributeFilter: %s", ex.what());
844 child = XMLHelper::getFirstChildElement(e,_AttributeResolver);
846 auto_ptr_char type(child->getAttributeNS(nullptr,_type));
847 log.info("building AttributeResolver of type %s...",type.get());
849 m_attrResolver = conf.AttributeResolverManager.newPlugin(type.get(),child);
851 catch (exception& ex) {
852 log.crit("error building AttributeResolver: %s", ex.what());
856 if (m_unsetHeaders.empty()) {
857 vector<string> unsetHeaders;
858 if (m_attrExtractor) {
859 Locker extlock(m_attrExtractor);
860 m_attrExtractor->getAttributeIds(unsetHeaders);
862 else if (m_base && m_base->m_attrExtractor) {
863 Locker extlock(m_base->m_attrExtractor);
864 m_base->m_attrExtractor->getAttributeIds(unsetHeaders);
866 if (m_attrResolver) {
867 Locker reslock(m_attrResolver);
868 m_attrResolver->getAttributeIds(unsetHeaders);
870 else if (m_base && m_base->m_attrResolver) {
871 Locker extlock(m_base->m_attrResolver);
872 m_base->m_attrResolver->getAttributeIds(unsetHeaders);
874 if (!unsetHeaders.empty()) {
875 string transformedprefix(m_attributePrefix.second);
877 pair<bool,const char*> prefix = getString("metadataAttributePrefix");
881 transformedprefix += (isalnum(*pch) ? toupper(*pch) : '_');
885 for (vector<string>::const_iterator hdr = unsetHeaders.begin(); hdr!=unsetHeaders.end(); ++hdr) {
889 transformed += (isalnum(*pch) ? toupper(*pch) : '_');
892 m_unsetHeaders.push_back(pair<string,string>(m_attributePrefix.first + *hdr, m_attributePrefix.second + transformed));
894 m_unsetHeaders.push_back(pair<string,string>(m_attributePrefix.first + prefix.second + *hdr, transformedprefix + transformed));
897 m_unsetHeaders.push_back(pair<string,string>(m_attributePrefix.first + "Shib-Application-ID", m_attributePrefix.second + "SHIB_APPLICATION_ID"));
901 if (conf.isEnabled(SPConfig::Credentials)) {
902 child = XMLHelper::getFirstChildElement(e,_CredentialResolver);
904 auto_ptr_char type(child->getAttributeNS(nullptr,_type));
905 log.info("building CredentialResolver of type %s...",type.get());
907 m_credResolver = xmlConf.CredentialResolverManager.newPlugin(type.get(),child);
909 catch (exception& ex) {
910 log.crit("error building CredentialResolver: %s", ex.what());
915 // Finally, load relying parties.
916 child = XMLHelper::getFirstChildElement(e,RelyingParty);
918 auto_ptr<DOMPropertySet> rp(new DOMPropertySet());
919 rp->load(child,nullptr,this);
921 m_partyMap[child->getAttributeNS(nullptr,saml2::Attribute::NAME_ATTRIB_NAME)]=rp.release();
922 child = XMLHelper::getNextSiblingElement(child,RelyingParty);
926 // Out of process only, we register a listener endpoint.
927 if (!conf.isEnabled(SPConfig::InProcess)) {
928 ListenerService* listener = sp->getListenerService(false);
930 string addr=string(getId()) + "::getHeaders::Application";
931 listener->regListener(addr.c_str(),this);
934 log.info("no ListenerService available, Application remoting disabled");
949 void XMLApplication::cleanup()
951 ListenerService* listener=getServiceProvider().getListenerService(false);
952 if (listener && SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess) && !SPConfig::getConfig().isEnabled(SPConfig::InProcess)) {
953 string addr=string(getId()) + "::getHeaders::Application";
954 listener->unregListener(addr.c_str(),this);
956 for_each(m_handlers.begin(),m_handlers.end(),xmltooling::cleanup<Handler>());
959 for_each(m_partyMap.begin(),m_partyMap.end(),cleanup_pair<xstring,PropertySet>());
961 delete m_credResolver;
962 m_credResolver = nullptr;
963 delete m_attrResolver;
964 m_attrResolver = nullptr;
966 m_attrFilter = nullptr;
967 delete m_attrExtractor;
968 m_attrExtractor = nullptr;
972 m_metadata = nullptr;
976 #ifdef SHIBSP_XERCESC_SHORT_ACCEPTNODE
979 DOMNodeFilter::FilterAction
981 XMLApplication::acceptNode(const DOMNode* node) const
983 const XMLCh* name=node->getLocalName();
984 if (XMLString::equals(name,ApplicationOverride) ||
985 XMLString::equals(name,_Audience) ||
986 XMLString::equals(name,Notify) ||
987 XMLString::equals(name,_Handler) ||
988 XMLString::equals(name,_AssertionConsumerService) ||
989 XMLString::equals(name,_ArtifactResolutionService) ||
990 XMLString::equals(name,_LogoutInitiator) ||
991 XMLString::equals(name,_ManageNameIDService) ||
992 XMLString::equals(name,_SessionInitiator) ||
993 XMLString::equals(name,_SingleLogoutService) ||
994 XMLString::equals(name,RelyingParty) ||
995 XMLString::equals(name,_MetadataProvider) ||
996 XMLString::equals(name,_TrustEngine) ||
997 XMLString::equals(name,_CredentialResolver) ||
998 XMLString::equals(name,_AttributeFilter) ||
999 XMLString::equals(name,_AttributeExtractor) ||
1000 XMLString::equals(name,_AttributeResolver))
1001 return FILTER_REJECT;
1003 return FILTER_ACCEPT;
1008 const PropertySet* XMLApplication::getRelyingParty(const EntityDescriptor* provider) const
1013 map<xstring,PropertySet*>::const_iterator i=m_partyMap.find(provider->getEntityID());
1014 if (i!=m_partyMap.end())
1016 const EntitiesDescriptor* group=dynamic_cast<const EntitiesDescriptor*>(provider->getParent());
1018 if (group->getName()) {
1019 i=m_partyMap.find(group->getName());
1020 if (i!=m_partyMap.end())
1023 group=dynamic_cast<const EntitiesDescriptor*>(group->getParent());
1028 const PropertySet* XMLApplication::getRelyingParty(const XMLCh* entityID) const
1033 map<xstring,PropertySet*>::const_iterator i=m_partyMap.find(entityID);
1034 if (i!=m_partyMap.end())
1041 string XMLApplication::getNotificationURL(const char* resource, bool front, unsigned int index) const
1043 const vector<string>& locs = front ? m_frontLogout : m_backLogout;
1045 return m_base ? m_base->getNotificationURL(resource, front, index) : string();
1046 else if (index >= locs.size())
1049 #ifdef HAVE_STRCASECMP
1050 if (!resource || (strncasecmp(resource,"http://",7) && strncasecmp(resource,"https://",8)))
1052 if (!resource || (strnicmp(resource,"http://",7) && strnicmp(resource,"https://",8)))
1054 throw ConfigurationException("Request URL was not absolute.");
1056 const char* handler=locs[index].c_str();
1058 // Should never happen...
1059 if (!handler || (*handler!='/' && strncmp(handler,"http:",5) && strncmp(handler,"https:",6)))
1060 throw ConfigurationException(
1061 "Invalid Location property ($1) in Notify element for Application ($2)",
1062 params(2, handler ? handler : "null", getId())
1065 // The "Location" property can be in one of three formats:
1067 // 1) a full URI: http://host/foo/bar
1068 // 2) a hostless URI: http:///foo/bar
1069 // 3) a relative path: /foo/bar
1071 // # Protocol Host Path
1072 // 1 handler handler handler
1073 // 2 handler resource handler
1074 // 3 resource resource handler
1076 const char* path = nullptr;
1078 // Decide whether to use the handler or the resource for the "protocol"
1080 if (*handler != '/') {
1088 // break apart the "protocol" string into protocol, host, and "the rest"
1089 const char* colon=strchr(prot,':');
1091 const char* slash=strchr(colon,'/');
1095 // Compute the actual protocol and store.
1096 string notifyURL(prot, colon-prot);
1098 // create the "host" from either the colon/slash or from the target string
1099 // If prot == handler then we're in either #1 or #2, else #3.
1100 // If slash == colon then we're in #2.
1101 if (prot != handler || slash == colon) {
1102 colon = strchr(resource, ':');
1103 colon += 3; // Get past the ://
1104 slash = strchr(colon, '/');
1106 string host(colon, (slash ? slash-colon : strlen(colon)));
1109 notifyURL += host + path;
1113 void XMLApplication::clearHeader(SPRequest& request, const char* rawname, const char* cginame) const
1115 if (!m_attributePrefix.first.empty()) {
1116 string temp = m_attributePrefix.first + rawname;
1117 string temp2 = m_attributePrefix.second + (cginame + 5);
1118 request.clearHeader(temp.c_str(), temp2.c_str());
1121 m_base->clearHeader(request, rawname, cginame);
1124 request.clearHeader(rawname, cginame);
1128 void XMLApplication::setHeader(SPRequest& request, const char* name, const char* value) const
1130 if (!m_attributePrefix.first.empty()) {
1131 string temp = m_attributePrefix.first + name;
1132 request.setHeader(temp.c_str(), value);
1135 m_base->setHeader(request, name, value);
1138 request.setHeader(name, value);
1142 string XMLApplication::getSecureHeader(const SPRequest& request, const char* name) const
1144 if (!m_attributePrefix.first.empty()) {
1145 string temp = m_attributePrefix.first + name;
1146 return request.getSecureHeader(temp.c_str());
1149 return m_base->getSecureHeader(request,name);
1152 return request.getSecureHeader(name);
1156 const SessionInitiator* XMLApplication::getDefaultSessionInitiator() const
1158 if (m_sessionInitDefault) return m_sessionInitDefault;
1159 return m_base ? m_base->getDefaultSessionInitiator() : nullptr;
1162 const SessionInitiator* XMLApplication::getSessionInitiatorById(const char* id) const
1164 map<string,const SessionInitiator*>::const_iterator i=m_sessionInitMap.find(id);
1165 if (i!=m_sessionInitMap.end()) return i->second;
1166 return m_base ? m_base->getSessionInitiatorById(id) : nullptr;
1169 const Handler* XMLApplication::getDefaultAssertionConsumerService() const
1171 if (m_acsDefault) return m_acsDefault;
1172 return m_base ? m_base->getDefaultAssertionConsumerService() : nullptr;
1175 const Handler* XMLApplication::getAssertionConsumerServiceByIndex(unsigned short index) const
1177 map<unsigned int,const Handler*>::const_iterator i=m_acsIndexMap.find(index);
1178 if (i!=m_acsIndexMap.end()) return i->second;
1179 return m_base ? m_base->getAssertionConsumerServiceByIndex(index) : nullptr;
1182 const vector<const Handler*>& XMLApplication::getAssertionConsumerServicesByBinding(const XMLCh* binding) const
1184 ACSBindingMap::const_iterator i=m_acsBindingMap.find(binding);
1185 if (i!=m_acsBindingMap.end())
1187 return m_base ? m_base->getAssertionConsumerServicesByBinding(binding) : g_noHandlers;
1190 const Handler* XMLApplication::getHandler(const char* path) const
1193 wrap = wrap.substr(0,wrap.find(';'));
1194 map<string,const Handler*>::const_iterator i=m_handlerMap.find(wrap.substr(0,wrap.find('?')));
1195 if (i!=m_handlerMap.end())
1197 return m_base ? m_base->getHandler(path) : nullptr;
1200 void XMLApplication::getHandlers(vector<const Handler*>& handlers) const
1202 handlers.insert(handlers.end(), m_handlers.begin(), m_handlers.end());
1204 for (map<string,const Handler*>::const_iterator h = m_base->m_handlerMap.begin(); h != m_base->m_handlerMap.end(); ++h) {
1205 if (m_handlerMap.count(h->first) == 0)
1206 handlers.push_back(h->second);
1211 #ifdef SHIBSP_XERCESC_SHORT_ACCEPTNODE
1214 DOMNodeFilter::FilterAction
1216 XMLConfigImpl::acceptNode(const DOMNode* node) const
1218 if (!XMLString::equals(node->getNamespaceURI(),shibspconstants::SHIB2SPCONFIG_NS))
1219 return FILTER_ACCEPT;
1220 const XMLCh* name=node->getLocalName();
1221 if (XMLString::equals(name,ApplicationDefaults) ||
1222 XMLString::equals(name,_ArtifactMap) ||
1223 XMLString::equals(name,_Extensions) ||
1224 XMLString::equals(name,Listener) ||
1225 XMLString::equals(name,_RequestMapper) ||
1226 XMLString::equals(name,_ReplayCache) ||
1227 XMLString::equals(name,SecurityPolicies) ||
1228 XMLString::equals(name,_SessionCache) ||
1229 XMLString::equals(name,Site) ||
1230 XMLString::equals(name,_StorageService) ||
1231 XMLString::equals(name,TCPListener) ||
1232 XMLString::equals(name,TransportOption) ||
1233 XMLString::equals(name,UnixListener))
1234 return FILTER_REJECT;
1236 return FILTER_ACCEPT;
1239 void XMLConfigImpl::doExtensions(const DOMElement* e, const char* label, Category& log)
1241 const DOMElement* exts=XMLHelper::getFirstChildElement(e,_Extensions);
1243 exts=XMLHelper::getFirstChildElement(exts,Library);
1245 auto_ptr_char path(exts->getAttributeNS(nullptr,_path));
1248 if (!XMLToolingConfig::getConfig().load_library(path.get(),(void*)exts))
1249 throw ConfigurationException("XMLToolingConfig::load_library failed.");
1250 log.debug("loaded %s extension library (%s)", label, path.get());
1253 catch (exception& e) {
1254 const XMLCh* fatal=exts->getAttributeNS(nullptr,_fatal);
1255 if (fatal && (*fatal==chLatin_t || *fatal==chDigit_1)) {
1256 log.fatal("unable to load mandatory %s extension library %s: %s", label, path.get(), e.what());
1260 log.crit("unable to load optional %s extension library %s: %s", label, path.get(), e.what());
1263 exts=XMLHelper::getNextSiblingElement(exts,Library);
1268 XMLConfigImpl::XMLConfigImpl(const DOMElement* e, bool first, const XMLConfig* outer, Category& log)
1269 : m_requestMapper(nullptr), m_outer(outer), m_document(nullptr)
1272 xmltooling::NDC ndc("XMLConfigImpl");
1276 SPConfig& conf=SPConfig::getConfig();
1278 SAMLConfig& samlConf=SAMLConfig::getConfig();
1280 XMLToolingConfig& xmlConf=XMLToolingConfig::getConfig();
1281 const DOMElement* SHAR=XMLHelper::getFirstChildElement(e,OutOfProcess);
1282 const DOMElement* SHIRE=XMLHelper::getFirstChildElement(e,InProcess);
1284 // Initialize log4cpp manually in order to redirect log messages as soon as possible.
1285 if (conf.isEnabled(SPConfig::Logging)) {
1286 const XMLCh* logconf=nullptr;
1287 if (conf.isEnabled(SPConfig::OutOfProcess))
1288 logconf=SHAR->getAttributeNS(nullptr,logger);
1289 else if (conf.isEnabled(SPConfig::InProcess))
1290 logconf=SHIRE->getAttributeNS(nullptr,logger);
1291 if (!logconf || !*logconf)
1292 logconf=e->getAttributeNS(nullptr,logger);
1293 if (logconf && *logconf) {
1294 auto_ptr_char logpath(logconf);
1295 log.debug("loading new logging configuration from (%s), check log destination for status of configuration",logpath.get());
1296 if (!XMLToolingConfig::getConfig().log_config(logpath.get()))
1297 log.crit("failed to load new logging configuration from (%s)", logpath.get());
1302 m_outer->m_tranLog = new TransactionLog();
1306 // Re-log library versions now that logging is set up.
1307 log.info("Shibboleth SP Version %s", PACKAGE_VERSION);
1310 "Library versions: Xerces-C %s, XML-Security-C %s, XMLTooling-C %s, OpenSAML-C %s, Shibboleth %s",
1311 XERCES_FULLVERSIONDOT, XSEC_FULLVERSIONDOT, XMLTOOLING_FULLVERSIONDOT, OPENSAML_FULLVERSIONDOT, SHIBSP_FULLVERSIONDOT
1315 "Library versions: Xerces-C %s, XMLTooling-C %s, Shibboleth %s",
1316 XERCES_FULLVERSIONDOT, XMLTOOLING_FULLVERSIONDOT, SHIBSP_FULLVERSIONDOT
1320 // First load any property sets.
1321 load(e,nullptr,this);
1323 const DOMElement* child;
1326 // Much of the processing can only occur on the first instantiation.
1329 pair<bool,unsigned int> skew=getUnsignedInt("clockSkew");
1331 xmlConf.clock_skew_secs=min(skew.second,(60*60*24*7*28));
1333 pair<bool,const char*> unsafe = getString("unsafeChars");
1335 TemplateEngine::unsafe_chars = unsafe.second;
1337 unsafe = getString("allowedSchemes");
1339 HTTPResponse::getAllowedSchemes().clear();
1340 string schemes=unsafe.second;
1341 unsigned int j_sch=0;
1342 for (unsigned int i_sch=0; i_sch < schemes.length(); i_sch++) {
1343 if (schemes.at(i_sch)==' ') {
1344 HTTPResponse::getAllowedSchemes().push_back(schemes.substr(j_sch, i_sch-j_sch));
1348 HTTPResponse::getAllowedSchemes().push_back(schemes.substr(j_sch, schemes.length()-j_sch));
1352 doExtensions(e, "global", log);
1353 if (conf.isEnabled(SPConfig::OutOfProcess))
1354 doExtensions(SHAR, "out of process", log);
1356 if (conf.isEnabled(SPConfig::InProcess))
1357 doExtensions(SHIRE, "in process", log);
1359 // Instantiate the ListenerService and SessionCache objects.
1360 if (conf.isEnabled(SPConfig::Listener)) {
1361 child=XMLHelper::getFirstChildElement(e,UnixListener);
1363 plugtype=UNIX_LISTENER_SERVICE;
1365 child=XMLHelper::getFirstChildElement(e,TCPListener);
1367 plugtype=TCP_LISTENER_SERVICE;
1369 child=XMLHelper::getFirstChildElement(e,Listener);
1371 auto_ptr_char type(child->getAttributeNS(nullptr,_type));
1373 plugtype=type.get();
1378 log.info("building ListenerService of type %s...", plugtype.c_str());
1379 m_outer->m_listener = conf.ListenerServiceManager.newPlugin(plugtype.c_str(), child);
1382 log.fatal("can't build ListenerService, missing conf:Listener element?");
1383 throw ConfigurationException("Can't build ListenerService, missing conf:Listener element?");
1388 if (m_outer->m_listener && conf.isEnabled(SPConfig::OutOfProcess) && !conf.isEnabled(SPConfig::InProcess)) {
1389 m_outer->m_listener->regListener("set::RelayState", const_cast<XMLConfig*>(m_outer));
1390 m_outer->m_listener->regListener("get::RelayState", const_cast<XMLConfig*>(m_outer));
1391 m_outer->m_listener->regListener("set::PostData", const_cast<XMLConfig*>(m_outer));
1392 m_outer->m_listener->regListener("get::PostData", const_cast<XMLConfig*>(m_outer));
1396 if (conf.isEnabled(SPConfig::Caching)) {
1397 if (conf.isEnabled(SPConfig::OutOfProcess)) {
1399 // First build any StorageServices.
1400 child=XMLHelper::getFirstChildElement(e,_StorageService);
1402 auto_ptr_char id(child->getAttributeNS(nullptr,_id));
1403 auto_ptr_char type(child->getAttributeNS(nullptr,_type));
1405 log.info("building StorageService (%s) of type %s...", id.get(), type.get());
1406 m_outer->m_storage[id.get()] = xmlConf.StorageServiceManager.newPlugin(type.get(),child);
1408 catch (exception& ex) {
1409 log.crit("failed to instantiate StorageService (%s): %s", id.get(), ex.what());
1411 child=XMLHelper::getNextSiblingElement(child,_StorageService);
1415 StorageService* replaySS=nullptr;
1416 child=XMLHelper::getFirstChildElement(e,_ReplayCache);
1418 auto_ptr_char ssid(child->getAttributeNS(nullptr,_StorageService));
1419 if (ssid.get() && *ssid.get()) {
1420 if (m_outer->m_storage.count(ssid.get()))
1421 replaySS = m_outer->m_storage[ssid.get()];
1423 log.info("building ReplayCache on top of StorageService (%s)...", ssid.get());
1425 log.warn("unable to locate StorageService (%s) for ReplayCache, using dedicated in-memory instance", ssid.get());
1427 xmlConf.setReplayCache(new ReplayCache(replaySS));
1430 log.warn("no ReplayCache built, missing conf:ReplayCache element?");
1434 child=XMLHelper::getFirstChildElement(e,_ArtifactMap);
1436 auto_ptr_char ssid(child->getAttributeNS(nullptr,_StorageService));
1437 if (ssid.get() && *ssid.get() && m_outer->m_storage.count(ssid.get())) {
1438 log.info("building ArtifactMap on top of StorageService (%s)...", ssid.get());
1439 samlConf.setArtifactMap(new ArtifactMap(child, m_outer->m_storage[ssid.get()]));
1442 if (samlConf.getArtifactMap()==nullptr) {
1443 log.info("building in-memory ArtifactMap...");
1444 samlConf.setArtifactMap(new ArtifactMap(child));
1448 child=XMLHelper::getFirstChildElement(e,_SessionCache);
1450 auto_ptr_char type(child->getAttributeNS(nullptr,_type));
1451 log.info("building SessionCache of type %s...",type.get());
1452 m_outer->m_sessionCache=conf.SessionCacheManager.newPlugin(type.get(), child);
1455 log.fatal("can't build SessionCache, missing conf:SessionCache element?");
1456 throw ConfigurationException("Can't build SessionCache, missing conf:SessionCache element?");
1461 child = XMLHelper::getLastChildElement(e, SecurityPolicies);
1463 const XMLCh* algs = nullptr;
1464 const DOMElement* alglist = XMLHelper::getLastChildElement(child, AlgorithmBlacklist);
1465 if (alglist && alglist->hasChildNodes()) {
1466 algs = alglist->getFirstChild()->getNodeValue();
1468 else if ((alglist = XMLHelper::getLastChildElement(child, AlgorithmWhitelist)) && alglist->hasChildNodes()) {
1469 algs = alglist->getFirstChild()->getNodeValue();
1472 #ifdef SHIBSP_XMLSEC_WHITELISTING
1474 XMLStringTokenizer tokenizer(algs);
1475 while (tokenizer.hasMoreTokens()) {
1476 token = tokenizer.nextToken();
1478 if (XMLString::equals(alglist->getLocalName(), AlgorithmBlacklist))
1479 XSECPlatformUtils::blacklistAlgorithm(token);
1481 XSECPlatformUtils::whitelistAlgorithm(token);
1485 log.fatal("XML-Security-C library prior to 1.6.0 does not support algorithm white/blacklists");
1486 throw ConfigurationException("XML-Security-C library prior to 1.6.0 does not support algorithm white/blacklists.");
1491 } // end of first-time-only stuff
1493 // Back to the fully dynamic stuff...next up is the RequestMapper.
1494 if (conf.isEnabled(SPConfig::RequestMapping)) {
1495 child=XMLHelper::getFirstChildElement(e,_RequestMapper);
1497 auto_ptr_char type(child->getAttributeNS(nullptr,_type));
1498 log.info("building RequestMapper of type %s...",type.get());
1499 m_requestMapper=conf.RequestMapperManager.newPlugin(type.get(),child);
1502 log.fatal("can't build RequestMapper, missing conf:RequestMapper element?");
1503 throw ConfigurationException("Can't build RequestMapper, missing conf:RequestMapper element?");
1508 // Load security policies.
1509 child = XMLHelper::getLastChildElement(e,SecurityPolicies);
1511 PolicyNodeFilter filter;
1512 child = XMLHelper::getFirstChildElement(child,Policy);
1514 auto_ptr_char id(child->getAttributeNS(nullptr,_id));
1515 pair< PropertySet*,vector<const SecurityPolicyRule*> >& rules = m_policyMap[id.get()];
1516 rules.first = nullptr;
1517 auto_ptr<DOMPropertySet> settings(new DOMPropertySet());
1518 settings->load(child, nullptr, &filter);
1519 rules.first = settings.release();
1521 // Process PolicyRule elements.
1522 const DOMElement* rule = XMLHelper::getFirstChildElement(child,PolicyRule);
1524 auto_ptr_char type(rule->getAttributeNS(nullptr,_type));
1526 rules.second.push_back(samlConf.SecurityPolicyRuleManager.newPlugin(type.get(),rule));
1528 catch (exception& ex) {
1529 log.crit("error instantiating policy rule (%s) in policy (%s): %s", type.get(), id.get(), ex.what());
1531 rule = XMLHelper::getNextSiblingElement(rule,PolicyRule);
1534 if (rules.second.size() == 0) {
1535 // Process Rule elements.
1536 log.warn("detected legacy Policy configuration, please convert to new PolicyRule syntax");
1537 rule = XMLHelper::getFirstChildElement(child,Rule);
1539 auto_ptr_char type(rule->getAttributeNS(nullptr,_type));
1541 rules.second.push_back(samlConf.SecurityPolicyRuleManager.newPlugin(type.get(),rule));
1543 catch (exception& ex) {
1544 log.crit("error instantiating policy rule (%s) in policy (%s): %s", type.get(), id.get(), ex.what());
1546 rule = XMLHelper::getNextSiblingElement(rule,Rule);
1549 // Manually add a basic Conditions rule.
1550 log.info("installing a default Conditions rule in policy (%s) for compatibility with legacy configuration", id.get());
1551 rules.second.push_back(samlConf.SecurityPolicyRuleManager.newPlugin(CONDITIONS_POLICY_RULE, nullptr));
1554 child = XMLHelper::getNextSiblingElement(child,Policy);
1558 // Process TransportOption elements.
1559 child = XMLHelper::getLastChildElement(e,TransportOption);
1561 if (child->hasChildNodes()) {
1562 auto_ptr_char provider(child->getAttributeNS(nullptr,_provider));
1563 auto_ptr_char option(child->getAttributeNS(nullptr,_option));
1564 auto_ptr_char value(child->getFirstChild()->getNodeValue());
1565 if (provider.get() && *provider.get() && option.get() && *option.get() && value.get() && *value.get()) {
1566 m_transportOptions.push_back(make_pair(string(provider.get()), make_pair(string(option.get()), string(value.get()))));
1569 child = XMLHelper::getPreviousSiblingElement(child,TransportOption);
1573 // Load the default application. This actually has a fixed ID of "default". ;-)
1574 child=XMLHelper::getLastChildElement(e,ApplicationDefaults);
1576 log.fatal("can't build default Application object, missing conf:ApplicationDefaults element?");
1577 throw ConfigurationException("can't build default Application object, missing conf:ApplicationDefaults element?");
1579 XMLApplication* defapp=new XMLApplication(m_outer,child);
1580 m_appmap[defapp->getId()]=defapp;
1582 // Load any overrides.
1583 child = XMLHelper::getFirstChildElement(child,ApplicationOverride);
1585 auto_ptr<XMLApplication> iapp(new XMLApplication(m_outer,child,defapp));
1586 if (m_appmap.count(iapp->getId()))
1587 log.crit("found conf:ApplicationOverride element with duplicate id attribute (%s), skipping it", iapp->getId());
1589 const char* iappid=iapp->getId();
1590 m_appmap[iappid]=iapp.release();
1593 child = XMLHelper::getNextSiblingElement(child,ApplicationOverride);
1596 catch (exception&) {
1602 XMLConfigImpl::~XMLConfigImpl()
1607 void XMLConfigImpl::cleanup()
1609 for_each(m_appmap.begin(),m_appmap.end(),cleanup_pair<string,Application>());
1612 for (map< string,pair<PropertySet*,vector<const SecurityPolicyRule*> > >::iterator i=m_policyMap.begin(); i!=m_policyMap.end(); ++i) {
1613 delete i->second.first;
1614 for_each(i->second.second.begin(), i->second.second.end(), xmltooling::cleanup<SecurityPolicyRule>());
1616 m_policyMap.clear();
1618 delete m_requestMapper;
1619 m_requestMapper = nullptr;
1621 m_document->release();
1622 m_document = nullptr;
1626 void XMLConfig::receive(DDF& in, ostream& out)
1628 if (!strcmp(in.name(), "get::RelayState")) {
1629 const char* id = in["id"].string();
1630 const char* key = in["key"].string();
1632 throw ListenerException("Required parameters missing for RelayState recovery.");
1635 StorageService* storage = getStorageService(id);
1637 if (storage->readString("RelayState",key,&relayState)>0) {
1638 if (in["clear"].integer())
1639 storage->deleteString("RelayState",key);
1643 Category::getInstance(SHIBSP_LOGCAT".ServiceProvider").error(
1644 "Storage-backed RelayState with invalid StorageService ID (%s)", id
1648 // Repack for return to caller.
1649 DDF ret=DDF(nullptr).unsafe_string(relayState.c_str());
1650 DDFJanitor jret(ret);
1653 else if (!strcmp(in.name(), "set::RelayState")) {
1654 const char* id = in["id"].string();
1655 const char* value = in["value"].string();
1657 throw ListenerException("Required parameters missing for RelayState creation.");
1660 StorageService* storage = getStorageService(id);
1662 SAMLConfig::getConfig().generateRandomBytes(rsKey,20);
1663 rsKey = SAMLArtifact::toHex(rsKey);
1664 storage->createString("RelayState", rsKey.c_str(), value, time(nullptr) + 600);
1667 Category::getInstance(SHIBSP_LOGCAT".ServiceProvider").error(
1668 "Storage-backed RelayState with invalid StorageService ID (%s)", id
1672 // Repack for return to caller.
1673 DDF ret=DDF(nullptr).string(rsKey.c_str());
1674 DDFJanitor jret(ret);
1677 else if (!strcmp(in.name(), "get::PostData")) {
1678 const char* id = in["id"].string();
1679 const char* key = in["key"].string();
1681 throw ListenerException("Required parameters missing for PostData recovery.");
1684 StorageService* storage = getStorageService(id);
1686 if (storage->readString("PostData",key,&postData) > 0) {
1687 storage->deleteString("PostData",key);
1691 Category::getInstance(SHIBSP_LOGCAT".ServiceProvider").error(
1692 "Storage-backed PostData with invalid StorageService ID (%s)", id
1695 // If the data's empty, we'll send nothing back.
1696 // If not, we don't need to round trip it, just send back the serialized DDF list.
1697 if (postData.empty()) {
1699 DDFJanitor jret(ret);
1706 else if (!strcmp(in.name(), "set::PostData")) {
1707 const char* id = in["id"].string();
1708 if (!id || !in["parameters"].islist())
1709 throw ListenerException("Required parameters missing for PostData creation.");
1712 StorageService* storage = getStorageService(id);
1714 SAMLConfig::getConfig().generateRandomBytes(rsKey,20);
1715 rsKey = SAMLArtifact::toHex(rsKey);
1716 ostringstream params;
1717 params << in["parameters"];
1718 storage->createString("PostData", rsKey.c_str(), params.str().c_str(), time(nullptr) + 600);
1721 Category::getInstance(SHIBSP_LOGCAT".ServiceProvider").error(
1722 "Storage-backed PostData with invalid StorageService ID (%s)", id
1726 // Repack for return to caller.
1727 DDF ret=DDF(nullptr).string(rsKey.c_str());
1728 DDFJanitor jret(ret);
1734 pair<bool,DOMElement*> XMLConfig::background_load()
1736 // Load from source using base class.
1737 pair<bool,DOMElement*> raw = ReloadableXMLFile::load();
1739 // If we own it, wrap it.
1740 XercesJanitor<DOMDocument> docjanitor(raw.first ? raw.second->getOwnerDocument() : nullptr);
1742 XMLConfigImpl* impl = new XMLConfigImpl(raw.second, (m_impl==nullptr), this, m_log);
1744 // If we held the document, transfer it to the impl. If we didn't, it's a no-op.
1745 impl->setDocument(docjanitor.release());
1747 // Perform the swap inside a lock.
1750 SharedLock locker(m_lock, false);
1754 return make_pair(false,(DOMElement*)nullptr);