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 "binding/ProtocolProvider.h"
34 #include "handler/LogoutInitiator.h"
35 #include "handler/SessionInitiator.h"
36 #include "remoting/ListenerService.h"
37 #include "util/DOMPropertySet.h"
38 #include "util/SPConstants.h"
40 #if defined(XMLTOOLING_LOG4SHIB)
41 # include <log4shib/PropertyConfigurator.hh>
42 #elif defined(XMLTOOLING_LOG4CPP)
43 # include <log4cpp/PropertyConfigurator.hh>
45 # error "Supported logging library not available."
48 #include <xercesc/util/XMLUniDefs.hpp>
49 #include <xercesc/util/XMLStringTokenizer.hpp>
50 #include <xmltooling/XMLToolingConfig.h>
51 #include <xmltooling/version.h>
52 #include <xmltooling/util/NDC.h>
53 #include <xmltooling/util/ReloadableXMLFile.h>
54 #include <xmltooling/util/TemplateEngine.h>
55 #include <xmltooling/util/Threads.h>
56 #include <xmltooling/util/XMLHelper.h>
59 # include "TransactionLog.h"
60 # include "attribute/filtering/AttributeFilter.h"
61 # include "attribute/resolver/AttributeExtractor.h"
62 # include "attribute/resolver/AttributeResolver.h"
63 # include "security/PKIXTrustEngine.h"
64 # include "security/SecurityPolicyProvider.h"
65 # include <saml/SAMLConfig.h>
66 # include <saml/version.h>
67 # include <saml/binding/ArtifactMap.h>
68 # include <saml/binding/SAMLArtifact.h>
69 # include <saml/saml1/core/Assertions.h>
70 # include <saml/saml2/core/Assertions.h>
71 # include <saml/saml2/binding/SAML2ArtifactType0004.h>
72 # include <saml/saml2/metadata/Metadata.h>
73 # include <saml/saml2/metadata/MetadataProvider.h>
74 # include <saml/util/SAMLConstants.h>
75 # include <xmltooling/security/ChainingTrustEngine.h>
76 # include <xmltooling/security/CredentialResolver.h>
77 # include <xmltooling/security/SecurityHelper.h>
78 # include <xmltooling/util/ReplayCache.h>
79 # include <xmltooling/util/StorageService.h>
80 # include <xsec/utils/XSECPlatformUtils.hpp>
81 using namespace opensaml::saml2;
82 using namespace opensaml::saml2p;
83 using namespace opensaml::saml2md;
84 using namespace opensaml;
86 # include "lite/SAMLConstants.h"
89 using namespace shibsp;
90 using namespace xmltooling;
94 # define min(a,b) (((a) < (b)) ? (a) : (b))
99 #if defined (_MSC_VER)
100 #pragma warning( push )
101 #pragma warning( disable : 4250 )
104 static vector<const Handler*> g_noHandlers;
106 // Application configuration wrapper
107 class SHIBSP_DLLLOCAL XMLApplication : public Application, public Remoted, public DOMPropertySet, public DOMNodeFilter
110 XMLApplication(const ServiceProvider*, const ProtocolProvider*, DOMElement*, const XMLApplication* base=nullptr);
111 ~XMLApplication() { cleanup(); }
113 const char* getHash() const {return m_hash.c_str();}
116 SAMLArtifact* generateSAML1Artifact(const EntityDescriptor* relyingParty) const {
117 throw ConfigurationException("No support for SAML 1.x artifact generation.");
119 SAML2Artifact* generateSAML2Artifact(const EntityDescriptor* relyingParty) const {
120 pair<bool,int> index = make_pair(false,0);
121 const PropertySet* props = getRelyingParty(relyingParty);
122 index = props->getInt("artifactEndpointIndex");
124 index = getArtifactEndpointIndex();
125 pair<bool,const char*> entityID = props->getString("entityID");
126 return new SAML2ArtifactType0004(
127 SecurityHelper::doHash("SHA1", entityID.second, strlen(entityID.second), false),
128 index.first ? index.second : 1
132 MetadataProvider* getMetadataProvider(bool required=true) const {
133 if (required && !m_base && !m_metadata)
134 throw ConfigurationException("No MetadataProvider available.");
135 return (!m_metadata && m_base) ? m_base->getMetadataProvider() : m_metadata;
137 TrustEngine* getTrustEngine(bool required=true) const {
138 if (required && !m_base && !m_trust)
139 throw ConfigurationException("No TrustEngine available.");
140 return (!m_trust && m_base) ? m_base->getTrustEngine() : m_trust;
142 AttributeExtractor* getAttributeExtractor() const {
143 return (!m_attrExtractor && m_base) ? m_base->getAttributeExtractor() : m_attrExtractor;
145 AttributeFilter* getAttributeFilter() const {
146 return (!m_attrFilter && m_base) ? m_base->getAttributeFilter() : m_attrFilter;
148 AttributeResolver* getAttributeResolver() const {
149 return (!m_attrResolver && m_base) ? m_base->getAttributeResolver() : m_attrResolver;
151 CredentialResolver* getCredentialResolver() const {
152 return (!m_credResolver && m_base) ? m_base->getCredentialResolver() : m_credResolver;
154 const PropertySet* getRelyingParty(const EntityDescriptor* provider) const;
155 const PropertySet* getRelyingParty(const XMLCh* entityID) const;
156 const vector<const XMLCh*>* getAudiences() const {
157 return (m_audiences.empty() && m_base) ? m_base->getAudiences() : &m_audiences;
160 string getNotificationURL(const char* resource, bool front, unsigned int index) const;
162 const vector<string>& getRemoteUserAttributeIds() const {
163 return (m_remoteUsers.empty() && m_base) ? m_base->getRemoteUserAttributeIds() : m_remoteUsers;
166 void clearHeader(SPRequest& request, const char* rawname, const char* cginame) const;
167 void setHeader(SPRequest& request, const char* name, const char* value) const;
168 string getSecureHeader(const SPRequest& request, const char* name) const;
170 const SessionInitiator* getDefaultSessionInitiator() const;
171 const SessionInitiator* getSessionInitiatorById(const char* id) const;
172 const Handler* getDefaultAssertionConsumerService() const;
173 const Handler* getAssertionConsumerServiceByIndex(unsigned short index) const;
174 const Handler* getAssertionConsumerServiceByProtocol(const XMLCh* protocol, const char* binding=nullptr) const;
175 const vector<const Handler*>& getAssertionConsumerServicesByBinding(const XMLCh* binding) const;
176 const Handler* getHandler(const char* path) const;
177 void getHandlers(vector<const Handler*>& handlers) const;
179 void receive(DDF& in, ostream& out) {
180 // Only current function is to return the headers to clear.
182 DDF ret=DDF(nullptr).list();
183 DDFJanitor jret(ret);
184 for (vector< pair<string,string> >::const_iterator i = m_unsetHeaders.begin(); i!=m_unsetHeaders.end(); ++i) {
185 header = DDF(i->first.c_str()).string(i->second.c_str());
191 // Provides filter to exclude special config elements.
192 #ifdef SHIBSP_XERCESC_SHORT_ACCEPTNODE
197 acceptNode(const DOMNode* node) const;
200 template <class T> T* doChainedPlugins(
201 PluginManager<T,string,const DOMElement*>& pluginMgr,
202 const char* pluginType,
203 const char* chainingType,
204 const XMLCh* localName,
208 void doAttributeInfo();
209 void doHandlers(const ProtocolProvider*, const DOMElement*, Category&);
210 void doSSO(const ProtocolProvider&, set<string>&, DOMElement*, Category&);
211 void doLogout(const ProtocolProvider&, set<string>&, DOMElement*, Category&);
212 void doNameIDMgmt(const ProtocolProvider&, set<string>&, DOMElement*, Category&);
213 void doArtifactResolution(const ProtocolProvider&, const char*, DOMElement*, Category&);
215 const XMLApplication* m_base;
217 std::pair<std::string,std::string> m_attributePrefix;
219 void doAttributePlugins(DOMElement* e, Category& log);
220 MetadataProvider* m_metadata;
221 TrustEngine* m_trust;
222 AttributeExtractor* m_attrExtractor;
223 AttributeFilter* m_attrFilter;
224 AttributeResolver* m_attrResolver;
225 CredentialResolver* m_credResolver;
226 vector<const XMLCh*> m_audiences;
228 // RelyingParty properties
229 map<xstring,PropertySet*> m_partyMap;
231 vector<string> m_remoteUsers,m_frontLogout,m_backLogout;
233 // manage handler objects
234 vector<Handler*> m_handlers;
236 // maps location (path info) to applicable handlers
237 map<string,const Handler*> m_handlerMap;
239 // maps unique indexes to consumer services
240 map<unsigned int,const Handler*> m_acsIndexMap;
242 // pointer to default consumer service
243 const Handler* m_acsDefault;
245 // maps binding strings to supporting consumer service(s)
246 typedef map< xstring,vector<const Handler*> > ACSBindingMap;
247 ACSBindingMap m_acsBindingMap;
249 // maps protocol strings to supporting consumer service(s)
250 typedef map< xstring,vector<const Handler*> > ACSProtocolMap;
251 ACSProtocolMap m_acsProtocolMap;
253 // pointer to default session initiator
254 const SessionInitiator* m_sessionInitDefault;
256 // maps unique ID strings to session initiators
257 map<string,const SessionInitiator*> m_sessionInitMap;
259 // pointer to default artifact resolution service
260 const Handler* m_artifactResolutionDefault;
262 pair<bool,int> getArtifactEndpointIndex() const {
263 if (m_artifactResolutionDefault) return m_artifactResolutionDefault->getInt("index");
264 return m_base ? m_base->getArtifactEndpointIndex() : make_pair(false,0);
268 // Top-level configuration implementation
269 class SHIBSP_DLLLOCAL XMLConfig;
270 class SHIBSP_DLLLOCAL XMLConfigImpl : public DOMPropertySet, public DOMNodeFilter
273 XMLConfigImpl(const DOMElement* e, bool first, XMLConfig* outer, Category& log);
276 RequestMapper* m_requestMapper;
277 map<string,Application*> m_appmap;
279 SecurityPolicyProvider* m_policy;
280 vector< pair< string, pair<string,string> > > m_transportOptions;
283 // Provides filter to exclude special config elements.
284 #ifdef SHIBSP_XERCESC_SHORT_ACCEPTNODE
289 acceptNode(const DOMNode* node) const;
291 void setDocument(DOMDocument* doc) {
296 void doExtensions(const DOMElement*, const char*, Category&);
297 void doListener(const DOMElement*, XMLConfig*, Category&);
298 void doCaching(const DOMElement*, XMLConfig*, Category&);
301 DOMDocument* m_document;
304 class SHIBSP_DLLLOCAL XMLConfig : public ServiceProvider, public ReloadableXMLFile
310 XMLConfig(const DOMElement* e) : ReloadableXMLFile(e, Category::getInstance(SHIBSP_LOGCAT".Config")),
311 m_impl(nullptr), m_listener(nullptr), m_sessionCache(nullptr)
325 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 {
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 TransactionLog* m_tranLog;
446 map<string,StorageService*> m_storage;
450 #if defined (_MSC_VER)
451 #pragma warning( pop )
454 static const XMLCh applicationId[] = UNICODE_LITERAL_13(a,p,p,l,i,c,a,t,i,o,n,I,d);
455 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);
456 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);
457 static const XMLCh _ArtifactMap[] = UNICODE_LITERAL_11(A,r,t,i,f,a,c,t,M,a,p);
458 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);
459 static const XMLCh _AttributeFilter[] = UNICODE_LITERAL_15(A,t,t,r,i,b,u,t,e,F,i,l,t,e,r);
460 static const XMLCh _AttributeResolver[] = UNICODE_LITERAL_17(A,t,t,r,i,b,u,t,e,R,e,s,o,l,v,e,r);
461 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);
462 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);
463 static const XMLCh _Audience[] = UNICODE_LITERAL_8(A,u,d,i,e,n,c,e);
464 static const XMLCh Binding[] = UNICODE_LITERAL_7(B,i,n,d,i,n,g);
465 static const XMLCh Channel[]= UNICODE_LITERAL_7(C,h,a,n,n,e,l);
466 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);
467 static const XMLCh _default[] = UNICODE_LITERAL_7(d,e,f,a,u,l,t);
468 static const XMLCh _Extensions[] = UNICODE_LITERAL_10(E,x,t,e,n,s,i,o,n,s);
469 static const XMLCh _fatal[] = UNICODE_LITERAL_5(f,a,t,a,l);
470 static const XMLCh _Handler[] = UNICODE_LITERAL_7(H,a,n,d,l,e,r);
471 static const XMLCh _id[] = UNICODE_LITERAL_2(i,d);
472 static const XMLCh _index[] = UNICODE_LITERAL_5(i,n,d,e,x);
473 static const XMLCh InProcess[] = UNICODE_LITERAL_9(I,n,P,r,o,c,e,s,s);
474 static const XMLCh Library[] = UNICODE_LITERAL_7(L,i,b,r,a,r,y);
475 static const XMLCh Listener[] = UNICODE_LITERAL_8(L,i,s,t,e,n,e,r);
476 static const XMLCh Location[] = UNICODE_LITERAL_8(L,o,c,a,t,i,o,n);
477 static const XMLCh logger[] = UNICODE_LITERAL_6(l,o,g,g,e,r);
478 static const XMLCh Logout[] = UNICODE_LITERAL_6(L,o,g,o,u,t);
479 static const XMLCh _LogoutInitiator[] = UNICODE_LITERAL_15(L,o,g,o,u,t,I,n,i,t,i,a,t,o,r);
480 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);
481 static const XMLCh _MetadataProvider[] = UNICODE_LITERAL_16(M,e,t,a,d,a,t,a,P,r,o,v,i,d,e,r);
482 static const XMLCh NameIDMgmt[] = UNICODE_LITERAL_10(N,a,m,e,I,D,M,g,m,t);
483 static const XMLCh Notify[] = UNICODE_LITERAL_6(N,o,t,i,f,y);
484 static const XMLCh _option[] = UNICODE_LITERAL_6(o,p,t,i,o,n);
485 static const XMLCh OutOfProcess[] = UNICODE_LITERAL_12(O,u,t,O,f,P,r,o,c,e,s,s);
486 static const XMLCh _path[] = UNICODE_LITERAL_4(p,a,t,h);
487 static const XMLCh _ProtocolProvider[] = UNICODE_LITERAL_16(P,r,o,t,o,c,o,l,P,r,o,v,i,d,e,r);
488 static const XMLCh _provider[] = UNICODE_LITERAL_8(p,r,o,v,i,d,e,r);
489 static const XMLCh RelyingParty[] = UNICODE_LITERAL_12(R,e,l,y,i,n,g,P,a,r,t,y);
490 static const XMLCh _ReplayCache[] = UNICODE_LITERAL_11(R,e,p,l,a,y,C,a,c,h,e);
491 static const XMLCh _RequestMapper[] = UNICODE_LITERAL_13(R,e,q,u,e,s,t,M,a,p,p,e,r);
492 static const XMLCh RequestMap[] = UNICODE_LITERAL_10(R,e,q,u,e,s,t,M,a,p);
493 static const XMLCh SecurityPolicies[] = UNICODE_LITERAL_16(S,e,c,u,r,i,t,y,P,o,l,i,c,i,e,s);
494 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);
495 static const XMLCh _SessionCache[] = UNICODE_LITERAL_12(S,e,s,s,i,o,n,C,a,c,h,e);
496 static const XMLCh _SessionInitiator[] = UNICODE_LITERAL_16(S,e,s,s,i,o,n,I,n,i,t,i,a,t,o,r);
497 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);
498 static const XMLCh Site[] = UNICODE_LITERAL_4(S,i,t,e);
499 static const XMLCh SSO[] = UNICODE_LITERAL_3(S,S,O);
500 static const XMLCh _StorageService[] = UNICODE_LITERAL_14(S,t,o,r,a,g,e,S,e,r,v,i,c,e);
501 static const XMLCh TCPListener[] = UNICODE_LITERAL_11(T,C,P,L,i,s,t,e,n,e,r);
502 static const XMLCh TransportOption[] = UNICODE_LITERAL_15(T,r,a,n,s,p,o,r,t,O,p,t,i,o,n);
503 static const XMLCh _TrustEngine[] = UNICODE_LITERAL_11(T,r,u,s,t,E,n,g,i,n,e);
504 static const XMLCh _type[] = UNICODE_LITERAL_4(t,y,p,e);
505 static const XMLCh UnixListener[] = UNICODE_LITERAL_12(U,n,i,x,L,i,s,t,e,n,e,r);
509 ServiceProvider* XMLServiceProviderFactory(const DOMElement* const & e)
511 return new XMLConfig(e);
515 XMLApplication::XMLApplication(
516 const ServiceProvider* sp,
517 const ProtocolProvider* pp,
519 const XMLApplication* base
520 ) : Application(sp), m_base(base),
522 m_metadata(nullptr), m_trust(nullptr),
523 m_attrExtractor(nullptr), m_attrFilter(nullptr), m_attrResolver(nullptr),
524 m_credResolver(nullptr),
526 m_acsDefault(nullptr), m_sessionInitDefault(nullptr), m_artifactResolutionDefault(nullptr)
529 xmltooling::NDC ndc("XMLApplication");
531 Category& log=Category::getInstance(SHIBSP_LOGCAT".Application");
534 // First load any property sets.
535 load(e,nullptr,this);
539 SPConfig& conf=SPConfig::getConfig();
541 XMLToolingConfig& xmlConf=XMLToolingConfig::getConfig();
544 // This used to be an actual hash, but now it's just a hex-encode to avoid xmlsec dependency.
545 static char DIGITS[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
546 string tohash=getId();
547 tohash+=getString("entityID").second;
548 for (const char* ch = tohash.c_str(); *ch; ++ch) {
549 m_hash += (DIGITS[((unsigned char)(0xF0 & *ch)) >> 4 ]);
550 m_hash += (DIGITS[0x0F & *ch]);
555 if (conf.isEnabled(SPConfig::Handlers))
556 doHandlers(pp, e, log);
559 DOMNodeList* nlist = e->getElementsByTagNameNS(shibspconstants::SHIB2SPCONFIG_NS, Notify);
560 for (XMLSize_t i = 0; nlist && i < nlist->getLength(); ++i) {
561 if (nlist->item(i)->getParentNode()->isSameNode(e)) {
562 const XMLCh* channel = static_cast<DOMElement*>(nlist->item(i))->getAttributeNS(nullptr, Channel);
563 string loc(XMLHelper::getAttrString(static_cast<DOMElement*>(nlist->item(i)), nullptr, Location));
565 if (channel && *channel == chLatin_f)
566 m_frontLogout.push_back(loc);
568 m_backLogout.push_back(loc);
574 nlist = e->getElementsByTagNameNS(samlconstants::SAML20_NS, Audience::LOCAL_NAME);
575 if (nlist && nlist->getLength()) {
576 log.warn("use of <saml:Audience> elements outside of a Security Policy Rule is deprecated");
577 for (XMLSize_t i = 0; i < nlist->getLength(); ++i)
578 if (nlist->item(i)->getParentNode()->isSameNode(e) && nlist->item(i)->hasChildNodes())
579 m_audiences.push_back(nlist->item(i)->getFirstChild()->getNodeValue());
582 if (conf.isEnabled(SPConfig::Metadata)) {
583 auto_ptr<MetadataProvider> mp(
585 SAMLConfig::getConfig().MetadataProviderManager, "MetadataProvider", CHAINING_METADATA_PROVIDER, _MetadataProvider, e, log
591 m_metadata = mp.release();
594 log.crit("no MetadataProvider available, configuration is probably unusable");
597 catch (exception& ex) {
598 log.crit("error initializing MetadataProvider: %s", ex.what());
602 if (conf.isEnabled(SPConfig::Trust)) {
603 m_trust = doChainedPlugins(xmlConf.TrustEngineManager, "TrustEngine", CHAINING_TRUSTENGINE, _TrustEngine, e, log);
604 if (!m_trust && !m_base) {
606 "no TrustEngine specified or installed, using default chain {%s, %s}",
607 EXPLICIT_KEY_TRUSTENGINE, SHIBBOLETH_PKIX_TRUSTENGINE
609 m_trust = xmlConf.TrustEngineManager.newPlugin(CHAINING_TRUSTENGINE, nullptr);
610 ChainingTrustEngine* trustchain = dynamic_cast<ChainingTrustEngine*>(m_trust);
612 trustchain->addTrustEngine(xmlConf.TrustEngineManager.newPlugin(EXPLICIT_KEY_TRUSTENGINE, nullptr));
613 trustchain->addTrustEngine(xmlConf.TrustEngineManager.newPlugin(SHIBBOLETH_PKIX_TRUSTENGINE, nullptr));
618 if (conf.isEnabled(SPConfig::AttributeResolution))
619 doAttributePlugins(e, log);
621 if (conf.isEnabled(SPConfig::Credentials)) {
622 m_credResolver = doChainedPlugins(
623 xmlConf.CredentialResolverManager, "CredentialResolver", CHAINING_CREDENTIAL_RESOLVER, _CredentialResolver, e, log
627 // Finally, load relying parties.
628 const DOMElement* child = XMLHelper::getFirstChildElement(e, RelyingParty);
630 if (child->hasAttributeNS(nullptr, saml2::Attribute::NAME_ATTRIB_NAME)) {
631 auto_ptr<DOMPropertySet> rp(new DOMPropertySet());
632 rp->load(child, nullptr, this);
634 m_partyMap[child->getAttributeNS(nullptr, saml2::Attribute::NAME_ATTRIB_NAME)] = rp.release();
636 child = XMLHelper::getNextSiblingElement(child, RelyingParty);
638 if (base && m_partyMap.empty() && !base->m_partyMap.empty()) {
639 // For inheritance of RPs to work, we have to pull them in to the override by cloning the DOM.
640 child = XMLHelper::getFirstChildElement(base->getElement(), RelyingParty);
642 if (child->hasAttributeNS(nullptr, saml2::Attribute::NAME_ATTRIB_NAME)) {
643 DOMElement* rpclone = static_cast<DOMElement*>(child->cloneNode(true));
644 auto_ptr<DOMPropertySet> rp(new DOMPropertySet());
645 rp->load(rpclone, nullptr, this);
647 m_partyMap[rpclone->getAttributeNS(nullptr, saml2::Attribute::NAME_ATTRIB_NAME)] = rp.release();
649 child = XMLHelper::getNextSiblingElement(child, RelyingParty);
654 // Out of process only, we register a listener endpoint.
655 if (!conf.isEnabled(SPConfig::InProcess)) {
656 ListenerService* listener = sp->getListenerService(false);
658 string addr=string(getId()) + "::getHeaders::Application";
659 listener->regListener(addr.c_str(),this);
662 log.info("no ListenerService available, Application remoting disabled");
678 template <class T> T* XMLApplication::doChainedPlugins(
679 PluginManager<T,string,const DOMElement*>& pluginMgr,
680 const char* pluginType,
681 const char* chainingType,
682 const XMLCh* localName,
688 DOMElement* child = XMLHelper::getFirstChildElement(e, localName);
690 // Check for multiple.
691 if (XMLHelper::getNextSiblingElement(child, localName)) {
692 log.info("multiple %s plugins, wrapping in a chain", pluginType);
693 DOMElement* chain = child->getOwnerDocument()->createElementNS(nullptr, localName);
695 chain->appendChild(child);
696 child = XMLHelper::getFirstChildElement(e, localName);
700 e->appendChild(chain);
703 // Only a single one.
704 t = XMLHelper::getAttrString(child, nullptr, _type);
709 log.info("building %s of type %s...", pluginType, t.c_str());
710 return pluginMgr.newPlugin(t.c_str(), child);
713 throw ConfigurationException("$1 element had no type attribute.", params(1, pluginType));
716 catch (exception& ex) {
717 log.crit("error building %s: %s", pluginType, ex.what());
724 void XMLApplication::doAttributeInfo()
726 // Populate prefix pair.
727 m_attributePrefix.second = "HTTP_";
728 pair<bool,const char*> prefix = getString("attributePrefix");
730 m_attributePrefix.first = prefix.second;
731 const char* pch = prefix.second;
733 m_attributePrefix.second += (isalnum(*pch) ? toupper(*pch) : '_');
738 // Load attribute ID lists for REMOTE_USER and header clearing.
739 if (SPConfig::getConfig().isEnabled(SPConfig::InProcess)) {
740 pair<bool,const char*> attributes = getString("REMOTE_USER");
741 if (attributes.first) {
742 char* dup = strdup(attributes.second);
745 while (start && *start) {
746 while (*start && isspace(*start))
750 pos = strchr(start,' ');
753 m_remoteUsers.push_back(start);
754 start = pos ? pos+1 : nullptr;
759 attributes = getString("unsetHeaders");
760 if (attributes.first) {
761 string transformedprefix(m_attributePrefix.second);
763 prefix = getString("metadataAttributePrefix");
767 transformedprefix += (isalnum(*pch) ? toupper(*pch) : '_');
771 char* dup = strdup(attributes.second);
774 while (start && *start) {
775 while (*start && isspace(*start))
779 pos = strchr(start,' ');
786 transformed += (isalnum(*pch) ? toupper(*pch) : '_');
790 m_unsetHeaders.push_back(pair<string,string>(m_attributePrefix.first + start, m_attributePrefix.second + transformed));
792 m_unsetHeaders.push_back(pair<string,string>(m_attributePrefix.first + prefix.second + start, transformedprefix + transformed));
793 start = pos ? pos+1 : nullptr;
796 m_unsetHeaders.push_back(pair<string,string>(m_attributePrefix.first + "Shib-Application-ID", m_attributePrefix.second + "SHIB_APPLICATION_ID"));
801 void XMLApplication::doHandlers(const ProtocolProvider* pp, const DOMElement* e, Category& log)
803 SPConfig& conf = SPConfig::getConfig();
805 Handler* handler = nullptr;
806 const PropertySet* sessions = getPropertySet("Sessions");
808 // Process assertion export handler.
809 pair<bool,const char*> location = sessions ? sessions->getString("exportLocation") : pair<bool,const char*>(false,nullptr);
810 if (location.first) {
812 DOMElement* exportElement = e->getOwnerDocument()->createElementNS(shibspconstants::SHIB2SPCONFIG_NS, _Handler);
813 exportElement->setAttributeNS(nullptr,Location,sessions->getXMLString("exportLocation").second);
814 pair<bool,const XMLCh*> exportACL = sessions->getXMLString("exportACL");
815 if (exportACL.first) {
816 static const XMLCh _acl[] = UNICODE_LITERAL_9(e,x,p,o,r,t,A,C,L);
817 exportElement->setAttributeNS(nullptr,_acl,exportACL.second);
819 handler = conf.HandlerManager.newPlugin(
820 samlconstants::SAML20_BINDING_URI, pair<const DOMElement*,const char*>(exportElement, getId())
822 m_handlers.push_back(handler);
824 // Insert into location map. If it contains the handlerURL, we skip past that part.
825 const char* hurl = sessions->getString("handlerURL").second;
827 hurl = "/Shibboleth.sso";
828 const char* pch = strstr(location.second, hurl);
830 location.second = pch + strlen(hurl);
831 if (*location.second == '/')
832 m_handlerMap[location.second]=handler;
834 m_handlerMap[string("/") + location.second]=handler;
836 catch (exception& ex) {
837 log.error("caught exception installing assertion lookup handler: %s", ex.what());
841 // Look for "shorthand" elements first.
842 set<string> protocols;
843 DOMElement* child = sessions ? XMLHelper::getFirstChildElement(sessions->getElement()) : nullptr;
845 if (XMLHelper::isNodeNamed(child, shibspconstants::SHIB2SPCONFIG_NS, SSO)) {
847 doSSO(*pp, protocols, child, log);
849 log.error("no ProtocolProvider, SSO auto-configure unsupported");
851 else if (XMLHelper::isNodeNamed(child, shibspconstants::SHIB2SPCONFIG_NS, Logout)) {
853 doLogout(*pp, protocols, child, log);
855 log.error("no ProtocolProvider, Logout auto-configure unsupported");
857 else if (XMLHelper::isNodeNamed(child, shibspconstants::SHIB2SPCONFIG_NS, NameIDMgmt)) {
859 doNameIDMgmt(*pp, protocols, child, log);
861 log.error("no ProtocolProvider, NameIDMgmt auto-configure unsupported");
864 break; // drop into next while loop
866 child = XMLHelper::getNextSiblingElement(child);
869 // Process other handlers.
870 bool hardACS=false, hardSessionInit=false, hardArt=false;
872 if (!child->hasAttributeNS(nullptr, Location)) {
873 auto_ptr_char hclass(child->getLocalName());
874 log.error("%s handler with no Location property cannot be processed", hclass.get());
875 child = XMLHelper::getNextSiblingElement(child);
879 if (XMLString::equals(child->getLocalName(), _AssertionConsumerService)) {
880 string bindprop(XMLHelper::getAttrString(child, nullptr, Binding));
881 if (bindprop.empty()) {
882 log.error("AssertionConsumerService element has no Binding attribute, skipping it...");
883 child = XMLHelper::getNextSiblingElement(child);
886 handler = conf.AssertionConsumerServiceManager.newPlugin(bindprop.c_str(), pair<const DOMElement*,const char*>(child, getId()));
887 // Map by binding and protocol (may be > 1 per protocol and binding)
888 m_acsBindingMap[handler->getXMLString("Binding").second].push_back(handler);
889 const XMLCh* protfamily = handler->getProtocolFamily();
891 m_acsProtocolMap[protfamily].push_back(handler);
892 m_acsIndexMap[handler->getUnsignedInt("index").second] = handler;
895 pair<bool,bool> defprop = handler->getBool("isDefault");
897 if (defprop.second) {
899 m_acsDefault = handler;
902 else if (!m_acsDefault)
903 m_acsDefault = handler;
906 else if (XMLString::equals(child->getLocalName(), _SessionInitiator)) {
907 string t(XMLHelper::getAttrString(child, nullptr, _type));
909 log.error("SessionInitiator element has no type attribute, skipping it...");
910 child = XMLHelper::getNextSiblingElement(child);
913 SessionInitiator* sihandler = conf.SessionInitiatorManager.newPlugin(t.c_str(), pair<const DOMElement*,const char*>(child, getId()));
915 pair<bool,const char*> si_id = handler->getString("id");
916 if (si_id.first && si_id.second)
917 m_sessionInitMap[si_id.second] = sihandler;
918 if (!hardSessionInit) {
919 pair<bool,bool> defprop = handler->getBool("isDefault");
921 if (defprop.second) {
922 hardSessionInit = true;
923 m_sessionInitDefault = sihandler;
926 else if (!m_sessionInitDefault) {
927 m_sessionInitDefault = sihandler;
931 else if (XMLString::equals(child->getLocalName(), _LogoutInitiator)) {
932 string t(XMLHelper::getAttrString(child, nullptr, _type));
934 log.error("LogoutInitiator element has no type attribute, skipping it...");
935 child = XMLHelper::getNextSiblingElement(child);
938 handler = conf.LogoutInitiatorManager.newPlugin(t.c_str(), pair<const DOMElement*,const char*>(child, getId()));
940 else if (XMLString::equals(child->getLocalName(), _ArtifactResolutionService)) {
941 string bindprop(XMLHelper::getAttrString(child, nullptr, Binding));
942 if (bindprop.empty()) {
943 log.error("ArtifactResolutionService element has no Binding attribute, skipping it...");
944 child = XMLHelper::getNextSiblingElement(child);
947 handler = conf.ArtifactResolutionServiceManager.newPlugin(bindprop.c_str(), pair<const DOMElement*,const char*>(child, getId()));
950 pair<bool,bool> defprop = handler->getBool("isDefault");
952 if (defprop.second) {
954 m_artifactResolutionDefault = handler;
957 else if (!m_artifactResolutionDefault)
958 m_artifactResolutionDefault = handler;
961 else if (XMLString::equals(child->getLocalName(), _SingleLogoutService)) {
962 string bindprop(XMLHelper::getAttrString(child, nullptr, Binding));
963 if (bindprop.empty()) {
964 log.error("SingleLogoutService element has no Binding attribute, skipping it...");
965 child = XMLHelper::getNextSiblingElement(child);
968 handler = conf.SingleLogoutServiceManager.newPlugin(bindprop.c_str(), pair<const DOMElement*,const char*>(child, getId()));
970 else if (XMLString::equals(child->getLocalName(), _ManageNameIDService)) {
971 string bindprop(XMLHelper::getAttrString(child, nullptr, Binding));
972 if (bindprop.empty()) {
973 log.error("ManageNameIDService element has no Binding attribute, skipping it...");
974 child = XMLHelper::getNextSiblingElement(child);
977 handler = conf.ManageNameIDServiceManager.newPlugin(bindprop.c_str(), pair<const DOMElement*,const char*>(child, getId()));
980 string t(XMLHelper::getAttrString(child, nullptr, _type));
982 log.error("Handler element has no type attribute, skipping it...");
983 child = XMLHelper::getNextSiblingElement(child);
986 handler = conf.HandlerManager.newPlugin(t.c_str(), pair<const DOMElement*,const char*>(child, getId()));
989 m_handlers.push_back(handler);
991 // Insert into location map.
992 location = handler->getString("Location");
993 if (location.first && *location.second == '/')
994 m_handlerMap[location.second] = handler;
995 else if (location.first)
996 m_handlerMap[string("/") + location.second] = handler;
998 catch (exception& ex) {
999 log.error("caught exception processing handler element: %s", ex.what());
1002 child = XMLHelper::getNextSiblingElement(child);
1006 void XMLApplication::doSSO(const ProtocolProvider& pp, set<string>& protocols, DOMElement* e, Category& log)
1008 if (!e->hasChildNodes())
1011 SPConfig& conf = SPConfig::getConfig();
1013 // Tokenize the protocol list inside the element.
1014 const XMLCh* protlist = e->getFirstChild()->getNodeValue();
1015 XMLStringTokenizer prottokens(protlist);
1016 while (prottokens.hasMoreTokens()) {
1017 auto_ptr_char prot(prottokens.nextToken());
1019 // Look for initiator.
1020 const PropertySet* initiator = pp.getInitiator(prot.get(), "SSO");
1022 log.info("auto-configuring SSO initiation for protocol (%s)", prot.get());
1023 pair<bool,const XMLCh*> inittype = initiator->getXMLString("id");
1024 if (inittype.first) {
1025 // Append a session initiator element of the designated type to the root element.
1026 DOMElement* sidom = e->getOwnerDocument()->createElementNS(shibspconstants::SHIB2SPCONFIG_NS, _SessionInitiator);
1027 sidom->setAttributeNS(nullptr, _type, inittype.second);
1028 e->appendChild(sidom);
1029 log.info("adding SessionInitiator of type (%s) to chain (/Login)", initiator->getString("id").second);
1031 doArtifactResolution(pp, prot.get(), e, log);
1032 protocols.insert(prot.get());
1035 log.error("missing id property on Initiator element, check config for protocol (%s)", prot.get());
1039 // Look for incoming bindings.
1040 const vector<const PropertySet*>& bindings = pp.getBindings(prot.get(), "SSO");
1041 if (!bindings.empty()) {
1042 log.info("auto-configuring SSO endpoints for protocol (%s)", prot.get());
1044 pair<bool,const XMLCh*> idprop,pathprop;
1045 for (vector<const PropertySet*>::const_iterator b = bindings.begin(); b != bindings.end(); ++b, ++index) {
1046 idprop = (*b)->getXMLString("id");
1047 pathprop = (*b)->getXMLString("path");
1048 if (idprop.first && pathprop.first) {
1049 DOMElement* acsdom = e->getOwnerDocument()->createElementNS(samlconstants::SAML20MD_NS, _AssertionConsumerService);
1050 acsdom->setAttributeNS(nullptr, Binding, idprop.second);
1051 acsdom->setAttributeNS(nullptr, Location, pathprop.second);
1052 xstring indexbuf(chDigit_1 + (index % 10), 1);
1054 indexbuf = (XMLCh)(chDigit_1 + (index / 10)) + indexbuf;
1055 acsdom->setAttributeNS(nullptr, _index, indexbuf.c_str());
1057 log.info("adding AssertionConsumerService for Binding (%s) at (%s)", (*b)->getString("id").second, (*b)->getString("path").second);
1058 Handler* handler = conf.AssertionConsumerServiceManager.newPlugin(
1059 (*b)->getString("id").second, pair<const DOMElement*,const char*>(acsdom, getId())
1061 m_handlers.push_back(handler);
1063 // Setup maps and defaults.
1064 m_acsBindingMap[handler->getXMLString("Binding").second].push_back(handler);
1065 const XMLCh* protfamily = handler->getProtocolFamily();
1067 m_acsProtocolMap[protfamily].push_back(handler);
1068 m_acsIndexMap[handler->getUnsignedInt("index").second] = handler;
1070 m_acsDefault = handler;
1072 // Insert into location map.
1073 pair<bool,const char*> location = handler->getString("Location");
1074 if (location.first && *location.second == '/')
1075 m_handlerMap[location.second] = handler;
1076 else if (location.first)
1077 m_handlerMap[string("/") + location.second] = handler;
1080 log.error("missing id or path property on Binding element, check config for protocol (%s)", prot.get());
1085 if (!initiator && bindings.empty()) {
1086 log.error("no SSO Initiator or Binding config for protocol (%s)", prot.get());
1090 // Handle discovery.
1091 static const XMLCh discoveryProtocol[] = UNICODE_LITERAL_17(d,i,s,c,o,v,e,r,y,P,r,o,t,o,c,o,l);
1092 static const XMLCh discoveryURL[] = UNICODE_LITERAL_12(d,i,s,c,o,v,e,r,y,U,R,L);
1093 static const XMLCh _URL[] = UNICODE_LITERAL_3(U,R,L);
1094 const XMLCh* discop = e->getAttributeNS(nullptr, discoveryProtocol);
1095 if (discop && *discop) {
1096 const XMLCh* discou = e->getAttributeNS(nullptr, discoveryURL);
1097 if (discou && *discou) {
1098 // Append a session initiator element of the designated type to the root element.
1099 DOMElement* sidom = e->getOwnerDocument()->createElementNS(shibspconstants::SHIB2SPCONFIG_NS, _SessionInitiator);
1100 sidom->setAttributeNS(nullptr, _type, discop);
1101 sidom->setAttributeNS(nullptr, _URL, discou);
1102 e->appendChild(sidom);
1103 if (log.isInfoEnabled()) {
1104 auto_ptr_char dp(discop);
1105 log.info("adding SessionInitiator of type (%s) to chain (/Login)", dp.get());
1109 log.error("SSO discoveryProtocol specified without discoveryURL");
1113 // Attach default Location to SSO element.
1114 static const XMLCh _loc[] = { chForwardSlash, chLatin_L, chLatin_o, chLatin_g, chLatin_i, chLatin_n, chNull };
1115 e->setAttributeNS(nullptr, Location, _loc);
1117 // Instantiate Chaining initiator around the SSO element.
1118 SessionInitiator* chain = conf.SessionInitiatorManager.newPlugin(
1119 CHAINING_SESSION_INITIATOR, pair<const DOMElement*,const char*>(e, getId())
1121 m_handlers.push_back(chain);
1122 m_sessionInitDefault = chain;
1123 m_handlerMap["/Login"] = chain;
1126 void XMLApplication::doLogout(const ProtocolProvider& pp, set<string>& protocols, DOMElement* e, Category& log)
1128 if (!e->hasChildNodes())
1131 SPConfig& conf = SPConfig::getConfig();
1133 // Tokenize the protocol list inside the element.
1134 const XMLCh* protlist = e->getFirstChild()->getNodeValue();
1135 XMLStringTokenizer prottokens(protlist);
1136 while (prottokens.hasMoreTokens()) {
1137 auto_ptr_char prot(prottokens.nextToken());
1139 // Look for initiator.
1140 const PropertySet* initiator = pp.getInitiator(prot.get(), "Logout");
1142 log.info("auto-configuring Logout initiation for protocol (%s)", prot.get());
1143 pair<bool,const XMLCh*> inittype = initiator->getXMLString("id");
1144 if (inittype.first) {
1145 // Append a logout initiator element of the designated type to the root element.
1146 DOMElement* lidom = e->getOwnerDocument()->createElementNS(shibspconstants::SHIB2SPCONFIG_NS, _LogoutInitiator);
1147 lidom->setAttributeNS(nullptr, _type, inittype.second);
1148 e->appendChild(lidom);
1149 log.info("adding LogoutInitiator of type (%s) to chain (/Logout)", initiator->getString("id").second);
1151 if (protocols.count(prot.get()) == 0) {
1152 doArtifactResolution(pp, prot.get(), e, log);
1153 protocols.insert(prot.get());
1157 log.error("missing id property on Initiator element, check config for protocol (%s)", prot.get());
1161 // Look for incoming bindings.
1162 const vector<const PropertySet*>& bindings = pp.getBindings(prot.get(), "Logout");
1163 if (!bindings.empty()) {
1164 log.info("auto-configuring Logout endpoints for protocol (%s)", prot.get());
1165 pair<bool,const XMLCh*> idprop,pathprop;
1166 for (vector<const PropertySet*>::const_iterator b = bindings.begin(); b != bindings.end(); ++b) {
1167 idprop = (*b)->getXMLString("id");
1168 pathprop = (*b)->getXMLString("path");
1169 if (idprop.first && pathprop.first) {
1170 DOMElement* slodom = e->getOwnerDocument()->createElementNS(samlconstants::SAML20MD_NS, _SingleLogoutService);
1171 slodom->setAttributeNS(nullptr, Binding, idprop.second);
1172 slodom->setAttributeNS(nullptr, Location, pathprop.second);
1174 log.info("adding SingleLogoutService for Binding (%s) at (%s)", (*b)->getString("id").second, (*b)->getString("path").second);
1175 Handler* handler = conf.SingleLogoutServiceManager.newPlugin(
1176 (*b)->getString("id").second, pair<const DOMElement*,const char*>(slodom, getId())
1178 m_handlers.push_back(handler);
1180 // Insert into location map.
1181 pair<bool,const char*> location = handler->getString("Location");
1182 if (location.first && *location.second == '/')
1183 m_handlerMap[location.second] = handler;
1184 else if (location.first)
1185 m_handlerMap[string("/") + location.second] = handler;
1188 log.error("missing id or path property on Binding element, check config for protocol (%s)", prot.get());
1192 if (protocols.count(prot.get()) == 0) {
1193 doArtifactResolution(pp, prot.get(), e, log);
1194 protocols.insert(prot.get());
1198 if (!initiator && bindings.empty()) {
1199 log.error("no Logout Initiator or Binding config for protocol (%s)", prot.get());
1203 // Attach default Location to Logout element.
1204 static const XMLCh _loc[] = { chForwardSlash, chLatin_L, chLatin_o, chLatin_g, chLatin_o, chLatin_u, chLatin_t, chNull };
1205 e->setAttributeNS(nullptr, Location, _loc);
1207 // Instantiate Chaining initiator around the SSO element.
1208 Handler* chain = conf.LogoutInitiatorManager.newPlugin(
1209 CHAINING_LOGOUT_INITIATOR, pair<const DOMElement*,const char*>(e, getId())
1211 m_handlers.push_back(chain);
1212 m_handlerMap["/Logout"] = chain;
1215 void XMLApplication::doNameIDMgmt(const ProtocolProvider& pp, set<string>& protocols, DOMElement* e, Category& log)
1217 if (!e->hasChildNodes())
1220 SPConfig& conf = SPConfig::getConfig();
1222 // Tokenize the protocol list inside the element.
1223 const XMLCh* protlist = e->getFirstChild()->getNodeValue();
1224 XMLStringTokenizer prottokens(protlist);
1225 while (prottokens.hasMoreTokens()) {
1226 auto_ptr_char prot(prottokens.nextToken());
1228 // Look for incoming bindings.
1229 const vector<const PropertySet*>& bindings = pp.getBindings(prot.get(), "NameIDMgmt");
1230 if (!bindings.empty()) {
1231 log.info("auto-configuring NameIDMgmt endpoints for protocol (%s)", prot.get());
1232 pair<bool,const XMLCh*> idprop,pathprop;
1233 for (vector<const PropertySet*>::const_iterator b = bindings.begin(); b != bindings.end(); ++b) {
1234 idprop = (*b)->getXMLString("id");
1235 pathprop = (*b)->getXMLString("path");
1236 if (idprop.first && pathprop.first) {
1237 DOMElement* nimdom = e->getOwnerDocument()->createElementNS(samlconstants::SAML20MD_NS, _ManageNameIDService);
1238 nimdom->setAttributeNS(nullptr, Binding, idprop.second);
1239 nimdom->setAttributeNS(nullptr, Location, pathprop.second);
1241 log.info("adding ManageNameIDService for Binding (%s) at (%s)", (*b)->getString("id").second, (*b)->getString("path").second);
1242 Handler* handler = conf.ManageNameIDServiceManager.newPlugin(
1243 (*b)->getString("id").second, pair<const DOMElement*,const char*>(nimdom, getId())
1245 m_handlers.push_back(handler);
1247 // Insert into location map.
1248 pair<bool,const char*> location = handler->getString("Location");
1249 if (location.first && *location.second == '/')
1250 m_handlerMap[location.second] = handler;
1251 else if (location.first)
1252 m_handlerMap[string("/") + location.second] = handler;
1255 log.error("missing id or path property on Binding element, check config for protocol (%s)", prot.get());
1259 if (protocols.count(prot.get()) == 0) {
1260 doArtifactResolution(pp, prot.get(), e, log);
1261 protocols.insert(prot.get());
1265 log.error("no NameIDMgmt Binding config for protocol (%s)", prot.get());
1270 void XMLApplication::doArtifactResolution(const ProtocolProvider& pp, const char* protocol, DOMElement* e, Category& log)
1272 SPConfig& conf = SPConfig::getConfig();
1274 // Look for incoming bindings.
1275 const vector<const PropertySet*>& bindings = pp.getBindings(protocol, "ArtifactResolution");
1276 if (!bindings.empty()) {
1277 log.info("auto-configuring ArtifactResolution endpoints for protocol (%s)", protocol);
1279 pair<bool,const XMLCh*> idprop,pathprop;
1280 for (vector<const PropertySet*>::const_iterator b = bindings.begin(); b != bindings.end(); ++b) {
1281 idprop = (*b)->getXMLString("id");
1282 pathprop = (*b)->getXMLString("path");
1283 if (idprop.first && pathprop.first) {
1284 DOMElement* artdom = e->getOwnerDocument()->createElementNS(samlconstants::SAML20MD_NS, _ArtifactResolutionService);
1285 artdom->setAttributeNS(nullptr, Binding, idprop.second);
1286 artdom->setAttributeNS(nullptr, Location, pathprop.second);
1287 xstring indexbuf(chDigit_1 + (index % 10), 1);
1289 indexbuf = (XMLCh)(chDigit_1 + (index / 10)) + indexbuf;
1290 artdom->setAttributeNS(nullptr, _index, indexbuf.c_str());
1292 log.info("adding ArtifactResolutionService for Binding (%s) at (%s)", (*b)->getString("id").second, (*b)->getString("path").second);
1293 Handler* handler = conf.ArtifactResolutionServiceManager.newPlugin(
1294 (*b)->getString("id").second, pair<const DOMElement*,const char*>(artdom, getId())
1296 m_handlers.push_back(handler);
1298 if (!m_artifactResolutionDefault)
1299 m_artifactResolutionDefault = handler;
1301 // Insert into location map.
1302 pair<bool,const char*> location = handler->getString("Location");
1303 if (location.first && *location.second == '/')
1304 m_handlerMap[location.second] = handler;
1305 else if (location.first)
1306 m_handlerMap[string("/") + location.second] = handler;
1309 log.error("missing id or path property on Binding element, check config for protocol (%s)", protocol);
1316 void XMLApplication::doAttributePlugins(DOMElement* e, Category& log)
1318 SPConfig& conf = SPConfig::getConfig();
1321 doChainedPlugins(conf.AttributeExtractorManager, "AttributeExtractor", CHAINING_ATTRIBUTE_EXTRACTOR, _AttributeExtractor, e, log);
1324 doChainedPlugins(conf.AttributeFilterManager, "AttributeFilter", CHAINING_ATTRIBUTE_FILTER, _AttributeFilter, e, log);
1327 doChainedPlugins(conf.AttributeResolverManager, "AttributeResolver", CHAINING_ATTRIBUTE_RESOLVER, _AttributeResolver, e, log);
1329 if (m_unsetHeaders.empty()) {
1330 vector<string> unsetHeaders;
1331 if (m_attrExtractor) {
1332 Locker extlock(m_attrExtractor);
1333 m_attrExtractor->getAttributeIds(unsetHeaders);
1335 else if (m_base && m_base->m_attrExtractor) {
1336 Locker extlock(m_base->m_attrExtractor);
1337 m_base->m_attrExtractor->getAttributeIds(unsetHeaders);
1339 if (m_attrResolver) {
1340 Locker reslock(m_attrResolver);
1341 m_attrResolver->getAttributeIds(unsetHeaders);
1343 else if (m_base && m_base->m_attrResolver) {
1344 Locker extlock(m_base->m_attrResolver);
1345 m_base->m_attrResolver->getAttributeIds(unsetHeaders);
1347 if (!unsetHeaders.empty()) {
1348 string transformedprefix(m_attributePrefix.second);
1350 pair<bool,const char*> prefix = getString("metadataAttributePrefix");
1352 pch = prefix.second;
1354 transformedprefix += (isalnum(*pch) ? toupper(*pch) : '_');
1358 for (vector<string>::const_iterator hdr = unsetHeaders.begin(); hdr!=unsetHeaders.end(); ++hdr) {
1362 transformed += (isalnum(*pch) ? toupper(*pch) : '_');
1365 m_unsetHeaders.push_back(pair<string,string>(m_attributePrefix.first + *hdr, m_attributePrefix.second + transformed));
1367 m_unsetHeaders.push_back(pair<string,string>(m_attributePrefix.first + prefix.second + *hdr, transformedprefix + transformed));
1370 m_unsetHeaders.push_back(pair<string,string>(m_attributePrefix.first + "Shib-Application-ID", m_attributePrefix.second + "SHIB_APPLICATION_ID"));
1375 void XMLApplication::cleanup()
1377 ListenerService* listener=getServiceProvider().getListenerService(false);
1378 if (listener && SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess) && !SPConfig::getConfig().isEnabled(SPConfig::InProcess)) {
1379 string addr=string(getId()) + "::getHeaders::Application";
1380 listener->unregListener(addr.c_str(),this);
1382 for_each(m_handlers.begin(),m_handlers.end(),xmltooling::cleanup<Handler>());
1385 for_each(m_partyMap.begin(),m_partyMap.end(),cleanup_pair<xstring,PropertySet>());
1387 delete m_credResolver;
1388 m_credResolver = nullptr;
1389 delete m_attrResolver;
1390 m_attrResolver = nullptr;
1391 delete m_attrFilter;
1392 m_attrFilter = nullptr;
1393 delete m_attrExtractor;
1394 m_attrExtractor = nullptr;
1398 m_metadata = nullptr;
1402 #ifdef SHIBSP_XERCESC_SHORT_ACCEPTNODE
1405 DOMNodeFilter::FilterAction
1407 XMLApplication::acceptNode(const DOMNode* node) const
1409 const XMLCh* name=node->getLocalName();
1410 if (XMLString::equals(name,ApplicationOverride) ||
1411 XMLString::equals(name,_Audience) ||
1412 XMLString::equals(name,Notify) ||
1413 XMLString::equals(name,_Handler) ||
1414 XMLString::equals(name,_AssertionConsumerService) ||
1415 XMLString::equals(name,_ArtifactResolutionService) ||
1416 XMLString::equals(name,Logout) ||
1417 XMLString::equals(name,_LogoutInitiator) ||
1418 XMLString::equals(name,_ManageNameIDService) ||
1419 XMLString::equals(name,NameIDMgmt) ||
1420 XMLString::equals(name,_SessionInitiator) ||
1421 XMLString::equals(name,_SingleLogoutService) ||
1422 XMLString::equals(name,SSO) ||
1423 XMLString::equals(name,RelyingParty) ||
1424 XMLString::equals(name,_MetadataProvider) ||
1425 XMLString::equals(name,_TrustEngine) ||
1426 XMLString::equals(name,_CredentialResolver) ||
1427 XMLString::equals(name,_AttributeFilter) ||
1428 XMLString::equals(name,_AttributeExtractor) ||
1429 XMLString::equals(name,_AttributeResolver))
1430 return FILTER_REJECT;
1432 return FILTER_ACCEPT;
1437 const PropertySet* XMLApplication::getRelyingParty(const EntityDescriptor* provider) const
1442 map<xstring,PropertySet*>::const_iterator i=m_partyMap.find(provider->getEntityID());
1443 if (i!=m_partyMap.end())
1445 const EntitiesDescriptor* group=dynamic_cast<const EntitiesDescriptor*>(provider->getParent());
1447 if (group->getName()) {
1448 i=m_partyMap.find(group->getName());
1449 if (i!=m_partyMap.end())
1452 group=dynamic_cast<const EntitiesDescriptor*>(group->getParent());
1457 const PropertySet* XMLApplication::getRelyingParty(const XMLCh* entityID) const
1462 map<xstring,PropertySet*>::const_iterator i=m_partyMap.find(entityID);
1463 if (i!=m_partyMap.end())
1470 string XMLApplication::getNotificationURL(const char* resource, bool front, unsigned int index) const
1472 const vector<string>& locs = front ? m_frontLogout : m_backLogout;
1474 return m_base ? m_base->getNotificationURL(resource, front, index) : string();
1475 else if (index >= locs.size())
1478 #ifdef HAVE_STRCASECMP
1479 if (!resource || (strncasecmp(resource,"http://",7) && strncasecmp(resource,"https://",8)))
1481 if (!resource || (strnicmp(resource,"http://",7) && strnicmp(resource,"https://",8)))
1483 throw ConfigurationException("Request URL was not absolute.");
1485 const char* handler=locs[index].c_str();
1487 // Should never happen...
1488 if (!handler || (*handler!='/' && strncmp(handler,"http:",5) && strncmp(handler,"https:",6)))
1489 throw ConfigurationException(
1490 "Invalid Location property ($1) in Notify element for Application ($2)",
1491 params(2, handler ? handler : "null", getId())
1494 // The "Location" property can be in one of three formats:
1496 // 1) a full URI: http://host/foo/bar
1497 // 2) a hostless URI: http:///foo/bar
1498 // 3) a relative path: /foo/bar
1500 // # Protocol Host Path
1501 // 1 handler handler handler
1502 // 2 handler resource handler
1503 // 3 resource resource handler
1505 const char* path = nullptr;
1507 // Decide whether to use the handler or the resource for the "protocol"
1509 if (*handler != '/') {
1517 // break apart the "protocol" string into protocol, host, and "the rest"
1518 const char* colon=strchr(prot,':');
1520 const char* slash=strchr(colon,'/');
1524 // Compute the actual protocol and store.
1525 string notifyURL(prot, colon-prot);
1527 // create the "host" from either the colon/slash or from the target string
1528 // If prot == handler then we're in either #1 or #2, else #3.
1529 // If slash == colon then we're in #2.
1530 if (prot != handler || slash == colon) {
1531 colon = strchr(resource, ':');
1532 colon += 3; // Get past the ://
1533 slash = strchr(colon, '/');
1535 string host(colon, (slash ? slash-colon : strlen(colon)));
1538 notifyURL += host + path;
1542 void XMLApplication::clearHeader(SPRequest& request, const char* rawname, const char* cginame) const
1544 if (!m_attributePrefix.first.empty()) {
1545 string temp = m_attributePrefix.first + rawname;
1546 string temp2 = m_attributePrefix.second + (cginame + 5);
1547 request.clearHeader(temp.c_str(), temp2.c_str());
1550 m_base->clearHeader(request, rawname, cginame);
1553 request.clearHeader(rawname, cginame);
1557 void XMLApplication::setHeader(SPRequest& request, const char* name, const char* value) const
1559 if (!m_attributePrefix.first.empty()) {
1560 string temp = m_attributePrefix.first + name;
1561 request.setHeader(temp.c_str(), value);
1564 m_base->setHeader(request, name, value);
1567 request.setHeader(name, value);
1571 string XMLApplication::getSecureHeader(const SPRequest& request, const char* name) const
1573 if (!m_attributePrefix.first.empty()) {
1574 string temp = m_attributePrefix.first + name;
1575 return request.getSecureHeader(temp.c_str());
1578 return m_base->getSecureHeader(request,name);
1581 return request.getSecureHeader(name);
1585 const SessionInitiator* XMLApplication::getDefaultSessionInitiator() const
1587 if (m_sessionInitDefault) return m_sessionInitDefault;
1588 return m_base ? m_base->getDefaultSessionInitiator() : nullptr;
1591 const SessionInitiator* XMLApplication::getSessionInitiatorById(const char* id) const
1593 map<string,const SessionInitiator*>::const_iterator i=m_sessionInitMap.find(id);
1594 if (i!=m_sessionInitMap.end()) return i->second;
1595 return m_base ? m_base->getSessionInitiatorById(id) : nullptr;
1598 const Handler* XMLApplication::getDefaultAssertionConsumerService() const
1600 if (m_acsDefault) return m_acsDefault;
1601 return m_base ? m_base->getDefaultAssertionConsumerService() : nullptr;
1604 const Handler* XMLApplication::getAssertionConsumerServiceByIndex(unsigned short index) const
1606 map<unsigned int,const Handler*>::const_iterator i=m_acsIndexMap.find(index);
1607 if (i != m_acsIndexMap.end()) return i->second;
1608 return m_base ? m_base->getAssertionConsumerServiceByIndex(index) : nullptr;
1611 const Handler* XMLApplication::getAssertionConsumerServiceByProtocol(const XMLCh* protocol, const char* binding) const
1613 ACSProtocolMap::const_iterator i=m_acsProtocolMap.find(protocol);
1614 if (i != m_acsProtocolMap.end() && !i->second.empty()) {
1615 if (!binding || !*binding)
1616 return i->second.front();
1617 for (ACSProtocolMap::value_type::second_type::const_iterator j = i->second.begin(); j != i->second.end(); ++j) {
1618 if (!strcmp(binding, (*j)->getString("Binding").second))
1622 return m_base ? m_base->getAssertionConsumerServiceByProtocol(protocol) : nullptr;
1625 const vector<const Handler*>& XMLApplication::getAssertionConsumerServicesByBinding(const XMLCh* binding) const
1627 ACSBindingMap::const_iterator i=m_acsBindingMap.find(binding);
1628 if (i != m_acsBindingMap.end())
1630 return m_base ? m_base->getAssertionConsumerServicesByBinding(binding) : g_noHandlers;
1633 const Handler* XMLApplication::getHandler(const char* path) const
1636 wrap = wrap.substr(0,wrap.find(';'));
1637 map<string,const Handler*>::const_iterator i=m_handlerMap.find(wrap.substr(0,wrap.find('?')));
1638 if (i!=m_handlerMap.end())
1640 return m_base ? m_base->getHandler(path) : nullptr;
1643 void XMLApplication::getHandlers(vector<const Handler*>& handlers) const
1645 handlers.insert(handlers.end(), m_handlers.begin(), m_handlers.end());
1647 for (map<string,const Handler*>::const_iterator h = m_base->m_handlerMap.begin(); h != m_base->m_handlerMap.end(); ++h) {
1648 if (m_handlerMap.count(h->first) == 0)
1649 handlers.push_back(h->second);
1654 #ifdef SHIBSP_XERCESC_SHORT_ACCEPTNODE
1657 DOMNodeFilter::FilterAction
1659 XMLConfigImpl::acceptNode(const DOMNode* node) const
1661 if (!XMLString::equals(node->getNamespaceURI(),shibspconstants::SHIB2SPCONFIG_NS))
1662 return FILTER_ACCEPT;
1663 const XMLCh* name=node->getLocalName();
1664 if (XMLString::equals(name,ApplicationDefaults) ||
1665 XMLString::equals(name,_ArtifactMap) ||
1666 XMLString::equals(name,_Extensions) ||
1667 XMLString::equals(name,Listener) ||
1668 XMLString::equals(name,_ProtocolProvider) ||
1669 XMLString::equals(name,_RequestMapper) ||
1670 XMLString::equals(name,_ReplayCache) ||
1671 XMLString::equals(name,SecurityPolicies) ||
1672 XMLString::equals(name,_SecurityPolicyProvider) ||
1673 XMLString::equals(name,_SessionCache) ||
1674 XMLString::equals(name,Site) ||
1675 XMLString::equals(name,_StorageService) ||
1676 XMLString::equals(name,TCPListener) ||
1677 XMLString::equals(name,TransportOption) ||
1678 XMLString::equals(name,UnixListener))
1679 return FILTER_REJECT;
1681 return FILTER_ACCEPT;
1684 void XMLConfigImpl::doExtensions(const DOMElement* e, const char* label, Category& log)
1686 const DOMElement* exts = XMLHelper::getFirstChildElement(e, _Extensions);
1688 exts = XMLHelper::getFirstChildElement(exts, Library);
1690 string path(XMLHelper::getAttrString(exts, nullptr, _path));
1692 if (!path.empty()) {
1693 if (!XMLToolingConfig::getConfig().load_library(path.c_str(), (void*)exts))
1694 throw ConfigurationException("XMLToolingConfig::load_library failed.");
1695 log.debug("loaded %s extension library (%s)", label, path.c_str());
1698 catch (exception& e) {
1699 if (XMLHelper::getAttrBool(exts, false, _fatal)) {
1700 log.fatal("unable to load mandatory %s extension library %s: %s", label, path.c_str(), e.what());
1704 log.crit("unable to load optional %s extension library %s: %s", label, path.c_str(), e.what());
1707 exts = XMLHelper::getNextSiblingElement(exts, Library);
1712 void XMLConfigImpl::doListener(const DOMElement* e, XMLConfig* conf, Category& log)
1715 string plugtype(TCP_LISTENER_SERVICE);
1717 string plugtype(UNIX_LISTENER_SERVICE);
1719 DOMElement* child = XMLHelper::getFirstChildElement(e, UnixListener);
1721 plugtype = UNIX_LISTENER_SERVICE;
1723 child = XMLHelper::getFirstChildElement(e, TCPListener);
1725 plugtype = TCP_LISTENER_SERVICE;
1727 child = XMLHelper::getFirstChildElement(e, Listener);
1729 auto_ptr_char type(child->getAttributeNS(nullptr, _type));
1730 if (type.get() && *type.get())
1731 plugtype = type.get();
1736 log.info("building ListenerService of type %s...", plugtype.c_str());
1737 conf->m_listener = SPConfig::getConfig().ListenerServiceManager.newPlugin(plugtype.c_str(), child);
1740 void XMLConfigImpl::doCaching(const DOMElement* e, XMLConfig* conf, Category& log)
1742 SPConfig& spConf = SPConfig::getConfig();
1744 SAMLConfig& samlConf = SAMLConfig::getConfig();
1749 if (spConf.isEnabled(SPConfig::OutOfProcess)) {
1750 XMLToolingConfig& xmlConf = XMLToolingConfig::getConfig();
1751 // First build any StorageServices.
1752 child = XMLHelper::getFirstChildElement(e, _StorageService);
1754 string id(XMLHelper::getAttrString(child, nullptr, _id));
1755 string t(XMLHelper::getAttrString(child, nullptr, _type));
1758 log.info("building StorageService (%s) of type %s...", id.c_str(), t.c_str());
1759 conf->m_storage[id] = xmlConf.StorageServiceManager.newPlugin(t.c_str(), child);
1761 catch (exception& ex) {
1762 log.crit("failed to instantiate StorageService (%s): %s", id.c_str(), ex.what());
1765 child = XMLHelper::getNextSiblingElement(child, _StorageService);
1768 if (conf->m_storage.empty()) {
1769 log.info("no StorageService plugin(s) installed, using (mem) in-memory instance");
1770 conf->m_storage["mem"] = xmlConf.StorageServiceManager.newPlugin(MEMORY_STORAGE_SERVICE, nullptr);
1774 StorageService* replaySS = nullptr;
1775 child = XMLHelper::getFirstChildElement(e, _ReplayCache);
1777 string ssid(XMLHelper::getAttrString(child, nullptr, _StorageService));
1778 if (!ssid.empty()) {
1779 if (conf->m_storage.count(ssid)) {
1780 log.info("building ReplayCache on top of StorageService (%s)...", ssid.c_str());
1781 replaySS = conf->m_storage[ssid];
1784 log.error("unable to locate StorageService (%s), using arbitrary instance for ReplayCache", ssid.c_str());
1785 replaySS = conf->m_storage.begin()->second;
1789 log.info("no StorageService specified for ReplayCache, using arbitrary instance");
1790 replaySS = conf->m_storage.begin()->second;
1794 log.info("no ReplayCache specified, using arbitrary StorageService instance");
1795 replaySS = conf->m_storage.begin()->second;
1797 xmlConf.setReplayCache(new ReplayCache(replaySS));
1800 child = XMLHelper::getFirstChildElement(e, _ArtifactMap);
1802 string ssid(XMLHelper::getAttrString(child, nullptr, _StorageService));
1803 if (!ssid.empty()) {
1804 if (conf->m_storage.count(ssid)) {
1805 log.info("building ArtifactMap on top of StorageService (%s)...", ssid.c_str());
1806 samlConf.setArtifactMap(new ArtifactMap(child, conf->m_storage[ssid]));
1809 log.error("unable to locate StorageService (%s), using in-memory ArtifactMap", ssid.c_str());
1810 samlConf.setArtifactMap(new ArtifactMap(child));
1814 log.info("no StorageService specified, using in-memory ArtifactMap");
1815 samlConf.setArtifactMap(new ArtifactMap(child));
1819 log.info("no ArtifactMap specified, building in-memory ArtifactMap...");
1820 samlConf.setArtifactMap(new ArtifactMap(child));
1822 } // end of out of process caching components
1825 child = XMLHelper::getFirstChildElement(e, _SessionCache);
1827 string t(XMLHelper::getAttrString(child, nullptr, _type));
1829 log.info("building SessionCache of type %s...", t.c_str());
1830 conf->m_sessionCache = spConf.SessionCacheManager.newPlugin(t.c_str(), child);
1833 if (!conf->m_sessionCache) {
1834 log.info("no SessionCache specified, using StorageService-backed instance");
1835 conf->m_sessionCache = spConf.SessionCacheManager.newPlugin(STORAGESERVICE_SESSION_CACHE, nullptr);
1839 XMLConfigImpl::XMLConfigImpl(const DOMElement* e, bool first, XMLConfig* outer, Category& log)
1840 : m_requestMapper(nullptr),
1847 xmltooling::NDC ndc("XMLConfigImpl");
1851 SPConfig& conf=SPConfig::getConfig();
1852 XMLToolingConfig& xmlConf=XMLToolingConfig::getConfig();
1853 const DOMElement* SHAR=XMLHelper::getFirstChildElement(e, OutOfProcess);
1854 const DOMElement* SHIRE=XMLHelper::getFirstChildElement(e, InProcess);
1856 // Initialize logging manually in order to redirect log messages as soon as possible.
1857 if (conf.isEnabled(SPConfig::Logging)) {
1859 if (conf.isEnabled(SPConfig::OutOfProcess))
1860 logconf = XMLHelper::getAttrString(SHAR, nullptr, logger);
1861 else if (conf.isEnabled(SPConfig::InProcess))
1862 logconf = XMLHelper::getAttrString(SHIRE, nullptr, logger);
1863 if (logconf.empty())
1864 logconf = XMLHelper::getAttrString(e, nullptr, logger);
1865 if (logconf.empty() && !getenv("SHIBSP_LOGGING")) {
1866 // No properties found, so default them.
1867 if (conf.isEnabled(SPConfig::OutOfProcess) && !conf.isEnabled(SPConfig::InProcess))
1868 logconf = "shibd.logger";
1869 else if (!conf.isEnabled(SPConfig::OutOfProcess) && conf.isEnabled(SPConfig::InProcess))
1870 logconf = "native.logger";
1872 logconf = "shibboleth.logger";
1874 if (!logconf.empty()) {
1875 log.debug("loading new logging configuration from (%s), check log destination for status of configuration", logconf.c_str());
1876 if (!XMLToolingConfig::getConfig().log_config(logconf.c_str()))
1877 log.crit("failed to load new logging configuration from (%s)", logconf.c_str());
1882 outer->m_tranLog = new TransactionLog();
1886 // Re-log library versions now that logging is set up.
1887 log.info("Shibboleth SP Version %s", PACKAGE_VERSION);
1890 "Library versions: %s %s, Xerces-C %s, XML-Security-C %s, XMLTooling-C %s, OpenSAML-C %s, Shibboleth %s",
1891 # if defined(LOG4SHIB_VERSION)
1892 "log4shib", LOG4SHIB_VERSION,
1893 # elif defined(LOG4CPP_VERSION)
1894 "log4cpp", LOG4CPP_VERSION,
1898 XERCES_FULLVERSIONDOT, XSEC_FULLVERSIONDOT, XMLTOOLING_FULLVERSIONDOT, OPENSAML_FULLVERSIONDOT, SHIBSP_FULLVERSIONDOT
1902 "Library versions: %s %s, Xerces-C %s, XMLTooling-C %s, Shibboleth %s",
1903 # if defined(LOG4SHIB_VERSION)
1904 "log4shib", LOG4SHIB_VERSION,
1905 # elif defined(LOG4CPP_VERSION)
1906 "log4cpp", LOG4CPP_VERSION,
1910 XERCES_FULLVERSIONDOT, XMLTOOLING_FULLVERSIONDOT, SHIBSP_FULLVERSIONDOT
1914 // First load any property sets.
1915 load(e,nullptr,this);
1919 // Much of the processing can only occur on the first instantiation.
1922 pair<bool,unsigned int> skew=getUnsignedInt("clockSkew");
1924 xmlConf.clock_skew_secs=min(skew.second,(60*60*24*7*28));
1926 pair<bool,const char*> unsafe = getString("unsafeChars");
1928 TemplateEngine::unsafe_chars = unsafe.second;
1930 unsafe = getString("allowedSchemes");
1932 HTTPResponse::getAllowedSchemes().clear();
1933 string schemes=unsafe.second;
1934 unsigned int j_sch=0;
1935 for (unsigned int i_sch=0; i_sch < schemes.length(); i_sch++) {
1936 if (schemes.at(i_sch)==' ') {
1937 HTTPResponse::getAllowedSchemes().push_back(schemes.substr(j_sch, i_sch-j_sch));
1941 HTTPResponse::getAllowedSchemes().push_back(schemes.substr(j_sch, schemes.length()-j_sch));
1945 doExtensions(e, "global", log);
1946 if (conf.isEnabled(SPConfig::OutOfProcess))
1947 doExtensions(SHAR, "out of process", log);
1949 if (conf.isEnabled(SPConfig::InProcess))
1950 doExtensions(SHIRE, "in process", log);
1952 // Instantiate the ListenerService and SessionCache objects.
1953 if (conf.isEnabled(SPConfig::Listener))
1954 doListener(e, outer, log);
1957 if (outer->m_listener && conf.isEnabled(SPConfig::OutOfProcess) && !conf.isEnabled(SPConfig::InProcess)) {
1958 outer->m_listener->regListener("set::RelayState", outer);
1959 outer->m_listener->regListener("get::RelayState", outer);
1960 outer->m_listener->regListener("set::PostData", outer);
1961 outer->m_listener->regListener("get::PostData", outer);
1964 if (conf.isEnabled(SPConfig::Caching))
1965 doCaching(e, outer, log);
1966 } // end of first-time-only stuff
1968 // Back to the fully dynamic stuff...next up is the RequestMapper.
1969 if (conf.isEnabled(SPConfig::RequestMapping)) {
1970 if (child = XMLHelper::getFirstChildElement(e, _RequestMapper)) {
1971 string t(XMLHelper::getAttrString(child, nullptr, _type));
1973 log.info("building RequestMapper of type %s...", t.c_str());
1974 m_requestMapper = conf.RequestMapperManager.newPlugin(t.c_str(), child);
1977 if (!m_requestMapper) {
1978 log.info("no RequestMapper specified, using 'Native' plugin with empty/default map");
1979 child = e->getOwnerDocument()->createElementNS(nullptr, _RequestMapper);
1980 DOMElement* mapperDummy = e->getOwnerDocument()->createElementNS(shibspconstants::SHIB2SPCONFIG_NS, RequestMap);
1981 mapperDummy->setAttributeNS(nullptr, applicationId, _default);
1982 child->appendChild(mapperDummy);
1983 m_requestMapper = conf.RequestMapperManager.newPlugin(NATIVE_REQUEST_MAPPER, child);
1988 // Load security policies.
1989 if (child = XMLHelper::getLastChildElement(e, _SecurityPolicyProvider)) {
1990 string t(XMLHelper::getAttrString(child, nullptr, _type));
1992 log.info("building SecurityPolicyProvider of type %s...", t.c_str());
1993 m_policy = conf.SecurityPolicyProviderManager.newPlugin(t.c_str(), child);
1996 throw ConfigurationException("can't build SecurityPolicyProvider, no type specified");
1999 else if (child = XMLHelper::getLastChildElement(e, SecurityPolicies)) {
2000 // For backward compatibility, wrap in a plugin element.
2001 DOMElement* polwrapper = e->getOwnerDocument()->createElementNS(nullptr, _SecurityPolicyProvider);
2002 polwrapper->appendChild(child);
2003 log.info("building SecurityPolicyProvider of type %s...", XML_SECURITYPOLICY_PROVIDER);
2004 m_policy = conf.SecurityPolicyProviderManager.newPlugin(XML_SECURITYPOLICY_PROVIDER, polwrapper);
2007 log.fatal("can't build SecurityPolicyProvider, missing conf:SecurityPolicyProvider element?");
2008 throw ConfigurationException("Can't build SecurityPolicyProvider, missing conf:SecurityPolicyProvider element?");
2012 if (!m_policy->getAlgorithmBlacklist().empty()) {
2013 #ifdef SHIBSP_XMLSEC_WHITELISTING
2014 for (vector<xstring>::const_iterator alg = m_policy->getAlgorithmBlacklist().begin(); alg != m_policy->getAlgorithmBlacklist().end(); ++alg)
2015 XSECPlatformUtils::blacklistAlgorithm(alg->c_str());
2017 log.crit("XML-Security-C library prior to 1.6.0 does not support algorithm white/blacklists");
2020 else if (!m_policy->getAlgorithmWhitelist().empty()) {
2021 #ifdef SHIBSP_XMLSEC_WHITELISTING
2022 for (vector<xstring>::const_iterator alg = m_policy->getAlgorithmWhitelist().begin(); alg != m_policy->getAlgorithmWhitelist().end(); ++alg)
2023 XSECPlatformUtils::whitelistAlgorithm(alg->c_str());
2025 log.crit("XML-Security-C library prior to 1.6.0 does not support algorithm white/blacklists");
2030 // Process TransportOption elements.
2031 child = XMLHelper::getLastChildElement(e, TransportOption);
2033 if (child->hasChildNodes()) {
2034 string provider(XMLHelper::getAttrString(child, nullptr, _provider));
2035 string option(XMLHelper::getAttrString(child, nullptr, _option));
2036 auto_ptr_char value(child->getFirstChild()->getNodeValue());
2037 if (!provider.empty() && !option.empty() && value.get() && *value.get()) {
2038 m_transportOptions.push_back(make_pair(provider, make_pair(option, string(value.get()))));
2041 child = XMLHelper::getPreviousSiblingElement(child, TransportOption);
2045 ProtocolProvider* pp = nullptr;
2046 if (conf.isEnabled(SPConfig::Handlers)) {
2047 if (child = XMLHelper::getLastChildElement(e, _ProtocolProvider)) {
2048 string t(XMLHelper::getAttrString(child, nullptr, _type));
2050 log.info("building ProtocolProvider of type %s...", t.c_str());
2051 pp = conf.ProtocolProviderManager.newPlugin(t.c_str(), child);
2055 auto_ptr<ProtocolProvider> ppwrapper(pp);
2056 Locker pplocker(pp);
2058 // Load the default application.
2059 child = XMLHelper::getLastChildElement(e, ApplicationDefaults);
2061 log.fatal("can't build default Application object, missing conf:ApplicationDefaults element?");
2062 throw ConfigurationException("can't build default Application object, missing conf:ApplicationDefaults element?");
2064 XMLApplication* defapp = new XMLApplication(outer, pp, child);
2065 m_appmap[defapp->getId()] = defapp;
2067 // Load any overrides.
2068 child = XMLHelper::getFirstChildElement(child, ApplicationOverride);
2070 auto_ptr<XMLApplication> iapp(new XMLApplication(outer, pp, child, defapp));
2071 if (m_appmap.count(iapp->getId()))
2072 log.crit("found conf:ApplicationOverride element with duplicate id attribute (%s), skipping it", iapp->getId());
2074 const char* iappid=iapp->getId();
2075 m_appmap[iappid] = iapp.release();
2078 child = XMLHelper::getNextSiblingElement(child, ApplicationOverride);
2081 // Check for extra AuthTypes to recognize.
2082 if (conf.isEnabled(SPConfig::InProcess)) {
2083 const PropertySet* inprocs = getPropertySet("InProcess");
2085 pair<bool,const char*> extraAuthTypes = inprocs->getString("extraAuthTypes");
2086 if (extraAuthTypes.first) {
2087 string types=extraAuthTypes.second;
2088 unsigned int j_types=0;
2089 for (unsigned int i_types=0; i_types < types.length(); i_types++) {
2090 if (types.at(i_types) == ' ') {
2091 outer->m_authTypes.insert(types.substr(j_types, i_types - j_types));
2092 j_types = i_types + 1;
2095 outer->m_authTypes.insert(types.substr(j_types, types.length() - j_types));
2100 catch (exception&) {
2106 XMLConfigImpl::~XMLConfigImpl()
2111 void XMLConfigImpl::cleanup()
2113 for_each(m_appmap.begin(),m_appmap.end(),cleanup_pair<string,Application>());
2119 delete m_requestMapper;
2120 m_requestMapper = nullptr;
2122 m_document->release();
2123 m_document = nullptr;
2127 void XMLConfig::receive(DDF& in, ostream& out)
2129 if (!strcmp(in.name(), "get::RelayState")) {
2130 const char* id = in["id"].string();
2131 const char* key = in["key"].string();
2133 throw ListenerException("Required parameters missing for RelayState recovery.");
2136 StorageService* storage = getStorageService(id);
2138 if (storage->readString("RelayState",key,&relayState)>0) {
2139 if (in["clear"].integer())
2140 storage->deleteString("RelayState",key);
2144 Category::getInstance(SHIBSP_LOGCAT".ServiceProvider").error(
2145 "Storage-backed RelayState with invalid StorageService ID (%s)", id
2149 // Repack for return to caller.
2150 DDF ret=DDF(nullptr).unsafe_string(relayState.c_str());
2151 DDFJanitor jret(ret);
2154 else if (!strcmp(in.name(), "set::RelayState")) {
2155 const char* id = in["id"].string();
2156 const char* value = in["value"].string();
2158 throw ListenerException("Required parameters missing for RelayState creation.");
2161 StorageService* storage = getStorageService(id);
2163 SAMLConfig::getConfig().generateRandomBytes(rsKey,20);
2164 rsKey = SAMLArtifact::toHex(rsKey);
2165 storage->createString("RelayState", rsKey.c_str(), value, time(nullptr) + 600);
2168 Category::getInstance(SHIBSP_LOGCAT".ServiceProvider").error(
2169 "Storage-backed RelayState with invalid StorageService ID (%s)", id
2173 // Repack for return to caller.
2174 DDF ret=DDF(nullptr).string(rsKey.c_str());
2175 DDFJanitor jret(ret);
2178 else if (!strcmp(in.name(), "get::PostData")) {
2179 const char* id = in["id"].string();
2180 const char* key = in["key"].string();
2182 throw ListenerException("Required parameters missing for PostData recovery.");
2185 StorageService* storage = getStorageService(id);
2187 if (storage->readString("PostData",key,&postData) > 0) {
2188 storage->deleteString("PostData",key);
2192 Category::getInstance(SHIBSP_LOGCAT".ServiceProvider").error(
2193 "Storage-backed PostData with invalid StorageService ID (%s)", id
2196 // If the data's empty, we'll send nothing back.
2197 // If not, we don't need to round trip it, just send back the serialized DDF list.
2198 if (postData.empty()) {
2200 DDFJanitor jret(ret);
2207 else if (!strcmp(in.name(), "set::PostData")) {
2208 const char* id = in["id"].string();
2209 if (!id || !in["parameters"].islist())
2210 throw ListenerException("Required parameters missing for PostData creation.");
2213 StorageService* storage = getStorageService(id);
2215 SAMLConfig::getConfig().generateRandomBytes(rsKey,20);
2216 rsKey = SAMLArtifact::toHex(rsKey);
2217 ostringstream params;
2218 params << in["parameters"];
2219 storage->createString("PostData", rsKey.c_str(), params.str().c_str(), time(nullptr) + 600);
2222 Category::getInstance(SHIBSP_LOGCAT".ServiceProvider").error(
2223 "Storage-backed PostData with invalid StorageService ID (%s)", id
2227 // Repack for return to caller.
2228 DDF ret=DDF(nullptr).string(rsKey.c_str());
2229 DDFJanitor jret(ret);
2235 pair<bool,DOMElement*> XMLConfig::background_load()
2237 // Load from source using base class.
2238 pair<bool,DOMElement*> raw = ReloadableXMLFile::load();
2240 // If we own it, wrap it.
2241 XercesJanitor<DOMDocument> docjanitor(raw.first ? raw.second->getOwnerDocument() : nullptr);
2243 XMLConfigImpl* impl = new XMLConfigImpl(raw.second, (m_impl==nullptr), this, m_log);
2245 // If we held the document, transfer it to the impl. If we didn't, it's a no-op.
2246 impl->setDocument(docjanitor.release());
2248 // Perform the swap inside a lock.
2251 SharedLock locker(m_lock, false);
2255 return make_pair(false,(DOMElement*)nullptr);