2 * Licensed to the University Corporation for Advanced Internet
3 * Development, Inc. (UCAID) under one or more contributor license
4 * agreements. See the NOTICE file distributed with this work for
5 * additional information regarding copyright ownership.
7 * UCAID licenses this file to you under the Apache License,
8 * Version 2.0 (the "License"); you may not use this file except
9 * in compliance with the License. You may obtain a copy of the
12 * http://www.apache.org/licenses/LICENSE-2.0
14 * Unless required by applicable law or agreed to in writing,
15 * software distributed under the License is distributed on an
16 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
17 * either express or implied. See the License for the specific
18 * language governing permissions and limitations under the License.
22 * XMLServiceProvider.cpp
24 * XML-based SP configuration and mgmt.
28 #include "exceptions.h"
30 #include "AccessControl.h"
31 #include "Application.h"
32 #include "RequestMapper.h"
33 #include "ServiceProvider.h"
34 #include "SessionCache.h"
36 #include "SPRequest.h"
37 #include "binding/ProtocolProvider.h"
38 #include "handler/LogoutInitiator.h"
39 #include "handler/SessionInitiator.h"
40 #include "remoting/ListenerService.h"
41 #include "util/DOMPropertySet.h"
42 #include "util/SPConstants.h"
44 #if defined(XMLTOOLING_LOG4SHIB)
45 # include <log4shib/PropertyConfigurator.hh>
46 #elif defined(XMLTOOLING_LOG4CPP)
47 # include <log4cpp/PropertyConfigurator.hh>
49 # error "Supported logging library not available."
52 #include <xercesc/util/XMLUniDefs.hpp>
53 #include <xercesc/util/XMLStringTokenizer.hpp>
54 #include <xmltooling/XMLToolingConfig.h>
55 #include <xmltooling/version.h>
56 #include <xmltooling/util/NDC.h>
57 #include <xmltooling/util/ReloadableXMLFile.h>
58 #include <xmltooling/util/TemplateEngine.h>
59 #include <xmltooling/util/Threads.h>
60 #include <xmltooling/util/XMLHelper.h>
63 # include "attribute/filtering/AttributeFilter.h"
64 # include "attribute/resolver/AttributeExtractor.h"
65 # include "attribute/resolver/AttributeResolver.h"
66 # include "security/PKIXTrustEngine.h"
67 # include "security/SecurityPolicyProvider.h"
68 # include <saml/SAMLConfig.h>
69 # include <saml/version.h>
70 # include <saml/binding/ArtifactMap.h>
71 # include <saml/binding/SAMLArtifact.h>
72 # include <saml/saml1/core/Assertions.h>
73 # include <saml/saml2/core/Assertions.h>
74 # include <saml/saml2/binding/SAML2ArtifactType0004.h>
75 # include <saml/saml2/metadata/Metadata.h>
76 # include <saml/saml2/metadata/MetadataProvider.h>
77 # include <saml/util/SAMLConstants.h>
78 # include <xmltooling/security/ChainingTrustEngine.h>
79 # include <xmltooling/security/CredentialResolver.h>
80 # include <xmltooling/security/SecurityHelper.h>
81 # include <xmltooling/util/ReplayCache.h>
82 # include <xmltooling/util/StorageService.h>
83 # include <xsec/utils/XSECPlatformUtils.hpp>
84 using namespace opensaml::saml2;
85 using namespace opensaml::saml2p;
86 using namespace opensaml::saml2md;
87 using namespace opensaml;
89 # include "lite/SAMLConstants.h"
92 using namespace shibsp;
93 using namespace xmltooling;
97 # define min(a,b) (((a) < (b)) ? (a) : (b))
102 #if defined (_MSC_VER)
103 #pragma warning( push )
104 #pragma warning( disable : 4250 )
107 static vector<const Handler*> g_noHandlers;
109 // Application configuration wrapper
110 class SHIBSP_DLLLOCAL XMLApplication : public Application, public Remoted, public DOMPropertySet, public DOMNodeFilter
113 XMLApplication(const ServiceProvider*, const ProtocolProvider*, DOMElement*, const XMLApplication* base=nullptr);
114 ~XMLApplication() { cleanup(); }
116 const char* getHash() const {return m_hash.c_str();}
119 SAMLArtifact* generateSAML1Artifact(const EntityDescriptor* relyingParty) const {
120 throw ConfigurationException("No support for SAML 1.x artifact generation.");
122 SAML2Artifact* generateSAML2Artifact(const EntityDescriptor* relyingParty) const {
123 pair<bool,int> index = make_pair(false,0);
124 const PropertySet* props = getRelyingParty(relyingParty);
125 index = props->getInt("artifactEndpointIndex");
127 index = getArtifactEndpointIndex();
128 pair<bool,const char*> entityID = props->getString("entityID");
129 return new SAML2ArtifactType0004(
130 SecurityHelper::doHash("SHA1", entityID.second, strlen(entityID.second), false),
131 index.first ? index.second : 1
135 MetadataProvider* getMetadataProvider(bool required=true) const {
136 if (required && !m_base && !m_metadata)
137 throw ConfigurationException("No MetadataProvider available.");
138 return (!m_metadata && m_base) ? m_base->getMetadataProvider(required) : m_metadata;
140 TrustEngine* getTrustEngine(bool required=true) const {
141 if (required && !m_base && !m_trust)
142 throw ConfigurationException("No TrustEngine available.");
143 return (!m_trust && m_base) ? m_base->getTrustEngine(required) : m_trust;
145 AttributeExtractor* getAttributeExtractor() const {
146 return (!m_attrExtractor && m_base) ? m_base->getAttributeExtractor() : m_attrExtractor;
148 AttributeFilter* getAttributeFilter() const {
149 return (!m_attrFilter && m_base) ? m_base->getAttributeFilter() : m_attrFilter;
151 AttributeResolver* getAttributeResolver() const {
152 return (!m_attrResolver && m_base) ? m_base->getAttributeResolver() : m_attrResolver;
154 CredentialResolver* getCredentialResolver() const {
155 return (!m_credResolver && m_base) ? m_base->getCredentialResolver() : m_credResolver;
157 const PropertySet* getRelyingParty(const EntityDescriptor* provider) const;
158 const PropertySet* getRelyingParty(const XMLCh* entityID) const;
159 const vector<const XMLCh*>* getAudiences() const {
160 return (m_audiences.empty() && m_base) ? m_base->getAudiences() : &m_audiences;
163 string getNotificationURL(const char* resource, bool front, unsigned int index) const;
165 const vector<string>& getRemoteUserAttributeIds() const {
166 return (m_remoteUsers.empty() && m_base) ? m_base->getRemoteUserAttributeIds() : m_remoteUsers;
169 void clearHeader(SPRequest& request, const char* rawname, const char* cginame) const;
170 void setHeader(SPRequest& request, const char* name, const char* value) const;
171 string getSecureHeader(const SPRequest& request, const char* name) const;
173 const SessionInitiator* getDefaultSessionInitiator() const;
174 const SessionInitiator* getSessionInitiatorById(const char* id) const;
175 const Handler* getDefaultAssertionConsumerService() const;
176 const Handler* getAssertionConsumerServiceByIndex(unsigned short index) const;
177 const Handler* getAssertionConsumerServiceByProtocol(const XMLCh* protocol, const char* binding=nullptr) const;
178 const vector<const Handler*>& getAssertionConsumerServicesByBinding(const XMLCh* binding) const;
179 const Handler* getHandler(const char* path) const;
180 void getHandlers(vector<const Handler*>& handlers) const;
182 void receive(DDF& in, ostream& out) {
183 // Only current function is to return the headers to clear.
185 DDF ret=DDF(nullptr).list();
186 DDFJanitor jret(ret);
187 for (vector< pair<string,string> >::const_iterator i = m_unsetHeaders.begin(); i!=m_unsetHeaders.end(); ++i) {
188 header = DDF(i->first.c_str()).string(i->second.c_str());
194 // Provides filter to exclude special config elements.
195 #ifdef SHIBSP_XERCESC_SHORT_ACCEPTNODE
200 acceptNode(const DOMNode* node) const;
203 template <class T> T* doChainedPlugins(
204 PluginManager<T,string,const DOMElement*>& pluginMgr,
205 const char* pluginType,
206 const char* chainingType,
207 const XMLCh* localName,
210 const char* dummyType=nullptr
212 void doAttributeInfo();
213 void doHandlers(const ProtocolProvider*, const DOMElement*, Category&);
214 void doSSO(const ProtocolProvider&, set<string>&, DOMElement*, Category&);
215 void doLogout(const ProtocolProvider&, set<string>&, DOMElement*, Category&);
216 void doNameIDMgmt(const ProtocolProvider&, set<string>&, DOMElement*, Category&);
217 void doArtifactResolution(const ProtocolProvider&, const char*, DOMElement*, Category&);
219 const XMLApplication* m_base;
221 std::pair<std::string,std::string> m_attributePrefix;
223 void doAttributePlugins(DOMElement* e, Category& log);
224 MetadataProvider* m_metadata;
225 TrustEngine* m_trust;
226 AttributeExtractor* m_attrExtractor;
227 AttributeFilter* m_attrFilter;
228 AttributeResolver* m_attrResolver;
229 CredentialResolver* m_credResolver;
230 vector<const XMLCh*> m_audiences;
232 // RelyingParty properties
233 map<xstring,PropertySet*> m_partyMap;
235 vector<string> m_remoteUsers,m_frontLogout,m_backLogout;
237 // manage handler objects
238 vector<Handler*> m_handlers;
240 // maps location (path info) to applicable handlers
241 map<string,const Handler*> m_handlerMap;
243 // maps unique indexes to consumer services
244 map<unsigned int,const Handler*> m_acsIndexMap;
246 // pointer to default consumer service
247 const Handler* m_acsDefault;
249 // maps binding strings to supporting consumer service(s)
250 typedef map< xstring,vector<const Handler*> > ACSBindingMap;
251 ACSBindingMap m_acsBindingMap;
253 // maps protocol strings to supporting consumer service(s)
254 typedef map< xstring,vector<const Handler*> > ACSProtocolMap;
255 ACSProtocolMap m_acsProtocolMap;
257 // pointer to default session initiator
258 const SessionInitiator* m_sessionInitDefault;
260 // maps unique ID strings to session initiators
261 map<string,const SessionInitiator*> m_sessionInitMap;
263 // pointer to default artifact resolution service
264 const Handler* m_artifactResolutionDefault;
266 pair<bool,int> getArtifactEndpointIndex() const {
267 if (m_artifactResolutionDefault) return m_artifactResolutionDefault->getInt("index");
268 return m_base ? m_base->getArtifactEndpointIndex() : make_pair(false,0);
272 // Top-level configuration implementation
273 class SHIBSP_DLLLOCAL XMLConfig;
274 class SHIBSP_DLLLOCAL XMLConfigImpl : public DOMPropertySet, public DOMNodeFilter
277 XMLConfigImpl(const DOMElement* e, bool first, XMLConfig* outer, Category& log);
280 RequestMapper* m_requestMapper;
281 map<string,Application*> m_appmap;
283 TransactionLog* m_tranLog;
284 SecurityPolicyProvider* m_policy;
285 vector< pair< string, pair<string,string> > > m_transportOptions;
288 // Provides filter to exclude special config elements.
289 #ifdef SHIBSP_XERCESC_SHORT_ACCEPTNODE
294 acceptNode(const DOMNode* node) const;
296 void setDocument(DOMDocument* doc) {
301 void doExtensions(const DOMElement*, const char*, Category&);
302 void doListener(const DOMElement*, XMLConfig*, Category&);
303 void doCaching(const DOMElement*, XMLConfig*, Category&);
306 DOMDocument* m_document;
309 class SHIBSP_DLLLOCAL XMLConfig : public ServiceProvider, public ReloadableXMLFile
315 XMLConfig(const DOMElement* e) : ReloadableXMLFile(e, Category::getInstance(SHIBSP_LOGCAT".Config")),
316 m_impl(nullptr), m_listener(nullptr), m_sessionCache(nullptr) {
326 delete m_sessionCache;
329 SAMLConfig::getConfig().setArtifactMap(nullptr);
330 XMLToolingConfig::getConfig().setReplayCache(nullptr);
331 for_each(m_storage.begin(), m_storage.end(), cleanup_pair<string,StorageService>());
338 ReloadableXMLFile::lock();
339 if (m_impl->m_policy)
340 m_impl->m_policy->lock();
344 if (m_impl->m_policy)
345 m_impl->m_policy->unlock();
346 ReloadableXMLFile::unlock();
351 const PropertySet* getParent() const { return m_impl->getParent(); }
352 void setParent(const PropertySet* parent) {return m_impl->setParent(parent);}
353 pair<bool,bool> getBool(const char* name, const char* ns=nullptr) const {return m_impl->getBool(name,ns);}
354 pair<bool,const char*> getString(const char* name, const char* ns=nullptr) const {return m_impl->getString(name,ns);}
355 pair<bool,const XMLCh*> getXMLString(const char* name, const char* ns=nullptr) const {return m_impl->getXMLString(name,ns);}
356 pair<bool,unsigned int> getUnsignedInt(const char* name, const char* ns=nullptr) const {return m_impl->getUnsignedInt(name,ns);}
357 pair<bool,int> getInt(const char* name, const char* ns=nullptr) const {return m_impl->getInt(name,ns);}
358 void getAll(map<string,const char*>& properties) const {return m_impl->getAll(properties);}
359 const PropertySet* getPropertySet(const char* name, const char* ns="urn:mace:shibboleth:2.0:native:sp:config") const {return m_impl->getPropertySet(name,ns);}
360 const DOMElement* getElement() const {return m_impl->getElement();}
365 void receive(DDF& in, ostream& out);
367 TransactionLog* getTransactionLog() const {
368 if (m_impl->m_tranLog)
369 return m_impl->m_tranLog;
370 throw ConfigurationException("No TransactionLog available.");
373 StorageService* getStorageService(const char* id) const {
375 map<string,StorageService*>::const_iterator i=m_storage.find(id);
376 if (i!=m_storage.end())
379 else if (!m_storage.empty())
380 return m_storage.begin()->second;
385 ListenerService* getListenerService(bool required=true) const {
386 if (required && !m_listener)
387 throw ConfigurationException("No ListenerService available.");
391 SessionCache* getSessionCache(bool required=true) const {
392 if (required && !m_sessionCache)
393 throw ConfigurationException("No SessionCache available.");
394 return m_sessionCache;
397 RequestMapper* getRequestMapper(bool required=true) const {
398 if (required && !m_impl->m_requestMapper)
399 throw ConfigurationException("No RequestMapper available.");
400 return m_impl->m_requestMapper;
403 const Application* getApplication(const char* applicationId) const {
404 map<string,Application*>::const_iterator i=m_impl->m_appmap.find(applicationId ? applicationId : "default");
405 return (i!=m_impl->m_appmap.end()) ? i->second : nullptr;
409 SecurityPolicyProvider* getSecurityPolicyProvider(bool required=true) const {
410 if (required && !m_impl->m_policy)
411 throw ConfigurationException("No SecurityPolicyProvider available.");
412 return m_impl->m_policy;
415 const PropertySet* getPolicySettings(const char* id) const {
416 return getSecurityPolicyProvider()->getPolicySettings(id);
419 const vector<const SecurityPolicyRule*>& getPolicyRules(const char* id) const {
420 return getSecurityPolicyProvider()->getPolicyRules(id);
423 bool setTransportOptions(SOAPTransport& transport) const {
425 vector< pair< string, pair<string,string> > >::const_iterator opt;
426 for (opt = m_impl->m_transportOptions.begin(); opt != m_impl->m_transportOptions.end(); ++opt) {
427 if (!transport.setProviderOption(opt->first.c_str(), opt->second.first.c_str(), opt->second.second.c_str())) {
428 m_log.error("failed to set SOAPTransport option (%s)", opt->second.first.c_str());
437 pair<bool,DOMElement*> background_load();
440 friend class XMLConfigImpl;
441 XMLConfigImpl* m_impl;
442 ListenerService* m_listener;
443 SessionCache* m_sessionCache;
445 map<string,StorageService*> m_storage;
449 #if defined (_MSC_VER)
450 #pragma warning( pop )
453 static const XMLCh applicationId[] = UNICODE_LITERAL_13(a,p,p,l,i,c,a,t,i,o,n,I,d);
454 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);
455 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);
456 static const XMLCh _ArtifactMap[] = UNICODE_LITERAL_11(A,r,t,i,f,a,c,t,M,a,p);
457 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);
458 static const XMLCh _AttributeFilter[] = UNICODE_LITERAL_15(A,t,t,r,i,b,u,t,e,F,i,l,t,e,r);
459 static const XMLCh _AttributeResolver[] = UNICODE_LITERAL_17(A,t,t,r,i,b,u,t,e,R,e,s,o,l,v,e,r);
460 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);
461 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);
462 static const XMLCh _Audience[] = UNICODE_LITERAL_8(A,u,d,i,e,n,c,e);
463 static const XMLCh Binding[] = UNICODE_LITERAL_7(B,i,n,d,i,n,g);
464 static const XMLCh Channel[]= UNICODE_LITERAL_7(C,h,a,n,n,e,l);
465 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);
466 static const XMLCh _default[] = UNICODE_LITERAL_7(d,e,f,a,u,l,t);
467 static const XMLCh _Extensions[] = UNICODE_LITERAL_10(E,x,t,e,n,s,i,o,n,s);
468 static const XMLCh _fatal[] = UNICODE_LITERAL_5(f,a,t,a,l);
469 static const XMLCh _Handler[] = UNICODE_LITERAL_7(H,a,n,d,l,e,r);
470 static const XMLCh _id[] = UNICODE_LITERAL_2(i,d);
471 static const XMLCh _index[] = UNICODE_LITERAL_5(i,n,d,e,x);
472 static const XMLCh InProcess[] = UNICODE_LITERAL_9(I,n,P,r,o,c,e,s,s);
473 static const XMLCh Library[] = UNICODE_LITERAL_7(L,i,b,r,a,r,y);
474 static const XMLCh Listener[] = UNICODE_LITERAL_8(L,i,s,t,e,n,e,r);
475 static const XMLCh Location[] = UNICODE_LITERAL_8(L,o,c,a,t,i,o,n);
476 static const XMLCh logger[] = UNICODE_LITERAL_6(l,o,g,g,e,r);
477 static const XMLCh Logout[] = UNICODE_LITERAL_6(L,o,g,o,u,t);
478 static const XMLCh _LogoutInitiator[] = UNICODE_LITERAL_15(L,o,g,o,u,t,I,n,i,t,i,a,t,o,r);
479 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);
480 static const XMLCh _MetadataProvider[] = UNICODE_LITERAL_16(M,e,t,a,d,a,t,a,P,r,o,v,i,d,e,r);
481 static const XMLCh NameIDMgmt[] = UNICODE_LITERAL_10(N,a,m,e,I,D,M,g,m,t);
482 static const XMLCh Notify[] = UNICODE_LITERAL_6(N,o,t,i,f,y);
483 static const XMLCh _option[] = UNICODE_LITERAL_6(o,p,t,i,o,n);
484 static const XMLCh OutOfProcess[] = UNICODE_LITERAL_12(O,u,t,O,f,P,r,o,c,e,s,s);
485 static const XMLCh _path[] = UNICODE_LITERAL_4(p,a,t,h);
486 static const XMLCh _ProtocolProvider[] = UNICODE_LITERAL_16(P,r,o,t,o,c,o,l,P,r,o,v,i,d,e,r);
487 static const XMLCh _provider[] = UNICODE_LITERAL_8(p,r,o,v,i,d,e,r);
488 static const XMLCh RelyingParty[] = UNICODE_LITERAL_12(R,e,l,y,i,n,g,P,a,r,t,y);
489 static const XMLCh _ReplayCache[] = UNICODE_LITERAL_11(R,e,p,l,a,y,C,a,c,h,e);
490 static const XMLCh _RequestMapper[] = UNICODE_LITERAL_13(R,e,q,u,e,s,t,M,a,p,p,e,r);
491 static const XMLCh RequestMap[] = UNICODE_LITERAL_10(R,e,q,u,e,s,t,M,a,p);
492 static const XMLCh SecurityPolicies[] = UNICODE_LITERAL_16(S,e,c,u,r,i,t,y,P,o,l,i,c,i,e,s);
493 static const XMLCh _SecurityPolicyProvider[] = UNICODE_LITERAL_22(S,e,c,u,r,i,t,y,P,o,l,i,c,y,P,r,o,v,i,d,e,r);
494 static const XMLCh _SessionCache[] = UNICODE_LITERAL_12(S,e,s,s,i,o,n,C,a,c,h,e);
495 static const XMLCh _SessionInitiator[] = UNICODE_LITERAL_16(S,e,s,s,i,o,n,I,n,i,t,i,a,t,o,r);
496 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);
497 static const XMLCh Site[] = UNICODE_LITERAL_4(S,i,t,e);
498 static const XMLCh SSO[] = UNICODE_LITERAL_3(S,S,O);
499 static const XMLCh _StorageService[] = UNICODE_LITERAL_14(S,t,o,r,a,g,e,S,e,r,v,i,c,e);
500 static const XMLCh TCPListener[] = UNICODE_LITERAL_11(T,C,P,L,i,s,t,e,n,e,r);
501 static const XMLCh tranLogFiller[] = UNICODE_LITERAL_13(t,r,a,n,L,o,g,F,i,l,l,e,r);
502 static const XMLCh tranLogFormat[] = UNICODE_LITERAL_13(t,r,a,n,L,o,g,F,o,r,m,a,t);
503 static const XMLCh TransportOption[] = UNICODE_LITERAL_15(T,r,a,n,s,p,o,r,t,O,p,t,i,o,n);
504 static const XMLCh _TrustEngine[] = UNICODE_LITERAL_11(T,r,u,s,t,E,n,g,i,n,e);
505 static const XMLCh _type[] = UNICODE_LITERAL_4(t,y,p,e);
506 static const XMLCh UnixListener[] = UNICODE_LITERAL_12(U,n,i,x,L,i,s,t,e,n,e,r);
510 ServiceProvider* XMLServiceProviderFactory(const DOMElement* const & e)
512 return new XMLConfig(e);
516 XMLApplication::XMLApplication(
517 const ServiceProvider* sp,
518 const ProtocolProvider* pp,
520 const XMLApplication* base
521 ) : Application(sp), m_base(base),
523 m_metadata(nullptr), m_trust(nullptr),
524 m_attrExtractor(nullptr), m_attrFilter(nullptr), m_attrResolver(nullptr),
525 m_credResolver(nullptr),
527 m_acsDefault(nullptr), m_sessionInitDefault(nullptr), m_artifactResolutionDefault(nullptr)
530 xmltooling::NDC ndc("XMLApplication");
532 Category& log=Category::getInstance(SHIBSP_LOGCAT".Application");
535 // First load any property sets.
536 load(e,nullptr,this);
540 SPConfig& conf=SPConfig::getConfig();
542 XMLToolingConfig& xmlConf=XMLToolingConfig::getConfig();
545 // This used to be an actual hash, but now it's just a hex-encode to avoid xmlsec dependency.
546 static char DIGITS[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
547 string tohash=getId();
548 tohash+=getString("entityID").second;
549 for (const char* ch = tohash.c_str(); *ch; ++ch) {
550 m_hash += (DIGITS[((unsigned char)(0xF0 & *ch)) >> 4 ]);
551 m_hash += (DIGITS[0x0F & *ch]);
556 if (conf.isEnabled(SPConfig::Handlers))
557 doHandlers(pp, e, log);
560 DOMNodeList* nlist = e->getElementsByTagNameNS(shibspconstants::SHIB2SPCONFIG_NS, Notify);
561 for (XMLSize_t i = 0; nlist && i < nlist->getLength(); ++i) {
562 if (nlist->item(i)->getParentNode()->isSameNode(e)) {
563 const XMLCh* channel = static_cast<DOMElement*>(nlist->item(i))->getAttributeNS(nullptr, Channel);
564 string loc(XMLHelper::getAttrString(static_cast<DOMElement*>(nlist->item(i)), nullptr, Location));
566 if (channel && *channel == chLatin_f)
567 m_frontLogout.push_back(loc);
569 m_backLogout.push_back(loc);
575 nlist = e->getElementsByTagNameNS(samlconstants::SAML20_NS, Audience::LOCAL_NAME);
576 if (nlist && nlist->getLength()) {
577 log.warn("use of <saml:Audience> elements outside of a Security Policy Rule is deprecated");
578 for (XMLSize_t i = 0; i < nlist->getLength(); ++i)
579 if (nlist->item(i)->getParentNode()->isSameNode(e) && nlist->item(i)->hasChildNodes())
580 m_audiences.push_back(nlist->item(i)->getFirstChild()->getNodeValue());
583 if (conf.isEnabled(SPConfig::Metadata)) {
584 auto_ptr<MetadataProvider> mp(
586 SAMLConfig::getConfig().MetadataProviderManager, "MetadataProvider", CHAINING_METADATA_PROVIDER, _MetadataProvider, e, log
592 m_metadata = mp.release();
595 log.crit("no MetadataProvider available, configuration is probably unusable");
598 catch (exception& ex) {
599 log.crit("error initializing MetadataProvider: %s", ex.what());
603 if (conf.isEnabled(SPConfig::Trust)) {
604 m_trust = doChainedPlugins(xmlConf.TrustEngineManager, "TrustEngine", CHAINING_TRUSTENGINE, _TrustEngine, e, log);
605 if (!m_trust && !m_base) {
607 "no TrustEngine specified or installed, using default chain {%s, %s}",
608 EXPLICIT_KEY_TRUSTENGINE, SHIBBOLETH_PKIX_TRUSTENGINE
610 m_trust = xmlConf.TrustEngineManager.newPlugin(CHAINING_TRUSTENGINE, nullptr);
611 ChainingTrustEngine* trustchain = dynamic_cast<ChainingTrustEngine*>(m_trust);
613 trustchain->addTrustEngine(xmlConf.TrustEngineManager.newPlugin(EXPLICIT_KEY_TRUSTENGINE, nullptr));
614 trustchain->addTrustEngine(xmlConf.TrustEngineManager.newPlugin(SHIBBOLETH_PKIX_TRUSTENGINE, nullptr));
619 if (conf.isEnabled(SPConfig::AttributeResolution))
620 doAttributePlugins(e, log);
622 if (conf.isEnabled(SPConfig::Credentials)) {
623 m_credResolver = doChainedPlugins(
624 xmlConf.CredentialResolverManager, "CredentialResolver", CHAINING_CREDENTIAL_RESOLVER, _CredentialResolver, e, log
628 // Finally, load relying parties.
629 const DOMElement* child = XMLHelper::getFirstChildElement(e, RelyingParty);
631 if (child->hasAttributeNS(nullptr, saml2::Attribute::NAME_ATTRIB_NAME)) {
632 auto_ptr<DOMPropertySet> rp(new DOMPropertySet());
633 rp->load(child, nullptr, this);
635 m_partyMap[child->getAttributeNS(nullptr, saml2::Attribute::NAME_ATTRIB_NAME)] = rp.release();
637 child = XMLHelper::getNextSiblingElement(child, RelyingParty);
639 if (base && m_partyMap.empty() && !base->m_partyMap.empty()) {
640 // For inheritance of RPs to work, we have to pull them in to the override by cloning the DOM.
641 child = XMLHelper::getFirstChildElement(base->getElement(), RelyingParty);
643 if (child->hasAttributeNS(nullptr, saml2::Attribute::NAME_ATTRIB_NAME)) {
644 DOMElement* rpclone = static_cast<DOMElement*>(child->cloneNode(true));
645 auto_ptr<DOMPropertySet> rp(new DOMPropertySet());
646 rp->load(rpclone, nullptr, this);
648 m_partyMap[rpclone->getAttributeNS(nullptr, saml2::Attribute::NAME_ATTRIB_NAME)] = rp.release();
650 child = XMLHelper::getNextSiblingElement(child, RelyingParty);
655 // Out of process only, we register a listener endpoint.
656 if (!conf.isEnabled(SPConfig::InProcess)) {
657 ListenerService* listener = sp->getListenerService(false);
659 string addr=string(getId()) + "::getHeaders::Application";
660 listener->regListener(addr.c_str(),this);
663 log.info("no ListenerService available, Application remoting disabled");
679 template <class T> T* XMLApplication::doChainedPlugins(
680 PluginManager<T,string,const DOMElement*>& pluginMgr,
681 const char* pluginType,
682 const char* chainingType,
683 const XMLCh* localName,
686 const char* dummyType
690 DOMElement* child = XMLHelper::getFirstChildElement(e, localName);
692 // Check for multiple.
693 if (XMLHelper::getNextSiblingElement(child, localName)) {
694 log.info("multiple %s plugins, wrapping in a chain", pluginType);
695 DOMElement* chain = child->getOwnerDocument()->createElementNS(nullptr, localName);
697 chain->appendChild(child);
698 child = XMLHelper::getFirstChildElement(e, localName);
702 e->appendChild(chain);
705 // Only a single one.
706 t = XMLHelper::getAttrString(child, nullptr, _type);
711 log.info("building %s of type %s...", pluginType, t.c_str());
712 return pluginMgr.newPlugin(t.c_str(), child);
715 throw ConfigurationException("$1 element had no type attribute.", params(1, pluginType));
718 catch (exception& ex) {
719 log.crit("error building %s: %s", pluginType, ex.what());
721 // Install a dummy version as a safety valve.
722 log.crit("installing safe %s in place of failed version", pluginType);
723 return pluginMgr.newPlugin(dummyType, nullptr);
731 void XMLApplication::doAttributeInfo()
733 // Populate prefix pair.
734 m_attributePrefix.second = "HTTP_";
735 pair<bool,const char*> prefix = getString("attributePrefix");
737 m_attributePrefix.first = prefix.second;
738 const char* pch = prefix.second;
740 m_attributePrefix.second += (isalnum(*pch) ? toupper(*pch) : '_');
745 pair<bool,const char*> attributes = getString("REMOTE_USER");
746 if (attributes.first) {
747 char* dup = strdup(attributes.second);
750 while (start && *start) {
751 while (*start && isspace(*start))
755 pos = strchr(start,' ');
758 m_remoteUsers.push_back(start);
759 start = pos ? pos+1 : nullptr;
764 // Load attribute ID lists for REMOTE_USER and header clearing.
765 if (SPConfig::getConfig().isEnabled(SPConfig::InProcess)) {
766 attributes = getString("unsetHeaders");
767 if (attributes.first) {
768 string transformedprefix(m_attributePrefix.second);
770 prefix = getString("metadataAttributePrefix");
774 transformedprefix += (isalnum(*pch) ? toupper(*pch) : '_');
778 char* dup = strdup(attributes.second);
781 while (start && *start) {
782 while (*start && isspace(*start))
786 pos = strchr(start,' ');
793 transformed += (isalnum(*pch) ? toupper(*pch) : '_');
797 m_unsetHeaders.push_back(pair<string,string>(m_attributePrefix.first + start, m_attributePrefix.second + transformed));
799 m_unsetHeaders.push_back(pair<string,string>(m_attributePrefix.first + prefix.second + start, transformedprefix + transformed));
800 start = pos ? pos+1 : nullptr;
803 m_unsetHeaders.push_back(pair<string,string>(m_attributePrefix.first + "Shib-Application-ID", m_attributePrefix.second + "SHIB_APPLICATION_ID"));
808 void XMLApplication::doHandlers(const ProtocolProvider* pp, const DOMElement* e, Category& log)
810 SPConfig& conf = SPConfig::getConfig();
812 Handler* handler = nullptr;
813 const PropertySet* sessions = getPropertySet("Sessions");
815 // Process assertion export handler.
816 pair<bool,const char*> location = sessions ? sessions->getString("exportLocation") : pair<bool,const char*>(false,nullptr);
817 if (location.first) {
819 DOMElement* exportElement = e->getOwnerDocument()->createElementNS(shibspconstants::SHIB2SPCONFIG_NS, _Handler);
820 exportElement->setAttributeNS(nullptr,Location,sessions->getXMLString("exportLocation").second);
821 pair<bool,const XMLCh*> exportACL = sessions->getXMLString("exportACL");
822 if (exportACL.first) {
823 static const XMLCh _acl[] = UNICODE_LITERAL_9(e,x,p,o,r,t,A,C,L);
824 exportElement->setAttributeNS(nullptr,_acl,exportACL.second);
826 handler = conf.HandlerManager.newPlugin(
827 samlconstants::SAML20_BINDING_URI, pair<const DOMElement*,const char*>(exportElement, getId())
829 m_handlers.push_back(handler);
831 // Insert into location map. If it contains the handlerURL, we skip past that part.
832 const char* hurl = sessions->getString("handlerURL").second;
834 hurl = "/Shibboleth.sso";
835 const char* pch = strstr(location.second, hurl);
837 location.second = pch + strlen(hurl);
838 if (*location.second == '/')
839 m_handlerMap[location.second]=handler;
841 m_handlerMap[string("/") + location.second]=handler;
843 catch (exception& ex) {
844 log.error("caught exception installing assertion lookup handler: %s", ex.what());
848 // Look for "shorthand" elements first.
849 set<string> protocols;
850 DOMElement* child = sessions ? XMLHelper::getFirstChildElement(sessions->getElement()) : nullptr;
852 if (XMLHelper::isNodeNamed(child, shibspconstants::SHIB2SPCONFIG_NS, SSO)) {
854 doSSO(*pp, protocols, child, log);
856 log.error("no ProtocolProvider, SSO auto-configure unsupported");
858 else if (XMLHelper::isNodeNamed(child, shibspconstants::SHIB2SPCONFIG_NS, Logout)) {
860 doLogout(*pp, protocols, child, log);
862 log.error("no ProtocolProvider, Logout auto-configure unsupported");
864 else if (XMLHelper::isNodeNamed(child, shibspconstants::SHIB2SPCONFIG_NS, NameIDMgmt)) {
866 doNameIDMgmt(*pp, protocols, child, log);
868 log.error("no ProtocolProvider, NameIDMgmt auto-configure unsupported");
871 break; // drop into next while loop
873 child = XMLHelper::getNextSiblingElement(child);
876 // Process other handlers.
877 bool hardACS=false, hardSessionInit=false, hardArt=false;
879 if (!child->hasAttributeNS(nullptr, Location)) {
880 auto_ptr_char hclass(child->getLocalName());
881 log.error("%s handler with no Location property cannot be processed", hclass.get());
882 child = XMLHelper::getNextSiblingElement(child);
886 if (XMLString::equals(child->getLocalName(), _AssertionConsumerService)) {
887 string bindprop(XMLHelper::getAttrString(child, nullptr, Binding));
888 if (bindprop.empty()) {
889 log.error("AssertionConsumerService element has no Binding attribute, skipping it...");
890 child = XMLHelper::getNextSiblingElement(child);
893 handler = conf.AssertionConsumerServiceManager.newPlugin(bindprop.c_str(), pair<const DOMElement*,const char*>(child, getId()));
894 // Map by binding and protocol (may be > 1 per protocol and binding)
895 m_acsBindingMap[handler->getXMLString("Binding").second].push_back(handler);
896 const XMLCh* protfamily = handler->getProtocolFamily();
898 m_acsProtocolMap[protfamily].push_back(handler);
899 m_acsIndexMap[handler->getUnsignedInt("index").second] = handler;
902 pair<bool,bool> defprop = handler->getBool("isDefault");
904 if (defprop.second) {
906 m_acsDefault = handler;
909 else if (!m_acsDefault)
910 m_acsDefault = handler;
913 else if (XMLString::equals(child->getLocalName(), _SessionInitiator)) {
914 string t(XMLHelper::getAttrString(child, nullptr, _type));
916 log.error("SessionInitiator element has no type attribute, skipping it...");
917 child = XMLHelper::getNextSiblingElement(child);
920 SessionInitiator* sihandler = conf.SessionInitiatorManager.newPlugin(t.c_str(), pair<const DOMElement*,const char*>(child, getId()));
922 pair<bool,const char*> si_id = handler->getString("id");
923 if (si_id.first && si_id.second)
924 m_sessionInitMap[si_id.second] = sihandler;
925 if (!hardSessionInit) {
926 pair<bool,bool> defprop = handler->getBool("isDefault");
928 if (defprop.second) {
929 hardSessionInit = true;
930 m_sessionInitDefault = sihandler;
933 else if (!m_sessionInitDefault) {
934 m_sessionInitDefault = sihandler;
938 else if (XMLString::equals(child->getLocalName(), _LogoutInitiator)) {
939 string t(XMLHelper::getAttrString(child, nullptr, _type));
941 log.error("LogoutInitiator element has no type attribute, skipping it...");
942 child = XMLHelper::getNextSiblingElement(child);
945 handler = conf.LogoutInitiatorManager.newPlugin(t.c_str(), pair<const DOMElement*,const char*>(child, getId()));
947 else if (XMLString::equals(child->getLocalName(), _ArtifactResolutionService)) {
948 string bindprop(XMLHelper::getAttrString(child, nullptr, Binding));
949 if (bindprop.empty()) {
950 log.error("ArtifactResolutionService element has no Binding attribute, skipping it...");
951 child = XMLHelper::getNextSiblingElement(child);
954 handler = conf.ArtifactResolutionServiceManager.newPlugin(bindprop.c_str(), pair<const DOMElement*,const char*>(child, getId()));
957 pair<bool,bool> defprop = handler->getBool("isDefault");
959 if (defprop.second) {
961 m_artifactResolutionDefault = handler;
964 else if (!m_artifactResolutionDefault)
965 m_artifactResolutionDefault = handler;
968 else if (XMLString::equals(child->getLocalName(), _SingleLogoutService)) {
969 string bindprop(XMLHelper::getAttrString(child, nullptr, Binding));
970 if (bindprop.empty()) {
971 log.error("SingleLogoutService element has no Binding attribute, skipping it...");
972 child = XMLHelper::getNextSiblingElement(child);
975 handler = conf.SingleLogoutServiceManager.newPlugin(bindprop.c_str(), pair<const DOMElement*,const char*>(child, getId()));
977 else if (XMLString::equals(child->getLocalName(), _ManageNameIDService)) {
978 string bindprop(XMLHelper::getAttrString(child, nullptr, Binding));
979 if (bindprop.empty()) {
980 log.error("ManageNameIDService element has no Binding attribute, skipping it...");
981 child = XMLHelper::getNextSiblingElement(child);
984 handler = conf.ManageNameIDServiceManager.newPlugin(bindprop.c_str(), pair<const DOMElement*,const char*>(child, getId()));
987 string t(XMLHelper::getAttrString(child, nullptr, _type));
989 log.error("Handler element has no type attribute, skipping it...");
990 child = XMLHelper::getNextSiblingElement(child);
993 handler = conf.HandlerManager.newPlugin(t.c_str(), pair<const DOMElement*,const char*>(child, getId()));
996 m_handlers.push_back(handler);
998 // Insert into location map.
999 location = handler->getString("Location");
1000 if (location.first && *location.second == '/')
1001 m_handlerMap[location.second] = handler;
1002 else if (location.first)
1003 m_handlerMap[string("/") + location.second] = handler;
1005 catch (exception& ex) {
1006 log.error("caught exception processing handler element: %s", ex.what());
1009 child = XMLHelper::getNextSiblingElement(child);
1013 void XMLApplication::doSSO(const ProtocolProvider& pp, set<string>& protocols, DOMElement* e, Category& log)
1015 if (!e->hasChildNodes())
1018 SPConfig& conf = SPConfig::getConfig();
1020 // Tokenize the protocol list inside the element.
1021 XMLStringTokenizer prottokens(e->getTextContent());
1022 while (prottokens.hasMoreTokens()) {
1023 auto_ptr_char prot(prottokens.nextToken());
1025 // Look for initiator.
1026 const PropertySet* initiator = pp.getInitiator(prot.get(), "SSO");
1028 log.info("auto-configuring SSO initiation for protocol (%s)", prot.get());
1029 pair<bool,const XMLCh*> inittype = initiator->getXMLString("id");
1030 if (inittype.first) {
1031 // Append a session initiator element of the designated type to the root element.
1032 DOMElement* sidom = e->getOwnerDocument()->createElementNS(shibspconstants::SHIB2SPCONFIG_NS, _SessionInitiator);
1033 sidom->setAttributeNS(nullptr, _type, inittype.second);
1034 e->appendChild(sidom);
1035 log.info("adding SessionInitiator of type (%s) to chain (/Login)", initiator->getString("id").second);
1037 doArtifactResolution(pp, prot.get(), e, log);
1038 protocols.insert(prot.get());
1041 log.error("missing id property on Initiator element, check config for protocol (%s)", prot.get());
1045 // Look for incoming bindings.
1046 const vector<const PropertySet*>& bindings = pp.getBindings(prot.get(), "SSO");
1047 if (!bindings.empty()) {
1048 log.info("auto-configuring SSO endpoints for protocol (%s)", prot.get());
1050 pair<bool,const XMLCh*> idprop,pathprop;
1051 for (vector<const PropertySet*>::const_iterator b = bindings.begin(); b != bindings.end(); ++b, ++index) {
1052 idprop = (*b)->getXMLString("id");
1053 pathprop = (*b)->getXMLString("path");
1054 if (idprop.first && pathprop.first) {
1055 DOMElement* acsdom = e->getOwnerDocument()->createElementNS(samlconstants::SAML20MD_NS, _AssertionConsumerService);
1056 acsdom->setAttributeNS(nullptr, Binding, idprop.second);
1057 acsdom->setAttributeNS(nullptr, Location, pathprop.second);
1058 xstring indexbuf(chDigit_1 + (index % 10), 1);
1060 indexbuf = (XMLCh)(chDigit_1 + (index / 10)) + indexbuf;
1061 acsdom->setAttributeNS(nullptr, _index, indexbuf.c_str());
1063 log.info("adding AssertionConsumerService for Binding (%s) at (%s)", (*b)->getString("id").second, (*b)->getString("path").second);
1064 Handler* handler = conf.AssertionConsumerServiceManager.newPlugin(
1065 (*b)->getString("id").second, pair<const DOMElement*,const char*>(acsdom, getId())
1067 m_handlers.push_back(handler);
1069 // Setup maps and defaults.
1070 m_acsBindingMap[handler->getXMLString("Binding").second].push_back(handler);
1071 const XMLCh* protfamily = handler->getProtocolFamily();
1073 m_acsProtocolMap[protfamily].push_back(handler);
1074 m_acsIndexMap[handler->getUnsignedInt("index").second] = handler;
1076 m_acsDefault = handler;
1078 // Insert into location map.
1079 pair<bool,const char*> location = handler->getString("Location");
1080 if (location.first && *location.second == '/')
1081 m_handlerMap[location.second] = handler;
1082 else if (location.first)
1083 m_handlerMap[string("/") + location.second] = handler;
1086 log.error("missing id or path property on Binding element, check config for protocol (%s)", prot.get());
1091 if (!initiator && bindings.empty()) {
1092 log.error("no SSO Initiator or Binding config for protocol (%s)", prot.get());
1096 // Handle discovery.
1097 static const XMLCh discoveryProtocol[] = UNICODE_LITERAL_17(d,i,s,c,o,v,e,r,y,P,r,o,t,o,c,o,l);
1098 static const XMLCh discoveryURL[] = UNICODE_LITERAL_12(d,i,s,c,o,v,e,r,y,U,R,L);
1099 static const XMLCh _URL[] = UNICODE_LITERAL_3(U,R,L);
1100 const XMLCh* discop = e->getAttributeNS(nullptr, discoveryProtocol);
1101 if (discop && *discop) {
1102 const XMLCh* discou = e->getAttributeNS(nullptr, discoveryURL);
1103 if (discou && *discou) {
1104 // Append a session initiator element of the designated type to the root element.
1105 DOMElement* sidom = e->getOwnerDocument()->createElementNS(shibspconstants::SHIB2SPCONFIG_NS, _SessionInitiator);
1106 sidom->setAttributeNS(nullptr, _type, discop);
1107 sidom->setAttributeNS(nullptr, _URL, discou);
1108 e->appendChild(sidom);
1109 if (log.isInfoEnabled()) {
1110 auto_ptr_char dp(discop);
1111 log.info("adding SessionInitiator of type (%s) to chain (/Login)", dp.get());
1115 log.error("SSO discoveryProtocol specified without discoveryURL");
1119 // Attach default Location to SSO element.
1120 static const XMLCh _loc[] = { chForwardSlash, chLatin_L, chLatin_o, chLatin_g, chLatin_i, chLatin_n, chNull };
1121 e->setAttributeNS(nullptr, Location, _loc);
1123 // Instantiate Chaining initiator around the SSO element.
1124 SessionInitiator* chain = conf.SessionInitiatorManager.newPlugin(
1125 CHAINING_SESSION_INITIATOR, pair<const DOMElement*,const char*>(e, getId())
1127 m_handlers.push_back(chain);
1128 m_sessionInitDefault = chain;
1129 m_handlerMap["/Login"] = chain;
1132 void XMLApplication::doLogout(const ProtocolProvider& pp, set<string>& protocols, DOMElement* e, Category& log)
1134 if (!e->hasChildNodes())
1137 SPConfig& conf = SPConfig::getConfig();
1139 // Tokenize the protocol list inside the element.
1140 XMLStringTokenizer prottokens(e->getTextContent());
1141 while (prottokens.hasMoreTokens()) {
1142 auto_ptr_char prot(prottokens.nextToken());
1144 // Look for initiator.
1145 const PropertySet* initiator = pp.getInitiator(prot.get(), "Logout");
1147 log.info("auto-configuring Logout initiation for protocol (%s)", prot.get());
1148 pair<bool,const XMLCh*> inittype = initiator->getXMLString("id");
1149 if (inittype.first) {
1150 // Append a logout initiator element of the designated type to the root element.
1151 DOMElement* lidom = e->getOwnerDocument()->createElementNS(shibspconstants::SHIB2SPCONFIG_NS, _LogoutInitiator);
1152 lidom->setAttributeNS(nullptr, _type, inittype.second);
1153 e->appendChild(lidom);
1154 log.info("adding LogoutInitiator of type (%s) to chain (/Logout)", initiator->getString("id").second);
1156 if (protocols.count(prot.get()) == 0) {
1157 doArtifactResolution(pp, prot.get(), e, log);
1158 protocols.insert(prot.get());
1162 log.error("missing id property on Initiator element, check config for protocol (%s)", prot.get());
1166 // Look for incoming bindings.
1167 const vector<const PropertySet*>& bindings = pp.getBindings(prot.get(), "Logout");
1168 if (!bindings.empty()) {
1169 log.info("auto-configuring Logout endpoints for protocol (%s)", prot.get());
1170 pair<bool,const XMLCh*> idprop,pathprop;
1171 for (vector<const PropertySet*>::const_iterator b = bindings.begin(); b != bindings.end(); ++b) {
1172 idprop = (*b)->getXMLString("id");
1173 pathprop = (*b)->getXMLString("path");
1174 if (idprop.first && pathprop.first) {
1175 DOMElement* slodom = e->getOwnerDocument()->createElementNS(samlconstants::SAML20MD_NS, _SingleLogoutService);
1176 slodom->setAttributeNS(nullptr, Binding, idprop.second);
1177 slodom->setAttributeNS(nullptr, Location, pathprop.second);
1179 log.info("adding SingleLogoutService for Binding (%s) at (%s)", (*b)->getString("id").second, (*b)->getString("path").second);
1180 Handler* handler = conf.SingleLogoutServiceManager.newPlugin(
1181 (*b)->getString("id").second, pair<const DOMElement*,const char*>(slodom, getId())
1183 m_handlers.push_back(handler);
1185 // Insert into location map.
1186 pair<bool,const char*> location = handler->getString("Location");
1187 if (location.first && *location.second == '/')
1188 m_handlerMap[location.second] = handler;
1189 else if (location.first)
1190 m_handlerMap[string("/") + location.second] = handler;
1193 log.error("missing id or path property on Binding element, check config for protocol (%s)", prot.get());
1197 if (protocols.count(prot.get()) == 0) {
1198 doArtifactResolution(pp, prot.get(), e, log);
1199 protocols.insert(prot.get());
1203 if (!initiator && bindings.empty()) {
1204 log.error("no Logout Initiator or Binding config for protocol (%s)", prot.get());
1208 // Attach default Location to Logout element.
1209 static const XMLCh _loc[] = { chForwardSlash, chLatin_L, chLatin_o, chLatin_g, chLatin_o, chLatin_u, chLatin_t, chNull };
1210 e->setAttributeNS(nullptr, Location, _loc);
1212 // Instantiate Chaining initiator around the SSO element.
1213 Handler* chain = conf.LogoutInitiatorManager.newPlugin(
1214 CHAINING_LOGOUT_INITIATOR, pair<const DOMElement*,const char*>(e, getId())
1216 m_handlers.push_back(chain);
1217 m_handlerMap["/Logout"] = chain;
1220 void XMLApplication::doNameIDMgmt(const ProtocolProvider& pp, set<string>& protocols, DOMElement* e, Category& log)
1222 if (!e->hasChildNodes())
1225 SPConfig& conf = SPConfig::getConfig();
1227 // Tokenize the protocol list inside the element.
1228 XMLStringTokenizer prottokens(e->getTextContent());
1229 while (prottokens.hasMoreTokens()) {
1230 auto_ptr_char prot(prottokens.nextToken());
1232 // Look for incoming bindings.
1233 const vector<const PropertySet*>& bindings = pp.getBindings(prot.get(), "NameIDMgmt");
1234 if (!bindings.empty()) {
1235 log.info("auto-configuring NameIDMgmt endpoints for protocol (%s)", prot.get());
1236 pair<bool,const XMLCh*> idprop,pathprop;
1237 for (vector<const PropertySet*>::const_iterator b = bindings.begin(); b != bindings.end(); ++b) {
1238 idprop = (*b)->getXMLString("id");
1239 pathprop = (*b)->getXMLString("path");
1240 if (idprop.first && pathprop.first) {
1241 DOMElement* nimdom = e->getOwnerDocument()->createElementNS(samlconstants::SAML20MD_NS, _ManageNameIDService);
1242 nimdom->setAttributeNS(nullptr, Binding, idprop.second);
1243 nimdom->setAttributeNS(nullptr, Location, pathprop.second);
1245 log.info("adding ManageNameIDService for Binding (%s) at (%s)", (*b)->getString("id").second, (*b)->getString("path").second);
1246 Handler* handler = conf.ManageNameIDServiceManager.newPlugin(
1247 (*b)->getString("id").second, pair<const DOMElement*,const char*>(nimdom, getId())
1249 m_handlers.push_back(handler);
1251 // Insert into location map.
1252 pair<bool,const char*> location = handler->getString("Location");
1253 if (location.first && *location.second == '/')
1254 m_handlerMap[location.second] = handler;
1255 else if (location.first)
1256 m_handlerMap[string("/") + location.second] = handler;
1259 log.error("missing id or path property on Binding element, check config for protocol (%s)", prot.get());
1263 if (protocols.count(prot.get()) == 0) {
1264 doArtifactResolution(pp, prot.get(), e, log);
1265 protocols.insert(prot.get());
1269 log.error("no NameIDMgmt Binding config for protocol (%s)", prot.get());
1274 void XMLApplication::doArtifactResolution(const ProtocolProvider& pp, const char* protocol, DOMElement* e, Category& log)
1276 SPConfig& conf = SPConfig::getConfig();
1278 // Look for incoming bindings.
1279 const vector<const PropertySet*>& bindings = pp.getBindings(protocol, "ArtifactResolution");
1280 if (!bindings.empty()) {
1281 log.info("auto-configuring ArtifactResolution endpoints for protocol (%s)", protocol);
1283 pair<bool,const XMLCh*> idprop,pathprop;
1284 for (vector<const PropertySet*>::const_iterator b = bindings.begin(); b != bindings.end(); ++b) {
1285 idprop = (*b)->getXMLString("id");
1286 pathprop = (*b)->getXMLString("path");
1287 if (idprop.first && pathprop.first) {
1288 DOMElement* artdom = e->getOwnerDocument()->createElementNS(samlconstants::SAML20MD_NS, _ArtifactResolutionService);
1289 artdom->setAttributeNS(nullptr, Binding, idprop.second);
1290 artdom->setAttributeNS(nullptr, Location, pathprop.second);
1291 xstring indexbuf(chDigit_1 + (index % 10), 1);
1293 indexbuf = (XMLCh)(chDigit_1 + (index / 10)) + indexbuf;
1294 artdom->setAttributeNS(nullptr, _index, indexbuf.c_str());
1296 log.info("adding ArtifactResolutionService for Binding (%s) at (%s)", (*b)->getString("id").second, (*b)->getString("path").second);
1297 Handler* handler = conf.ArtifactResolutionServiceManager.newPlugin(
1298 (*b)->getString("id").second, pair<const DOMElement*,const char*>(artdom, getId())
1300 m_handlers.push_back(handler);
1302 if (!m_artifactResolutionDefault)
1303 m_artifactResolutionDefault = handler;
1305 // Insert into location map.
1306 pair<bool,const char*> location = handler->getString("Location");
1307 if (location.first && *location.second == '/')
1308 m_handlerMap[location.second] = handler;
1309 else if (location.first)
1310 m_handlerMap[string("/") + location.second] = handler;
1313 log.error("missing id or path property on Binding element, check config for protocol (%s)", protocol);
1320 void XMLApplication::doAttributePlugins(DOMElement* e, Category& log)
1322 SPConfig& conf = SPConfig::getConfig();
1325 doChainedPlugins(conf.AttributeExtractorManager, "AttributeExtractor", CHAINING_ATTRIBUTE_EXTRACTOR, _AttributeExtractor, e, log);
1328 doChainedPlugins(conf.AttributeFilterManager, "AttributeFilter", CHAINING_ATTRIBUTE_FILTER, _AttributeFilter, e, log, DUMMY_ATTRIBUTE_FILTER);
1331 doChainedPlugins(conf.AttributeResolverManager, "AttributeResolver", CHAINING_ATTRIBUTE_RESOLVER, _AttributeResolver, e, log);
1333 if (m_unsetHeaders.empty()) {
1334 vector<string> unsetHeaders;
1335 if (m_attrExtractor) {
1336 Locker extlock(m_attrExtractor);
1337 m_attrExtractor->getAttributeIds(unsetHeaders);
1339 else if (m_base && m_base->m_attrExtractor) {
1340 Locker extlock(m_base->m_attrExtractor);
1341 m_base->m_attrExtractor->getAttributeIds(unsetHeaders);
1343 if (m_attrResolver) {
1344 Locker reslock(m_attrResolver);
1345 m_attrResolver->getAttributeIds(unsetHeaders);
1347 else if (m_base && m_base->m_attrResolver) {
1348 Locker extlock(m_base->m_attrResolver);
1349 m_base->m_attrResolver->getAttributeIds(unsetHeaders);
1351 if (!unsetHeaders.empty()) {
1352 string transformedprefix(m_attributePrefix.second);
1354 pair<bool,const char*> prefix = getString("metadataAttributePrefix");
1356 pch = prefix.second;
1358 transformedprefix += (isalnum(*pch) ? toupper(*pch) : '_');
1362 for (vector<string>::const_iterator hdr = unsetHeaders.begin(); hdr!=unsetHeaders.end(); ++hdr) {
1366 transformed += (isalnum(*pch) ? toupper(*pch) : '_');
1369 m_unsetHeaders.push_back(pair<string,string>(m_attributePrefix.first + *hdr, m_attributePrefix.second + transformed));
1371 m_unsetHeaders.push_back(pair<string,string>(m_attributePrefix.first + prefix.second + *hdr, transformedprefix + transformed));
1374 m_unsetHeaders.push_back(pair<string,string>(m_attributePrefix.first + "Shib-Application-ID", m_attributePrefix.second + "SHIB_APPLICATION_ID"));
1379 void XMLApplication::cleanup()
1381 ListenerService* listener=getServiceProvider().getListenerService(false);
1382 if (listener && SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess) && !SPConfig::getConfig().isEnabled(SPConfig::InProcess)) {
1383 string addr=string(getId()) + "::getHeaders::Application";
1384 listener->unregListener(addr.c_str(),this);
1386 for_each(m_handlers.begin(),m_handlers.end(),xmltooling::cleanup<Handler>());
1389 for_each(m_partyMap.begin(),m_partyMap.end(),cleanup_pair<xstring,PropertySet>());
1391 delete m_credResolver;
1392 m_credResolver = nullptr;
1393 delete m_attrResolver;
1394 m_attrResolver = nullptr;
1395 delete m_attrFilter;
1396 m_attrFilter = nullptr;
1397 delete m_attrExtractor;
1398 m_attrExtractor = nullptr;
1402 m_metadata = nullptr;
1406 #ifdef SHIBSP_XERCESC_SHORT_ACCEPTNODE
1409 DOMNodeFilter::FilterAction
1411 XMLApplication::acceptNode(const DOMNode* node) const
1413 const XMLCh* name=node->getLocalName();
1414 if (XMLString::equals(name,ApplicationOverride) ||
1415 XMLString::equals(name,_Audience) ||
1416 XMLString::equals(name,Notify) ||
1417 XMLString::equals(name,_Handler) ||
1418 XMLString::equals(name,_AssertionConsumerService) ||
1419 XMLString::equals(name,_ArtifactResolutionService) ||
1420 XMLString::equals(name,Logout) ||
1421 XMLString::equals(name,_LogoutInitiator) ||
1422 XMLString::equals(name,_ManageNameIDService) ||
1423 XMLString::equals(name,NameIDMgmt) ||
1424 XMLString::equals(name,_SessionInitiator) ||
1425 XMLString::equals(name,_SingleLogoutService) ||
1426 XMLString::equals(name,SSO) ||
1427 XMLString::equals(name,RelyingParty) ||
1428 XMLString::equals(name,_MetadataProvider) ||
1429 XMLString::equals(name,_TrustEngine) ||
1430 XMLString::equals(name,_CredentialResolver) ||
1431 XMLString::equals(name,_AttributeFilter) ||
1432 XMLString::equals(name,_AttributeExtractor) ||
1433 XMLString::equals(name,_AttributeResolver))
1434 return FILTER_REJECT;
1436 return FILTER_ACCEPT;
1441 const PropertySet* XMLApplication::getRelyingParty(const EntityDescriptor* provider) const
1446 map<xstring,PropertySet*>::const_iterator i=m_partyMap.find(provider->getEntityID());
1447 if (i!=m_partyMap.end())
1449 const EntitiesDescriptor* group=dynamic_cast<const EntitiesDescriptor*>(provider->getParent());
1451 if (group->getName()) {
1452 i=m_partyMap.find(group->getName());
1453 if (i!=m_partyMap.end())
1456 group=dynamic_cast<const EntitiesDescriptor*>(group->getParent());
1461 const PropertySet* XMLApplication::getRelyingParty(const XMLCh* entityID) const
1466 map<xstring,PropertySet*>::const_iterator i=m_partyMap.find(entityID);
1467 if (i!=m_partyMap.end())
1474 string XMLApplication::getNotificationURL(const char* resource, bool front, unsigned int index) const
1476 const vector<string>& locs = front ? m_frontLogout : m_backLogout;
1478 return m_base ? m_base->getNotificationURL(resource, front, index) : string();
1479 else if (index >= locs.size())
1482 #ifdef HAVE_STRCASECMP
1483 if (!resource || (strncasecmp(resource,"http://",7) && strncasecmp(resource,"https://",8)))
1485 if (!resource || (strnicmp(resource,"http://",7) && strnicmp(resource,"https://",8)))
1487 throw ConfigurationException("Request URL was not absolute.");
1489 const char* handler=locs[index].c_str();
1491 // Should never happen...
1492 if (!handler || (*handler!='/' && strncmp(handler,"http:",5) && strncmp(handler,"https:",6)))
1493 throw ConfigurationException(
1494 "Invalid Location property ($1) in Notify element for Application ($2)",
1495 params(2, handler ? handler : "null", getId())
1498 // The "Location" property can be in one of three formats:
1500 // 1) a full URI: http://host/foo/bar
1501 // 2) a hostless URI: http:///foo/bar
1502 // 3) a relative path: /foo/bar
1504 // # Protocol Host Path
1505 // 1 handler handler handler
1506 // 2 handler resource handler
1507 // 3 resource resource handler
1509 const char* path = nullptr;
1511 // Decide whether to use the handler or the resource for the "protocol"
1513 if (*handler != '/') {
1521 // break apart the "protocol" string into protocol, host, and "the rest"
1522 const char* colon=strchr(prot,':');
1524 const char* slash=strchr(colon,'/');
1528 // Compute the actual protocol and store.
1529 string notifyURL(prot, colon-prot);
1531 // create the "host" from either the colon/slash or from the target string
1532 // If prot == handler then we're in either #1 or #2, else #3.
1533 // If slash == colon then we're in #2.
1534 if (prot != handler || slash == colon) {
1535 colon = strchr(resource, ':');
1536 colon += 3; // Get past the ://
1537 slash = strchr(colon, '/');
1539 string host(colon, (slash ? slash-colon : strlen(colon)));
1542 notifyURL += host + path;
1546 void XMLApplication::clearHeader(SPRequest& request, const char* rawname, const char* cginame) const
1548 if (!m_attributePrefix.first.empty()) {
1549 string temp = m_attributePrefix.first + rawname;
1550 string temp2 = m_attributePrefix.second + (cginame + 5);
1551 request.clearHeader(temp.c_str(), temp2.c_str());
1554 m_base->clearHeader(request, rawname, cginame);
1557 request.clearHeader(rawname, cginame);
1561 void XMLApplication::setHeader(SPRequest& request, const char* name, const char* value) const
1563 if (!m_attributePrefix.first.empty()) {
1564 string temp = m_attributePrefix.first + name;
1565 request.setHeader(temp.c_str(), value);
1568 m_base->setHeader(request, name, value);
1571 request.setHeader(name, value);
1575 string XMLApplication::getSecureHeader(const SPRequest& request, const char* name) const
1577 if (!m_attributePrefix.first.empty()) {
1578 string temp = m_attributePrefix.first + name;
1579 return request.getSecureHeader(temp.c_str());
1582 return m_base->getSecureHeader(request,name);
1585 return request.getSecureHeader(name);
1589 const SessionInitiator* XMLApplication::getDefaultSessionInitiator() const
1591 if (m_sessionInitDefault) return m_sessionInitDefault;
1592 return m_base ? m_base->getDefaultSessionInitiator() : nullptr;
1595 const SessionInitiator* XMLApplication::getSessionInitiatorById(const char* id) const
1597 map<string,const SessionInitiator*>::const_iterator i=m_sessionInitMap.find(id);
1598 if (i!=m_sessionInitMap.end()) return i->second;
1599 return m_base ? m_base->getSessionInitiatorById(id) : nullptr;
1602 const Handler* XMLApplication::getDefaultAssertionConsumerService() const
1604 if (m_acsDefault) return m_acsDefault;
1605 return m_base ? m_base->getDefaultAssertionConsumerService() : nullptr;
1608 const Handler* XMLApplication::getAssertionConsumerServiceByIndex(unsigned short index) const
1610 map<unsigned int,const Handler*>::const_iterator i=m_acsIndexMap.find(index);
1611 if (i != m_acsIndexMap.end()) return i->second;
1612 return m_base ? m_base->getAssertionConsumerServiceByIndex(index) : nullptr;
1615 const Handler* XMLApplication::getAssertionConsumerServiceByProtocol(const XMLCh* protocol, const char* binding) const
1617 ACSProtocolMap::const_iterator i=m_acsProtocolMap.find(protocol);
1618 if (i != m_acsProtocolMap.end() && !i->second.empty()) {
1619 if (!binding || !*binding)
1620 return i->second.front();
1621 for (ACSProtocolMap::value_type::second_type::const_iterator j = i->second.begin(); j != i->second.end(); ++j) {
1622 if (!strcmp(binding, (*j)->getString("Binding").second))
1626 return m_base ? m_base->getAssertionConsumerServiceByProtocol(protocol) : nullptr;
1629 const vector<const Handler*>& XMLApplication::getAssertionConsumerServicesByBinding(const XMLCh* binding) const
1631 ACSBindingMap::const_iterator i=m_acsBindingMap.find(binding);
1632 if (i != m_acsBindingMap.end())
1634 return m_base ? m_base->getAssertionConsumerServicesByBinding(binding) : g_noHandlers;
1637 const Handler* XMLApplication::getHandler(const char* path) const
1640 wrap = wrap.substr(0,wrap.find(';'));
1641 map<string,const Handler*>::const_iterator i=m_handlerMap.find(wrap.substr(0,wrap.find('?')));
1642 if (i!=m_handlerMap.end())
1644 return m_base ? m_base->getHandler(path) : nullptr;
1647 void XMLApplication::getHandlers(vector<const Handler*>& handlers) const
1649 handlers.insert(handlers.end(), m_handlers.begin(), m_handlers.end());
1651 for (map<string,const Handler*>::const_iterator h = m_base->m_handlerMap.begin(); h != m_base->m_handlerMap.end(); ++h) {
1652 if (m_handlerMap.count(h->first) == 0)
1653 handlers.push_back(h->second);
1658 #ifdef SHIBSP_XERCESC_SHORT_ACCEPTNODE
1661 DOMNodeFilter::FilterAction
1663 XMLConfigImpl::acceptNode(const DOMNode* node) const
1665 if (!XMLString::equals(node->getNamespaceURI(),shibspconstants::SHIB2SPCONFIG_NS))
1666 return FILTER_ACCEPT;
1667 const XMLCh* name=node->getLocalName();
1668 if (XMLString::equals(name,ApplicationDefaults) ||
1669 XMLString::equals(name,_ArtifactMap) ||
1670 XMLString::equals(name,_Extensions) ||
1671 XMLString::equals(name,Listener) ||
1672 XMLString::equals(name,_ProtocolProvider) ||
1673 XMLString::equals(name,_RequestMapper) ||
1674 XMLString::equals(name,_ReplayCache) ||
1675 XMLString::equals(name,SecurityPolicies) ||
1676 XMLString::equals(name,_SecurityPolicyProvider) ||
1677 XMLString::equals(name,_SessionCache) ||
1678 XMLString::equals(name,Site) ||
1679 XMLString::equals(name,_StorageService) ||
1680 XMLString::equals(name,TCPListener) ||
1681 XMLString::equals(name,TransportOption) ||
1682 XMLString::equals(name,UnixListener))
1683 return FILTER_REJECT;
1685 return FILTER_ACCEPT;
1688 void XMLConfigImpl::doExtensions(const DOMElement* e, const char* label, Category& log)
1690 const DOMElement* exts = XMLHelper::getFirstChildElement(e, _Extensions);
1692 exts = XMLHelper::getFirstChildElement(exts, Library);
1694 string path(XMLHelper::getAttrString(exts, nullptr, _path));
1696 if (!path.empty()) {
1697 if (!XMLToolingConfig::getConfig().load_library(path.c_str(), (void*)exts))
1698 throw ConfigurationException("XMLToolingConfig::load_library failed.");
1699 log.debug("loaded %s extension library (%s)", label, path.c_str());
1702 catch (exception& e) {
1703 if (XMLHelper::getAttrBool(exts, false, _fatal)) {
1704 log.fatal("unable to load mandatory %s extension library %s: %s", label, path.c_str(), e.what());
1708 log.crit("unable to load optional %s extension library %s: %s", label, path.c_str(), e.what());
1711 exts = XMLHelper::getNextSiblingElement(exts, Library);
1716 void XMLConfigImpl::doListener(const DOMElement* e, XMLConfig* conf, Category& log)
1719 string plugtype(TCP_LISTENER_SERVICE);
1721 string plugtype(UNIX_LISTENER_SERVICE);
1723 DOMElement* child = XMLHelper::getFirstChildElement(e, UnixListener);
1725 plugtype = UNIX_LISTENER_SERVICE;
1727 child = XMLHelper::getFirstChildElement(e, TCPListener);
1729 plugtype = TCP_LISTENER_SERVICE;
1731 child = XMLHelper::getFirstChildElement(e, Listener);
1733 auto_ptr_char type(child->getAttributeNS(nullptr, _type));
1734 if (type.get() && *type.get())
1735 plugtype = type.get();
1740 log.info("building ListenerService of type %s...", plugtype.c_str());
1741 conf->m_listener = SPConfig::getConfig().ListenerServiceManager.newPlugin(plugtype.c_str(), child);
1744 void XMLConfigImpl::doCaching(const DOMElement* e, XMLConfig* conf, Category& log)
1746 SPConfig& spConf = SPConfig::getConfig();
1748 SAMLConfig& samlConf = SAMLConfig::getConfig();
1753 if (spConf.isEnabled(SPConfig::OutOfProcess)) {
1754 XMLToolingConfig& xmlConf = XMLToolingConfig::getConfig();
1755 // First build any StorageServices.
1756 child = XMLHelper::getFirstChildElement(e, _StorageService);
1758 string id(XMLHelper::getAttrString(child, nullptr, _id));
1759 string t(XMLHelper::getAttrString(child, nullptr, _type));
1762 log.info("building StorageService (%s) of type %s...", id.c_str(), t.c_str());
1763 conf->m_storage[id] = xmlConf.StorageServiceManager.newPlugin(t.c_str(), child);
1765 catch (exception& ex) {
1766 log.crit("failed to instantiate StorageService (%s): %s", id.c_str(), ex.what());
1769 child = XMLHelper::getNextSiblingElement(child, _StorageService);
1772 if (conf->m_storage.empty()) {
1773 log.info("no StorageService plugin(s) installed, using (mem) in-memory instance");
1774 conf->m_storage["mem"] = xmlConf.StorageServiceManager.newPlugin(MEMORY_STORAGE_SERVICE, nullptr);
1778 StorageService* replaySS = nullptr;
1779 child = XMLHelper::getFirstChildElement(e, _ReplayCache);
1781 string ssid(XMLHelper::getAttrString(child, nullptr, _StorageService));
1782 if (!ssid.empty()) {
1783 if (conf->m_storage.count(ssid)) {
1784 log.info("building ReplayCache on top of StorageService (%s)...", ssid.c_str());
1785 replaySS = conf->m_storage[ssid];
1788 log.error("unable to locate StorageService (%s), using arbitrary instance for ReplayCache", ssid.c_str());
1789 replaySS = conf->m_storage.begin()->second;
1793 log.info("no StorageService specified for ReplayCache, using arbitrary instance");
1794 replaySS = conf->m_storage.begin()->second;
1798 log.info("no ReplayCache specified, using arbitrary StorageService instance");
1799 replaySS = conf->m_storage.begin()->second;
1801 xmlConf.setReplayCache(new ReplayCache(replaySS));
1804 child = XMLHelper::getFirstChildElement(e, _ArtifactMap);
1806 string ssid(XMLHelper::getAttrString(child, nullptr, _StorageService));
1807 if (!ssid.empty()) {
1808 if (conf->m_storage.count(ssid)) {
1809 log.info("building ArtifactMap on top of StorageService (%s)...", ssid.c_str());
1810 samlConf.setArtifactMap(new ArtifactMap(child, conf->m_storage[ssid]));
1813 log.error("unable to locate StorageService (%s), using in-memory ArtifactMap", ssid.c_str());
1814 samlConf.setArtifactMap(new ArtifactMap(child));
1818 log.info("no StorageService specified, using in-memory ArtifactMap");
1819 samlConf.setArtifactMap(new ArtifactMap(child));
1823 log.info("no ArtifactMap specified, building in-memory ArtifactMap...");
1824 samlConf.setArtifactMap(new ArtifactMap(child));
1826 } // end of out of process caching components
1829 child = XMLHelper::getFirstChildElement(e, _SessionCache);
1831 string t(XMLHelper::getAttrString(child, nullptr, _type));
1833 log.info("building SessionCache of type %s...", t.c_str());
1834 conf->m_sessionCache = spConf.SessionCacheManager.newPlugin(t.c_str(), child);
1837 if (!conf->m_sessionCache) {
1838 log.info("no SessionCache specified, using StorageService-backed instance");
1839 conf->m_sessionCache = spConf.SessionCacheManager.newPlugin(STORAGESERVICE_SESSION_CACHE, nullptr);
1843 XMLConfigImpl::XMLConfigImpl(const DOMElement* e, bool first, XMLConfig* outer, Category& log)
1844 : m_requestMapper(nullptr),
1852 xmltooling::NDC ndc("XMLConfigImpl");
1856 SPConfig& conf=SPConfig::getConfig();
1857 XMLToolingConfig& xmlConf=XMLToolingConfig::getConfig();
1858 const DOMElement* SHAR=XMLHelper::getFirstChildElement(e, OutOfProcess);
1859 const DOMElement* SHIRE=XMLHelper::getFirstChildElement(e, InProcess);
1861 // Initialize logging manually in order to redirect log messages as soon as possible.
1862 if (conf.isEnabled(SPConfig::Logging)) {
1864 if (conf.isEnabled(SPConfig::OutOfProcess))
1865 logconf = XMLHelper::getAttrString(SHAR, nullptr, logger);
1866 else if (conf.isEnabled(SPConfig::InProcess))
1867 logconf = XMLHelper::getAttrString(SHIRE, nullptr, logger);
1868 if (logconf.empty())
1869 logconf = XMLHelper::getAttrString(e, nullptr, logger);
1870 if (logconf.empty() && !getenv("SHIBSP_LOGGING")) {
1871 // No properties found, so default them.
1872 if (conf.isEnabled(SPConfig::OutOfProcess) && !conf.isEnabled(SPConfig::InProcess))
1873 logconf = "shibd.logger";
1874 else if (!conf.isEnabled(SPConfig::OutOfProcess) && conf.isEnabled(SPConfig::InProcess))
1875 logconf = "native.logger";
1877 logconf = "shibboleth.logger";
1879 if (!logconf.empty()) {
1880 log.debug("loading new logging configuration from (%s), check log destination for status of configuration", logconf.c_str());
1881 if (!XMLToolingConfig::getConfig().log_config(logconf.c_str()))
1882 log.crit("failed to load new logging configuration from (%s)", logconf.c_str());
1886 m_tranLog = new TransactionLog(
1887 XMLHelper::getAttrString(SHAR, nullptr, tranLogFormat).c_str(),
1888 XMLHelper::getAttrString(SHAR, nullptr, tranLogFiller).c_str()
1893 // Re-log library versions now that logging is set up.
1894 log.info("Shibboleth SP Version %s", PACKAGE_VERSION);
1897 "Library versions: %s %s, Xerces-C %s, XML-Security-C %s, XMLTooling-C %s, OpenSAML-C %s, Shibboleth %s",
1898 # if defined(LOG4SHIB_VERSION)
1899 "log4shib", LOG4SHIB_VERSION,
1900 # elif defined(LOG4CPP_VERSION)
1901 "log4cpp", LOG4CPP_VERSION,
1905 XERCES_FULLVERSIONDOT, XSEC_FULLVERSIONDOT, gXMLToolingDotVersionStr, gOpenSAMLDotVersionStr, gShibSPDotVersionStr
1909 "Library versions: %s %s, Xerces-C %s, XMLTooling-C %s, Shibboleth %s",
1910 # if defined(LOG4SHIB_VERSION)
1911 "log4shib", LOG4SHIB_VERSION,
1912 # elif defined(LOG4CPP_VERSION)
1913 "log4cpp", LOG4CPP_VERSION,
1917 XERCES_FULLVERSIONDOT, gXMLToolingDotVersionStr, gShibSPDotVersionStr
1921 // First load any property sets.
1922 load(e,nullptr,this);
1926 // Much of the processing can only occur on the first instantiation.
1929 pair<bool,unsigned int> skew=getUnsignedInt("clockSkew");
1931 xmlConf.clock_skew_secs=min(skew.second,(60*60*24*7*28));
1933 pair<bool,const char*> unsafe = getString("unsafeChars");
1935 TemplateEngine::unsafe_chars = unsafe.second;
1937 unsafe = getString("allowedSchemes");
1939 HTTPResponse::getAllowedSchemes().clear();
1940 string schemes=unsafe.second;
1941 unsigned int j_sch=0;
1942 for (unsigned int i_sch=0; i_sch < schemes.length(); i_sch++) {
1943 if (schemes.at(i_sch)==' ') {
1944 HTTPResponse::getAllowedSchemes().push_back(schemes.substr(j_sch, i_sch-j_sch));
1948 HTTPResponse::getAllowedSchemes().push_back(schemes.substr(j_sch, schemes.length()-j_sch));
1952 doExtensions(e, "global", log);
1953 if (conf.isEnabled(SPConfig::OutOfProcess))
1954 doExtensions(SHAR, "out of process", log);
1956 if (conf.isEnabled(SPConfig::InProcess))
1957 doExtensions(SHIRE, "in process", log);
1959 // Instantiate the ListenerService and SessionCache objects.
1960 if (conf.isEnabled(SPConfig::Listener))
1961 doListener(e, outer, log);
1964 if (outer->m_listener && conf.isEnabled(SPConfig::OutOfProcess) && !conf.isEnabled(SPConfig::InProcess)) {
1965 outer->m_listener->regListener("set::RelayState", outer);
1966 outer->m_listener->regListener("get::RelayState", outer);
1967 outer->m_listener->regListener("set::PostData", outer);
1968 outer->m_listener->regListener("get::PostData", outer);
1971 if (conf.isEnabled(SPConfig::Caching))
1972 doCaching(e, outer, log);
1973 } // end of first-time-only stuff
1975 // Back to the fully dynamic stuff...next up is the RequestMapper.
1976 if (conf.isEnabled(SPConfig::RequestMapping)) {
1977 if (child = XMLHelper::getFirstChildElement(e, _RequestMapper)) {
1978 string t(XMLHelper::getAttrString(child, nullptr, _type));
1980 log.info("building RequestMapper of type %s...", t.c_str());
1981 m_requestMapper = conf.RequestMapperManager.newPlugin(t.c_str(), child);
1984 if (!m_requestMapper) {
1985 log.info("no RequestMapper specified, using 'Native' plugin with empty/default map");
1986 child = e->getOwnerDocument()->createElementNS(nullptr, _RequestMapper);
1987 DOMElement* mapperDummy = e->getOwnerDocument()->createElementNS(shibspconstants::SHIB2SPCONFIG_NS, RequestMap);
1988 mapperDummy->setAttributeNS(nullptr, applicationId, _default);
1989 child->appendChild(mapperDummy);
1990 m_requestMapper = conf.RequestMapperManager.newPlugin(NATIVE_REQUEST_MAPPER, child);
1995 // Load security policies.
1996 if (child = XMLHelper::getLastChildElement(e, _SecurityPolicyProvider)) {
1997 string t(XMLHelper::getAttrString(child, nullptr, _type));
1999 log.info("building SecurityPolicyProvider of type %s...", t.c_str());
2000 m_policy = conf.SecurityPolicyProviderManager.newPlugin(t.c_str(), child);
2003 throw ConfigurationException("can't build SecurityPolicyProvider, no type specified");
2006 else if (child = XMLHelper::getLastChildElement(e, SecurityPolicies)) {
2007 // For backward compatibility, wrap in a plugin element.
2008 DOMElement* polwrapper = e->getOwnerDocument()->createElementNS(nullptr, _SecurityPolicyProvider);
2009 polwrapper->appendChild(child);
2010 log.info("building SecurityPolicyProvider of type %s...", XML_SECURITYPOLICY_PROVIDER);
2011 m_policy = conf.SecurityPolicyProviderManager.newPlugin(XML_SECURITYPOLICY_PROVIDER, polwrapper);
2014 log.fatal("can't build SecurityPolicyProvider, missing conf:SecurityPolicyProvider element?");
2015 throw ConfigurationException("Can't build SecurityPolicyProvider, missing conf:SecurityPolicyProvider element?");
2019 if (!m_policy->getAlgorithmBlacklist().empty()) {
2020 #ifdef SHIBSP_XMLSEC_WHITELISTING
2021 for (vector<xstring>::const_iterator alg = m_policy->getAlgorithmBlacklist().begin(); alg != m_policy->getAlgorithmBlacklist().end(); ++alg)
2022 XSECPlatformUtils::blacklistAlgorithm(alg->c_str());
2024 log.crit("XML-Security-C library prior to 1.6.0 does not support algorithm white/blacklists");
2027 else if (!m_policy->getAlgorithmWhitelist().empty()) {
2028 #ifdef SHIBSP_XMLSEC_WHITELISTING
2029 for (vector<xstring>::const_iterator alg = m_policy->getAlgorithmWhitelist().begin(); alg != m_policy->getAlgorithmWhitelist().end(); ++alg)
2030 XSECPlatformUtils::whitelistAlgorithm(alg->c_str());
2032 log.crit("XML-Security-C library prior to 1.6.0 does not support algorithm white/blacklists");
2037 // Process TransportOption elements.
2038 child = XMLHelper::getLastChildElement(e, TransportOption);
2040 if (child->hasChildNodes()) {
2041 string provider(XMLHelper::getAttrString(child, nullptr, _provider));
2042 string option(XMLHelper::getAttrString(child, nullptr, _option));
2043 auto_ptr_char value(child->getFirstChild()->getNodeValue());
2044 if (!provider.empty() && !option.empty() && value.get() && *value.get()) {
2045 m_transportOptions.push_back(make_pair(provider, make_pair(option, string(value.get()))));
2048 child = XMLHelper::getPreviousSiblingElement(child, TransportOption);
2052 ProtocolProvider* pp = nullptr;
2053 if (conf.isEnabled(SPConfig::Handlers)) {
2054 if (child = XMLHelper::getLastChildElement(e, _ProtocolProvider)) {
2055 string t(XMLHelper::getAttrString(child, nullptr, _type));
2057 log.info("building ProtocolProvider of type %s...", t.c_str());
2058 pp = conf.ProtocolProviderManager.newPlugin(t.c_str(), child);
2062 auto_ptr<ProtocolProvider> ppwrapper(pp);
2063 Locker pplocker(pp);
2065 // Load the default application.
2066 child = XMLHelper::getLastChildElement(e, ApplicationDefaults);
2068 log.fatal("can't build default Application object, missing conf:ApplicationDefaults element?");
2069 throw ConfigurationException("can't build default Application object, missing conf:ApplicationDefaults element?");
2071 XMLApplication* defapp = new XMLApplication(outer, pp, child);
2072 m_appmap[defapp->getId()] = defapp;
2074 // Load any overrides.
2075 child = XMLHelper::getFirstChildElement(child, ApplicationOverride);
2077 auto_ptr<XMLApplication> iapp(new XMLApplication(outer, pp, child, defapp));
2078 if (m_appmap.count(iapp->getId()))
2079 log.crit("found conf:ApplicationOverride element with duplicate id attribute (%s), skipping it", iapp->getId());
2081 const char* iappid=iapp->getId();
2082 m_appmap[iappid] = iapp.release();
2085 child = XMLHelper::getNextSiblingElement(child, ApplicationOverride);
2088 // Check for extra AuthTypes to recognize.
2089 if (conf.isEnabled(SPConfig::InProcess)) {
2090 const PropertySet* inprocs = getPropertySet("InProcess");
2092 pair<bool,const char*> extraAuthTypes = inprocs->getString("extraAuthTypes");
2093 if (extraAuthTypes.first) {
2094 string types=extraAuthTypes.second;
2095 unsigned int j_types=0;
2096 for (unsigned int i_types=0; i_types < types.length(); i_types++) {
2097 if (types.at(i_types) == ' ') {
2098 outer->m_authTypes.insert(types.substr(j_types, i_types - j_types));
2099 j_types = i_types + 1;
2102 outer->m_authTypes.insert(types.substr(j_types, types.length() - j_types));
2107 catch (exception&) {
2113 XMLConfigImpl::~XMLConfigImpl()
2118 void XMLConfigImpl::cleanup()
2120 for_each(m_appmap.begin(),m_appmap.end(),cleanup_pair<string,Application>());
2126 m_tranLog = nullptr;
2128 delete m_requestMapper;
2129 m_requestMapper = nullptr;
2131 m_document->release();
2132 m_document = nullptr;
2136 void XMLConfig::receive(DDF& in, ostream& out)
2138 if (!strcmp(in.name(), "get::RelayState")) {
2139 const char* id = in["id"].string();
2140 const char* key = in["key"].string();
2142 throw ListenerException("Required parameters missing for RelayState recovery.");
2145 StorageService* storage = getStorageService(id);
2147 if (storage->readString("RelayState",key,&relayState)>0) {
2148 if (in["clear"].integer())
2149 storage->deleteString("RelayState",key);
2151 else if (storage->readText("RelayState",key,&relayState)>0) {
2152 if (in["clear"].integer())
2153 storage->deleteText("RelayState",key);
2157 Category::getInstance(SHIBSP_LOGCAT".ServiceProvider").error(
2158 "Storage-backed RelayState with invalid StorageService ID (%s)", id
2162 // Repack for return to caller.
2163 DDF ret=DDF(nullptr).unsafe_string(relayState.c_str());
2164 DDFJanitor jret(ret);
2167 else if (!strcmp(in.name(), "set::RelayState")) {
2168 const char* id = in["id"].string();
2169 const char* value = in["value"].string();
2171 throw ListenerException("Required parameters missing for RelayState creation.");
2174 StorageService* storage = getStorageService(id);
2176 SAMLConfig::getConfig().generateRandomBytes(rsKey,32);
2177 rsKey = SAMLArtifact::toHex(rsKey);
2178 if (strlen(value) <= storage->getCapabilities().getStringSize())
2179 storage->createString("RelayState", rsKey.c_str(), value, time(nullptr) + 600);
2181 storage->createText("RelayState", rsKey.c_str(), value, time(nullptr) + 600);
2184 Category::getInstance(SHIBSP_LOGCAT".ServiceProvider").error(
2185 "Storage-backed RelayState with invalid StorageService ID (%s)", id
2189 // Repack for return to caller.
2190 DDF ret=DDF(nullptr).string(rsKey.c_str());
2191 DDFJanitor jret(ret);
2194 else if (!strcmp(in.name(), "get::PostData")) {
2195 const char* id = in["id"].string();
2196 const char* key = in["key"].string();
2198 throw ListenerException("Required parameters missing for PostData recovery.");
2201 StorageService* storage = getStorageService(id);
2203 if (storage->readText("PostData",key,&postData) > 0) {
2204 storage->deleteText("PostData",key);
2208 Category::getInstance(SHIBSP_LOGCAT".ServiceProvider").error(
2209 "Storage-backed PostData with invalid StorageService ID (%s)", id
2212 // If the data's empty, we'll send nothing back.
2213 // If not, we don't need to round trip it, just send back the serialized DDF list.
2214 if (postData.empty()) {
2216 DDFJanitor jret(ret);
2223 else if (!strcmp(in.name(), "set::PostData")) {
2224 const char* id = in["id"].string();
2225 if (!id || !in["parameters"].islist())
2226 throw ListenerException("Required parameters missing for PostData creation.");
2229 StorageService* storage = getStorageService(id);
2231 SAMLConfig::getConfig().generateRandomBytes(rsKey,32);
2232 rsKey = SAMLArtifact::toHex(rsKey);
2233 ostringstream params;
2234 params << in["parameters"];
2235 storage->createText("PostData", rsKey.c_str(), params.str().c_str(), time(nullptr) + 600);
2238 Category::getInstance(SHIBSP_LOGCAT".ServiceProvider").error(
2239 "Storage-backed PostData with invalid StorageService ID (%s)", id
2243 // Repack for return to caller.
2244 DDF ret=DDF(nullptr).string(rsKey.c_str());
2245 DDFJanitor jret(ret);
2251 pair<bool,DOMElement*> XMLConfig::background_load()
2253 // Load from source using base class.
2254 pair<bool,DOMElement*> raw = ReloadableXMLFile::load();
2256 // If we own it, wrap it.
2257 XercesJanitor<DOMDocument> docjanitor(raw.first ? raw.second->getOwnerDocument() : nullptr);
2259 XMLConfigImpl* impl = new XMLConfigImpl(raw.second, (m_impl==nullptr), this, m_log);
2261 // If we held the document, transfer it to the impl. If we didn't, it's a no-op.
2262 impl->setDocument(docjanitor.release());
2264 // Perform the swap inside a lock.
2267 SharedLock locker(m_lock, false);
2271 return make_pair(false,(DOMElement*)nullptr);