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 "TransactionLog.h"
64 # include "attribute/filtering/AttributeFilter.h"
65 # include "attribute/resolver/AttributeExtractor.h"
66 # include "attribute/resolver/AttributeResolver.h"
67 # include "security/PKIXTrustEngine.h"
68 # include "security/SecurityPolicyProvider.h"
69 # include <saml/SAMLConfig.h>
70 # include <saml/version.h>
71 # include <saml/binding/ArtifactMap.h>
72 # include <saml/binding/SAMLArtifact.h>
73 # include <saml/saml1/core/Assertions.h>
74 # include <saml/saml2/core/Assertions.h>
75 # include <saml/saml2/binding/SAML2ArtifactType0004.h>
76 # include <saml/saml2/metadata/Metadata.h>
77 # include <saml/saml2/metadata/MetadataProvider.h>
78 # include <saml/util/SAMLConstants.h>
79 # include <xmltooling/security/ChainingTrustEngine.h>
80 # include <xmltooling/security/CredentialResolver.h>
81 # include <xmltooling/security/SecurityHelper.h>
82 # include <xmltooling/util/ReplayCache.h>
83 # include <xmltooling/util/StorageService.h>
84 # include <xsec/utils/XSECPlatformUtils.hpp>
85 using namespace opensaml::saml2;
86 using namespace opensaml::saml2p;
87 using namespace opensaml::saml2md;
88 using namespace opensaml;
90 # include "lite/SAMLConstants.h"
93 using namespace shibsp;
94 using namespace xmltooling;
98 # define min(a,b) (((a) < (b)) ? (a) : (b))
103 #if defined (_MSC_VER)
104 #pragma warning( push )
105 #pragma warning( disable : 4250 )
108 static vector<const Handler*> g_noHandlers;
110 // Application configuration wrapper
111 class SHIBSP_DLLLOCAL XMLApplication : public Application, public Remoted, public DOMPropertySet, public DOMNodeFilter
114 XMLApplication(const ServiceProvider*, const ProtocolProvider*, DOMElement*, const XMLApplication* base=nullptr);
115 ~XMLApplication() { cleanup(); }
117 const char* getHash() const {return m_hash.c_str();}
120 SAMLArtifact* generateSAML1Artifact(const EntityDescriptor* relyingParty) const {
121 throw ConfigurationException("No support for SAML 1.x artifact generation.");
123 SAML2Artifact* generateSAML2Artifact(const EntityDescriptor* relyingParty) const {
124 pair<bool,int> index = make_pair(false,0);
125 const PropertySet* props = getRelyingParty(relyingParty);
126 index = props->getInt("artifactEndpointIndex");
128 index = getArtifactEndpointIndex();
129 pair<bool,const char*> entityID = props->getString("entityID");
130 return new SAML2ArtifactType0004(
131 SecurityHelper::doHash("SHA1", entityID.second, strlen(entityID.second), false),
132 index.first ? index.second : 1
136 MetadataProvider* getMetadataProvider(bool required=true) const {
137 if (required && !m_base && !m_metadata)
138 throw ConfigurationException("No MetadataProvider available.");
139 return (!m_metadata && m_base) ? m_base->getMetadataProvider(required) : m_metadata;
141 TrustEngine* getTrustEngine(bool required=true) const {
142 if (required && !m_base && !m_trust)
143 throw ConfigurationException("No TrustEngine available.");
144 return (!m_trust && m_base) ? m_base->getTrustEngine(required) : m_trust;
146 AttributeExtractor* getAttributeExtractor() const {
147 return (!m_attrExtractor && m_base) ? m_base->getAttributeExtractor() : m_attrExtractor;
149 AttributeFilter* getAttributeFilter() const {
150 return (!m_attrFilter && m_base) ? m_base->getAttributeFilter() : m_attrFilter;
152 AttributeResolver* getAttributeResolver() const {
153 return (!m_attrResolver && m_base) ? m_base->getAttributeResolver() : m_attrResolver;
155 CredentialResolver* getCredentialResolver() const {
156 return (!m_credResolver && m_base) ? m_base->getCredentialResolver() : m_credResolver;
158 const PropertySet* getRelyingParty(const EntityDescriptor* provider) const;
159 const PropertySet* getRelyingParty(const XMLCh* entityID) const;
160 const vector<const XMLCh*>* getAudiences() const {
161 return (m_audiences.empty() && m_base) ? m_base->getAudiences() : &m_audiences;
164 string getNotificationURL(const char* resource, bool front, unsigned int index) const;
166 const vector<string>& getRemoteUserAttributeIds() const {
167 return (m_remoteUsers.empty() && m_base) ? m_base->getRemoteUserAttributeIds() : m_remoteUsers;
170 void clearHeader(SPRequest& request, const char* rawname, const char* cginame) const;
171 void setHeader(SPRequest& request, const char* name, const char* value) const;
172 string getSecureHeader(const SPRequest& request, const char* name) const;
174 const SessionInitiator* getDefaultSessionInitiator() const;
175 const SessionInitiator* getSessionInitiatorById(const char* id) const;
176 const Handler* getDefaultAssertionConsumerService() const;
177 const Handler* getAssertionConsumerServiceByIndex(unsigned short index) const;
178 const Handler* getAssertionConsumerServiceByProtocol(const XMLCh* protocol, const char* binding=nullptr) const;
179 const vector<const Handler*>& getAssertionConsumerServicesByBinding(const XMLCh* binding) const;
180 const Handler* getHandler(const char* path) const;
181 void getHandlers(vector<const Handler*>& handlers) const;
183 void receive(DDF& in, ostream& out) {
184 // Only current function is to return the headers to clear.
186 DDF ret=DDF(nullptr).list();
187 DDFJanitor jret(ret);
188 for (vector< pair<string,string> >::const_iterator i = m_unsetHeaders.begin(); i!=m_unsetHeaders.end(); ++i) {
189 header = DDF(i->first.c_str()).string(i->second.c_str());
195 // Provides filter to exclude special config elements.
196 #ifdef SHIBSP_XERCESC_SHORT_ACCEPTNODE
201 acceptNode(const DOMNode* node) const;
204 template <class T> T* doChainedPlugins(
205 PluginManager<T,string,const DOMElement*>& pluginMgr,
206 const char* pluginType,
207 const char* chainingType,
208 const XMLCh* localName,
211 const char* dummyType=nullptr
213 void doAttributeInfo();
214 void doHandlers(const ProtocolProvider*, const DOMElement*, Category&);
215 void doSSO(const ProtocolProvider&, set<string>&, DOMElement*, Category&);
216 void doLogout(const ProtocolProvider&, set<string>&, DOMElement*, Category&);
217 void doNameIDMgmt(const ProtocolProvider&, set<string>&, DOMElement*, Category&);
218 void doArtifactResolution(const ProtocolProvider&, const char*, DOMElement*, Category&);
220 const XMLApplication* m_base;
222 std::pair<std::string,std::string> m_attributePrefix;
224 void doAttributePlugins(DOMElement* e, Category& log);
225 MetadataProvider* m_metadata;
226 TrustEngine* m_trust;
227 AttributeExtractor* m_attrExtractor;
228 AttributeFilter* m_attrFilter;
229 AttributeResolver* m_attrResolver;
230 CredentialResolver* m_credResolver;
231 vector<const XMLCh*> m_audiences;
233 // RelyingParty properties
234 map<xstring,PropertySet*> m_partyMap;
236 vector<string> m_remoteUsers,m_frontLogout,m_backLogout;
238 // manage handler objects
239 vector<Handler*> m_handlers;
241 // maps location (path info) to applicable handlers
242 map<string,const Handler*> m_handlerMap;
244 // maps unique indexes to consumer services
245 map<unsigned int,const Handler*> m_acsIndexMap;
247 // pointer to default consumer service
248 const Handler* m_acsDefault;
250 // maps binding strings to supporting consumer service(s)
251 typedef map< xstring,vector<const Handler*> > ACSBindingMap;
252 ACSBindingMap m_acsBindingMap;
254 // maps protocol strings to supporting consumer service(s)
255 typedef map< xstring,vector<const Handler*> > ACSProtocolMap;
256 ACSProtocolMap m_acsProtocolMap;
258 // pointer to default session initiator
259 const SessionInitiator* m_sessionInitDefault;
261 // maps unique ID strings to session initiators
262 map<string,const SessionInitiator*> m_sessionInitMap;
264 // pointer to default artifact resolution service
265 const Handler* m_artifactResolutionDefault;
267 pair<bool,int> getArtifactEndpointIndex() const {
268 if (m_artifactResolutionDefault) return m_artifactResolutionDefault->getInt("index");
269 return m_base ? m_base->getArtifactEndpointIndex() : make_pair(false,0);
273 // Top-level configuration implementation
274 class SHIBSP_DLLLOCAL XMLConfig;
275 class SHIBSP_DLLLOCAL XMLConfigImpl : public DOMPropertySet, public DOMNodeFilter
278 XMLConfigImpl(const DOMElement* e, bool first, XMLConfig* outer, Category& log);
281 RequestMapper* m_requestMapper;
282 map<string,Application*> m_appmap;
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)
330 delete m_sessionCache;
334 SAMLConfig::getConfig().setArtifactMap(nullptr);
335 XMLToolingConfig::getConfig().setReplayCache(nullptr);
336 for_each(m_storage.begin(), m_storage.end(), cleanup_pair<string,StorageService>());
343 ReloadableXMLFile::lock();
344 if (m_impl->m_policy)
345 m_impl->m_policy->lock();
349 if (m_impl->m_policy)
350 m_impl->m_policy->unlock();
351 ReloadableXMLFile::unlock();
356 const PropertySet* getParent() const { return m_impl->getParent(); }
357 void setParent(const PropertySet* parent) {return m_impl->setParent(parent);}
358 pair<bool,bool> getBool(const char* name, const char* ns=nullptr) const {return m_impl->getBool(name,ns);}
359 pair<bool,const char*> getString(const char* name, const char* ns=nullptr) const {return m_impl->getString(name,ns);}
360 pair<bool,const XMLCh*> getXMLString(const char* name, const char* ns=nullptr) const {return m_impl->getXMLString(name,ns);}
361 pair<bool,unsigned int> getUnsignedInt(const char* name, const char* ns=nullptr) const {return m_impl->getUnsignedInt(name,ns);}
362 pair<bool,int> getInt(const char* name, const char* ns=nullptr) const {return m_impl->getInt(name,ns);}
363 void getAll(map<string,const char*>& properties) const {return m_impl->getAll(properties);}
364 const PropertySet* getPropertySet(const char* name, const char* ns="urn:mace:shibboleth:2.0:native:sp:config") const {return m_impl->getPropertySet(name,ns);}
365 const DOMElement* getElement() const {return m_impl->getElement();}
370 void receive(DDF& in, ostream& out);
372 TransactionLog* getTransactionLog() const {
375 throw ConfigurationException("No TransactionLog available.");
378 StorageService* getStorageService(const char* id) const {
380 map<string,StorageService*>::const_iterator i=m_storage.find(id);
381 if (i!=m_storage.end())
384 else if (!m_storage.empty())
385 return m_storage.begin()->second;
390 ListenerService* getListenerService(bool required=true) const {
391 if (required && !m_listener)
392 throw ConfigurationException("No ListenerService available.");
396 SessionCache* getSessionCache(bool required=true) const {
397 if (required && !m_sessionCache)
398 throw ConfigurationException("No SessionCache available.");
399 return m_sessionCache;
402 RequestMapper* getRequestMapper(bool required=true) const {
403 if (required && !m_impl->m_requestMapper)
404 throw ConfigurationException("No RequestMapper available.");
405 return m_impl->m_requestMapper;
408 const Application* getApplication(const char* applicationId) const {
409 map<string,Application*>::const_iterator i=m_impl->m_appmap.find(applicationId ? applicationId : "default");
410 return (i!=m_impl->m_appmap.end()) ? i->second : nullptr;
414 SecurityPolicyProvider* getSecurityPolicyProvider(bool required=true) const {
415 if (required && !m_impl->m_policy)
416 throw ConfigurationException("No SecurityPolicyProvider available.");
417 return m_impl->m_policy;
420 const PropertySet* getPolicySettings(const char* id) const {
421 return getSecurityPolicyProvider()->getPolicySettings(id);
424 const vector<const SecurityPolicyRule*>& getPolicyRules(const char* id) const {
425 return getSecurityPolicyProvider()->getPolicyRules(id);
428 bool setTransportOptions(SOAPTransport& transport) const {
430 vector< pair< string, pair<string,string> > >::const_iterator opt;
431 for (opt = m_impl->m_transportOptions.begin(); opt != m_impl->m_transportOptions.end(); ++opt) {
432 if (!transport.setProviderOption(opt->first.c_str(), opt->second.first.c_str(), opt->second.second.c_str())) {
433 m_log.error("failed to set SOAPTransport option (%s)", opt->second.first.c_str());
442 pair<bool,DOMElement*> background_load();
445 friend class XMLConfigImpl;
446 XMLConfigImpl* m_impl;
447 ListenerService* m_listener;
448 SessionCache* m_sessionCache;
450 TransactionLog* m_tranLog;
451 map<string,StorageService*> m_storage;
455 #if defined (_MSC_VER)
456 #pragma warning( pop )
459 static const XMLCh applicationId[] = UNICODE_LITERAL_13(a,p,p,l,i,c,a,t,i,o,n,I,d);
460 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);
461 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);
462 static const XMLCh _ArtifactMap[] = UNICODE_LITERAL_11(A,r,t,i,f,a,c,t,M,a,p);
463 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);
464 static const XMLCh _AttributeFilter[] = UNICODE_LITERAL_15(A,t,t,r,i,b,u,t,e,F,i,l,t,e,r);
465 static const XMLCh _AttributeResolver[] = UNICODE_LITERAL_17(A,t,t,r,i,b,u,t,e,R,e,s,o,l,v,e,r);
466 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);
467 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);
468 static const XMLCh _Audience[] = UNICODE_LITERAL_8(A,u,d,i,e,n,c,e);
469 static const XMLCh Binding[] = UNICODE_LITERAL_7(B,i,n,d,i,n,g);
470 static const XMLCh Channel[]= UNICODE_LITERAL_7(C,h,a,n,n,e,l);
471 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);
472 static const XMLCh _default[] = UNICODE_LITERAL_7(d,e,f,a,u,l,t);
473 static const XMLCh _Extensions[] = UNICODE_LITERAL_10(E,x,t,e,n,s,i,o,n,s);
474 static const XMLCh _fatal[] = UNICODE_LITERAL_5(f,a,t,a,l);
475 static const XMLCh _Handler[] = UNICODE_LITERAL_7(H,a,n,d,l,e,r);
476 static const XMLCh _id[] = UNICODE_LITERAL_2(i,d);
477 static const XMLCh _index[] = UNICODE_LITERAL_5(i,n,d,e,x);
478 static const XMLCh InProcess[] = UNICODE_LITERAL_9(I,n,P,r,o,c,e,s,s);
479 static const XMLCh Library[] = UNICODE_LITERAL_7(L,i,b,r,a,r,y);
480 static const XMLCh Listener[] = UNICODE_LITERAL_8(L,i,s,t,e,n,e,r);
481 static const XMLCh Location[] = UNICODE_LITERAL_8(L,o,c,a,t,i,o,n);
482 static const XMLCh logger[] = UNICODE_LITERAL_6(l,o,g,g,e,r);
483 static const XMLCh Logout[] = UNICODE_LITERAL_6(L,o,g,o,u,t);
484 static const XMLCh _LogoutInitiator[] = UNICODE_LITERAL_15(L,o,g,o,u,t,I,n,i,t,i,a,t,o,r);
485 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);
486 static const XMLCh _MetadataProvider[] = UNICODE_LITERAL_16(M,e,t,a,d,a,t,a,P,r,o,v,i,d,e,r);
487 static const XMLCh NameIDMgmt[] = UNICODE_LITERAL_10(N,a,m,e,I,D,M,g,m,t);
488 static const XMLCh Notify[] = UNICODE_LITERAL_6(N,o,t,i,f,y);
489 static const XMLCh _option[] = UNICODE_LITERAL_6(o,p,t,i,o,n);
490 static const XMLCh OutOfProcess[] = UNICODE_LITERAL_12(O,u,t,O,f,P,r,o,c,e,s,s);
491 static const XMLCh _path[] = UNICODE_LITERAL_4(p,a,t,h);
492 static const XMLCh _ProtocolProvider[] = UNICODE_LITERAL_16(P,r,o,t,o,c,o,l,P,r,o,v,i,d,e,r);
493 static const XMLCh _provider[] = UNICODE_LITERAL_8(p,r,o,v,i,d,e,r);
494 static const XMLCh RelyingParty[] = UNICODE_LITERAL_12(R,e,l,y,i,n,g,P,a,r,t,y);
495 static const XMLCh _ReplayCache[] = UNICODE_LITERAL_11(R,e,p,l,a,y,C,a,c,h,e);
496 static const XMLCh _RequestMapper[] = UNICODE_LITERAL_13(R,e,q,u,e,s,t,M,a,p,p,e,r);
497 static const XMLCh RequestMap[] = UNICODE_LITERAL_10(R,e,q,u,e,s,t,M,a,p);
498 static const XMLCh SecurityPolicies[] = UNICODE_LITERAL_16(S,e,c,u,r,i,t,y,P,o,l,i,c,i,e,s);
499 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);
500 static const XMLCh _SessionCache[] = UNICODE_LITERAL_12(S,e,s,s,i,o,n,C,a,c,h,e);
501 static const XMLCh _SessionInitiator[] = UNICODE_LITERAL_16(S,e,s,s,i,o,n,I,n,i,t,i,a,t,o,r);
502 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);
503 static const XMLCh Site[] = UNICODE_LITERAL_4(S,i,t,e);
504 static const XMLCh SSO[] = UNICODE_LITERAL_3(S,S,O);
505 static const XMLCh _StorageService[] = UNICODE_LITERAL_14(S,t,o,r,a,g,e,S,e,r,v,i,c,e);
506 static const XMLCh TCPListener[] = UNICODE_LITERAL_11(T,C,P,L,i,s,t,e,n,e,r);
507 static const XMLCh TransportOption[] = UNICODE_LITERAL_15(T,r,a,n,s,p,o,r,t,O,p,t,i,o,n);
508 static const XMLCh _TrustEngine[] = UNICODE_LITERAL_11(T,r,u,s,t,E,n,g,i,n,e);
509 static const XMLCh _type[] = UNICODE_LITERAL_4(t,y,p,e);
510 static const XMLCh UnixListener[] = UNICODE_LITERAL_12(U,n,i,x,L,i,s,t,e,n,e,r);
514 ServiceProvider* XMLServiceProviderFactory(const DOMElement* const & e)
516 return new XMLConfig(e);
520 XMLApplication::XMLApplication(
521 const ServiceProvider* sp,
522 const ProtocolProvider* pp,
524 const XMLApplication* base
525 ) : Application(sp), m_base(base),
527 m_metadata(nullptr), m_trust(nullptr),
528 m_attrExtractor(nullptr), m_attrFilter(nullptr), m_attrResolver(nullptr),
529 m_credResolver(nullptr),
531 m_acsDefault(nullptr), m_sessionInitDefault(nullptr), m_artifactResolutionDefault(nullptr)
534 xmltooling::NDC ndc("XMLApplication");
536 Category& log=Category::getInstance(SHIBSP_LOGCAT".Application");
539 // First load any property sets.
540 load(e,nullptr,this);
544 SPConfig& conf=SPConfig::getConfig();
546 XMLToolingConfig& xmlConf=XMLToolingConfig::getConfig();
549 // This used to be an actual hash, but now it's just a hex-encode to avoid xmlsec dependency.
550 static char DIGITS[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
551 string tohash=getId();
552 tohash+=getString("entityID").second;
553 for (const char* ch = tohash.c_str(); *ch; ++ch) {
554 m_hash += (DIGITS[((unsigned char)(0xF0 & *ch)) >> 4 ]);
555 m_hash += (DIGITS[0x0F & *ch]);
560 if (conf.isEnabled(SPConfig::Handlers))
561 doHandlers(pp, e, log);
564 DOMNodeList* nlist = e->getElementsByTagNameNS(shibspconstants::SHIB2SPCONFIG_NS, Notify);
565 for (XMLSize_t i = 0; nlist && i < nlist->getLength(); ++i) {
566 if (nlist->item(i)->getParentNode()->isSameNode(e)) {
567 const XMLCh* channel = static_cast<DOMElement*>(nlist->item(i))->getAttributeNS(nullptr, Channel);
568 string loc(XMLHelper::getAttrString(static_cast<DOMElement*>(nlist->item(i)), nullptr, Location));
570 if (channel && *channel == chLatin_f)
571 m_frontLogout.push_back(loc);
573 m_backLogout.push_back(loc);
579 nlist = e->getElementsByTagNameNS(samlconstants::SAML20_NS, Audience::LOCAL_NAME);
580 if (nlist && nlist->getLength()) {
581 log.warn("use of <saml:Audience> elements outside of a Security Policy Rule is deprecated");
582 for (XMLSize_t i = 0; i < nlist->getLength(); ++i)
583 if (nlist->item(i)->getParentNode()->isSameNode(e) && nlist->item(i)->hasChildNodes())
584 m_audiences.push_back(nlist->item(i)->getFirstChild()->getNodeValue());
587 if (conf.isEnabled(SPConfig::Metadata)) {
588 auto_ptr<MetadataProvider> mp(
590 SAMLConfig::getConfig().MetadataProviderManager, "MetadataProvider", CHAINING_METADATA_PROVIDER, _MetadataProvider, e, log
596 m_metadata = mp.release();
599 log.crit("no MetadataProvider available, configuration is probably unusable");
602 catch (exception& ex) {
603 log.crit("error initializing MetadataProvider: %s", ex.what());
607 if (conf.isEnabled(SPConfig::Trust)) {
608 m_trust = doChainedPlugins(xmlConf.TrustEngineManager, "TrustEngine", CHAINING_TRUSTENGINE, _TrustEngine, e, log);
609 if (!m_trust && !m_base) {
611 "no TrustEngine specified or installed, using default chain {%s, %s}",
612 EXPLICIT_KEY_TRUSTENGINE, SHIBBOLETH_PKIX_TRUSTENGINE
614 m_trust = xmlConf.TrustEngineManager.newPlugin(CHAINING_TRUSTENGINE, nullptr);
615 ChainingTrustEngine* trustchain = dynamic_cast<ChainingTrustEngine*>(m_trust);
617 trustchain->addTrustEngine(xmlConf.TrustEngineManager.newPlugin(EXPLICIT_KEY_TRUSTENGINE, nullptr));
618 trustchain->addTrustEngine(xmlConf.TrustEngineManager.newPlugin(SHIBBOLETH_PKIX_TRUSTENGINE, nullptr));
623 if (conf.isEnabled(SPConfig::AttributeResolution))
624 doAttributePlugins(e, log);
626 if (conf.isEnabled(SPConfig::Credentials)) {
627 m_credResolver = doChainedPlugins(
628 xmlConf.CredentialResolverManager, "CredentialResolver", CHAINING_CREDENTIAL_RESOLVER, _CredentialResolver, e, log
632 // Finally, load relying parties.
633 const DOMElement* child = XMLHelper::getFirstChildElement(e, RelyingParty);
635 if (child->hasAttributeNS(nullptr, saml2::Attribute::NAME_ATTRIB_NAME)) {
636 auto_ptr<DOMPropertySet> rp(new DOMPropertySet());
637 rp->load(child, nullptr, this);
639 m_partyMap[child->getAttributeNS(nullptr, saml2::Attribute::NAME_ATTRIB_NAME)] = rp.release();
641 child = XMLHelper::getNextSiblingElement(child, RelyingParty);
643 if (base && m_partyMap.empty() && !base->m_partyMap.empty()) {
644 // For inheritance of RPs to work, we have to pull them in to the override by cloning the DOM.
645 child = XMLHelper::getFirstChildElement(base->getElement(), RelyingParty);
647 if (child->hasAttributeNS(nullptr, saml2::Attribute::NAME_ATTRIB_NAME)) {
648 DOMElement* rpclone = static_cast<DOMElement*>(child->cloneNode(true));
649 auto_ptr<DOMPropertySet> rp(new DOMPropertySet());
650 rp->load(rpclone, nullptr, this);
652 m_partyMap[rpclone->getAttributeNS(nullptr, saml2::Attribute::NAME_ATTRIB_NAME)] = rp.release();
654 child = XMLHelper::getNextSiblingElement(child, RelyingParty);
659 // Out of process only, we register a listener endpoint.
660 if (!conf.isEnabled(SPConfig::InProcess)) {
661 ListenerService* listener = sp->getListenerService(false);
663 string addr=string(getId()) + "::getHeaders::Application";
664 listener->regListener(addr.c_str(),this);
667 log.info("no ListenerService available, Application remoting disabled");
683 template <class T> T* XMLApplication::doChainedPlugins(
684 PluginManager<T,string,const DOMElement*>& pluginMgr,
685 const char* pluginType,
686 const char* chainingType,
687 const XMLCh* localName,
690 const char* dummyType
694 DOMElement* child = XMLHelper::getFirstChildElement(e, localName);
696 // Check for multiple.
697 if (XMLHelper::getNextSiblingElement(child, localName)) {
698 log.info("multiple %s plugins, wrapping in a chain", pluginType);
699 DOMElement* chain = child->getOwnerDocument()->createElementNS(nullptr, localName);
701 chain->appendChild(child);
702 child = XMLHelper::getFirstChildElement(e, localName);
706 e->appendChild(chain);
709 // Only a single one.
710 t = XMLHelper::getAttrString(child, nullptr, _type);
715 log.info("building %s of type %s...", pluginType, t.c_str());
716 return pluginMgr.newPlugin(t.c_str(), child);
719 throw ConfigurationException("$1 element had no type attribute.", params(1, pluginType));
722 catch (exception& ex) {
723 log.crit("error building %s: %s", pluginType, ex.what());
725 // Install a dummy version as a safety valve.
726 log.crit("installing safe %s in place of failed version", pluginType);
727 return pluginMgr.newPlugin(dummyType, nullptr);
735 void XMLApplication::doAttributeInfo()
737 // Populate prefix pair.
738 m_attributePrefix.second = "HTTP_";
739 pair<bool,const char*> prefix = getString("attributePrefix");
741 m_attributePrefix.first = prefix.second;
742 const char* pch = prefix.second;
744 m_attributePrefix.second += (isalnum(*pch) ? toupper(*pch) : '_');
749 // Load attribute ID lists for REMOTE_USER and header clearing.
750 if (SPConfig::getConfig().isEnabled(SPConfig::InProcess)) {
751 pair<bool,const char*> attributes = getString("REMOTE_USER");
752 if (attributes.first) {
753 char* dup = strdup(attributes.second);
756 while (start && *start) {
757 while (*start && isspace(*start))
761 pos = strchr(start,' ');
764 m_remoteUsers.push_back(start);
765 start = pos ? pos+1 : nullptr;
770 attributes = getString("unsetHeaders");
771 if (attributes.first) {
772 string transformedprefix(m_attributePrefix.second);
774 prefix = getString("metadataAttributePrefix");
778 transformedprefix += (isalnum(*pch) ? toupper(*pch) : '_');
782 char* dup = strdup(attributes.second);
785 while (start && *start) {
786 while (*start && isspace(*start))
790 pos = strchr(start,' ');
797 transformed += (isalnum(*pch) ? toupper(*pch) : '_');
801 m_unsetHeaders.push_back(pair<string,string>(m_attributePrefix.first + start, m_attributePrefix.second + transformed));
803 m_unsetHeaders.push_back(pair<string,string>(m_attributePrefix.first + prefix.second + start, transformedprefix + transformed));
804 start = pos ? pos+1 : nullptr;
807 m_unsetHeaders.push_back(pair<string,string>(m_attributePrefix.first + "Shib-Application-ID", m_attributePrefix.second + "SHIB_APPLICATION_ID"));
812 void XMLApplication::doHandlers(const ProtocolProvider* pp, const DOMElement* e, Category& log)
814 SPConfig& conf = SPConfig::getConfig();
816 Handler* handler = nullptr;
817 const PropertySet* sessions = getPropertySet("Sessions");
819 // Process assertion export handler.
820 pair<bool,const char*> location = sessions ? sessions->getString("exportLocation") : pair<bool,const char*>(false,nullptr);
821 if (location.first) {
823 DOMElement* exportElement = e->getOwnerDocument()->createElementNS(shibspconstants::SHIB2SPCONFIG_NS, _Handler);
824 exportElement->setAttributeNS(nullptr,Location,sessions->getXMLString("exportLocation").second);
825 pair<bool,const XMLCh*> exportACL = sessions->getXMLString("exportACL");
826 if (exportACL.first) {
827 static const XMLCh _acl[] = UNICODE_LITERAL_9(e,x,p,o,r,t,A,C,L);
828 exportElement->setAttributeNS(nullptr,_acl,exportACL.second);
830 handler = conf.HandlerManager.newPlugin(
831 samlconstants::SAML20_BINDING_URI, pair<const DOMElement*,const char*>(exportElement, getId())
833 m_handlers.push_back(handler);
835 // Insert into location map. If it contains the handlerURL, we skip past that part.
836 const char* hurl = sessions->getString("handlerURL").second;
838 hurl = "/Shibboleth.sso";
839 const char* pch = strstr(location.second, hurl);
841 location.second = pch + strlen(hurl);
842 if (*location.second == '/')
843 m_handlerMap[location.second]=handler;
845 m_handlerMap[string("/") + location.second]=handler;
847 catch (exception& ex) {
848 log.error("caught exception installing assertion lookup handler: %s", ex.what());
852 // Look for "shorthand" elements first.
853 set<string> protocols;
854 DOMElement* child = sessions ? XMLHelper::getFirstChildElement(sessions->getElement()) : nullptr;
856 if (XMLHelper::isNodeNamed(child, shibspconstants::SHIB2SPCONFIG_NS, SSO)) {
858 doSSO(*pp, protocols, child, log);
860 log.error("no ProtocolProvider, SSO auto-configure unsupported");
862 else if (XMLHelper::isNodeNamed(child, shibspconstants::SHIB2SPCONFIG_NS, Logout)) {
864 doLogout(*pp, protocols, child, log);
866 log.error("no ProtocolProvider, Logout auto-configure unsupported");
868 else if (XMLHelper::isNodeNamed(child, shibspconstants::SHIB2SPCONFIG_NS, NameIDMgmt)) {
870 doNameIDMgmt(*pp, protocols, child, log);
872 log.error("no ProtocolProvider, NameIDMgmt auto-configure unsupported");
875 break; // drop into next while loop
877 child = XMLHelper::getNextSiblingElement(child);
880 // Process other handlers.
881 bool hardACS=false, hardSessionInit=false, hardArt=false;
883 if (!child->hasAttributeNS(nullptr, Location)) {
884 auto_ptr_char hclass(child->getLocalName());
885 log.error("%s handler with no Location property cannot be processed", hclass.get());
886 child = XMLHelper::getNextSiblingElement(child);
890 if (XMLString::equals(child->getLocalName(), _AssertionConsumerService)) {
891 string bindprop(XMLHelper::getAttrString(child, nullptr, Binding));
892 if (bindprop.empty()) {
893 log.error("AssertionConsumerService element has no Binding attribute, skipping it...");
894 child = XMLHelper::getNextSiblingElement(child);
897 handler = conf.AssertionConsumerServiceManager.newPlugin(bindprop.c_str(), pair<const DOMElement*,const char*>(child, getId()));
898 // Map by binding and protocol (may be > 1 per protocol and binding)
899 m_acsBindingMap[handler->getXMLString("Binding").second].push_back(handler);
900 const XMLCh* protfamily = handler->getProtocolFamily();
902 m_acsProtocolMap[protfamily].push_back(handler);
903 m_acsIndexMap[handler->getUnsignedInt("index").second] = handler;
906 pair<bool,bool> defprop = handler->getBool("isDefault");
908 if (defprop.second) {
910 m_acsDefault = handler;
913 else if (!m_acsDefault)
914 m_acsDefault = handler;
917 else if (XMLString::equals(child->getLocalName(), _SessionInitiator)) {
918 string t(XMLHelper::getAttrString(child, nullptr, _type));
920 log.error("SessionInitiator element has no type attribute, skipping it...");
921 child = XMLHelper::getNextSiblingElement(child);
924 SessionInitiator* sihandler = conf.SessionInitiatorManager.newPlugin(t.c_str(), pair<const DOMElement*,const char*>(child, getId()));
926 pair<bool,const char*> si_id = handler->getString("id");
927 if (si_id.first && si_id.second)
928 m_sessionInitMap[si_id.second] = sihandler;
929 if (!hardSessionInit) {
930 pair<bool,bool> defprop = handler->getBool("isDefault");
932 if (defprop.second) {
933 hardSessionInit = true;
934 m_sessionInitDefault = sihandler;
937 else if (!m_sessionInitDefault) {
938 m_sessionInitDefault = sihandler;
942 else if (XMLString::equals(child->getLocalName(), _LogoutInitiator)) {
943 string t(XMLHelper::getAttrString(child, nullptr, _type));
945 log.error("LogoutInitiator element has no type attribute, skipping it...");
946 child = XMLHelper::getNextSiblingElement(child);
949 handler = conf.LogoutInitiatorManager.newPlugin(t.c_str(), pair<const DOMElement*,const char*>(child, getId()));
951 else if (XMLString::equals(child->getLocalName(), _ArtifactResolutionService)) {
952 string bindprop(XMLHelper::getAttrString(child, nullptr, Binding));
953 if (bindprop.empty()) {
954 log.error("ArtifactResolutionService element has no Binding attribute, skipping it...");
955 child = XMLHelper::getNextSiblingElement(child);
958 handler = conf.ArtifactResolutionServiceManager.newPlugin(bindprop.c_str(), pair<const DOMElement*,const char*>(child, getId()));
961 pair<bool,bool> defprop = handler->getBool("isDefault");
963 if (defprop.second) {
965 m_artifactResolutionDefault = handler;
968 else if (!m_artifactResolutionDefault)
969 m_artifactResolutionDefault = handler;
972 else if (XMLString::equals(child->getLocalName(), _SingleLogoutService)) {
973 string bindprop(XMLHelper::getAttrString(child, nullptr, Binding));
974 if (bindprop.empty()) {
975 log.error("SingleLogoutService element has no Binding attribute, skipping it...");
976 child = XMLHelper::getNextSiblingElement(child);
979 handler = conf.SingleLogoutServiceManager.newPlugin(bindprop.c_str(), pair<const DOMElement*,const char*>(child, getId()));
981 else if (XMLString::equals(child->getLocalName(), _ManageNameIDService)) {
982 string bindprop(XMLHelper::getAttrString(child, nullptr, Binding));
983 if (bindprop.empty()) {
984 log.error("ManageNameIDService element has no Binding attribute, skipping it...");
985 child = XMLHelper::getNextSiblingElement(child);
988 handler = conf.ManageNameIDServiceManager.newPlugin(bindprop.c_str(), pair<const DOMElement*,const char*>(child, getId()));
991 string t(XMLHelper::getAttrString(child, nullptr, _type));
993 log.error("Handler element has no type attribute, skipping it...");
994 child = XMLHelper::getNextSiblingElement(child);
997 handler = conf.HandlerManager.newPlugin(t.c_str(), pair<const DOMElement*,const char*>(child, getId()));
1000 m_handlers.push_back(handler);
1002 // Insert into location map.
1003 location = handler->getString("Location");
1004 if (location.first && *location.second == '/')
1005 m_handlerMap[location.second] = handler;
1006 else if (location.first)
1007 m_handlerMap[string("/") + location.second] = handler;
1009 catch (exception& ex) {
1010 log.error("caught exception processing handler element: %s", ex.what());
1013 child = XMLHelper::getNextSiblingElement(child);
1017 void XMLApplication::doSSO(const ProtocolProvider& pp, set<string>& protocols, DOMElement* e, Category& log)
1019 if (!e->hasChildNodes())
1022 SPConfig& conf = SPConfig::getConfig();
1024 // Tokenize the protocol list inside the element.
1025 XMLStringTokenizer prottokens(e->getTextContent());
1026 while (prottokens.hasMoreTokens()) {
1027 auto_ptr_char prot(prottokens.nextToken());
1029 // Look for initiator.
1030 const PropertySet* initiator = pp.getInitiator(prot.get(), "SSO");
1032 log.info("auto-configuring SSO initiation for protocol (%s)", prot.get());
1033 pair<bool,const XMLCh*> inittype = initiator->getXMLString("id");
1034 if (inittype.first) {
1035 // Append a session initiator element of the designated type to the root element.
1036 DOMElement* sidom = e->getOwnerDocument()->createElementNS(shibspconstants::SHIB2SPCONFIG_NS, _SessionInitiator);
1037 sidom->setAttributeNS(nullptr, _type, inittype.second);
1038 e->appendChild(sidom);
1039 log.info("adding SessionInitiator of type (%s) to chain (/Login)", initiator->getString("id").second);
1041 doArtifactResolution(pp, prot.get(), e, log);
1042 protocols.insert(prot.get());
1045 log.error("missing id property on Initiator element, check config for protocol (%s)", prot.get());
1049 // Look for incoming bindings.
1050 const vector<const PropertySet*>& bindings = pp.getBindings(prot.get(), "SSO");
1051 if (!bindings.empty()) {
1052 log.info("auto-configuring SSO endpoints for protocol (%s)", prot.get());
1054 pair<bool,const XMLCh*> idprop,pathprop;
1055 for (vector<const PropertySet*>::const_iterator b = bindings.begin(); b != bindings.end(); ++b, ++index) {
1056 idprop = (*b)->getXMLString("id");
1057 pathprop = (*b)->getXMLString("path");
1058 if (idprop.first && pathprop.first) {
1059 DOMElement* acsdom = e->getOwnerDocument()->createElementNS(samlconstants::SAML20MD_NS, _AssertionConsumerService);
1060 acsdom->setAttributeNS(nullptr, Binding, idprop.second);
1061 acsdom->setAttributeNS(nullptr, Location, pathprop.second);
1062 xstring indexbuf(chDigit_1 + (index % 10), 1);
1064 indexbuf = (XMLCh)(chDigit_1 + (index / 10)) + indexbuf;
1065 acsdom->setAttributeNS(nullptr, _index, indexbuf.c_str());
1067 log.info("adding AssertionConsumerService for Binding (%s) at (%s)", (*b)->getString("id").second, (*b)->getString("path").second);
1068 Handler* handler = conf.AssertionConsumerServiceManager.newPlugin(
1069 (*b)->getString("id").second, pair<const DOMElement*,const char*>(acsdom, getId())
1071 m_handlers.push_back(handler);
1073 // Setup maps and defaults.
1074 m_acsBindingMap[handler->getXMLString("Binding").second].push_back(handler);
1075 const XMLCh* protfamily = handler->getProtocolFamily();
1077 m_acsProtocolMap[protfamily].push_back(handler);
1078 m_acsIndexMap[handler->getUnsignedInt("index").second] = handler;
1080 m_acsDefault = handler;
1082 // Insert into location map.
1083 pair<bool,const char*> location = handler->getString("Location");
1084 if (location.first && *location.second == '/')
1085 m_handlerMap[location.second] = handler;
1086 else if (location.first)
1087 m_handlerMap[string("/") + location.second] = handler;
1090 log.error("missing id or path property on Binding element, check config for protocol (%s)", prot.get());
1095 if (!initiator && bindings.empty()) {
1096 log.error("no SSO Initiator or Binding config for protocol (%s)", prot.get());
1100 // Handle discovery.
1101 static const XMLCh discoveryProtocol[] = UNICODE_LITERAL_17(d,i,s,c,o,v,e,r,y,P,r,o,t,o,c,o,l);
1102 static const XMLCh discoveryURL[] = UNICODE_LITERAL_12(d,i,s,c,o,v,e,r,y,U,R,L);
1103 static const XMLCh _URL[] = UNICODE_LITERAL_3(U,R,L);
1104 const XMLCh* discop = e->getAttributeNS(nullptr, discoveryProtocol);
1105 if (discop && *discop) {
1106 const XMLCh* discou = e->getAttributeNS(nullptr, discoveryURL);
1107 if (discou && *discou) {
1108 // Append a session initiator element of the designated type to the root element.
1109 DOMElement* sidom = e->getOwnerDocument()->createElementNS(shibspconstants::SHIB2SPCONFIG_NS, _SessionInitiator);
1110 sidom->setAttributeNS(nullptr, _type, discop);
1111 sidom->setAttributeNS(nullptr, _URL, discou);
1112 e->appendChild(sidom);
1113 if (log.isInfoEnabled()) {
1114 auto_ptr_char dp(discop);
1115 log.info("adding SessionInitiator of type (%s) to chain (/Login)", dp.get());
1119 log.error("SSO discoveryProtocol specified without discoveryURL");
1123 // Attach default Location to SSO element.
1124 static const XMLCh _loc[] = { chForwardSlash, chLatin_L, chLatin_o, chLatin_g, chLatin_i, chLatin_n, chNull };
1125 e->setAttributeNS(nullptr, Location, _loc);
1127 // Instantiate Chaining initiator around the SSO element.
1128 SessionInitiator* chain = conf.SessionInitiatorManager.newPlugin(
1129 CHAINING_SESSION_INITIATOR, pair<const DOMElement*,const char*>(e, getId())
1131 m_handlers.push_back(chain);
1132 m_sessionInitDefault = chain;
1133 m_handlerMap["/Login"] = chain;
1136 void XMLApplication::doLogout(const ProtocolProvider& pp, set<string>& protocols, DOMElement* e, Category& log)
1138 if (!e->hasChildNodes())
1141 SPConfig& conf = SPConfig::getConfig();
1143 // Tokenize the protocol list inside the element.
1144 XMLStringTokenizer prottokens(e->getTextContent());
1145 while (prottokens.hasMoreTokens()) {
1146 auto_ptr_char prot(prottokens.nextToken());
1148 // Look for initiator.
1149 const PropertySet* initiator = pp.getInitiator(prot.get(), "Logout");
1151 log.info("auto-configuring Logout initiation for protocol (%s)", prot.get());
1152 pair<bool,const XMLCh*> inittype = initiator->getXMLString("id");
1153 if (inittype.first) {
1154 // Append a logout initiator element of the designated type to the root element.
1155 DOMElement* lidom = e->getOwnerDocument()->createElementNS(shibspconstants::SHIB2SPCONFIG_NS, _LogoutInitiator);
1156 lidom->setAttributeNS(nullptr, _type, inittype.second);
1157 e->appendChild(lidom);
1158 log.info("adding LogoutInitiator of type (%s) to chain (/Logout)", initiator->getString("id").second);
1160 if (protocols.count(prot.get()) == 0) {
1161 doArtifactResolution(pp, prot.get(), e, log);
1162 protocols.insert(prot.get());
1166 log.error("missing id property on Initiator element, check config for protocol (%s)", prot.get());
1170 // Look for incoming bindings.
1171 const vector<const PropertySet*>& bindings = pp.getBindings(prot.get(), "Logout");
1172 if (!bindings.empty()) {
1173 log.info("auto-configuring Logout endpoints for protocol (%s)", prot.get());
1174 pair<bool,const XMLCh*> idprop,pathprop;
1175 for (vector<const PropertySet*>::const_iterator b = bindings.begin(); b != bindings.end(); ++b) {
1176 idprop = (*b)->getXMLString("id");
1177 pathprop = (*b)->getXMLString("path");
1178 if (idprop.first && pathprop.first) {
1179 DOMElement* slodom = e->getOwnerDocument()->createElementNS(samlconstants::SAML20MD_NS, _SingleLogoutService);
1180 slodom->setAttributeNS(nullptr, Binding, idprop.second);
1181 slodom->setAttributeNS(nullptr, Location, pathprop.second);
1183 log.info("adding SingleLogoutService for Binding (%s) at (%s)", (*b)->getString("id").second, (*b)->getString("path").second);
1184 Handler* handler = conf.SingleLogoutServiceManager.newPlugin(
1185 (*b)->getString("id").second, pair<const DOMElement*,const char*>(slodom, getId())
1187 m_handlers.push_back(handler);
1189 // Insert into location map.
1190 pair<bool,const char*> location = handler->getString("Location");
1191 if (location.first && *location.second == '/')
1192 m_handlerMap[location.second] = handler;
1193 else if (location.first)
1194 m_handlerMap[string("/") + location.second] = handler;
1197 log.error("missing id or path property on Binding element, check config for protocol (%s)", prot.get());
1201 if (protocols.count(prot.get()) == 0) {
1202 doArtifactResolution(pp, prot.get(), e, log);
1203 protocols.insert(prot.get());
1207 if (!initiator && bindings.empty()) {
1208 log.error("no Logout Initiator or Binding config for protocol (%s)", prot.get());
1212 // Attach default Location to Logout element.
1213 static const XMLCh _loc[] = { chForwardSlash, chLatin_L, chLatin_o, chLatin_g, chLatin_o, chLatin_u, chLatin_t, chNull };
1214 e->setAttributeNS(nullptr, Location, _loc);
1216 // Instantiate Chaining initiator around the SSO element.
1217 Handler* chain = conf.LogoutInitiatorManager.newPlugin(
1218 CHAINING_LOGOUT_INITIATOR, pair<const DOMElement*,const char*>(e, getId())
1220 m_handlers.push_back(chain);
1221 m_handlerMap["/Logout"] = chain;
1224 void XMLApplication::doNameIDMgmt(const ProtocolProvider& pp, set<string>& protocols, DOMElement* e, Category& log)
1226 if (!e->hasChildNodes())
1229 SPConfig& conf = SPConfig::getConfig();
1231 // Tokenize the protocol list inside the element.
1232 XMLStringTokenizer prottokens(e->getTextContent());
1233 while (prottokens.hasMoreTokens()) {
1234 auto_ptr_char prot(prottokens.nextToken());
1236 // Look for incoming bindings.
1237 const vector<const PropertySet*>& bindings = pp.getBindings(prot.get(), "NameIDMgmt");
1238 if (!bindings.empty()) {
1239 log.info("auto-configuring NameIDMgmt endpoints for protocol (%s)", prot.get());
1240 pair<bool,const XMLCh*> idprop,pathprop;
1241 for (vector<const PropertySet*>::const_iterator b = bindings.begin(); b != bindings.end(); ++b) {
1242 idprop = (*b)->getXMLString("id");
1243 pathprop = (*b)->getXMLString("path");
1244 if (idprop.first && pathprop.first) {
1245 DOMElement* nimdom = e->getOwnerDocument()->createElementNS(samlconstants::SAML20MD_NS, _ManageNameIDService);
1246 nimdom->setAttributeNS(nullptr, Binding, idprop.second);
1247 nimdom->setAttributeNS(nullptr, Location, pathprop.second);
1249 log.info("adding ManageNameIDService for Binding (%s) at (%s)", (*b)->getString("id").second, (*b)->getString("path").second);
1250 Handler* handler = conf.ManageNameIDServiceManager.newPlugin(
1251 (*b)->getString("id").second, pair<const DOMElement*,const char*>(nimdom, getId())
1253 m_handlers.push_back(handler);
1255 // Insert into location map.
1256 pair<bool,const char*> location = handler->getString("Location");
1257 if (location.first && *location.second == '/')
1258 m_handlerMap[location.second] = handler;
1259 else if (location.first)
1260 m_handlerMap[string("/") + location.second] = handler;
1263 log.error("missing id or path property on Binding element, check config for protocol (%s)", prot.get());
1267 if (protocols.count(prot.get()) == 0) {
1268 doArtifactResolution(pp, prot.get(), e, log);
1269 protocols.insert(prot.get());
1273 log.error("no NameIDMgmt Binding config for protocol (%s)", prot.get());
1278 void XMLApplication::doArtifactResolution(const ProtocolProvider& pp, const char* protocol, DOMElement* e, Category& log)
1280 SPConfig& conf = SPConfig::getConfig();
1282 // Look for incoming bindings.
1283 const vector<const PropertySet*>& bindings = pp.getBindings(protocol, "ArtifactResolution");
1284 if (!bindings.empty()) {
1285 log.info("auto-configuring ArtifactResolution endpoints for protocol (%s)", protocol);
1287 pair<bool,const XMLCh*> idprop,pathprop;
1288 for (vector<const PropertySet*>::const_iterator b = bindings.begin(); b != bindings.end(); ++b) {
1289 idprop = (*b)->getXMLString("id");
1290 pathprop = (*b)->getXMLString("path");
1291 if (idprop.first && pathprop.first) {
1292 DOMElement* artdom = e->getOwnerDocument()->createElementNS(samlconstants::SAML20MD_NS, _ArtifactResolutionService);
1293 artdom->setAttributeNS(nullptr, Binding, idprop.second);
1294 artdom->setAttributeNS(nullptr, Location, pathprop.second);
1295 xstring indexbuf(chDigit_1 + (index % 10), 1);
1297 indexbuf = (XMLCh)(chDigit_1 + (index / 10)) + indexbuf;
1298 artdom->setAttributeNS(nullptr, _index, indexbuf.c_str());
1300 log.info("adding ArtifactResolutionService for Binding (%s) at (%s)", (*b)->getString("id").second, (*b)->getString("path").second);
1301 Handler* handler = conf.ArtifactResolutionServiceManager.newPlugin(
1302 (*b)->getString("id").second, pair<const DOMElement*,const char*>(artdom, getId())
1304 m_handlers.push_back(handler);
1306 if (!m_artifactResolutionDefault)
1307 m_artifactResolutionDefault = handler;
1309 // Insert into location map.
1310 pair<bool,const char*> location = handler->getString("Location");
1311 if (location.first && *location.second == '/')
1312 m_handlerMap[location.second] = handler;
1313 else if (location.first)
1314 m_handlerMap[string("/") + location.second] = handler;
1317 log.error("missing id or path property on Binding element, check config for protocol (%s)", protocol);
1324 void XMLApplication::doAttributePlugins(DOMElement* e, Category& log)
1326 SPConfig& conf = SPConfig::getConfig();
1329 doChainedPlugins(conf.AttributeExtractorManager, "AttributeExtractor", CHAINING_ATTRIBUTE_EXTRACTOR, _AttributeExtractor, e, log);
1332 doChainedPlugins(conf.AttributeFilterManager, "AttributeFilter", CHAINING_ATTRIBUTE_FILTER, _AttributeFilter, e, log, DUMMY_ATTRIBUTE_FILTER);
1335 doChainedPlugins(conf.AttributeResolverManager, "AttributeResolver", CHAINING_ATTRIBUTE_RESOLVER, _AttributeResolver, e, log);
1337 if (m_unsetHeaders.empty()) {
1338 vector<string> unsetHeaders;
1339 if (m_attrExtractor) {
1340 Locker extlock(m_attrExtractor);
1341 m_attrExtractor->getAttributeIds(unsetHeaders);
1343 else if (m_base && m_base->m_attrExtractor) {
1344 Locker extlock(m_base->m_attrExtractor);
1345 m_base->m_attrExtractor->getAttributeIds(unsetHeaders);
1347 if (m_attrResolver) {
1348 Locker reslock(m_attrResolver);
1349 m_attrResolver->getAttributeIds(unsetHeaders);
1351 else if (m_base && m_base->m_attrResolver) {
1352 Locker extlock(m_base->m_attrResolver);
1353 m_base->m_attrResolver->getAttributeIds(unsetHeaders);
1355 if (!unsetHeaders.empty()) {
1356 string transformedprefix(m_attributePrefix.second);
1358 pair<bool,const char*> prefix = getString("metadataAttributePrefix");
1360 pch = prefix.second;
1362 transformedprefix += (isalnum(*pch) ? toupper(*pch) : '_');
1366 for (vector<string>::const_iterator hdr = unsetHeaders.begin(); hdr!=unsetHeaders.end(); ++hdr) {
1370 transformed += (isalnum(*pch) ? toupper(*pch) : '_');
1373 m_unsetHeaders.push_back(pair<string,string>(m_attributePrefix.first + *hdr, m_attributePrefix.second + transformed));
1375 m_unsetHeaders.push_back(pair<string,string>(m_attributePrefix.first + prefix.second + *hdr, transformedprefix + transformed));
1378 m_unsetHeaders.push_back(pair<string,string>(m_attributePrefix.first + "Shib-Application-ID", m_attributePrefix.second + "SHIB_APPLICATION_ID"));
1383 void XMLApplication::cleanup()
1385 ListenerService* listener=getServiceProvider().getListenerService(false);
1386 if (listener && SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess) && !SPConfig::getConfig().isEnabled(SPConfig::InProcess)) {
1387 string addr=string(getId()) + "::getHeaders::Application";
1388 listener->unregListener(addr.c_str(),this);
1390 for_each(m_handlers.begin(),m_handlers.end(),xmltooling::cleanup<Handler>());
1393 for_each(m_partyMap.begin(),m_partyMap.end(),cleanup_pair<xstring,PropertySet>());
1395 delete m_credResolver;
1396 m_credResolver = nullptr;
1397 delete m_attrResolver;
1398 m_attrResolver = nullptr;
1399 delete m_attrFilter;
1400 m_attrFilter = nullptr;
1401 delete m_attrExtractor;
1402 m_attrExtractor = nullptr;
1406 m_metadata = nullptr;
1410 #ifdef SHIBSP_XERCESC_SHORT_ACCEPTNODE
1413 DOMNodeFilter::FilterAction
1415 XMLApplication::acceptNode(const DOMNode* node) const
1417 const XMLCh* name=node->getLocalName();
1418 if (XMLString::equals(name,ApplicationOverride) ||
1419 XMLString::equals(name,_Audience) ||
1420 XMLString::equals(name,Notify) ||
1421 XMLString::equals(name,_Handler) ||
1422 XMLString::equals(name,_AssertionConsumerService) ||
1423 XMLString::equals(name,_ArtifactResolutionService) ||
1424 XMLString::equals(name,Logout) ||
1425 XMLString::equals(name,_LogoutInitiator) ||
1426 XMLString::equals(name,_ManageNameIDService) ||
1427 XMLString::equals(name,NameIDMgmt) ||
1428 XMLString::equals(name,_SessionInitiator) ||
1429 XMLString::equals(name,_SingleLogoutService) ||
1430 XMLString::equals(name,SSO) ||
1431 XMLString::equals(name,RelyingParty) ||
1432 XMLString::equals(name,_MetadataProvider) ||
1433 XMLString::equals(name,_TrustEngine) ||
1434 XMLString::equals(name,_CredentialResolver) ||
1435 XMLString::equals(name,_AttributeFilter) ||
1436 XMLString::equals(name,_AttributeExtractor) ||
1437 XMLString::equals(name,_AttributeResolver))
1438 return FILTER_REJECT;
1440 return FILTER_ACCEPT;
1445 const PropertySet* XMLApplication::getRelyingParty(const EntityDescriptor* provider) const
1450 map<xstring,PropertySet*>::const_iterator i=m_partyMap.find(provider->getEntityID());
1451 if (i!=m_partyMap.end())
1453 const EntitiesDescriptor* group=dynamic_cast<const EntitiesDescriptor*>(provider->getParent());
1455 if (group->getName()) {
1456 i=m_partyMap.find(group->getName());
1457 if (i!=m_partyMap.end())
1460 group=dynamic_cast<const EntitiesDescriptor*>(group->getParent());
1465 const PropertySet* XMLApplication::getRelyingParty(const XMLCh* entityID) const
1470 map<xstring,PropertySet*>::const_iterator i=m_partyMap.find(entityID);
1471 if (i!=m_partyMap.end())
1478 string XMLApplication::getNotificationURL(const char* resource, bool front, unsigned int index) const
1480 const vector<string>& locs = front ? m_frontLogout : m_backLogout;
1482 return m_base ? m_base->getNotificationURL(resource, front, index) : string();
1483 else if (index >= locs.size())
1486 #ifdef HAVE_STRCASECMP
1487 if (!resource || (strncasecmp(resource,"http://",7) && strncasecmp(resource,"https://",8)))
1489 if (!resource || (strnicmp(resource,"http://",7) && strnicmp(resource,"https://",8)))
1491 throw ConfigurationException("Request URL was not absolute.");
1493 const char* handler=locs[index].c_str();
1495 // Should never happen...
1496 if (!handler || (*handler!='/' && strncmp(handler,"http:",5) && strncmp(handler,"https:",6)))
1497 throw ConfigurationException(
1498 "Invalid Location property ($1) in Notify element for Application ($2)",
1499 params(2, handler ? handler : "null", getId())
1502 // The "Location" property can be in one of three formats:
1504 // 1) a full URI: http://host/foo/bar
1505 // 2) a hostless URI: http:///foo/bar
1506 // 3) a relative path: /foo/bar
1508 // # Protocol Host Path
1509 // 1 handler handler handler
1510 // 2 handler resource handler
1511 // 3 resource resource handler
1513 const char* path = nullptr;
1515 // Decide whether to use the handler or the resource for the "protocol"
1517 if (*handler != '/') {
1525 // break apart the "protocol" string into protocol, host, and "the rest"
1526 const char* colon=strchr(prot,':');
1528 const char* slash=strchr(colon,'/');
1532 // Compute the actual protocol and store.
1533 string notifyURL(prot, colon-prot);
1535 // create the "host" from either the colon/slash or from the target string
1536 // If prot == handler then we're in either #1 or #2, else #3.
1537 // If slash == colon then we're in #2.
1538 if (prot != handler || slash == colon) {
1539 colon = strchr(resource, ':');
1540 colon += 3; // Get past the ://
1541 slash = strchr(colon, '/');
1543 string host(colon, (slash ? slash-colon : strlen(colon)));
1546 notifyURL += host + path;
1550 void XMLApplication::clearHeader(SPRequest& request, const char* rawname, const char* cginame) const
1552 if (!m_attributePrefix.first.empty()) {
1553 string temp = m_attributePrefix.first + rawname;
1554 string temp2 = m_attributePrefix.second + (cginame + 5);
1555 request.clearHeader(temp.c_str(), temp2.c_str());
1558 m_base->clearHeader(request, rawname, cginame);
1561 request.clearHeader(rawname, cginame);
1565 void XMLApplication::setHeader(SPRequest& request, const char* name, const char* value) const
1567 if (!m_attributePrefix.first.empty()) {
1568 string temp = m_attributePrefix.first + name;
1569 request.setHeader(temp.c_str(), value);
1572 m_base->setHeader(request, name, value);
1575 request.setHeader(name, value);
1579 string XMLApplication::getSecureHeader(const SPRequest& request, const char* name) const
1581 if (!m_attributePrefix.first.empty()) {
1582 string temp = m_attributePrefix.first + name;
1583 return request.getSecureHeader(temp.c_str());
1586 return m_base->getSecureHeader(request,name);
1589 return request.getSecureHeader(name);
1593 const SessionInitiator* XMLApplication::getDefaultSessionInitiator() const
1595 if (m_sessionInitDefault) return m_sessionInitDefault;
1596 return m_base ? m_base->getDefaultSessionInitiator() : nullptr;
1599 const SessionInitiator* XMLApplication::getSessionInitiatorById(const char* id) const
1601 map<string,const SessionInitiator*>::const_iterator i=m_sessionInitMap.find(id);
1602 if (i!=m_sessionInitMap.end()) return i->second;
1603 return m_base ? m_base->getSessionInitiatorById(id) : nullptr;
1606 const Handler* XMLApplication::getDefaultAssertionConsumerService() const
1608 if (m_acsDefault) return m_acsDefault;
1609 return m_base ? m_base->getDefaultAssertionConsumerService() : nullptr;
1612 const Handler* XMLApplication::getAssertionConsumerServiceByIndex(unsigned short index) const
1614 map<unsigned int,const Handler*>::const_iterator i=m_acsIndexMap.find(index);
1615 if (i != m_acsIndexMap.end()) return i->second;
1616 return m_base ? m_base->getAssertionConsumerServiceByIndex(index) : nullptr;
1619 const Handler* XMLApplication::getAssertionConsumerServiceByProtocol(const XMLCh* protocol, const char* binding) const
1621 ACSProtocolMap::const_iterator i=m_acsProtocolMap.find(protocol);
1622 if (i != m_acsProtocolMap.end() && !i->second.empty()) {
1623 if (!binding || !*binding)
1624 return i->second.front();
1625 for (ACSProtocolMap::value_type::second_type::const_iterator j = i->second.begin(); j != i->second.end(); ++j) {
1626 if (!strcmp(binding, (*j)->getString("Binding").second))
1630 return m_base ? m_base->getAssertionConsumerServiceByProtocol(protocol) : nullptr;
1633 const vector<const Handler*>& XMLApplication::getAssertionConsumerServicesByBinding(const XMLCh* binding) const
1635 ACSBindingMap::const_iterator i=m_acsBindingMap.find(binding);
1636 if (i != m_acsBindingMap.end())
1638 return m_base ? m_base->getAssertionConsumerServicesByBinding(binding) : g_noHandlers;
1641 const Handler* XMLApplication::getHandler(const char* path) const
1644 wrap = wrap.substr(0,wrap.find(';'));
1645 map<string,const Handler*>::const_iterator i=m_handlerMap.find(wrap.substr(0,wrap.find('?')));
1646 if (i!=m_handlerMap.end())
1648 return m_base ? m_base->getHandler(path) : nullptr;
1651 void XMLApplication::getHandlers(vector<const Handler*>& handlers) const
1653 handlers.insert(handlers.end(), m_handlers.begin(), m_handlers.end());
1655 for (map<string,const Handler*>::const_iterator h = m_base->m_handlerMap.begin(); h != m_base->m_handlerMap.end(); ++h) {
1656 if (m_handlerMap.count(h->first) == 0)
1657 handlers.push_back(h->second);
1662 #ifdef SHIBSP_XERCESC_SHORT_ACCEPTNODE
1665 DOMNodeFilter::FilterAction
1667 XMLConfigImpl::acceptNode(const DOMNode* node) const
1669 if (!XMLString::equals(node->getNamespaceURI(),shibspconstants::SHIB2SPCONFIG_NS))
1670 return FILTER_ACCEPT;
1671 const XMLCh* name=node->getLocalName();
1672 if (XMLString::equals(name,ApplicationDefaults) ||
1673 XMLString::equals(name,_ArtifactMap) ||
1674 XMLString::equals(name,_Extensions) ||
1675 XMLString::equals(name,Listener) ||
1676 XMLString::equals(name,_ProtocolProvider) ||
1677 XMLString::equals(name,_RequestMapper) ||
1678 XMLString::equals(name,_ReplayCache) ||
1679 XMLString::equals(name,SecurityPolicies) ||
1680 XMLString::equals(name,_SecurityPolicyProvider) ||
1681 XMLString::equals(name,_SessionCache) ||
1682 XMLString::equals(name,Site) ||
1683 XMLString::equals(name,_StorageService) ||
1684 XMLString::equals(name,TCPListener) ||
1685 XMLString::equals(name,TransportOption) ||
1686 XMLString::equals(name,UnixListener))
1687 return FILTER_REJECT;
1689 return FILTER_ACCEPT;
1692 void XMLConfigImpl::doExtensions(const DOMElement* e, const char* label, Category& log)
1694 const DOMElement* exts = XMLHelper::getFirstChildElement(e, _Extensions);
1696 exts = XMLHelper::getFirstChildElement(exts, Library);
1698 string path(XMLHelper::getAttrString(exts, nullptr, _path));
1700 if (!path.empty()) {
1701 if (!XMLToolingConfig::getConfig().load_library(path.c_str(), (void*)exts))
1702 throw ConfigurationException("XMLToolingConfig::load_library failed.");
1703 log.debug("loaded %s extension library (%s)", label, path.c_str());
1706 catch (exception& e) {
1707 if (XMLHelper::getAttrBool(exts, false, _fatal)) {
1708 log.fatal("unable to load mandatory %s extension library %s: %s", label, path.c_str(), e.what());
1712 log.crit("unable to load optional %s extension library %s: %s", label, path.c_str(), e.what());
1715 exts = XMLHelper::getNextSiblingElement(exts, Library);
1720 void XMLConfigImpl::doListener(const DOMElement* e, XMLConfig* conf, Category& log)
1723 string plugtype(TCP_LISTENER_SERVICE);
1725 string plugtype(UNIX_LISTENER_SERVICE);
1727 DOMElement* child = XMLHelper::getFirstChildElement(e, UnixListener);
1729 plugtype = UNIX_LISTENER_SERVICE;
1731 child = XMLHelper::getFirstChildElement(e, TCPListener);
1733 plugtype = TCP_LISTENER_SERVICE;
1735 child = XMLHelper::getFirstChildElement(e, Listener);
1737 auto_ptr_char type(child->getAttributeNS(nullptr, _type));
1738 if (type.get() && *type.get())
1739 plugtype = type.get();
1744 log.info("building ListenerService of type %s...", plugtype.c_str());
1745 conf->m_listener = SPConfig::getConfig().ListenerServiceManager.newPlugin(plugtype.c_str(), child);
1748 void XMLConfigImpl::doCaching(const DOMElement* e, XMLConfig* conf, Category& log)
1750 SPConfig& spConf = SPConfig::getConfig();
1752 SAMLConfig& samlConf = SAMLConfig::getConfig();
1757 if (spConf.isEnabled(SPConfig::OutOfProcess)) {
1758 XMLToolingConfig& xmlConf = XMLToolingConfig::getConfig();
1759 // First build any StorageServices.
1760 child = XMLHelper::getFirstChildElement(e, _StorageService);
1762 string id(XMLHelper::getAttrString(child, nullptr, _id));
1763 string t(XMLHelper::getAttrString(child, nullptr, _type));
1766 log.info("building StorageService (%s) of type %s...", id.c_str(), t.c_str());
1767 conf->m_storage[id] = xmlConf.StorageServiceManager.newPlugin(t.c_str(), child);
1769 catch (exception& ex) {
1770 log.crit("failed to instantiate StorageService (%s): %s", id.c_str(), ex.what());
1773 child = XMLHelper::getNextSiblingElement(child, _StorageService);
1776 if (conf->m_storage.empty()) {
1777 log.info("no StorageService plugin(s) installed, using (mem) in-memory instance");
1778 conf->m_storage["mem"] = xmlConf.StorageServiceManager.newPlugin(MEMORY_STORAGE_SERVICE, nullptr);
1782 StorageService* replaySS = nullptr;
1783 child = XMLHelper::getFirstChildElement(e, _ReplayCache);
1785 string ssid(XMLHelper::getAttrString(child, nullptr, _StorageService));
1786 if (!ssid.empty()) {
1787 if (conf->m_storage.count(ssid)) {
1788 log.info("building ReplayCache on top of StorageService (%s)...", ssid.c_str());
1789 replaySS = conf->m_storage[ssid];
1792 log.error("unable to locate StorageService (%s), using arbitrary instance for ReplayCache", ssid.c_str());
1793 replaySS = conf->m_storage.begin()->second;
1797 log.info("no StorageService specified for ReplayCache, using arbitrary instance");
1798 replaySS = conf->m_storage.begin()->second;
1802 log.info("no ReplayCache specified, using arbitrary StorageService instance");
1803 replaySS = conf->m_storage.begin()->second;
1805 xmlConf.setReplayCache(new ReplayCache(replaySS));
1808 child = XMLHelper::getFirstChildElement(e, _ArtifactMap);
1810 string ssid(XMLHelper::getAttrString(child, nullptr, _StorageService));
1811 if (!ssid.empty()) {
1812 if (conf->m_storage.count(ssid)) {
1813 log.info("building ArtifactMap on top of StorageService (%s)...", ssid.c_str());
1814 samlConf.setArtifactMap(new ArtifactMap(child, conf->m_storage[ssid]));
1817 log.error("unable to locate StorageService (%s), using in-memory ArtifactMap", ssid.c_str());
1818 samlConf.setArtifactMap(new ArtifactMap(child));
1822 log.info("no StorageService specified, using in-memory ArtifactMap");
1823 samlConf.setArtifactMap(new ArtifactMap(child));
1827 log.info("no ArtifactMap specified, building in-memory ArtifactMap...");
1828 samlConf.setArtifactMap(new ArtifactMap(child));
1830 } // end of out of process caching components
1833 child = XMLHelper::getFirstChildElement(e, _SessionCache);
1835 string t(XMLHelper::getAttrString(child, nullptr, _type));
1837 log.info("building SessionCache of type %s...", t.c_str());
1838 conf->m_sessionCache = spConf.SessionCacheManager.newPlugin(t.c_str(), child);
1841 if (!conf->m_sessionCache) {
1842 log.info("no SessionCache specified, using StorageService-backed instance");
1843 conf->m_sessionCache = spConf.SessionCacheManager.newPlugin(STORAGESERVICE_SESSION_CACHE, nullptr);
1847 XMLConfigImpl::XMLConfigImpl(const DOMElement* e, bool first, XMLConfig* outer, Category& log)
1848 : m_requestMapper(nullptr),
1855 xmltooling::NDC ndc("XMLConfigImpl");
1859 SPConfig& conf=SPConfig::getConfig();
1860 XMLToolingConfig& xmlConf=XMLToolingConfig::getConfig();
1861 const DOMElement* SHAR=XMLHelper::getFirstChildElement(e, OutOfProcess);
1862 const DOMElement* SHIRE=XMLHelper::getFirstChildElement(e, InProcess);
1864 // Initialize logging manually in order to redirect log messages as soon as possible.
1865 if (conf.isEnabled(SPConfig::Logging)) {
1867 if (conf.isEnabled(SPConfig::OutOfProcess))
1868 logconf = XMLHelper::getAttrString(SHAR, nullptr, logger);
1869 else if (conf.isEnabled(SPConfig::InProcess))
1870 logconf = XMLHelper::getAttrString(SHIRE, nullptr, logger);
1871 if (logconf.empty())
1872 logconf = XMLHelper::getAttrString(e, nullptr, logger);
1873 if (logconf.empty() && !getenv("SHIBSP_LOGGING")) {
1874 // No properties found, so default them.
1875 if (conf.isEnabled(SPConfig::OutOfProcess) && !conf.isEnabled(SPConfig::InProcess))
1876 logconf = "shibd.logger";
1877 else if (!conf.isEnabled(SPConfig::OutOfProcess) && conf.isEnabled(SPConfig::InProcess))
1878 logconf = "native.logger";
1880 logconf = "shibboleth.logger";
1882 if (!logconf.empty()) {
1883 log.debug("loading new logging configuration from (%s), check log destination for status of configuration", logconf.c_str());
1884 if (!XMLToolingConfig::getConfig().log_config(logconf.c_str()))
1885 log.crit("failed to load new logging configuration from (%s)", logconf.c_str());
1890 outer->m_tranLog = new TransactionLog();
1894 // Re-log library versions now that logging is set up.
1895 log.info("Shibboleth SP Version %s", PACKAGE_VERSION);
1898 "Library versions: %s %s, Xerces-C %s, XML-Security-C %s, XMLTooling-C %s, OpenSAML-C %s, Shibboleth %s",
1899 # if defined(LOG4SHIB_VERSION)
1900 "log4shib", LOG4SHIB_VERSION,
1901 # elif defined(LOG4CPP_VERSION)
1902 "log4cpp", LOG4CPP_VERSION,
1906 XERCES_FULLVERSIONDOT, XSEC_FULLVERSIONDOT, gXMLToolingDotVersionStr, gOpenSAMLDotVersionStr, gShibSPDotVersionStr
1910 "Library versions: %s %s, Xerces-C %s, XMLTooling-C %s, Shibboleth %s",
1911 # if defined(LOG4SHIB_VERSION)
1912 "log4shib", LOG4SHIB_VERSION,
1913 # elif defined(LOG4CPP_VERSION)
1914 "log4cpp", LOG4CPP_VERSION,
1918 XERCES_FULLVERSIONDOT, gXMLToolingDotVersionStr, gShibSPDotVersionStr
1922 // First load any property sets.
1923 load(e,nullptr,this);
1927 // Much of the processing can only occur on the first instantiation.
1930 pair<bool,unsigned int> skew=getUnsignedInt("clockSkew");
1932 xmlConf.clock_skew_secs=min(skew.second,(60*60*24*7*28));
1934 pair<bool,const char*> unsafe = getString("unsafeChars");
1936 TemplateEngine::unsafe_chars = unsafe.second;
1938 unsafe = getString("allowedSchemes");
1940 HTTPResponse::getAllowedSchemes().clear();
1941 string schemes=unsafe.second;
1942 unsigned int j_sch=0;
1943 for (unsigned int i_sch=0; i_sch < schemes.length(); i_sch++) {
1944 if (schemes.at(i_sch)==' ') {
1945 HTTPResponse::getAllowedSchemes().push_back(schemes.substr(j_sch, i_sch-j_sch));
1949 HTTPResponse::getAllowedSchemes().push_back(schemes.substr(j_sch, schemes.length()-j_sch));
1953 doExtensions(e, "global", log);
1954 if (conf.isEnabled(SPConfig::OutOfProcess))
1955 doExtensions(SHAR, "out of process", log);
1957 if (conf.isEnabled(SPConfig::InProcess))
1958 doExtensions(SHIRE, "in process", log);
1960 // Instantiate the ListenerService and SessionCache objects.
1961 if (conf.isEnabled(SPConfig::Listener))
1962 doListener(e, outer, log);
1965 if (outer->m_listener && conf.isEnabled(SPConfig::OutOfProcess) && !conf.isEnabled(SPConfig::InProcess)) {
1966 outer->m_listener->regListener("set::RelayState", outer);
1967 outer->m_listener->regListener("get::RelayState", outer);
1968 outer->m_listener->regListener("set::PostData", outer);
1969 outer->m_listener->regListener("get::PostData", outer);
1972 if (conf.isEnabled(SPConfig::Caching))
1973 doCaching(e, outer, log);
1974 } // end of first-time-only stuff
1976 // Back to the fully dynamic stuff...next up is the RequestMapper.
1977 if (conf.isEnabled(SPConfig::RequestMapping)) {
1978 if (child = XMLHelper::getFirstChildElement(e, _RequestMapper)) {
1979 string t(XMLHelper::getAttrString(child, nullptr, _type));
1981 log.info("building RequestMapper of type %s...", t.c_str());
1982 m_requestMapper = conf.RequestMapperManager.newPlugin(t.c_str(), child);
1985 if (!m_requestMapper) {
1986 log.info("no RequestMapper specified, using 'Native' plugin with empty/default map");
1987 child = e->getOwnerDocument()->createElementNS(nullptr, _RequestMapper);
1988 DOMElement* mapperDummy = e->getOwnerDocument()->createElementNS(shibspconstants::SHIB2SPCONFIG_NS, RequestMap);
1989 mapperDummy->setAttributeNS(nullptr, applicationId, _default);
1990 child->appendChild(mapperDummy);
1991 m_requestMapper = conf.RequestMapperManager.newPlugin(NATIVE_REQUEST_MAPPER, child);
1996 // Load security policies.
1997 if (child = XMLHelper::getLastChildElement(e, _SecurityPolicyProvider)) {
1998 string t(XMLHelper::getAttrString(child, nullptr, _type));
2000 log.info("building SecurityPolicyProvider of type %s...", t.c_str());
2001 m_policy = conf.SecurityPolicyProviderManager.newPlugin(t.c_str(), child);
2004 throw ConfigurationException("can't build SecurityPolicyProvider, no type specified");
2007 else if (child = XMLHelper::getLastChildElement(e, SecurityPolicies)) {
2008 // For backward compatibility, wrap in a plugin element.
2009 DOMElement* polwrapper = e->getOwnerDocument()->createElementNS(nullptr, _SecurityPolicyProvider);
2010 polwrapper->appendChild(child);
2011 log.info("building SecurityPolicyProvider of type %s...", XML_SECURITYPOLICY_PROVIDER);
2012 m_policy = conf.SecurityPolicyProviderManager.newPlugin(XML_SECURITYPOLICY_PROVIDER, polwrapper);
2015 log.fatal("can't build SecurityPolicyProvider, missing conf:SecurityPolicyProvider element?");
2016 throw ConfigurationException("Can't build SecurityPolicyProvider, missing conf:SecurityPolicyProvider element?");
2020 if (!m_policy->getAlgorithmBlacklist().empty()) {
2021 #ifdef SHIBSP_XMLSEC_WHITELISTING
2022 for (vector<xstring>::const_iterator alg = m_policy->getAlgorithmBlacklist().begin(); alg != m_policy->getAlgorithmBlacklist().end(); ++alg)
2023 XSECPlatformUtils::blacklistAlgorithm(alg->c_str());
2025 log.crit("XML-Security-C library prior to 1.6.0 does not support algorithm white/blacklists");
2028 else if (!m_policy->getAlgorithmWhitelist().empty()) {
2029 #ifdef SHIBSP_XMLSEC_WHITELISTING
2030 for (vector<xstring>::const_iterator alg = m_policy->getAlgorithmWhitelist().begin(); alg != m_policy->getAlgorithmWhitelist().end(); ++alg)
2031 XSECPlatformUtils::whitelistAlgorithm(alg->c_str());
2033 log.crit("XML-Security-C library prior to 1.6.0 does not support algorithm white/blacklists");
2038 // Process TransportOption elements.
2039 child = XMLHelper::getLastChildElement(e, TransportOption);
2041 if (child->hasChildNodes()) {
2042 string provider(XMLHelper::getAttrString(child, nullptr, _provider));
2043 string option(XMLHelper::getAttrString(child, nullptr, _option));
2044 auto_ptr_char value(child->getFirstChild()->getNodeValue());
2045 if (!provider.empty() && !option.empty() && value.get() && *value.get()) {
2046 m_transportOptions.push_back(make_pair(provider, make_pair(option, string(value.get()))));
2049 child = XMLHelper::getPreviousSiblingElement(child, TransportOption);
2053 ProtocolProvider* pp = nullptr;
2054 if (conf.isEnabled(SPConfig::Handlers)) {
2055 if (child = XMLHelper::getLastChildElement(e, _ProtocolProvider)) {
2056 string t(XMLHelper::getAttrString(child, nullptr, _type));
2058 log.info("building ProtocolProvider of type %s...", t.c_str());
2059 pp = conf.ProtocolProviderManager.newPlugin(t.c_str(), child);
2063 auto_ptr<ProtocolProvider> ppwrapper(pp);
2064 Locker pplocker(pp);
2066 // Load the default application.
2067 child = XMLHelper::getLastChildElement(e, ApplicationDefaults);
2069 log.fatal("can't build default Application object, missing conf:ApplicationDefaults element?");
2070 throw ConfigurationException("can't build default Application object, missing conf:ApplicationDefaults element?");
2072 XMLApplication* defapp = new XMLApplication(outer, pp, child);
2073 m_appmap[defapp->getId()] = defapp;
2075 // Load any overrides.
2076 child = XMLHelper::getFirstChildElement(child, ApplicationOverride);
2078 auto_ptr<XMLApplication> iapp(new XMLApplication(outer, pp, child, defapp));
2079 if (m_appmap.count(iapp->getId()))
2080 log.crit("found conf:ApplicationOverride element with duplicate id attribute (%s), skipping it", iapp->getId());
2082 const char* iappid=iapp->getId();
2083 m_appmap[iappid] = iapp.release();
2086 child = XMLHelper::getNextSiblingElement(child, ApplicationOverride);
2089 // Check for extra AuthTypes to recognize.
2090 if (conf.isEnabled(SPConfig::InProcess)) {
2091 const PropertySet* inprocs = getPropertySet("InProcess");
2093 pair<bool,const char*> extraAuthTypes = inprocs->getString("extraAuthTypes");
2094 if (extraAuthTypes.first) {
2095 string types=extraAuthTypes.second;
2096 unsigned int j_types=0;
2097 for (unsigned int i_types=0; i_types < types.length(); i_types++) {
2098 if (types.at(i_types) == ' ') {
2099 outer->m_authTypes.insert(types.substr(j_types, i_types - j_types));
2100 j_types = i_types + 1;
2103 outer->m_authTypes.insert(types.substr(j_types, types.length() - j_types));
2108 catch (exception&) {
2114 XMLConfigImpl::~XMLConfigImpl()
2119 void XMLConfigImpl::cleanup()
2121 for_each(m_appmap.begin(),m_appmap.end(),cleanup_pair<string,Application>());
2127 delete m_requestMapper;
2128 m_requestMapper = nullptr;
2130 m_document->release();
2131 m_document = nullptr;
2135 void XMLConfig::receive(DDF& in, ostream& out)
2137 if (!strcmp(in.name(), "get::RelayState")) {
2138 const char* id = in["id"].string();
2139 const char* key = in["key"].string();
2141 throw ListenerException("Required parameters missing for RelayState recovery.");
2144 StorageService* storage = getStorageService(id);
2146 if (storage->readString("RelayState",key,&relayState)>0) {
2147 if (in["clear"].integer())
2148 storage->deleteString("RelayState",key);
2152 Category::getInstance(SHIBSP_LOGCAT".ServiceProvider").error(
2153 "Storage-backed RelayState with invalid StorageService ID (%s)", id
2157 // Repack for return to caller.
2158 DDF ret=DDF(nullptr).unsafe_string(relayState.c_str());
2159 DDFJanitor jret(ret);
2162 else if (!strcmp(in.name(), "set::RelayState")) {
2163 const char* id = in["id"].string();
2164 const char* value = in["value"].string();
2166 throw ListenerException("Required parameters missing for RelayState creation.");
2169 StorageService* storage = getStorageService(id);
2171 SAMLConfig::getConfig().generateRandomBytes(rsKey,20);
2172 rsKey = SAMLArtifact::toHex(rsKey);
2173 storage->createString("RelayState", rsKey.c_str(), value, time(nullptr) + 600);
2176 Category::getInstance(SHIBSP_LOGCAT".ServiceProvider").error(
2177 "Storage-backed RelayState with invalid StorageService ID (%s)", id
2181 // Repack for return to caller.
2182 DDF ret=DDF(nullptr).string(rsKey.c_str());
2183 DDFJanitor jret(ret);
2186 else if (!strcmp(in.name(), "get::PostData")) {
2187 const char* id = in["id"].string();
2188 const char* key = in["key"].string();
2190 throw ListenerException("Required parameters missing for PostData recovery.");
2193 StorageService* storage = getStorageService(id);
2195 if (storage->readString("PostData",key,&postData) > 0) {
2196 storage->deleteString("PostData",key);
2200 Category::getInstance(SHIBSP_LOGCAT".ServiceProvider").error(
2201 "Storage-backed PostData with invalid StorageService ID (%s)", id
2204 // If the data's empty, we'll send nothing back.
2205 // If not, we don't need to round trip it, just send back the serialized DDF list.
2206 if (postData.empty()) {
2208 DDFJanitor jret(ret);
2215 else if (!strcmp(in.name(), "set::PostData")) {
2216 const char* id = in["id"].string();
2217 if (!id || !in["parameters"].islist())
2218 throw ListenerException("Required parameters missing for PostData creation.");
2221 StorageService* storage = getStorageService(id);
2223 SAMLConfig::getConfig().generateRandomBytes(rsKey,20);
2224 rsKey = SAMLArtifact::toHex(rsKey);
2225 ostringstream params;
2226 params << in["parameters"];
2227 storage->createString("PostData", rsKey.c_str(), params.str().c_str(), time(nullptr) + 600);
2230 Category::getInstance(SHIBSP_LOGCAT".ServiceProvider").error(
2231 "Storage-backed PostData with invalid StorageService ID (%s)", id
2235 // Repack for return to caller.
2236 DDF ret=DDF(nullptr).string(rsKey.c_str());
2237 DDFJanitor jret(ret);
2243 pair<bool,DOMElement*> XMLConfig::background_load()
2245 // Load from source using base class.
2246 pair<bool,DOMElement*> raw = ReloadableXMLFile::load();
2248 // If we own it, wrap it.
2249 XercesJanitor<DOMDocument> docjanitor(raw.first ? raw.second->getOwnerDocument() : nullptr);
2251 XMLConfigImpl* impl = new XMLConfigImpl(raw.second, (m_impl==nullptr), this, m_log);
2253 // If we held the document, transfer it to the impl. If we didn't, it's a no-op.
2254 impl->setDocument(docjanitor.release());
2256 // Perform the swap inside a lock.
2259 SharedLock locker(m_lock, false);
2263 return make_pair(false,(DOMElement*)nullptr);