2 * Licensed to UCAID under one or more contributor license agreements.
3 * See the NOTICE file distributed with this work for additional information
4 * regarding copyright ownership. The ASF licenses this file to you under
5 * the Apache License, Version 2.0 (the "License"); you may not use this
6 * file except in compliance with the License. You may obtain a copy of the
9 * http://www.apache.org/licenses/LICENSE-2.0
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
19 * XMLServiceProvider.cpp
21 * XML-based SP configuration and mgmt.
25 #include "exceptions.h"
27 #include "AccessControl.h"
28 #include "Application.h"
29 #include "RequestMapper.h"
30 #include "ServiceProvider.h"
31 #include "SessionCache.h"
33 #include "SPRequest.h"
34 #include "binding/ProtocolProvider.h"
35 #include "handler/LogoutInitiator.h"
36 #include "handler/SessionInitiator.h"
37 #include "remoting/ListenerService.h"
38 #include "util/DOMPropertySet.h"
39 #include "util/SPConstants.h"
41 #if defined(XMLTOOLING_LOG4SHIB)
42 # include <log4shib/PropertyConfigurator.hh>
43 #elif defined(XMLTOOLING_LOG4CPP)
44 # include <log4cpp/PropertyConfigurator.hh>
46 # error "Supported logging library not available."
49 #include <xercesc/util/XMLUniDefs.hpp>
50 #include <xercesc/util/XMLStringTokenizer.hpp>
51 #include <xmltooling/XMLToolingConfig.h>
52 #include <xmltooling/version.h>
53 #include <xmltooling/util/NDC.h>
54 #include <xmltooling/util/ReloadableXMLFile.h>
55 #include <xmltooling/util/TemplateEngine.h>
56 #include <xmltooling/util/Threads.h>
57 #include <xmltooling/util/XMLHelper.h>
60 # include "TransactionLog.h"
61 # include "attribute/filtering/AttributeFilter.h"
62 # include "attribute/resolver/AttributeExtractor.h"
63 # include "attribute/resolver/AttributeResolver.h"
64 # include "security/PKIXTrustEngine.h"
65 # include "security/SecurityPolicyProvider.h"
66 # include <saml/SAMLConfig.h>
67 # include <saml/version.h>
68 # include <saml/binding/ArtifactMap.h>
69 # include <saml/binding/SAMLArtifact.h>
70 # include <saml/saml1/core/Assertions.h>
71 # include <saml/saml2/core/Assertions.h>
72 # include <saml/saml2/binding/SAML2ArtifactType0004.h>
73 # include <saml/saml2/metadata/Metadata.h>
74 # include <saml/saml2/metadata/MetadataProvider.h>
75 # include <saml/util/SAMLConstants.h>
76 # include <xmltooling/security/ChainingTrustEngine.h>
77 # include <xmltooling/security/CredentialResolver.h>
78 # include <xmltooling/security/SecurityHelper.h>
79 # include <xmltooling/util/ReplayCache.h>
80 # include <xmltooling/util/StorageService.h>
81 # include <xsec/utils/XSECPlatformUtils.hpp>
82 using namespace opensaml::saml2;
83 using namespace opensaml::saml2p;
84 using namespace opensaml::saml2md;
85 using namespace opensaml;
87 # include "lite/SAMLConstants.h"
90 using namespace shibsp;
91 using namespace xmltooling;
95 # define min(a,b) (((a) < (b)) ? (a) : (b))
100 #if defined (_MSC_VER)
101 #pragma warning( push )
102 #pragma warning( disable : 4250 )
105 static vector<const Handler*> g_noHandlers;
107 // Application configuration wrapper
108 class SHIBSP_DLLLOCAL XMLApplication : public Application, public Remoted, public DOMPropertySet, public DOMNodeFilter
111 XMLApplication(const ServiceProvider*, const ProtocolProvider*, DOMElement*, const XMLApplication* base=nullptr);
112 ~XMLApplication() { cleanup(); }
114 const char* getHash() const {return m_hash.c_str();}
117 SAMLArtifact* generateSAML1Artifact(const EntityDescriptor* relyingParty) const {
118 throw ConfigurationException("No support for SAML 1.x artifact generation.");
120 SAML2Artifact* generateSAML2Artifact(const EntityDescriptor* relyingParty) const {
121 pair<bool,int> index = make_pair(false,0);
122 const PropertySet* props = getRelyingParty(relyingParty);
123 index = props->getInt("artifactEndpointIndex");
125 index = getArtifactEndpointIndex();
126 pair<bool,const char*> entityID = props->getString("entityID");
127 return new SAML2ArtifactType0004(
128 SecurityHelper::doHash("SHA1", entityID.second, strlen(entityID.second), false),
129 index.first ? index.second : 1
133 MetadataProvider* getMetadataProvider(bool required=true) const {
134 if (required && !m_base && !m_metadata)
135 throw ConfigurationException("No MetadataProvider available.");
136 return (!m_metadata && m_base) ? m_base->getMetadataProvider() : m_metadata;
138 TrustEngine* getTrustEngine(bool required=true) const {
139 if (required && !m_base && !m_trust)
140 throw ConfigurationException("No TrustEngine available.");
141 return (!m_trust && m_base) ? m_base->getTrustEngine() : m_trust;
143 AttributeExtractor* getAttributeExtractor() const {
144 return (!m_attrExtractor && m_base) ? m_base->getAttributeExtractor() : m_attrExtractor;
146 AttributeFilter* getAttributeFilter() const {
147 return (!m_attrFilter && m_base) ? m_base->getAttributeFilter() : m_attrFilter;
149 AttributeResolver* getAttributeResolver() const {
150 return (!m_attrResolver && m_base) ? m_base->getAttributeResolver() : m_attrResolver;
152 CredentialResolver* getCredentialResolver() const {
153 return (!m_credResolver && m_base) ? m_base->getCredentialResolver() : m_credResolver;
155 const PropertySet* getRelyingParty(const EntityDescriptor* provider) const;
156 const PropertySet* getRelyingParty(const XMLCh* entityID) const;
157 const vector<const XMLCh*>* getAudiences() const {
158 return (m_audiences.empty() && m_base) ? m_base->getAudiences() : &m_audiences;
161 string getNotificationURL(const char* resource, bool front, unsigned int index) const;
163 const vector<string>& getRemoteUserAttributeIds() const {
164 return (m_remoteUsers.empty() && m_base) ? m_base->getRemoteUserAttributeIds() : m_remoteUsers;
167 void clearHeader(SPRequest& request, const char* rawname, const char* cginame) const;
168 void setHeader(SPRequest& request, const char* name, const char* value) const;
169 string getSecureHeader(const SPRequest& request, const char* name) const;
171 const SessionInitiator* getDefaultSessionInitiator() const;
172 const SessionInitiator* getSessionInitiatorById(const char* id) const;
173 const Handler* getDefaultAssertionConsumerService() const;
174 const Handler* getAssertionConsumerServiceByIndex(unsigned short index) const;
175 const Handler* getAssertionConsumerServiceByProtocol(const XMLCh* protocol, const char* binding=nullptr) const;
176 const vector<const Handler*>& getAssertionConsumerServicesByBinding(const XMLCh* binding) const;
177 const Handler* getHandler(const char* path) const;
178 void getHandlers(vector<const Handler*>& handlers) const;
180 void receive(DDF& in, ostream& out) {
181 // Only current function is to return the headers to clear.
183 DDF ret=DDF(nullptr).list();
184 DDFJanitor jret(ret);
185 for (vector< pair<string,string> >::const_iterator i = m_unsetHeaders.begin(); i!=m_unsetHeaders.end(); ++i) {
186 header = DDF(i->first.c_str()).string(i->second.c_str());
192 // Provides filter to exclude special config elements.
193 #ifdef SHIBSP_XERCESC_SHORT_ACCEPTNODE
198 acceptNode(const DOMNode* node) const;
201 template <class T> T* doChainedPlugins(
202 PluginManager<T,string,const DOMElement*>& pluginMgr,
203 const char* pluginType,
204 const char* chainingType,
205 const XMLCh* localName,
208 const char* dummyType=nullptr
210 void doAttributeInfo();
211 void doHandlers(const ProtocolProvider*, const DOMElement*, Category&);
212 void doSSO(const ProtocolProvider&, set<string>&, DOMElement*, Category&);
213 void doLogout(const ProtocolProvider&, set<string>&, DOMElement*, Category&);
214 void doNameIDMgmt(const ProtocolProvider&, set<string>&, DOMElement*, Category&);
215 void doArtifactResolution(const ProtocolProvider&, const char*, DOMElement*, Category&);
217 const XMLApplication* m_base;
219 std::pair<std::string,std::string> m_attributePrefix;
221 void doAttributePlugins(DOMElement* e, Category& log);
222 MetadataProvider* m_metadata;
223 TrustEngine* m_trust;
224 AttributeExtractor* m_attrExtractor;
225 AttributeFilter* m_attrFilter;
226 AttributeResolver* m_attrResolver;
227 CredentialResolver* m_credResolver;
228 vector<const XMLCh*> m_audiences;
230 // RelyingParty properties
231 map<xstring,PropertySet*> m_partyMap;
233 vector<string> m_remoteUsers,m_frontLogout,m_backLogout;
235 // manage handler objects
236 vector<Handler*> m_handlers;
238 // maps location (path info) to applicable handlers
239 map<string,const Handler*> m_handlerMap;
241 // maps unique indexes to consumer services
242 map<unsigned int,const Handler*> m_acsIndexMap;
244 // pointer to default consumer service
245 const Handler* m_acsDefault;
247 // maps binding strings to supporting consumer service(s)
248 typedef map< xstring,vector<const Handler*> > ACSBindingMap;
249 ACSBindingMap m_acsBindingMap;
251 // maps protocol strings to supporting consumer service(s)
252 typedef map< xstring,vector<const Handler*> > ACSProtocolMap;
253 ACSProtocolMap m_acsProtocolMap;
255 // pointer to default session initiator
256 const SessionInitiator* m_sessionInitDefault;
258 // maps unique ID strings to session initiators
259 map<string,const SessionInitiator*> m_sessionInitMap;
261 // pointer to default artifact resolution service
262 const Handler* m_artifactResolutionDefault;
264 pair<bool,int> getArtifactEndpointIndex() const {
265 if (m_artifactResolutionDefault) return m_artifactResolutionDefault->getInt("index");
266 return m_base ? m_base->getArtifactEndpointIndex() : make_pair(false,0);
270 // Top-level configuration implementation
271 class SHIBSP_DLLLOCAL XMLConfig;
272 class SHIBSP_DLLLOCAL XMLConfigImpl : public DOMPropertySet, public DOMNodeFilter
275 XMLConfigImpl(const DOMElement* e, bool first, XMLConfig* outer, Category& log);
278 RequestMapper* m_requestMapper;
279 map<string,Application*> m_appmap;
281 SecurityPolicyProvider* m_policy;
282 vector< pair< string, pair<string,string> > > m_transportOptions;
285 // Provides filter to exclude special config elements.
286 #ifdef SHIBSP_XERCESC_SHORT_ACCEPTNODE
291 acceptNode(const DOMNode* node) const;
293 void setDocument(DOMDocument* doc) {
298 void doExtensions(const DOMElement*, const char*, Category&);
299 void doListener(const DOMElement*, XMLConfig*, Category&);
300 void doCaching(const DOMElement*, XMLConfig*, Category&);
303 DOMDocument* m_document;
306 class SHIBSP_DLLLOCAL XMLConfig : public ServiceProvider, public ReloadableXMLFile
312 XMLConfig(const DOMElement* e) : ReloadableXMLFile(e, Category::getInstance(SHIBSP_LOGCAT".Config")),
313 m_impl(nullptr), m_listener(nullptr), m_sessionCache(nullptr)
327 delete m_sessionCache;
331 SAMLConfig::getConfig().setArtifactMap(nullptr);
332 XMLToolingConfig::getConfig().setReplayCache(nullptr);
333 for_each(m_storage.begin(), m_storage.end(), cleanup_pair<string,StorageService>());
340 ReloadableXMLFile::lock();
341 if (m_impl->m_policy)
342 m_impl->m_policy->lock();
346 if (m_impl->m_policy)
347 m_impl->m_policy->unlock();
348 ReloadableXMLFile::unlock();
353 const PropertySet* getParent() const { return m_impl->getParent(); }
354 void setParent(const PropertySet* parent) {return m_impl->setParent(parent);}
355 pair<bool,bool> getBool(const char* name, const char* ns=nullptr) const {return m_impl->getBool(name,ns);}
356 pair<bool,const char*> getString(const char* name, const char* ns=nullptr) const {return m_impl->getString(name,ns);}
357 pair<bool,const XMLCh*> getXMLString(const char* name, const char* ns=nullptr) const {return m_impl->getXMLString(name,ns);}
358 pair<bool,unsigned int> getUnsignedInt(const char* name, const char* ns=nullptr) const {return m_impl->getUnsignedInt(name,ns);}
359 pair<bool,int> getInt(const char* name, const char* ns=nullptr) const {return m_impl->getInt(name,ns);}
360 void getAll(map<string,const char*>& properties) const {return m_impl->getAll(properties);}
361 const PropertySet* getPropertySet(const char* name, const char* ns="urn:mace:shibboleth:2.0:native:sp:config") const {return m_impl->getPropertySet(name,ns);}
362 const DOMElement* getElement() const {return m_impl->getElement();}
367 void receive(DDF& in, ostream& out);
369 TransactionLog* getTransactionLog() const {
372 throw ConfigurationException("No TransactionLog available.");
375 StorageService* getStorageService(const char* id) const {
377 map<string,StorageService*>::const_iterator i=m_storage.find(id);
378 if (i!=m_storage.end())
381 else if (!m_storage.empty())
382 return m_storage.begin()->second;
387 ListenerService* getListenerService(bool required=true) const {
388 if (required && !m_listener)
389 throw ConfigurationException("No ListenerService available.");
393 SessionCache* getSessionCache(bool required=true) const {
394 if (required && !m_sessionCache)
395 throw ConfigurationException("No SessionCache available.");
396 return m_sessionCache;
399 RequestMapper* getRequestMapper(bool required=true) const {
400 if (required && !m_impl->m_requestMapper)
401 throw ConfigurationException("No RequestMapper available.");
402 return m_impl->m_requestMapper;
405 const Application* getApplication(const char* applicationId) const {
406 map<string,Application*>::const_iterator i=m_impl->m_appmap.find(applicationId ? applicationId : "default");
407 return (i!=m_impl->m_appmap.end()) ? i->second : nullptr;
411 SecurityPolicyProvider* getSecurityPolicyProvider(bool required=true) const {
412 if (required && !m_impl->m_policy)
413 throw ConfigurationException("No SecurityPolicyProvider available.");
414 return m_impl->m_policy;
417 const PropertySet* getPolicySettings(const char* id) const {
418 return getSecurityPolicyProvider()->getPolicySettings(id);
421 const vector<const SecurityPolicyRule*>& getPolicyRules(const char* id) const {
422 return getSecurityPolicyProvider()->getPolicyRules(id);
425 bool setTransportOptions(SOAPTransport& transport) const {
427 vector< pair< string, pair<string,string> > >::const_iterator opt;
428 for (opt = m_impl->m_transportOptions.begin(); opt != m_impl->m_transportOptions.end(); ++opt) {
429 if (!transport.setProviderOption(opt->first.c_str(), opt->second.first.c_str(), opt->second.second.c_str())) {
430 m_log.error("failed to set SOAPTransport option (%s)", opt->second.first.c_str());
439 pair<bool,DOMElement*> background_load();
442 friend class XMLConfigImpl;
443 XMLConfigImpl* m_impl;
444 ListenerService* m_listener;
445 SessionCache* m_sessionCache;
447 TransactionLog* m_tranLog;
448 map<string,StorageService*> m_storage;
452 #if defined (_MSC_VER)
453 #pragma warning( pop )
456 static const XMLCh applicationId[] = UNICODE_LITERAL_13(a,p,p,l,i,c,a,t,i,o,n,I,d);
457 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);
458 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);
459 static const XMLCh _ArtifactMap[] = UNICODE_LITERAL_11(A,r,t,i,f,a,c,t,M,a,p);
460 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);
461 static const XMLCh _AttributeFilter[] = UNICODE_LITERAL_15(A,t,t,r,i,b,u,t,e,F,i,l,t,e,r);
462 static const XMLCh _AttributeResolver[] = UNICODE_LITERAL_17(A,t,t,r,i,b,u,t,e,R,e,s,o,l,v,e,r);
463 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);
464 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);
465 static const XMLCh _Audience[] = UNICODE_LITERAL_8(A,u,d,i,e,n,c,e);
466 static const XMLCh Binding[] = UNICODE_LITERAL_7(B,i,n,d,i,n,g);
467 static const XMLCh Channel[]= UNICODE_LITERAL_7(C,h,a,n,n,e,l);
468 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);
469 static const XMLCh _default[] = UNICODE_LITERAL_7(d,e,f,a,u,l,t);
470 static const XMLCh _Extensions[] = UNICODE_LITERAL_10(E,x,t,e,n,s,i,o,n,s);
471 static const XMLCh _fatal[] = UNICODE_LITERAL_5(f,a,t,a,l);
472 static const XMLCh _Handler[] = UNICODE_LITERAL_7(H,a,n,d,l,e,r);
473 static const XMLCh _id[] = UNICODE_LITERAL_2(i,d);
474 static const XMLCh _index[] = UNICODE_LITERAL_5(i,n,d,e,x);
475 static const XMLCh InProcess[] = UNICODE_LITERAL_9(I,n,P,r,o,c,e,s,s);
476 static const XMLCh Library[] = UNICODE_LITERAL_7(L,i,b,r,a,r,y);
477 static const XMLCh Listener[] = UNICODE_LITERAL_8(L,i,s,t,e,n,e,r);
478 static const XMLCh Location[] = UNICODE_LITERAL_8(L,o,c,a,t,i,o,n);
479 static const XMLCh logger[] = UNICODE_LITERAL_6(l,o,g,g,e,r);
480 static const XMLCh Logout[] = UNICODE_LITERAL_6(L,o,g,o,u,t);
481 static const XMLCh _LogoutInitiator[] = UNICODE_LITERAL_15(L,o,g,o,u,t,I,n,i,t,i,a,t,o,r);
482 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);
483 static const XMLCh _MetadataProvider[] = UNICODE_LITERAL_16(M,e,t,a,d,a,t,a,P,r,o,v,i,d,e,r);
484 static const XMLCh NameIDMgmt[] = UNICODE_LITERAL_10(N,a,m,e,I,D,M,g,m,t);
485 static const XMLCh Notify[] = UNICODE_LITERAL_6(N,o,t,i,f,y);
486 static const XMLCh _option[] = UNICODE_LITERAL_6(o,p,t,i,o,n);
487 static const XMLCh OutOfProcess[] = UNICODE_LITERAL_12(O,u,t,O,f,P,r,o,c,e,s,s);
488 static const XMLCh _path[] = UNICODE_LITERAL_4(p,a,t,h);
489 static const XMLCh _ProtocolProvider[] = UNICODE_LITERAL_16(P,r,o,t,o,c,o,l,P,r,o,v,i,d,e,r);
490 static const XMLCh _provider[] = UNICODE_LITERAL_8(p,r,o,v,i,d,e,r);
491 static const XMLCh RelyingParty[] = UNICODE_LITERAL_12(R,e,l,y,i,n,g,P,a,r,t,y);
492 static const XMLCh _ReplayCache[] = UNICODE_LITERAL_11(R,e,p,l,a,y,C,a,c,h,e);
493 static const XMLCh _RequestMapper[] = UNICODE_LITERAL_13(R,e,q,u,e,s,t,M,a,p,p,e,r);
494 static const XMLCh RequestMap[] = UNICODE_LITERAL_10(R,e,q,u,e,s,t,M,a,p);
495 static const XMLCh SecurityPolicies[] = UNICODE_LITERAL_16(S,e,c,u,r,i,t,y,P,o,l,i,c,i,e,s);
496 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);
497 static const XMLCh _SessionCache[] = UNICODE_LITERAL_12(S,e,s,s,i,o,n,C,a,c,h,e);
498 static const XMLCh _SessionInitiator[] = UNICODE_LITERAL_16(S,e,s,s,i,o,n,I,n,i,t,i,a,t,o,r);
499 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);
500 static const XMLCh Site[] = UNICODE_LITERAL_4(S,i,t,e);
501 static const XMLCh SSO[] = UNICODE_LITERAL_3(S,S,O);
502 static const XMLCh _StorageService[] = UNICODE_LITERAL_14(S,t,o,r,a,g,e,S,e,r,v,i,c,e);
503 static const XMLCh TCPListener[] = UNICODE_LITERAL_11(T,C,P,L,i,s,t,e,n,e,r);
504 static const XMLCh TransportOption[] = UNICODE_LITERAL_15(T,r,a,n,s,p,o,r,t,O,p,t,i,o,n);
505 static const XMLCh _TrustEngine[] = UNICODE_LITERAL_11(T,r,u,s,t,E,n,g,i,n,e);
506 static const XMLCh _type[] = UNICODE_LITERAL_4(t,y,p,e);
507 static const XMLCh UnixListener[] = UNICODE_LITERAL_12(U,n,i,x,L,i,s,t,e,n,e,r);
511 ServiceProvider* XMLServiceProviderFactory(const DOMElement* const & e)
513 return new XMLConfig(e);
517 XMLApplication::XMLApplication(
518 const ServiceProvider* sp,
519 const ProtocolProvider* pp,
521 const XMLApplication* base
522 ) : Application(sp), m_base(base),
524 m_metadata(nullptr), m_trust(nullptr),
525 m_attrExtractor(nullptr), m_attrFilter(nullptr), m_attrResolver(nullptr),
526 m_credResolver(nullptr),
528 m_acsDefault(nullptr), m_sessionInitDefault(nullptr), m_artifactResolutionDefault(nullptr)
531 xmltooling::NDC ndc("XMLApplication");
533 Category& log=Category::getInstance(SHIBSP_LOGCAT".Application");
536 // First load any property sets.
537 load(e,nullptr,this);
541 SPConfig& conf=SPConfig::getConfig();
543 XMLToolingConfig& xmlConf=XMLToolingConfig::getConfig();
546 // This used to be an actual hash, but now it's just a hex-encode to avoid xmlsec dependency.
547 static char DIGITS[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
548 string tohash=getId();
549 tohash+=getString("entityID").second;
550 for (const char* ch = tohash.c_str(); *ch; ++ch) {
551 m_hash += (DIGITS[((unsigned char)(0xF0 & *ch)) >> 4 ]);
552 m_hash += (DIGITS[0x0F & *ch]);
557 if (conf.isEnabled(SPConfig::Handlers))
558 doHandlers(pp, e, log);
561 DOMNodeList* nlist = e->getElementsByTagNameNS(shibspconstants::SHIB2SPCONFIG_NS, Notify);
562 for (XMLSize_t i = 0; nlist && i < nlist->getLength(); ++i) {
563 if (nlist->item(i)->getParentNode()->isSameNode(e)) {
564 const XMLCh* channel = static_cast<DOMElement*>(nlist->item(i))->getAttributeNS(nullptr, Channel);
565 string loc(XMLHelper::getAttrString(static_cast<DOMElement*>(nlist->item(i)), nullptr, Location));
567 if (channel && *channel == chLatin_f)
568 m_frontLogout.push_back(loc);
570 m_backLogout.push_back(loc);
576 nlist = e->getElementsByTagNameNS(samlconstants::SAML20_NS, Audience::LOCAL_NAME);
577 if (nlist && nlist->getLength()) {
578 log.warn("use of <saml:Audience> elements outside of a Security Policy Rule is deprecated");
579 for (XMLSize_t i = 0; i < nlist->getLength(); ++i)
580 if (nlist->item(i)->getParentNode()->isSameNode(e) && nlist->item(i)->hasChildNodes())
581 m_audiences.push_back(nlist->item(i)->getFirstChild()->getNodeValue());
584 if (conf.isEnabled(SPConfig::Metadata)) {
585 auto_ptr<MetadataProvider> mp(
587 SAMLConfig::getConfig().MetadataProviderManager, "MetadataProvider", CHAINING_METADATA_PROVIDER, _MetadataProvider, e, log
593 m_metadata = mp.release();
596 log.crit("no MetadataProvider available, configuration is probably unusable");
599 catch (exception& ex) {
600 log.crit("error initializing MetadataProvider: %s", ex.what());
604 if (conf.isEnabled(SPConfig::Trust)) {
605 m_trust = doChainedPlugins(xmlConf.TrustEngineManager, "TrustEngine", CHAINING_TRUSTENGINE, _TrustEngine, e, log);
606 if (!m_trust && !m_base) {
608 "no TrustEngine specified or installed, using default chain {%s, %s}",
609 EXPLICIT_KEY_TRUSTENGINE, SHIBBOLETH_PKIX_TRUSTENGINE
611 m_trust = xmlConf.TrustEngineManager.newPlugin(CHAINING_TRUSTENGINE, nullptr);
612 ChainingTrustEngine* trustchain = dynamic_cast<ChainingTrustEngine*>(m_trust);
614 trustchain->addTrustEngine(xmlConf.TrustEngineManager.newPlugin(EXPLICIT_KEY_TRUSTENGINE, nullptr));
615 trustchain->addTrustEngine(xmlConf.TrustEngineManager.newPlugin(SHIBBOLETH_PKIX_TRUSTENGINE, nullptr));
620 if (conf.isEnabled(SPConfig::AttributeResolution))
621 doAttributePlugins(e, log);
623 if (conf.isEnabled(SPConfig::Credentials)) {
624 m_credResolver = doChainedPlugins(
625 xmlConf.CredentialResolverManager, "CredentialResolver", CHAINING_CREDENTIAL_RESOLVER, _CredentialResolver, e, log
629 // Finally, load relying parties.
630 const DOMElement* child = XMLHelper::getFirstChildElement(e, RelyingParty);
632 if (child->hasAttributeNS(nullptr, saml2::Attribute::NAME_ATTRIB_NAME)) {
633 auto_ptr<DOMPropertySet> rp(new DOMPropertySet());
634 rp->load(child, nullptr, this);
636 m_partyMap[child->getAttributeNS(nullptr, saml2::Attribute::NAME_ATTRIB_NAME)] = rp.release();
638 child = XMLHelper::getNextSiblingElement(child, RelyingParty);
640 if (base && m_partyMap.empty() && !base->m_partyMap.empty()) {
641 // For inheritance of RPs to work, we have to pull them in to the override by cloning the DOM.
642 child = XMLHelper::getFirstChildElement(base->getElement(), RelyingParty);
644 if (child->hasAttributeNS(nullptr, saml2::Attribute::NAME_ATTRIB_NAME)) {
645 DOMElement* rpclone = static_cast<DOMElement*>(child->cloneNode(true));
646 auto_ptr<DOMPropertySet> rp(new DOMPropertySet());
647 rp->load(rpclone, nullptr, this);
649 m_partyMap[rpclone->getAttributeNS(nullptr, saml2::Attribute::NAME_ATTRIB_NAME)] = rp.release();
651 child = XMLHelper::getNextSiblingElement(child, RelyingParty);
656 // Out of process only, we register a listener endpoint.
657 if (!conf.isEnabled(SPConfig::InProcess)) {
658 ListenerService* listener = sp->getListenerService(false);
660 string addr=string(getId()) + "::getHeaders::Application";
661 listener->regListener(addr.c_str(),this);
664 log.info("no ListenerService available, Application remoting disabled");
680 template <class T> T* XMLApplication::doChainedPlugins(
681 PluginManager<T,string,const DOMElement*>& pluginMgr,
682 const char* pluginType,
683 const char* chainingType,
684 const XMLCh* localName,
687 const char* dummyType
691 DOMElement* child = XMLHelper::getFirstChildElement(e, localName);
693 // Check for multiple.
694 if (XMLHelper::getNextSiblingElement(child, localName)) {
695 log.info("multiple %s plugins, wrapping in a chain", pluginType);
696 DOMElement* chain = child->getOwnerDocument()->createElementNS(nullptr, localName);
698 chain->appendChild(child);
699 child = XMLHelper::getFirstChildElement(e, localName);
703 e->appendChild(chain);
706 // Only a single one.
707 t = XMLHelper::getAttrString(child, nullptr, _type);
712 log.info("building %s of type %s...", pluginType, t.c_str());
713 return pluginMgr.newPlugin(t.c_str(), child);
716 throw ConfigurationException("$1 element had no type attribute.", params(1, pluginType));
719 catch (exception& ex) {
720 log.crit("error building %s: %s", pluginType, ex.what());
722 // Install a dummy version as a safety valve.
723 log.crit("installing safe %s in place of failed version", pluginType);
724 return pluginMgr.newPlugin(dummyType, nullptr);
732 void XMLApplication::doAttributeInfo()
734 // Populate prefix pair.
735 m_attributePrefix.second = "HTTP_";
736 pair<bool,const char*> prefix = getString("attributePrefix");
738 m_attributePrefix.first = prefix.second;
739 const char* pch = prefix.second;
741 m_attributePrefix.second += (isalnum(*pch) ? toupper(*pch) : '_');
746 // Load attribute ID lists for REMOTE_USER and header clearing.
747 if (SPConfig::getConfig().isEnabled(SPConfig::InProcess)) {
748 pair<bool,const char*> attributes = getString("REMOTE_USER");
749 if (attributes.first) {
750 char* dup = strdup(attributes.second);
753 while (start && *start) {
754 while (*start && isspace(*start))
758 pos = strchr(start,' ');
761 m_remoteUsers.push_back(start);
762 start = pos ? pos+1 : nullptr;
767 attributes = getString("unsetHeaders");
768 if (attributes.first) {
769 string transformedprefix(m_attributePrefix.second);
771 prefix = getString("metadataAttributePrefix");
775 transformedprefix += (isalnum(*pch) ? toupper(*pch) : '_');
779 char* dup = strdup(attributes.second);
782 while (start && *start) {
783 while (*start && isspace(*start))
787 pos = strchr(start,' ');
794 transformed += (isalnum(*pch) ? toupper(*pch) : '_');
798 m_unsetHeaders.push_back(pair<string,string>(m_attributePrefix.first + start, m_attributePrefix.second + transformed));
800 m_unsetHeaders.push_back(pair<string,string>(m_attributePrefix.first + prefix.second + start, transformedprefix + transformed));
801 start = pos ? pos+1 : nullptr;
804 m_unsetHeaders.push_back(pair<string,string>(m_attributePrefix.first + "Shib-Application-ID", m_attributePrefix.second + "SHIB_APPLICATION_ID"));
809 void XMLApplication::doHandlers(const ProtocolProvider* pp, const DOMElement* e, Category& log)
811 SPConfig& conf = SPConfig::getConfig();
813 Handler* handler = nullptr;
814 const PropertySet* sessions = getPropertySet("Sessions");
816 // Process assertion export handler.
817 pair<bool,const char*> location = sessions ? sessions->getString("exportLocation") : pair<bool,const char*>(false,nullptr);
818 if (location.first) {
820 DOMElement* exportElement = e->getOwnerDocument()->createElementNS(shibspconstants::SHIB2SPCONFIG_NS, _Handler);
821 exportElement->setAttributeNS(nullptr,Location,sessions->getXMLString("exportLocation").second);
822 pair<bool,const XMLCh*> exportACL = sessions->getXMLString("exportACL");
823 if (exportACL.first) {
824 static const XMLCh _acl[] = UNICODE_LITERAL_9(e,x,p,o,r,t,A,C,L);
825 exportElement->setAttributeNS(nullptr,_acl,exportACL.second);
827 handler = conf.HandlerManager.newPlugin(
828 samlconstants::SAML20_BINDING_URI, pair<const DOMElement*,const char*>(exportElement, getId())
830 m_handlers.push_back(handler);
832 // Insert into location map. If it contains the handlerURL, we skip past that part.
833 const char* hurl = sessions->getString("handlerURL").second;
835 hurl = "/Shibboleth.sso";
836 const char* pch = strstr(location.second, hurl);
838 location.second = pch + strlen(hurl);
839 if (*location.second == '/')
840 m_handlerMap[location.second]=handler;
842 m_handlerMap[string("/") + location.second]=handler;
844 catch (exception& ex) {
845 log.error("caught exception installing assertion lookup handler: %s", ex.what());
849 // Look for "shorthand" elements first.
850 set<string> protocols;
851 DOMElement* child = sessions ? XMLHelper::getFirstChildElement(sessions->getElement()) : nullptr;
853 if (XMLHelper::isNodeNamed(child, shibspconstants::SHIB2SPCONFIG_NS, SSO)) {
855 doSSO(*pp, protocols, child, log);
857 log.error("no ProtocolProvider, SSO auto-configure unsupported");
859 else if (XMLHelper::isNodeNamed(child, shibspconstants::SHIB2SPCONFIG_NS, Logout)) {
861 doLogout(*pp, protocols, child, log);
863 log.error("no ProtocolProvider, Logout auto-configure unsupported");
865 else if (XMLHelper::isNodeNamed(child, shibspconstants::SHIB2SPCONFIG_NS, NameIDMgmt)) {
867 doNameIDMgmt(*pp, protocols, child, log);
869 log.error("no ProtocolProvider, NameIDMgmt auto-configure unsupported");
872 break; // drop into next while loop
874 child = XMLHelper::getNextSiblingElement(child);
877 // Process other handlers.
878 bool hardACS=false, hardSessionInit=false, hardArt=false;
880 if (!child->hasAttributeNS(nullptr, Location)) {
881 auto_ptr_char hclass(child->getLocalName());
882 log.error("%s handler with no Location property cannot be processed", hclass.get());
883 child = XMLHelper::getNextSiblingElement(child);
887 if (XMLString::equals(child->getLocalName(), _AssertionConsumerService)) {
888 string bindprop(XMLHelper::getAttrString(child, nullptr, Binding));
889 if (bindprop.empty()) {
890 log.error("AssertionConsumerService element has no Binding attribute, skipping it...");
891 child = XMLHelper::getNextSiblingElement(child);
894 handler = conf.AssertionConsumerServiceManager.newPlugin(bindprop.c_str(), pair<const DOMElement*,const char*>(child, getId()));
895 // Map by binding and protocol (may be > 1 per protocol and binding)
896 m_acsBindingMap[handler->getXMLString("Binding").second].push_back(handler);
897 const XMLCh* protfamily = handler->getProtocolFamily();
899 m_acsProtocolMap[protfamily].push_back(handler);
900 m_acsIndexMap[handler->getUnsignedInt("index").second] = handler;
903 pair<bool,bool> defprop = handler->getBool("isDefault");
905 if (defprop.second) {
907 m_acsDefault = handler;
910 else if (!m_acsDefault)
911 m_acsDefault = handler;
914 else if (XMLString::equals(child->getLocalName(), _SessionInitiator)) {
915 string t(XMLHelper::getAttrString(child, nullptr, _type));
917 log.error("SessionInitiator element has no type attribute, skipping it...");
918 child = XMLHelper::getNextSiblingElement(child);
921 SessionInitiator* sihandler = conf.SessionInitiatorManager.newPlugin(t.c_str(), pair<const DOMElement*,const char*>(child, getId()));
923 pair<bool,const char*> si_id = handler->getString("id");
924 if (si_id.first && si_id.second)
925 m_sessionInitMap[si_id.second] = sihandler;
926 if (!hardSessionInit) {
927 pair<bool,bool> defprop = handler->getBool("isDefault");
929 if (defprop.second) {
930 hardSessionInit = true;
931 m_sessionInitDefault = sihandler;
934 else if (!m_sessionInitDefault) {
935 m_sessionInitDefault = sihandler;
939 else if (XMLString::equals(child->getLocalName(), _LogoutInitiator)) {
940 string t(XMLHelper::getAttrString(child, nullptr, _type));
942 log.error("LogoutInitiator element has no type attribute, skipping it...");
943 child = XMLHelper::getNextSiblingElement(child);
946 handler = conf.LogoutInitiatorManager.newPlugin(t.c_str(), pair<const DOMElement*,const char*>(child, getId()));
948 else if (XMLString::equals(child->getLocalName(), _ArtifactResolutionService)) {
949 string bindprop(XMLHelper::getAttrString(child, nullptr, Binding));
950 if (bindprop.empty()) {
951 log.error("ArtifactResolutionService element has no Binding attribute, skipping it...");
952 child = XMLHelper::getNextSiblingElement(child);
955 handler = conf.ArtifactResolutionServiceManager.newPlugin(bindprop.c_str(), pair<const DOMElement*,const char*>(child, getId()));
958 pair<bool,bool> defprop = handler->getBool("isDefault");
960 if (defprop.second) {
962 m_artifactResolutionDefault = handler;
965 else if (!m_artifactResolutionDefault)
966 m_artifactResolutionDefault = handler;
969 else if (XMLString::equals(child->getLocalName(), _SingleLogoutService)) {
970 string bindprop(XMLHelper::getAttrString(child, nullptr, Binding));
971 if (bindprop.empty()) {
972 log.error("SingleLogoutService element has no Binding attribute, skipping it...");
973 child = XMLHelper::getNextSiblingElement(child);
976 handler = conf.SingleLogoutServiceManager.newPlugin(bindprop.c_str(), pair<const DOMElement*,const char*>(child, getId()));
978 else if (XMLString::equals(child->getLocalName(), _ManageNameIDService)) {
979 string bindprop(XMLHelper::getAttrString(child, nullptr, Binding));
980 if (bindprop.empty()) {
981 log.error("ManageNameIDService element has no Binding attribute, skipping it...");
982 child = XMLHelper::getNextSiblingElement(child);
985 handler = conf.ManageNameIDServiceManager.newPlugin(bindprop.c_str(), pair<const DOMElement*,const char*>(child, getId()));
988 string t(XMLHelper::getAttrString(child, nullptr, _type));
990 log.error("Handler element has no type attribute, skipping it...");
991 child = XMLHelper::getNextSiblingElement(child);
994 handler = conf.HandlerManager.newPlugin(t.c_str(), pair<const DOMElement*,const char*>(child, getId()));
997 m_handlers.push_back(handler);
999 // Insert into location map.
1000 location = handler->getString("Location");
1001 if (location.first && *location.second == '/')
1002 m_handlerMap[location.second] = handler;
1003 else if (location.first)
1004 m_handlerMap[string("/") + location.second] = handler;
1006 catch (exception& ex) {
1007 log.error("caught exception processing handler element: %s", ex.what());
1010 child = XMLHelper::getNextSiblingElement(child);
1014 void XMLApplication::doSSO(const ProtocolProvider& pp, set<string>& protocols, DOMElement* e, Category& log)
1016 if (!e->hasChildNodes())
1019 SPConfig& conf = SPConfig::getConfig();
1021 // Tokenize the protocol list inside the element.
1022 XMLStringTokenizer prottokens(e->getTextContent());
1023 while (prottokens.hasMoreTokens()) {
1024 auto_ptr_char prot(prottokens.nextToken());
1026 // Look for initiator.
1027 const PropertySet* initiator = pp.getInitiator(prot.get(), "SSO");
1029 log.info("auto-configuring SSO initiation for protocol (%s)", prot.get());
1030 pair<bool,const XMLCh*> inittype = initiator->getXMLString("id");
1031 if (inittype.first) {
1032 // Append a session initiator element of the designated type to the root element.
1033 DOMElement* sidom = e->getOwnerDocument()->createElementNS(shibspconstants::SHIB2SPCONFIG_NS, _SessionInitiator);
1034 sidom->setAttributeNS(nullptr, _type, inittype.second);
1035 e->appendChild(sidom);
1036 log.info("adding SessionInitiator of type (%s) to chain (/Login)", initiator->getString("id").second);
1038 doArtifactResolution(pp, prot.get(), e, log);
1039 protocols.insert(prot.get());
1042 log.error("missing id property on Initiator element, check config for protocol (%s)", prot.get());
1046 // Look for incoming bindings.
1047 const vector<const PropertySet*>& bindings = pp.getBindings(prot.get(), "SSO");
1048 if (!bindings.empty()) {
1049 log.info("auto-configuring SSO endpoints for protocol (%s)", prot.get());
1051 pair<bool,const XMLCh*> idprop,pathprop;
1052 for (vector<const PropertySet*>::const_iterator b = bindings.begin(); b != bindings.end(); ++b, ++index) {
1053 idprop = (*b)->getXMLString("id");
1054 pathprop = (*b)->getXMLString("path");
1055 if (idprop.first && pathprop.first) {
1056 DOMElement* acsdom = e->getOwnerDocument()->createElementNS(samlconstants::SAML20MD_NS, _AssertionConsumerService);
1057 acsdom->setAttributeNS(nullptr, Binding, idprop.second);
1058 acsdom->setAttributeNS(nullptr, Location, pathprop.second);
1059 xstring indexbuf(chDigit_1 + (index % 10), 1);
1061 indexbuf = (XMLCh)(chDigit_1 + (index / 10)) + indexbuf;
1062 acsdom->setAttributeNS(nullptr, _index, indexbuf.c_str());
1064 log.info("adding AssertionConsumerService for Binding (%s) at (%s)", (*b)->getString("id").second, (*b)->getString("path").second);
1065 Handler* handler = conf.AssertionConsumerServiceManager.newPlugin(
1066 (*b)->getString("id").second, pair<const DOMElement*,const char*>(acsdom, getId())
1068 m_handlers.push_back(handler);
1070 // Setup maps and defaults.
1071 m_acsBindingMap[handler->getXMLString("Binding").second].push_back(handler);
1072 const XMLCh* protfamily = handler->getProtocolFamily();
1074 m_acsProtocolMap[protfamily].push_back(handler);
1075 m_acsIndexMap[handler->getUnsignedInt("index").second] = handler;
1077 m_acsDefault = handler;
1079 // Insert into location map.
1080 pair<bool,const char*> location = handler->getString("Location");
1081 if (location.first && *location.second == '/')
1082 m_handlerMap[location.second] = handler;
1083 else if (location.first)
1084 m_handlerMap[string("/") + location.second] = handler;
1087 log.error("missing id or path property on Binding element, check config for protocol (%s)", prot.get());
1092 if (!initiator && bindings.empty()) {
1093 log.error("no SSO Initiator or Binding config for protocol (%s)", prot.get());
1097 // Handle discovery.
1098 static const XMLCh discoveryProtocol[] = UNICODE_LITERAL_17(d,i,s,c,o,v,e,r,y,P,r,o,t,o,c,o,l);
1099 static const XMLCh discoveryURL[] = UNICODE_LITERAL_12(d,i,s,c,o,v,e,r,y,U,R,L);
1100 static const XMLCh _URL[] = UNICODE_LITERAL_3(U,R,L);
1101 const XMLCh* discop = e->getAttributeNS(nullptr, discoveryProtocol);
1102 if (discop && *discop) {
1103 const XMLCh* discou = e->getAttributeNS(nullptr, discoveryURL);
1104 if (discou && *discou) {
1105 // Append a session initiator element of the designated type to the root element.
1106 DOMElement* sidom = e->getOwnerDocument()->createElementNS(shibspconstants::SHIB2SPCONFIG_NS, _SessionInitiator);
1107 sidom->setAttributeNS(nullptr, _type, discop);
1108 sidom->setAttributeNS(nullptr, _URL, discou);
1109 e->appendChild(sidom);
1110 if (log.isInfoEnabled()) {
1111 auto_ptr_char dp(discop);
1112 log.info("adding SessionInitiator of type (%s) to chain (/Login)", dp.get());
1116 log.error("SSO discoveryProtocol specified without discoveryURL");
1120 // Attach default Location to SSO element.
1121 static const XMLCh _loc[] = { chForwardSlash, chLatin_L, chLatin_o, chLatin_g, chLatin_i, chLatin_n, chNull };
1122 e->setAttributeNS(nullptr, Location, _loc);
1124 // Instantiate Chaining initiator around the SSO element.
1125 SessionInitiator* chain = conf.SessionInitiatorManager.newPlugin(
1126 CHAINING_SESSION_INITIATOR, pair<const DOMElement*,const char*>(e, getId())
1128 m_handlers.push_back(chain);
1129 m_sessionInitDefault = chain;
1130 m_handlerMap["/Login"] = chain;
1133 void XMLApplication::doLogout(const ProtocolProvider& pp, set<string>& protocols, DOMElement* e, Category& log)
1135 if (!e->hasChildNodes())
1138 SPConfig& conf = SPConfig::getConfig();
1140 // Tokenize the protocol list inside the element.
1141 XMLStringTokenizer prottokens(e->getTextContent());
1142 while (prottokens.hasMoreTokens()) {
1143 auto_ptr_char prot(prottokens.nextToken());
1145 // Look for initiator.
1146 const PropertySet* initiator = pp.getInitiator(prot.get(), "Logout");
1148 log.info("auto-configuring Logout initiation for protocol (%s)", prot.get());
1149 pair<bool,const XMLCh*> inittype = initiator->getXMLString("id");
1150 if (inittype.first) {
1151 // Append a logout initiator element of the designated type to the root element.
1152 DOMElement* lidom = e->getOwnerDocument()->createElementNS(shibspconstants::SHIB2SPCONFIG_NS, _LogoutInitiator);
1153 lidom->setAttributeNS(nullptr, _type, inittype.second);
1154 e->appendChild(lidom);
1155 log.info("adding LogoutInitiator of type (%s) to chain (/Logout)", initiator->getString("id").second);
1157 if (protocols.count(prot.get()) == 0) {
1158 doArtifactResolution(pp, prot.get(), e, log);
1159 protocols.insert(prot.get());
1163 log.error("missing id property on Initiator element, check config for protocol (%s)", prot.get());
1167 // Look for incoming bindings.
1168 const vector<const PropertySet*>& bindings = pp.getBindings(prot.get(), "Logout");
1169 if (!bindings.empty()) {
1170 log.info("auto-configuring Logout endpoints for protocol (%s)", prot.get());
1171 pair<bool,const XMLCh*> idprop,pathprop;
1172 for (vector<const PropertySet*>::const_iterator b = bindings.begin(); b != bindings.end(); ++b) {
1173 idprop = (*b)->getXMLString("id");
1174 pathprop = (*b)->getXMLString("path");
1175 if (idprop.first && pathprop.first) {
1176 DOMElement* slodom = e->getOwnerDocument()->createElementNS(samlconstants::SAML20MD_NS, _SingleLogoutService);
1177 slodom->setAttributeNS(nullptr, Binding, idprop.second);
1178 slodom->setAttributeNS(nullptr, Location, pathprop.second);
1180 log.info("adding SingleLogoutService for Binding (%s) at (%s)", (*b)->getString("id").second, (*b)->getString("path").second);
1181 Handler* handler = conf.SingleLogoutServiceManager.newPlugin(
1182 (*b)->getString("id").second, pair<const DOMElement*,const char*>(slodom, getId())
1184 m_handlers.push_back(handler);
1186 // Insert into location map.
1187 pair<bool,const char*> location = handler->getString("Location");
1188 if (location.first && *location.second == '/')
1189 m_handlerMap[location.second] = handler;
1190 else if (location.first)
1191 m_handlerMap[string("/") + location.second] = handler;
1194 log.error("missing id or path property on Binding element, check config for protocol (%s)", prot.get());
1198 if (protocols.count(prot.get()) == 0) {
1199 doArtifactResolution(pp, prot.get(), e, log);
1200 protocols.insert(prot.get());
1204 if (!initiator && bindings.empty()) {
1205 log.error("no Logout Initiator or Binding config for protocol (%s)", prot.get());
1209 // Attach default Location to Logout element.
1210 static const XMLCh _loc[] = { chForwardSlash, chLatin_L, chLatin_o, chLatin_g, chLatin_o, chLatin_u, chLatin_t, chNull };
1211 e->setAttributeNS(nullptr, Location, _loc);
1213 // Instantiate Chaining initiator around the SSO element.
1214 Handler* chain = conf.LogoutInitiatorManager.newPlugin(
1215 CHAINING_LOGOUT_INITIATOR, pair<const DOMElement*,const char*>(e, getId())
1217 m_handlers.push_back(chain);
1218 m_handlerMap["/Logout"] = chain;
1221 void XMLApplication::doNameIDMgmt(const ProtocolProvider& pp, set<string>& protocols, DOMElement* e, Category& log)
1223 if (!e->hasChildNodes())
1226 SPConfig& conf = SPConfig::getConfig();
1228 // Tokenize the protocol list inside the element.
1229 XMLStringTokenizer prottokens(e->getTextContent());
1230 while (prottokens.hasMoreTokens()) {
1231 auto_ptr_char prot(prottokens.nextToken());
1233 // Look for incoming bindings.
1234 const vector<const PropertySet*>& bindings = pp.getBindings(prot.get(), "NameIDMgmt");
1235 if (!bindings.empty()) {
1236 log.info("auto-configuring NameIDMgmt endpoints for protocol (%s)", prot.get());
1237 pair<bool,const XMLCh*> idprop,pathprop;
1238 for (vector<const PropertySet*>::const_iterator b = bindings.begin(); b != bindings.end(); ++b) {
1239 idprop = (*b)->getXMLString("id");
1240 pathprop = (*b)->getXMLString("path");
1241 if (idprop.first && pathprop.first) {
1242 DOMElement* nimdom = e->getOwnerDocument()->createElementNS(samlconstants::SAML20MD_NS, _ManageNameIDService);
1243 nimdom->setAttributeNS(nullptr, Binding, idprop.second);
1244 nimdom->setAttributeNS(nullptr, Location, pathprop.second);
1246 log.info("adding ManageNameIDService for Binding (%s) at (%s)", (*b)->getString("id").second, (*b)->getString("path").second);
1247 Handler* handler = conf.ManageNameIDServiceManager.newPlugin(
1248 (*b)->getString("id").second, pair<const DOMElement*,const char*>(nimdom, getId())
1250 m_handlers.push_back(handler);
1252 // Insert into location map.
1253 pair<bool,const char*> location = handler->getString("Location");
1254 if (location.first && *location.second == '/')
1255 m_handlerMap[location.second] = handler;
1256 else if (location.first)
1257 m_handlerMap[string("/") + location.second] = handler;
1260 log.error("missing id or path property on Binding element, check config for protocol (%s)", prot.get());
1264 if (protocols.count(prot.get()) == 0) {
1265 doArtifactResolution(pp, prot.get(), e, log);
1266 protocols.insert(prot.get());
1270 log.error("no NameIDMgmt Binding config for protocol (%s)", prot.get());
1275 void XMLApplication::doArtifactResolution(const ProtocolProvider& pp, const char* protocol, DOMElement* e, Category& log)
1277 SPConfig& conf = SPConfig::getConfig();
1279 // Look for incoming bindings.
1280 const vector<const PropertySet*>& bindings = pp.getBindings(protocol, "ArtifactResolution");
1281 if (!bindings.empty()) {
1282 log.info("auto-configuring ArtifactResolution endpoints for protocol (%s)", protocol);
1284 pair<bool,const XMLCh*> idprop,pathprop;
1285 for (vector<const PropertySet*>::const_iterator b = bindings.begin(); b != bindings.end(); ++b) {
1286 idprop = (*b)->getXMLString("id");
1287 pathprop = (*b)->getXMLString("path");
1288 if (idprop.first && pathprop.first) {
1289 DOMElement* artdom = e->getOwnerDocument()->createElementNS(samlconstants::SAML20MD_NS, _ArtifactResolutionService);
1290 artdom->setAttributeNS(nullptr, Binding, idprop.second);
1291 artdom->setAttributeNS(nullptr, Location, pathprop.second);
1292 xstring indexbuf(chDigit_1 + (index % 10), 1);
1294 indexbuf = (XMLCh)(chDigit_1 + (index / 10)) + indexbuf;
1295 artdom->setAttributeNS(nullptr, _index, indexbuf.c_str());
1297 log.info("adding ArtifactResolutionService for Binding (%s) at (%s)", (*b)->getString("id").second, (*b)->getString("path").second);
1298 Handler* handler = conf.ArtifactResolutionServiceManager.newPlugin(
1299 (*b)->getString("id").second, pair<const DOMElement*,const char*>(artdom, getId())
1301 m_handlers.push_back(handler);
1303 if (!m_artifactResolutionDefault)
1304 m_artifactResolutionDefault = handler;
1306 // Insert into location map.
1307 pair<bool,const char*> location = handler->getString("Location");
1308 if (location.first && *location.second == '/')
1309 m_handlerMap[location.second] = handler;
1310 else if (location.first)
1311 m_handlerMap[string("/") + location.second] = handler;
1314 log.error("missing id or path property on Binding element, check config for protocol (%s)", protocol);
1321 void XMLApplication::doAttributePlugins(DOMElement* e, Category& log)
1323 SPConfig& conf = SPConfig::getConfig();
1326 doChainedPlugins(conf.AttributeExtractorManager, "AttributeExtractor", CHAINING_ATTRIBUTE_EXTRACTOR, _AttributeExtractor, e, log);
1329 doChainedPlugins(conf.AttributeFilterManager, "AttributeFilter", CHAINING_ATTRIBUTE_FILTER, _AttributeFilter, e, log, DUMMY_ATTRIBUTE_FILTER);
1332 doChainedPlugins(conf.AttributeResolverManager, "AttributeResolver", CHAINING_ATTRIBUTE_RESOLVER, _AttributeResolver, e, log);
1334 if (m_unsetHeaders.empty()) {
1335 vector<string> unsetHeaders;
1336 if (m_attrExtractor) {
1337 Locker extlock(m_attrExtractor);
1338 m_attrExtractor->getAttributeIds(unsetHeaders);
1340 else if (m_base && m_base->m_attrExtractor) {
1341 Locker extlock(m_base->m_attrExtractor);
1342 m_base->m_attrExtractor->getAttributeIds(unsetHeaders);
1344 if (m_attrResolver) {
1345 Locker reslock(m_attrResolver);
1346 m_attrResolver->getAttributeIds(unsetHeaders);
1348 else if (m_base && m_base->m_attrResolver) {
1349 Locker extlock(m_base->m_attrResolver);
1350 m_base->m_attrResolver->getAttributeIds(unsetHeaders);
1352 if (!unsetHeaders.empty()) {
1353 string transformedprefix(m_attributePrefix.second);
1355 pair<bool,const char*> prefix = getString("metadataAttributePrefix");
1357 pch = prefix.second;
1359 transformedprefix += (isalnum(*pch) ? toupper(*pch) : '_');
1363 for (vector<string>::const_iterator hdr = unsetHeaders.begin(); hdr!=unsetHeaders.end(); ++hdr) {
1367 transformed += (isalnum(*pch) ? toupper(*pch) : '_');
1370 m_unsetHeaders.push_back(pair<string,string>(m_attributePrefix.first + *hdr, m_attributePrefix.second + transformed));
1372 m_unsetHeaders.push_back(pair<string,string>(m_attributePrefix.first + prefix.second + *hdr, transformedprefix + transformed));
1375 m_unsetHeaders.push_back(pair<string,string>(m_attributePrefix.first + "Shib-Application-ID", m_attributePrefix.second + "SHIB_APPLICATION_ID"));
1380 void XMLApplication::cleanup()
1382 ListenerService* listener=getServiceProvider().getListenerService(false);
1383 if (listener && SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess) && !SPConfig::getConfig().isEnabled(SPConfig::InProcess)) {
1384 string addr=string(getId()) + "::getHeaders::Application";
1385 listener->unregListener(addr.c_str(),this);
1387 for_each(m_handlers.begin(),m_handlers.end(),xmltooling::cleanup<Handler>());
1390 for_each(m_partyMap.begin(),m_partyMap.end(),cleanup_pair<xstring,PropertySet>());
1392 delete m_credResolver;
1393 m_credResolver = nullptr;
1394 delete m_attrResolver;
1395 m_attrResolver = nullptr;
1396 delete m_attrFilter;
1397 m_attrFilter = nullptr;
1398 delete m_attrExtractor;
1399 m_attrExtractor = nullptr;
1403 m_metadata = nullptr;
1407 #ifdef SHIBSP_XERCESC_SHORT_ACCEPTNODE
1410 DOMNodeFilter::FilterAction
1412 XMLApplication::acceptNode(const DOMNode* node) const
1414 const XMLCh* name=node->getLocalName();
1415 if (XMLString::equals(name,ApplicationOverride) ||
1416 XMLString::equals(name,_Audience) ||
1417 XMLString::equals(name,Notify) ||
1418 XMLString::equals(name,_Handler) ||
1419 XMLString::equals(name,_AssertionConsumerService) ||
1420 XMLString::equals(name,_ArtifactResolutionService) ||
1421 XMLString::equals(name,Logout) ||
1422 XMLString::equals(name,_LogoutInitiator) ||
1423 XMLString::equals(name,_ManageNameIDService) ||
1424 XMLString::equals(name,NameIDMgmt) ||
1425 XMLString::equals(name,_SessionInitiator) ||
1426 XMLString::equals(name,_SingleLogoutService) ||
1427 XMLString::equals(name,SSO) ||
1428 XMLString::equals(name,RelyingParty) ||
1429 XMLString::equals(name,_MetadataProvider) ||
1430 XMLString::equals(name,_TrustEngine) ||
1431 XMLString::equals(name,_CredentialResolver) ||
1432 XMLString::equals(name,_AttributeFilter) ||
1433 XMLString::equals(name,_AttributeExtractor) ||
1434 XMLString::equals(name,_AttributeResolver))
1435 return FILTER_REJECT;
1437 return FILTER_ACCEPT;
1442 const PropertySet* XMLApplication::getRelyingParty(const EntityDescriptor* provider) const
1447 map<xstring,PropertySet*>::const_iterator i=m_partyMap.find(provider->getEntityID());
1448 if (i!=m_partyMap.end())
1450 const EntitiesDescriptor* group=dynamic_cast<const EntitiesDescriptor*>(provider->getParent());
1452 if (group->getName()) {
1453 i=m_partyMap.find(group->getName());
1454 if (i!=m_partyMap.end())
1457 group=dynamic_cast<const EntitiesDescriptor*>(group->getParent());
1462 const PropertySet* XMLApplication::getRelyingParty(const XMLCh* entityID) const
1467 map<xstring,PropertySet*>::const_iterator i=m_partyMap.find(entityID);
1468 if (i!=m_partyMap.end())
1475 string XMLApplication::getNotificationURL(const char* resource, bool front, unsigned int index) const
1477 const vector<string>& locs = front ? m_frontLogout : m_backLogout;
1479 return m_base ? m_base->getNotificationURL(resource, front, index) : string();
1480 else if (index >= locs.size())
1483 #ifdef HAVE_STRCASECMP
1484 if (!resource || (strncasecmp(resource,"http://",7) && strncasecmp(resource,"https://",8)))
1486 if (!resource || (strnicmp(resource,"http://",7) && strnicmp(resource,"https://",8)))
1488 throw ConfigurationException("Request URL was not absolute.");
1490 const char* handler=locs[index].c_str();
1492 // Should never happen...
1493 if (!handler || (*handler!='/' && strncmp(handler,"http:",5) && strncmp(handler,"https:",6)))
1494 throw ConfigurationException(
1495 "Invalid Location property ($1) in Notify element for Application ($2)",
1496 params(2, handler ? handler : "null", getId())
1499 // The "Location" property can be in one of three formats:
1501 // 1) a full URI: http://host/foo/bar
1502 // 2) a hostless URI: http:///foo/bar
1503 // 3) a relative path: /foo/bar
1505 // # Protocol Host Path
1506 // 1 handler handler handler
1507 // 2 handler resource handler
1508 // 3 resource resource handler
1510 const char* path = nullptr;
1512 // Decide whether to use the handler or the resource for the "protocol"
1514 if (*handler != '/') {
1522 // break apart the "protocol" string into protocol, host, and "the rest"
1523 const char* colon=strchr(prot,':');
1525 const char* slash=strchr(colon,'/');
1529 // Compute the actual protocol and store.
1530 string notifyURL(prot, colon-prot);
1532 // create the "host" from either the colon/slash or from the target string
1533 // If prot == handler then we're in either #1 or #2, else #3.
1534 // If slash == colon then we're in #2.
1535 if (prot != handler || slash == colon) {
1536 colon = strchr(resource, ':');
1537 colon += 3; // Get past the ://
1538 slash = strchr(colon, '/');
1540 string host(colon, (slash ? slash-colon : strlen(colon)));
1543 notifyURL += host + path;
1547 void XMLApplication::clearHeader(SPRequest& request, const char* rawname, const char* cginame) const
1549 if (!m_attributePrefix.first.empty()) {
1550 string temp = m_attributePrefix.first + rawname;
1551 string temp2 = m_attributePrefix.second + (cginame + 5);
1552 request.clearHeader(temp.c_str(), temp2.c_str());
1555 m_base->clearHeader(request, rawname, cginame);
1558 request.clearHeader(rawname, cginame);
1562 void XMLApplication::setHeader(SPRequest& request, const char* name, const char* value) const
1564 if (!m_attributePrefix.first.empty()) {
1565 string temp = m_attributePrefix.first + name;
1566 request.setHeader(temp.c_str(), value);
1569 m_base->setHeader(request, name, value);
1572 request.setHeader(name, value);
1576 string XMLApplication::getSecureHeader(const SPRequest& request, const char* name) const
1578 if (!m_attributePrefix.first.empty()) {
1579 string temp = m_attributePrefix.first + name;
1580 return request.getSecureHeader(temp.c_str());
1583 return m_base->getSecureHeader(request,name);
1586 return request.getSecureHeader(name);
1590 const SessionInitiator* XMLApplication::getDefaultSessionInitiator() const
1592 if (m_sessionInitDefault) return m_sessionInitDefault;
1593 return m_base ? m_base->getDefaultSessionInitiator() : nullptr;
1596 const SessionInitiator* XMLApplication::getSessionInitiatorById(const char* id) const
1598 map<string,const SessionInitiator*>::const_iterator i=m_sessionInitMap.find(id);
1599 if (i!=m_sessionInitMap.end()) return i->second;
1600 return m_base ? m_base->getSessionInitiatorById(id) : nullptr;
1603 const Handler* XMLApplication::getDefaultAssertionConsumerService() const
1605 if (m_acsDefault) return m_acsDefault;
1606 return m_base ? m_base->getDefaultAssertionConsumerService() : nullptr;
1609 const Handler* XMLApplication::getAssertionConsumerServiceByIndex(unsigned short index) const
1611 map<unsigned int,const Handler*>::const_iterator i=m_acsIndexMap.find(index);
1612 if (i != m_acsIndexMap.end()) return i->second;
1613 return m_base ? m_base->getAssertionConsumerServiceByIndex(index) : nullptr;
1616 const Handler* XMLApplication::getAssertionConsumerServiceByProtocol(const XMLCh* protocol, const char* binding) const
1618 ACSProtocolMap::const_iterator i=m_acsProtocolMap.find(protocol);
1619 if (i != m_acsProtocolMap.end() && !i->second.empty()) {
1620 if (!binding || !*binding)
1621 return i->second.front();
1622 for (ACSProtocolMap::value_type::second_type::const_iterator j = i->second.begin(); j != i->second.end(); ++j) {
1623 if (!strcmp(binding, (*j)->getString("Binding").second))
1627 return m_base ? m_base->getAssertionConsumerServiceByProtocol(protocol) : nullptr;
1630 const vector<const Handler*>& XMLApplication::getAssertionConsumerServicesByBinding(const XMLCh* binding) const
1632 ACSBindingMap::const_iterator i=m_acsBindingMap.find(binding);
1633 if (i != m_acsBindingMap.end())
1635 return m_base ? m_base->getAssertionConsumerServicesByBinding(binding) : g_noHandlers;
1638 const Handler* XMLApplication::getHandler(const char* path) const
1641 wrap = wrap.substr(0,wrap.find(';'));
1642 map<string,const Handler*>::const_iterator i=m_handlerMap.find(wrap.substr(0,wrap.find('?')));
1643 if (i!=m_handlerMap.end())
1645 return m_base ? m_base->getHandler(path) : nullptr;
1648 void XMLApplication::getHandlers(vector<const Handler*>& handlers) const
1650 handlers.insert(handlers.end(), m_handlers.begin(), m_handlers.end());
1652 for (map<string,const Handler*>::const_iterator h = m_base->m_handlerMap.begin(); h != m_base->m_handlerMap.end(); ++h) {
1653 if (m_handlerMap.count(h->first) == 0)
1654 handlers.push_back(h->second);
1659 #ifdef SHIBSP_XERCESC_SHORT_ACCEPTNODE
1662 DOMNodeFilter::FilterAction
1664 XMLConfigImpl::acceptNode(const DOMNode* node) const
1666 if (!XMLString::equals(node->getNamespaceURI(),shibspconstants::SHIB2SPCONFIG_NS))
1667 return FILTER_ACCEPT;
1668 const XMLCh* name=node->getLocalName();
1669 if (XMLString::equals(name,ApplicationDefaults) ||
1670 XMLString::equals(name,_ArtifactMap) ||
1671 XMLString::equals(name,_Extensions) ||
1672 XMLString::equals(name,Listener) ||
1673 XMLString::equals(name,_ProtocolProvider) ||
1674 XMLString::equals(name,_RequestMapper) ||
1675 XMLString::equals(name,_ReplayCache) ||
1676 XMLString::equals(name,SecurityPolicies) ||
1677 XMLString::equals(name,_SecurityPolicyProvider) ||
1678 XMLString::equals(name,_SessionCache) ||
1679 XMLString::equals(name,Site) ||
1680 XMLString::equals(name,_StorageService) ||
1681 XMLString::equals(name,TCPListener) ||
1682 XMLString::equals(name,TransportOption) ||
1683 XMLString::equals(name,UnixListener))
1684 return FILTER_REJECT;
1686 return FILTER_ACCEPT;
1689 void XMLConfigImpl::doExtensions(const DOMElement* e, const char* label, Category& log)
1691 const DOMElement* exts = XMLHelper::getFirstChildElement(e, _Extensions);
1693 exts = XMLHelper::getFirstChildElement(exts, Library);
1695 string path(XMLHelper::getAttrString(exts, nullptr, _path));
1697 if (!path.empty()) {
1698 if (!XMLToolingConfig::getConfig().load_library(path.c_str(), (void*)exts))
1699 throw ConfigurationException("XMLToolingConfig::load_library failed.");
1700 log.debug("loaded %s extension library (%s)", label, path.c_str());
1703 catch (exception& e) {
1704 if (XMLHelper::getAttrBool(exts, false, _fatal)) {
1705 log.fatal("unable to load mandatory %s extension library %s: %s", label, path.c_str(), e.what());
1709 log.crit("unable to load optional %s extension library %s: %s", label, path.c_str(), e.what());
1712 exts = XMLHelper::getNextSiblingElement(exts, Library);
1717 void XMLConfigImpl::doListener(const DOMElement* e, XMLConfig* conf, Category& log)
1720 string plugtype(TCP_LISTENER_SERVICE);
1722 string plugtype(UNIX_LISTENER_SERVICE);
1724 DOMElement* child = XMLHelper::getFirstChildElement(e, UnixListener);
1726 plugtype = UNIX_LISTENER_SERVICE;
1728 child = XMLHelper::getFirstChildElement(e, TCPListener);
1730 plugtype = TCP_LISTENER_SERVICE;
1732 child = XMLHelper::getFirstChildElement(e, Listener);
1734 auto_ptr_char type(child->getAttributeNS(nullptr, _type));
1735 if (type.get() && *type.get())
1736 plugtype = type.get();
1741 log.info("building ListenerService of type %s...", plugtype.c_str());
1742 conf->m_listener = SPConfig::getConfig().ListenerServiceManager.newPlugin(plugtype.c_str(), child);
1745 void XMLConfigImpl::doCaching(const DOMElement* e, XMLConfig* conf, Category& log)
1747 SPConfig& spConf = SPConfig::getConfig();
1749 SAMLConfig& samlConf = SAMLConfig::getConfig();
1754 if (spConf.isEnabled(SPConfig::OutOfProcess)) {
1755 XMLToolingConfig& xmlConf = XMLToolingConfig::getConfig();
1756 // First build any StorageServices.
1757 child = XMLHelper::getFirstChildElement(e, _StorageService);
1759 string id(XMLHelper::getAttrString(child, nullptr, _id));
1760 string t(XMLHelper::getAttrString(child, nullptr, _type));
1763 log.info("building StorageService (%s) of type %s...", id.c_str(), t.c_str());
1764 conf->m_storage[id] = xmlConf.StorageServiceManager.newPlugin(t.c_str(), child);
1766 catch (exception& ex) {
1767 log.crit("failed to instantiate StorageService (%s): %s", id.c_str(), ex.what());
1770 child = XMLHelper::getNextSiblingElement(child, _StorageService);
1773 if (conf->m_storage.empty()) {
1774 log.info("no StorageService plugin(s) installed, using (mem) in-memory instance");
1775 conf->m_storage["mem"] = xmlConf.StorageServiceManager.newPlugin(MEMORY_STORAGE_SERVICE, nullptr);
1779 StorageService* replaySS = nullptr;
1780 child = XMLHelper::getFirstChildElement(e, _ReplayCache);
1782 string ssid(XMLHelper::getAttrString(child, nullptr, _StorageService));
1783 if (!ssid.empty()) {
1784 if (conf->m_storage.count(ssid)) {
1785 log.info("building ReplayCache on top of StorageService (%s)...", ssid.c_str());
1786 replaySS = conf->m_storage[ssid];
1789 log.error("unable to locate StorageService (%s), using arbitrary instance for ReplayCache", ssid.c_str());
1790 replaySS = conf->m_storage.begin()->second;
1794 log.info("no StorageService specified for ReplayCache, using arbitrary instance");
1795 replaySS = conf->m_storage.begin()->second;
1799 log.info("no ReplayCache specified, using arbitrary StorageService instance");
1800 replaySS = conf->m_storage.begin()->second;
1802 xmlConf.setReplayCache(new ReplayCache(replaySS));
1805 child = XMLHelper::getFirstChildElement(e, _ArtifactMap);
1807 string ssid(XMLHelper::getAttrString(child, nullptr, _StorageService));
1808 if (!ssid.empty()) {
1809 if (conf->m_storage.count(ssid)) {
1810 log.info("building ArtifactMap on top of StorageService (%s)...", ssid.c_str());
1811 samlConf.setArtifactMap(new ArtifactMap(child, conf->m_storage[ssid]));
1814 log.error("unable to locate StorageService (%s), using in-memory ArtifactMap", ssid.c_str());
1815 samlConf.setArtifactMap(new ArtifactMap(child));
1819 log.info("no StorageService specified, using in-memory ArtifactMap");
1820 samlConf.setArtifactMap(new ArtifactMap(child));
1824 log.info("no ArtifactMap specified, building in-memory ArtifactMap...");
1825 samlConf.setArtifactMap(new ArtifactMap(child));
1827 } // end of out of process caching components
1830 child = XMLHelper::getFirstChildElement(e, _SessionCache);
1832 string t(XMLHelper::getAttrString(child, nullptr, _type));
1834 log.info("building SessionCache of type %s...", t.c_str());
1835 conf->m_sessionCache = spConf.SessionCacheManager.newPlugin(t.c_str(), child);
1838 if (!conf->m_sessionCache) {
1839 log.info("no SessionCache specified, using StorageService-backed instance");
1840 conf->m_sessionCache = spConf.SessionCacheManager.newPlugin(STORAGESERVICE_SESSION_CACHE, nullptr);
1844 XMLConfigImpl::XMLConfigImpl(const DOMElement* e, bool first, XMLConfig* outer, Category& log)
1845 : m_requestMapper(nullptr),
1852 xmltooling::NDC ndc("XMLConfigImpl");
1856 SPConfig& conf=SPConfig::getConfig();
1857 XMLToolingConfig& xmlConf=XMLToolingConfig::getConfig();
1858 const DOMElement* SHAR=XMLHelper::getFirstChildElement(e, OutOfProcess);
1859 const DOMElement* SHIRE=XMLHelper::getFirstChildElement(e, InProcess);
1861 // Initialize logging manually in order to redirect log messages as soon as possible.
1862 if (conf.isEnabled(SPConfig::Logging)) {
1864 if (conf.isEnabled(SPConfig::OutOfProcess))
1865 logconf = XMLHelper::getAttrString(SHAR, nullptr, logger);
1866 else if (conf.isEnabled(SPConfig::InProcess))
1867 logconf = XMLHelper::getAttrString(SHIRE, nullptr, logger);
1868 if (logconf.empty())
1869 logconf = XMLHelper::getAttrString(e, nullptr, logger);
1870 if (logconf.empty() && !getenv("SHIBSP_LOGGING")) {
1871 // No properties found, so default them.
1872 if (conf.isEnabled(SPConfig::OutOfProcess) && !conf.isEnabled(SPConfig::InProcess))
1873 logconf = "shibd.logger";
1874 else if (!conf.isEnabled(SPConfig::OutOfProcess) && conf.isEnabled(SPConfig::InProcess))
1875 logconf = "native.logger";
1877 logconf = "shibboleth.logger";
1879 if (!logconf.empty()) {
1880 log.debug("loading new logging configuration from (%s), check log destination for status of configuration", logconf.c_str());
1881 if (!XMLToolingConfig::getConfig().log_config(logconf.c_str()))
1882 log.crit("failed to load new logging configuration from (%s)", logconf.c_str());
1887 outer->m_tranLog = new TransactionLog();
1891 // Re-log library versions now that logging is set up.
1892 log.info("Shibboleth SP Version %s", PACKAGE_VERSION);
1895 "Library versions: %s %s, Xerces-C %s, XML-Security-C %s, XMLTooling-C %s, OpenSAML-C %s, Shibboleth %s",
1896 # if defined(LOG4SHIB_VERSION)
1897 "log4shib", LOG4SHIB_VERSION,
1898 # elif defined(LOG4CPP_VERSION)
1899 "log4cpp", LOG4CPP_VERSION,
1903 XERCES_FULLVERSIONDOT, XSEC_FULLVERSIONDOT, gXMLToolingDotVersionStr, gOpenSAMLDotVersionStr, gShibSPDotVersionStr
1907 "Library versions: %s %s, Xerces-C %s, XMLTooling-C %s, Shibboleth %s",
1908 # if defined(LOG4SHIB_VERSION)
1909 "log4shib", LOG4SHIB_VERSION,
1910 # elif defined(LOG4CPP_VERSION)
1911 "log4cpp", LOG4CPP_VERSION,
1915 XERCES_FULLVERSIONDOT, gXMLToolingDotVersionStr, gShibSPDotVersionStr
1919 // First load any property sets.
1920 load(e,nullptr,this);
1924 // Much of the processing can only occur on the first instantiation.
1927 pair<bool,unsigned int> skew=getUnsignedInt("clockSkew");
1929 xmlConf.clock_skew_secs=min(skew.second,(60*60*24*7*28));
1931 pair<bool,const char*> unsafe = getString("unsafeChars");
1933 TemplateEngine::unsafe_chars = unsafe.second;
1935 unsafe = getString("allowedSchemes");
1937 HTTPResponse::getAllowedSchemes().clear();
1938 string schemes=unsafe.second;
1939 unsigned int j_sch=0;
1940 for (unsigned int i_sch=0; i_sch < schemes.length(); i_sch++) {
1941 if (schemes.at(i_sch)==' ') {
1942 HTTPResponse::getAllowedSchemes().push_back(schemes.substr(j_sch, i_sch-j_sch));
1946 HTTPResponse::getAllowedSchemes().push_back(schemes.substr(j_sch, schemes.length()-j_sch));
1950 doExtensions(e, "global", log);
1951 if (conf.isEnabled(SPConfig::OutOfProcess))
1952 doExtensions(SHAR, "out of process", log);
1954 if (conf.isEnabled(SPConfig::InProcess))
1955 doExtensions(SHIRE, "in process", log);
1957 // Instantiate the ListenerService and SessionCache objects.
1958 if (conf.isEnabled(SPConfig::Listener))
1959 doListener(e, outer, log);
1962 if (outer->m_listener && conf.isEnabled(SPConfig::OutOfProcess) && !conf.isEnabled(SPConfig::InProcess)) {
1963 outer->m_listener->regListener("set::RelayState", outer);
1964 outer->m_listener->regListener("get::RelayState", outer);
1965 outer->m_listener->regListener("set::PostData", outer);
1966 outer->m_listener->regListener("get::PostData", outer);
1969 if (conf.isEnabled(SPConfig::Caching))
1970 doCaching(e, outer, log);
1971 } // end of first-time-only stuff
1973 // Back to the fully dynamic stuff...next up is the RequestMapper.
1974 if (conf.isEnabled(SPConfig::RequestMapping)) {
1975 if (child = XMLHelper::getFirstChildElement(e, _RequestMapper)) {
1976 string t(XMLHelper::getAttrString(child, nullptr, _type));
1978 log.info("building RequestMapper of type %s...", t.c_str());
1979 m_requestMapper = conf.RequestMapperManager.newPlugin(t.c_str(), child);
1982 if (!m_requestMapper) {
1983 log.info("no RequestMapper specified, using 'Native' plugin with empty/default map");
1984 child = e->getOwnerDocument()->createElementNS(nullptr, _RequestMapper);
1985 DOMElement* mapperDummy = e->getOwnerDocument()->createElementNS(shibspconstants::SHIB2SPCONFIG_NS, RequestMap);
1986 mapperDummy->setAttributeNS(nullptr, applicationId, _default);
1987 child->appendChild(mapperDummy);
1988 m_requestMapper = conf.RequestMapperManager.newPlugin(NATIVE_REQUEST_MAPPER, child);
1993 // Load security policies.
1994 if (child = XMLHelper::getLastChildElement(e, _SecurityPolicyProvider)) {
1995 string t(XMLHelper::getAttrString(child, nullptr, _type));
1997 log.info("building SecurityPolicyProvider of type %s...", t.c_str());
1998 m_policy = conf.SecurityPolicyProviderManager.newPlugin(t.c_str(), child);
2001 throw ConfigurationException("can't build SecurityPolicyProvider, no type specified");
2004 else if (child = XMLHelper::getLastChildElement(e, SecurityPolicies)) {
2005 // For backward compatibility, wrap in a plugin element.
2006 DOMElement* polwrapper = e->getOwnerDocument()->createElementNS(nullptr, _SecurityPolicyProvider);
2007 polwrapper->appendChild(child);
2008 log.info("building SecurityPolicyProvider of type %s...", XML_SECURITYPOLICY_PROVIDER);
2009 m_policy = conf.SecurityPolicyProviderManager.newPlugin(XML_SECURITYPOLICY_PROVIDER, polwrapper);
2012 log.fatal("can't build SecurityPolicyProvider, missing conf:SecurityPolicyProvider element?");
2013 throw ConfigurationException("Can't build SecurityPolicyProvider, missing conf:SecurityPolicyProvider element?");
2017 if (!m_policy->getAlgorithmBlacklist().empty()) {
2018 #ifdef SHIBSP_XMLSEC_WHITELISTING
2019 for (vector<xstring>::const_iterator alg = m_policy->getAlgorithmBlacklist().begin(); alg != m_policy->getAlgorithmBlacklist().end(); ++alg)
2020 XSECPlatformUtils::blacklistAlgorithm(alg->c_str());
2022 log.crit("XML-Security-C library prior to 1.6.0 does not support algorithm white/blacklists");
2025 else if (!m_policy->getAlgorithmWhitelist().empty()) {
2026 #ifdef SHIBSP_XMLSEC_WHITELISTING
2027 for (vector<xstring>::const_iterator alg = m_policy->getAlgorithmWhitelist().begin(); alg != m_policy->getAlgorithmWhitelist().end(); ++alg)
2028 XSECPlatformUtils::whitelistAlgorithm(alg->c_str());
2030 log.crit("XML-Security-C library prior to 1.6.0 does not support algorithm white/blacklists");
2035 // Process TransportOption elements.
2036 child = XMLHelper::getLastChildElement(e, TransportOption);
2038 if (child->hasChildNodes()) {
2039 string provider(XMLHelper::getAttrString(child, nullptr, _provider));
2040 string option(XMLHelper::getAttrString(child, nullptr, _option));
2041 auto_ptr_char value(child->getFirstChild()->getNodeValue());
2042 if (!provider.empty() && !option.empty() && value.get() && *value.get()) {
2043 m_transportOptions.push_back(make_pair(provider, make_pair(option, string(value.get()))));
2046 child = XMLHelper::getPreviousSiblingElement(child, TransportOption);
2050 ProtocolProvider* pp = nullptr;
2051 if (conf.isEnabled(SPConfig::Handlers)) {
2052 if (child = XMLHelper::getLastChildElement(e, _ProtocolProvider)) {
2053 string t(XMLHelper::getAttrString(child, nullptr, _type));
2055 log.info("building ProtocolProvider of type %s...", t.c_str());
2056 pp = conf.ProtocolProviderManager.newPlugin(t.c_str(), child);
2060 auto_ptr<ProtocolProvider> ppwrapper(pp);
2061 Locker pplocker(pp);
2063 // Load the default application.
2064 child = XMLHelper::getLastChildElement(e, ApplicationDefaults);
2066 log.fatal("can't build default Application object, missing conf:ApplicationDefaults element?");
2067 throw ConfigurationException("can't build default Application object, missing conf:ApplicationDefaults element?");
2069 XMLApplication* defapp = new XMLApplication(outer, pp, child);
2070 m_appmap[defapp->getId()] = defapp;
2072 // Load any overrides.
2073 child = XMLHelper::getFirstChildElement(child, ApplicationOverride);
2075 auto_ptr<XMLApplication> iapp(new XMLApplication(outer, pp, child, defapp));
2076 if (m_appmap.count(iapp->getId()))
2077 log.crit("found conf:ApplicationOverride element with duplicate id attribute (%s), skipping it", iapp->getId());
2079 const char* iappid=iapp->getId();
2080 m_appmap[iappid] = iapp.release();
2083 child = XMLHelper::getNextSiblingElement(child, ApplicationOverride);
2086 // Check for extra AuthTypes to recognize.
2087 if (conf.isEnabled(SPConfig::InProcess)) {
2088 const PropertySet* inprocs = getPropertySet("InProcess");
2090 pair<bool,const char*> extraAuthTypes = inprocs->getString("extraAuthTypes");
2091 if (extraAuthTypes.first) {
2092 string types=extraAuthTypes.second;
2093 unsigned int j_types=0;
2094 for (unsigned int i_types=0; i_types < types.length(); i_types++) {
2095 if (types.at(i_types) == ' ') {
2096 outer->m_authTypes.insert(types.substr(j_types, i_types - j_types));
2097 j_types = i_types + 1;
2100 outer->m_authTypes.insert(types.substr(j_types, types.length() - j_types));
2105 catch (exception&) {
2111 XMLConfigImpl::~XMLConfigImpl()
2116 void XMLConfigImpl::cleanup()
2118 for_each(m_appmap.begin(),m_appmap.end(),cleanup_pair<string,Application>());
2124 delete m_requestMapper;
2125 m_requestMapper = nullptr;
2127 m_document->release();
2128 m_document = nullptr;
2132 void XMLConfig::receive(DDF& in, ostream& out)
2134 if (!strcmp(in.name(), "get::RelayState")) {
2135 const char* id = in["id"].string();
2136 const char* key = in["key"].string();
2138 throw ListenerException("Required parameters missing for RelayState recovery.");
2141 StorageService* storage = getStorageService(id);
2143 if (storage->readString("RelayState",key,&relayState)>0) {
2144 if (in["clear"].integer())
2145 storage->deleteString("RelayState",key);
2149 Category::getInstance(SHIBSP_LOGCAT".ServiceProvider").error(
2150 "Storage-backed RelayState with invalid StorageService ID (%s)", id
2154 // Repack for return to caller.
2155 DDF ret=DDF(nullptr).unsafe_string(relayState.c_str());
2156 DDFJanitor jret(ret);
2159 else if (!strcmp(in.name(), "set::RelayState")) {
2160 const char* id = in["id"].string();
2161 const char* value = in["value"].string();
2163 throw ListenerException("Required parameters missing for RelayState creation.");
2166 StorageService* storage = getStorageService(id);
2168 SAMLConfig::getConfig().generateRandomBytes(rsKey,20);
2169 rsKey = SAMLArtifact::toHex(rsKey);
2170 storage->createString("RelayState", rsKey.c_str(), value, time(nullptr) + 600);
2173 Category::getInstance(SHIBSP_LOGCAT".ServiceProvider").error(
2174 "Storage-backed RelayState with invalid StorageService ID (%s)", id
2178 // Repack for return to caller.
2179 DDF ret=DDF(nullptr).string(rsKey.c_str());
2180 DDFJanitor jret(ret);
2183 else if (!strcmp(in.name(), "get::PostData")) {
2184 const char* id = in["id"].string();
2185 const char* key = in["key"].string();
2187 throw ListenerException("Required parameters missing for PostData recovery.");
2190 StorageService* storage = getStorageService(id);
2192 if (storage->readString("PostData",key,&postData) > 0) {
2193 storage->deleteString("PostData",key);
2197 Category::getInstance(SHIBSP_LOGCAT".ServiceProvider").error(
2198 "Storage-backed PostData with invalid StorageService ID (%s)", id
2201 // If the data's empty, we'll send nothing back.
2202 // If not, we don't need to round trip it, just send back the serialized DDF list.
2203 if (postData.empty()) {
2205 DDFJanitor jret(ret);
2212 else if (!strcmp(in.name(), "set::PostData")) {
2213 const char* id = in["id"].string();
2214 if (!id || !in["parameters"].islist())
2215 throw ListenerException("Required parameters missing for PostData creation.");
2218 StorageService* storage = getStorageService(id);
2220 SAMLConfig::getConfig().generateRandomBytes(rsKey,20);
2221 rsKey = SAMLArtifact::toHex(rsKey);
2222 ostringstream params;
2223 params << in["parameters"];
2224 storage->createString("PostData", rsKey.c_str(), params.str().c_str(), time(nullptr) + 600);
2227 Category::getInstance(SHIBSP_LOGCAT".ServiceProvider").error(
2228 "Storage-backed PostData with invalid StorageService ID (%s)", id
2232 // Repack for return to caller.
2233 DDF ret=DDF(nullptr).string(rsKey.c_str());
2234 DDFJanitor jret(ret);
2240 pair<bool,DOMElement*> XMLConfig::background_load()
2242 // Load from source using base class.
2243 pair<bool,DOMElement*> raw = ReloadableXMLFile::load();
2245 // If we own it, wrap it.
2246 XercesJanitor<DOMDocument> docjanitor(raw.first ? raw.second->getOwnerDocument() : nullptr);
2248 XMLConfigImpl* impl = new XMLConfigImpl(raw.second, (m_impl==nullptr), this, m_log);
2250 // If we held the document, transfer it to the impl. If we didn't, it's a no-op.
2251 impl->setDocument(docjanitor.release());
2253 // Perform the swap inside a lock.
2256 SharedLock locker(m_lock, false);
2260 return make_pair(false,(DOMElement*)nullptr);