2 * Copyright 2001-2010 Internet2
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
18 * XMLServiceProvider.cpp
20 * XML-based SP configuration and mgmt.
24 #include "exceptions.h"
26 #include "AccessControl.h"
27 #include "Application.h"
28 #include "RequestMapper.h"
29 #include "ServiceProvider.h"
30 #include "SessionCache.h"
32 #include "SPRequest.h"
33 #include "binding/ProtocolProvider.h"
34 #include "handler/LogoutInitiator.h"
35 #include "handler/SessionInitiator.h"
36 #include "remoting/ListenerService.h"
37 #include "util/DOMPropertySet.h"
38 #include "util/SPConstants.h"
40 #if defined(XMLTOOLING_LOG4SHIB)
41 # include <log4shib/PropertyConfigurator.hh>
42 #elif defined(XMLTOOLING_LOG4CPP)
43 # include <log4cpp/PropertyConfigurator.hh>
45 # error "Supported logging library not available."
48 #include <xercesc/util/XMLUniDefs.hpp>
49 #include <xercesc/util/XMLStringTokenizer.hpp>
50 #include <xmltooling/XMLToolingConfig.h>
51 #include <xmltooling/version.h>
52 #include <xmltooling/util/NDC.h>
53 #include <xmltooling/util/ReloadableXMLFile.h>
54 #include <xmltooling/util/TemplateEngine.h>
55 #include <xmltooling/util/Threads.h>
56 #include <xmltooling/util/XMLHelper.h>
59 # include "TransactionLog.h"
60 # include "attribute/filtering/AttributeFilter.h"
61 # include "attribute/resolver/AttributeExtractor.h"
62 # include "attribute/resolver/AttributeResolver.h"
63 # include "security/PKIXTrustEngine.h"
64 # include "security/SecurityPolicyProvider.h"
65 # include <saml/SAMLConfig.h>
66 # include <saml/version.h>
67 # include <saml/binding/ArtifactMap.h>
68 # include <saml/binding/SAMLArtifact.h>
69 # include <saml/saml1/core/Assertions.h>
70 # include <saml/saml2/core/Assertions.h>
71 # include <saml/saml2/binding/SAML2ArtifactType0004.h>
72 # include <saml/saml2/metadata/Metadata.h>
73 # include <saml/saml2/metadata/MetadataProvider.h>
74 # include <saml/util/SAMLConstants.h>
75 # include <xmltooling/security/ChainingTrustEngine.h>
76 # include <xmltooling/security/CredentialResolver.h>
77 # include <xmltooling/security/SecurityHelper.h>
78 # include <xmltooling/util/ReplayCache.h>
79 # include <xmltooling/util/StorageService.h>
80 # include <xsec/utils/XSECPlatformUtils.hpp>
81 using namespace opensaml::saml2;
82 using namespace opensaml::saml2p;
83 using namespace opensaml::saml2md;
84 using namespace opensaml;
86 # include "lite/SAMLConstants.h"
89 using namespace shibsp;
90 using namespace xmltooling;
94 # define min(a,b) (((a) < (b)) ? (a) : (b))
99 #if defined (_MSC_VER)
100 #pragma warning( push )
101 #pragma warning( disable : 4250 )
104 static vector<const Handler*> g_noHandlers;
106 // Application configuration wrapper
107 class SHIBSP_DLLLOCAL XMLApplication : public Application, public Remoted, public DOMPropertySet, public DOMNodeFilter
110 XMLApplication(const ServiceProvider*, const ProtocolProvider*, DOMElement*, const XMLApplication* base=nullptr);
111 ~XMLApplication() { cleanup(); }
113 const char* getHash() const {return m_hash.c_str();}
116 SAMLArtifact* generateSAML1Artifact(const EntityDescriptor* relyingParty) const {
117 throw ConfigurationException("No support for SAML 1.x artifact generation.");
119 SAML2Artifact* generateSAML2Artifact(const EntityDescriptor* relyingParty) const {
120 pair<bool,int> index = make_pair(false,0);
121 const PropertySet* props = getRelyingParty(relyingParty);
122 index = props->getInt("artifactEndpointIndex");
124 index = getArtifactEndpointIndex();
125 pair<bool,const char*> entityID = props->getString("entityID");
126 return new SAML2ArtifactType0004(
127 SecurityHelper::doHash("SHA1", entityID.second, strlen(entityID.second), false),
128 index.first ? index.second : 1
132 MetadataProvider* getMetadataProvider(bool required=true) const {
133 if (required && !m_base && !m_metadata)
134 throw ConfigurationException("No MetadataProvider available.");
135 return (!m_metadata && m_base) ? m_base->getMetadataProvider() : m_metadata;
137 TrustEngine* getTrustEngine(bool required=true) const {
138 if (required && !m_base && !m_trust)
139 throw ConfigurationException("No TrustEngine available.");
140 return (!m_trust && m_base) ? m_base->getTrustEngine() : m_trust;
142 AttributeExtractor* getAttributeExtractor() const {
143 return (!m_attrExtractor && m_base) ? m_base->getAttributeExtractor() : m_attrExtractor;
145 AttributeFilter* getAttributeFilter() const {
146 return (!m_attrFilter && m_base) ? m_base->getAttributeFilter() : m_attrFilter;
148 AttributeResolver* getAttributeResolver() const {
149 return (!m_attrResolver && m_base) ? m_base->getAttributeResolver() : m_attrResolver;
151 CredentialResolver* getCredentialResolver() const {
152 return (!m_credResolver && m_base) ? m_base->getCredentialResolver() : m_credResolver;
154 const PropertySet* getRelyingParty(const EntityDescriptor* provider) const;
155 const PropertySet* getRelyingParty(const XMLCh* entityID) const;
156 const vector<const XMLCh*>* getAudiences() const {
157 return (m_audiences.empty() && m_base) ? m_base->getAudiences() : &m_audiences;
160 string getNotificationURL(const char* resource, bool front, unsigned int index) const;
162 const vector<string>& getRemoteUserAttributeIds() const {
163 return (m_remoteUsers.empty() && m_base) ? m_base->getRemoteUserAttributeIds() : m_remoteUsers;
166 void clearHeader(SPRequest& request, const char* rawname, const char* cginame) const;
167 void setHeader(SPRequest& request, const char* name, const char* value) const;
168 string getSecureHeader(const SPRequest& request, const char* name) const;
170 const SessionInitiator* getDefaultSessionInitiator() const;
171 const SessionInitiator* getSessionInitiatorById(const char* id) const;
172 const Handler* getDefaultAssertionConsumerService() const;
173 const Handler* getAssertionConsumerServiceByIndex(unsigned short index) const;
174 const Handler* getAssertionConsumerServiceByProtocol(const XMLCh* protocol, const char* binding=nullptr) const;
175 const vector<const Handler*>& getAssertionConsumerServicesByBinding(const XMLCh* binding) const;
176 const Handler* getHandler(const char* path) const;
177 void getHandlers(vector<const Handler*>& handlers) const;
179 void receive(DDF& in, ostream& out) {
180 // Only current function is to return the headers to clear.
182 DDF ret=DDF(nullptr).list();
183 DDFJanitor jret(ret);
184 for (vector< pair<string,string> >::const_iterator i = m_unsetHeaders.begin(); i!=m_unsetHeaders.end(); ++i) {
185 header = DDF(i->first.c_str()).string(i->second.c_str());
191 // Provides filter to exclude special config elements.
192 #ifdef SHIBSP_XERCESC_SHORT_ACCEPTNODE
197 acceptNode(const DOMNode* node) const;
200 template <class T> T* doChainedPlugins(
201 PluginManager<T,string,const DOMElement*>& pluginMgr,
202 const char* pluginType,
203 const char* chainingType,
204 const XMLCh* localName,
208 void doAttributeInfo();
209 void doHandlers(const ProtocolProvider*, const DOMElement*, Category&);
210 void doSSO(const ProtocolProvider&, set<string>&, DOMElement*, Category&);
211 void doLogout(const ProtocolProvider&, set<string>&, DOMElement*, Category&);
212 void doNameIDMgmt(const ProtocolProvider&, set<string>&, DOMElement*, Category&);
213 void doArtifactResolution(const ProtocolProvider&, const char*, DOMElement*, Category&);
215 const XMLApplication* m_base;
217 std::pair<std::string,std::string> m_attributePrefix;
219 void doAttributePlugins(DOMElement* e, Category& log);
220 MetadataProvider* m_metadata;
221 TrustEngine* m_trust;
222 AttributeExtractor* m_attrExtractor;
223 AttributeFilter* m_attrFilter;
224 AttributeResolver* m_attrResolver;
225 CredentialResolver* m_credResolver;
226 vector<const XMLCh*> m_audiences;
228 // RelyingParty properties
229 map<xstring,PropertySet*> m_partyMap;
231 vector<string> m_remoteUsers,m_frontLogout,m_backLogout;
233 // manage handler objects
234 vector<Handler*> m_handlers;
236 // maps location (path info) to applicable handlers
237 map<string,const Handler*> m_handlerMap;
239 // maps unique indexes to consumer services
240 map<unsigned int,const Handler*> m_acsIndexMap;
242 // pointer to default consumer service
243 const Handler* m_acsDefault;
245 // maps binding strings to supporting consumer service(s)
246 typedef map< xstring,vector<const Handler*> > ACSBindingMap;
247 ACSBindingMap m_acsBindingMap;
249 // maps protocol strings to supporting consumer service(s)
250 typedef map< xstring,vector<const Handler*> > ACSProtocolMap;
251 ACSProtocolMap m_acsProtocolMap;
253 // pointer to default session initiator
254 const SessionInitiator* m_sessionInitDefault;
256 // maps unique ID strings to session initiators
257 map<string,const SessionInitiator*> m_sessionInitMap;
259 // pointer to default artifact resolution service
260 const Handler* m_artifactResolutionDefault;
262 pair<bool,int> getArtifactEndpointIndex() const {
263 if (m_artifactResolutionDefault) return m_artifactResolutionDefault->getInt("index");
264 return m_base ? m_base->getArtifactEndpointIndex() : make_pair(false,0);
268 // Top-level configuration implementation
269 class SHIBSP_DLLLOCAL XMLConfig;
270 class SHIBSP_DLLLOCAL XMLConfigImpl : public DOMPropertySet, public DOMNodeFilter
273 XMLConfigImpl(const DOMElement* e, bool first, XMLConfig* outer, Category& log);
276 RequestMapper* m_requestMapper;
277 map<string,Application*> m_appmap;
279 SecurityPolicyProvider* m_policy;
280 vector< pair< string, pair<string,string> > > m_transportOptions;
283 // Provides filter to exclude special config elements.
284 #ifdef SHIBSP_XERCESC_SHORT_ACCEPTNODE
289 acceptNode(const DOMNode* node) const;
291 void setDocument(DOMDocument* doc) {
296 void doExtensions(const DOMElement*, const char*, Category&);
297 void doListener(const DOMElement*, XMLConfig*, Category&);
298 void doCaching(const DOMElement*, XMLConfig*, Category&);
301 DOMDocument* m_document;
304 class SHIBSP_DLLLOCAL XMLConfig : public ServiceProvider, public ReloadableXMLFile
310 XMLConfig(const DOMElement* e) : ReloadableXMLFile(e, Category::getInstance(SHIBSP_LOGCAT".Config")),
311 m_impl(nullptr), m_listener(nullptr), m_sessionCache(nullptr)
325 delete m_sessionCache;
329 SAMLConfig::getConfig().setArtifactMap(nullptr);
330 XMLToolingConfig::getConfig().setReplayCache(nullptr);
331 for_each(m_storage.begin(), m_storage.end(), cleanup_pair<string,StorageService>());
338 ReloadableXMLFile::lock();
339 if (m_impl->m_policy)
340 m_impl->m_policy->lock();
344 if (m_impl->m_policy)
345 m_impl->m_policy->unlock();
346 ReloadableXMLFile::unlock();
351 const PropertySet* getParent() const { return m_impl->getParent(); }
352 void setParent(const PropertySet* parent) {return m_impl->setParent(parent);}
353 pair<bool,bool> getBool(const char* name, const char* ns=nullptr) const {return m_impl->getBool(name,ns);}
354 pair<bool,const char*> getString(const char* name, const char* ns=nullptr) const {return m_impl->getString(name,ns);}
355 pair<bool,const XMLCh*> getXMLString(const char* name, const char* ns=nullptr) const {return m_impl->getXMLString(name,ns);}
356 pair<bool,unsigned int> getUnsignedInt(const char* name, const char* ns=nullptr) const {return m_impl->getUnsignedInt(name,ns);}
357 pair<bool,int> getInt(const char* name, const char* ns=nullptr) const {return m_impl->getInt(name,ns);}
358 void getAll(map<string,const char*>& properties) const {return m_impl->getAll(properties);}
359 const PropertySet* getPropertySet(const char* name, const char* ns="urn:mace:shibboleth:2.0:native:sp:config") const {return m_impl->getPropertySet(name,ns);}
360 const DOMElement* getElement() const {return m_impl->getElement();}
365 void receive(DDF& in, ostream& out);
367 TransactionLog* getTransactionLog() const {
370 throw ConfigurationException("No TransactionLog available.");
373 StorageService* getStorageService(const char* id) const {
375 map<string,StorageService*>::const_iterator i=m_storage.find(id);
376 if (i!=m_storage.end())
379 else if (!m_storage.empty())
380 return m_storage.begin()->second;
385 ListenerService* getListenerService(bool required=true) const {
386 if (required && !m_listener)
387 throw ConfigurationException("No ListenerService available.");
391 SessionCache* getSessionCache(bool required=true) const {
392 if (required && !m_sessionCache)
393 throw ConfigurationException("No SessionCache available.");
394 return m_sessionCache;
397 RequestMapper* getRequestMapper(bool required=true) const {
398 if (required && !m_impl->m_requestMapper)
399 throw ConfigurationException("No RequestMapper available.");
400 return m_impl->m_requestMapper;
403 const Application* getApplication(const char* applicationId) const {
404 map<string,Application*>::const_iterator i=m_impl->m_appmap.find(applicationId ? applicationId : "default");
405 return (i!=m_impl->m_appmap.end()) ? i->second : nullptr;
409 SecurityPolicyProvider* getSecurityPolicyProvider(bool required=true) const {
410 if (required && !m_impl->m_policy)
411 throw ConfigurationException("No SecurityPolicyProvider available.");
412 return m_impl->m_policy;
415 const PropertySet* getPolicySettings(const char* id) const {
416 return getSecurityPolicyProvider()->getPolicySettings(id);
419 const vector<const SecurityPolicyRule*>& getPolicyRules(const char* id) const {
420 return getSecurityPolicyProvider()->getPolicyRules(id);
423 bool setTransportOptions(SOAPTransport& transport) const {
425 vector< pair< string, pair<string,string> > >::const_iterator opt;
426 for (opt = m_impl->m_transportOptions.begin(); opt != m_impl->m_transportOptions.end(); ++opt) {
427 if (!transport.setProviderOption(opt->first.c_str(), opt->second.first.c_str(), opt->second.second.c_str())) {
428 m_log.error("failed to set SOAPTransport option (%s)", opt->second.first.c_str());
437 pair<bool,DOMElement*> background_load();
440 friend class XMLConfigImpl;
441 XMLConfigImpl* m_impl;
442 ListenerService* m_listener;
443 SessionCache* m_sessionCache;
445 TransactionLog* m_tranLog;
446 map<string,StorageService*> m_storage;
450 #if defined (_MSC_VER)
451 #pragma warning( pop )
454 static const XMLCh applicationId[] = UNICODE_LITERAL_13(a,p,p,l,i,c,a,t,i,o,n,I,d);
455 static const XMLCh ApplicationOverride[] = UNICODE_LITERAL_19(A,p,p,l,i,c,a,t,i,o,n,O,v,e,r,r,i,d,e);
456 static const XMLCh ApplicationDefaults[] = UNICODE_LITERAL_19(A,p,p,l,i,c,a,t,i,o,n,D,e,f,a,u,l,t,s);
457 static const XMLCh _ArtifactMap[] = UNICODE_LITERAL_11(A,r,t,i,f,a,c,t,M,a,p);
458 static const XMLCh _AttributeExtractor[] = UNICODE_LITERAL_18(A,t,t,r,i,b,u,t,e,E,x,t,r,a,c,t,o,r);
459 static const XMLCh _AttributeFilter[] = UNICODE_LITERAL_15(A,t,t,r,i,b,u,t,e,F,i,l,t,e,r);
460 static const XMLCh _AttributeResolver[] = UNICODE_LITERAL_17(A,t,t,r,i,b,u,t,e,R,e,s,o,l,v,e,r);
461 static const XMLCh _AssertionConsumerService[] = UNICODE_LITERAL_24(A,s,s,e,r,t,i,o,n,C,o,n,s,u,m,e,r,S,e,r,v,i,c,e);
462 static const XMLCh _ArtifactResolutionService[] =UNICODE_LITERAL_25(A,r,t,i,f,a,c,t,R,e,s,o,l,u,t,i,o,n,S,e,r,v,i,c,e);
463 static const XMLCh _Audience[] = UNICODE_LITERAL_8(A,u,d,i,e,n,c,e);
464 static const XMLCh Binding[] = UNICODE_LITERAL_7(B,i,n,d,i,n,g);
465 static const XMLCh Channel[]= UNICODE_LITERAL_7(C,h,a,n,n,e,l);
466 static const XMLCh _CredentialResolver[] = UNICODE_LITERAL_18(C,r,e,d,e,n,t,i,a,l,R,e,s,o,l,v,e,r);
467 static const XMLCh _default[] = UNICODE_LITERAL_7(d,e,f,a,u,l,t);
468 static const XMLCh _Extensions[] = UNICODE_LITERAL_10(E,x,t,e,n,s,i,o,n,s);
469 static const XMLCh _fatal[] = UNICODE_LITERAL_5(f,a,t,a,l);
470 static const XMLCh _Handler[] = UNICODE_LITERAL_7(H,a,n,d,l,e,r);
471 static const XMLCh _id[] = UNICODE_LITERAL_2(i,d);
472 static const XMLCh _index[] = UNICODE_LITERAL_5(i,n,d,e,x);
473 static const XMLCh InProcess[] = UNICODE_LITERAL_9(I,n,P,r,o,c,e,s,s);
474 static const XMLCh Library[] = UNICODE_LITERAL_7(L,i,b,r,a,r,y);
475 static const XMLCh Listener[] = UNICODE_LITERAL_8(L,i,s,t,e,n,e,r);
476 static const XMLCh Location[] = UNICODE_LITERAL_8(L,o,c,a,t,i,o,n);
477 static const XMLCh logger[] = UNICODE_LITERAL_6(l,o,g,g,e,r);
478 static const XMLCh Logout[] = UNICODE_LITERAL_6(L,o,g,o,u,t);
479 static const XMLCh _LogoutInitiator[] = UNICODE_LITERAL_15(L,o,g,o,u,t,I,n,i,t,i,a,t,o,r);
480 static const XMLCh _ManageNameIDService[] = UNICODE_LITERAL_19(M,a,n,a,g,e,N,a,m,e,I,D,S,e,r,v,i,c,e);
481 static const XMLCh _MetadataProvider[] = UNICODE_LITERAL_16(M,e,t,a,d,a,t,a,P,r,o,v,i,d,e,r);
482 static const XMLCh NameIDMgmt[] = UNICODE_LITERAL_10(N,a,m,e,I,D,M,g,m,t);
483 static const XMLCh Notify[] = UNICODE_LITERAL_6(N,o,t,i,f,y);
484 static const XMLCh _option[] = UNICODE_LITERAL_6(o,p,t,i,o,n);
485 static const XMLCh OutOfProcess[] = UNICODE_LITERAL_12(O,u,t,O,f,P,r,o,c,e,s,s);
486 static const XMLCh _path[] = UNICODE_LITERAL_4(p,a,t,h);
487 static const XMLCh _ProtocolProvider[] = UNICODE_LITERAL_16(P,r,o,t,o,c,o,l,P,r,o,v,i,d,e,r);
488 static const XMLCh _provider[] = UNICODE_LITERAL_8(p,r,o,v,i,d,e,r);
489 static const XMLCh RelyingParty[] = UNICODE_LITERAL_12(R,e,l,y,i,n,g,P,a,r,t,y);
490 static const XMLCh _ReplayCache[] = UNICODE_LITERAL_11(R,e,p,l,a,y,C,a,c,h,e);
491 static const XMLCh _RequestMapper[] = UNICODE_LITERAL_13(R,e,q,u,e,s,t,M,a,p,p,e,r);
492 static const XMLCh RequestMap[] = UNICODE_LITERAL_10(R,e,q,u,e,s,t,M,a,p);
493 static const XMLCh SecurityPolicies[] = UNICODE_LITERAL_16(S,e,c,u,r,i,t,y,P,o,l,i,c,i,e,s);
494 static const XMLCh _SecurityPolicyProvider[] = UNICODE_LITERAL_22(S,e,c,u,r,i,t,y,P,o,l,i,c,y,P,r,o,v,i,d,e,r);
495 static const XMLCh _SessionCache[] = UNICODE_LITERAL_12(S,e,s,s,i,o,n,C,a,c,h,e);
496 static const XMLCh _SessionInitiator[] = UNICODE_LITERAL_16(S,e,s,s,i,o,n,I,n,i,t,i,a,t,o,r);
497 static const XMLCh _SingleLogoutService[] = UNICODE_LITERAL_19(S,i,n,g,l,e,L,o,g,o,u,t,S,e,r,v,i,c,e);
498 static const XMLCh Site[] = UNICODE_LITERAL_4(S,i,t,e);
499 static const XMLCh SSO[] = UNICODE_LITERAL_3(S,S,O);
500 static const XMLCh _StorageService[] = UNICODE_LITERAL_14(S,t,o,r,a,g,e,S,e,r,v,i,c,e);
501 static const XMLCh TCPListener[] = UNICODE_LITERAL_11(T,C,P,L,i,s,t,e,n,e,r);
502 static const XMLCh TransportOption[] = UNICODE_LITERAL_15(T,r,a,n,s,p,o,r,t,O,p,t,i,o,n);
503 static const XMLCh _TrustEngine[] = UNICODE_LITERAL_11(T,r,u,s,t,E,n,g,i,n,e);
504 static const XMLCh _type[] = UNICODE_LITERAL_4(t,y,p,e);
505 static const XMLCh UnixListener[] = UNICODE_LITERAL_12(U,n,i,x,L,i,s,t,e,n,e,r);
509 ServiceProvider* XMLServiceProviderFactory(const DOMElement* const & e)
511 return new XMLConfig(e);
515 XMLApplication::XMLApplication(
516 const ServiceProvider* sp,
517 const ProtocolProvider* pp,
519 const XMLApplication* base
520 ) : Application(sp), m_base(base),
522 m_metadata(nullptr), m_trust(nullptr),
523 m_attrExtractor(nullptr), m_attrFilter(nullptr), m_attrResolver(nullptr),
524 m_credResolver(nullptr),
526 m_acsDefault(nullptr), m_sessionInitDefault(nullptr), m_artifactResolutionDefault(nullptr)
529 xmltooling::NDC ndc("XMLApplication");
531 Category& log=Category::getInstance(SHIBSP_LOGCAT".Application");
534 // First load any property sets.
535 load(e,nullptr,this);
539 SPConfig& conf=SPConfig::getConfig();
541 XMLToolingConfig& xmlConf=XMLToolingConfig::getConfig();
544 // This used to be an actual hash, but now it's just a hex-encode to avoid xmlsec dependency.
545 static char DIGITS[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
546 string tohash=getId();
547 tohash+=getString("entityID").second;
548 for (const char* ch = tohash.c_str(); *ch; ++ch) {
549 m_hash += (DIGITS[((unsigned char)(0xF0 & *ch)) >> 4 ]);
550 m_hash += (DIGITS[0x0F & *ch]);
555 if (conf.isEnabled(SPConfig::Handlers))
556 doHandlers(pp, e, log);
559 DOMNodeList* nlist = e->getElementsByTagNameNS(shibspconstants::SHIB2SPCONFIG_NS, Notify);
560 for (XMLSize_t i = 0; nlist && i < nlist->getLength(); ++i) {
561 if (nlist->item(i)->getParentNode()->isSameNode(e)) {
562 const XMLCh* channel = static_cast<DOMElement*>(nlist->item(i))->getAttributeNS(nullptr, Channel);
563 string loc(XMLHelper::getAttrString(static_cast<DOMElement*>(nlist->item(i)), nullptr, Location));
565 if (channel && *channel == chLatin_f)
566 m_frontLogout.push_back(loc);
568 m_backLogout.push_back(loc);
574 nlist = e->getElementsByTagNameNS(samlconstants::SAML20_NS, Audience::LOCAL_NAME);
575 if (nlist && nlist->getLength()) {
576 log.warn("use of <saml:Audience> elements outside of a Security Policy Rule is deprecated");
577 for (XMLSize_t i = 0; i < nlist->getLength(); ++i)
578 if (nlist->item(i)->getParentNode()->isSameNode(e) && nlist->item(i)->hasChildNodes())
579 m_audiences.push_back(nlist->item(i)->getFirstChild()->getNodeValue());
582 if (conf.isEnabled(SPConfig::Metadata)) {
583 auto_ptr<MetadataProvider> mp(
585 SAMLConfig::getConfig().MetadataProviderManager, "MetadataProvider", CHAINING_METADATA_PROVIDER, _MetadataProvider, e, log
591 m_metadata = mp.release();
594 log.crit("no MetadataProvider available, configuration is probably unusable");
597 catch (exception& ex) {
598 log.crit("error initializing MetadataProvider: %s", ex.what());
602 if (conf.isEnabled(SPConfig::Trust)) {
603 m_trust = doChainedPlugins(xmlConf.TrustEngineManager, "TrustEngine", CHAINING_TRUSTENGINE, _TrustEngine, e, log);
604 if (!m_trust && !m_base) {
606 "no TrustEngine specified or installed, using default chain {%s, %s}",
607 EXPLICIT_KEY_TRUSTENGINE, SHIBBOLETH_PKIX_TRUSTENGINE
609 m_trust = xmlConf.TrustEngineManager.newPlugin(CHAINING_TRUSTENGINE, nullptr);
610 ChainingTrustEngine* trustchain = dynamic_cast<ChainingTrustEngine*>(m_trust);
612 trustchain->addTrustEngine(xmlConf.TrustEngineManager.newPlugin(EXPLICIT_KEY_TRUSTENGINE, nullptr));
613 trustchain->addTrustEngine(xmlConf.TrustEngineManager.newPlugin(SHIBBOLETH_PKIX_TRUSTENGINE, nullptr));
618 if (conf.isEnabled(SPConfig::AttributeResolution))
619 doAttributePlugins(e, log);
621 if (conf.isEnabled(SPConfig::Credentials)) {
622 m_credResolver = doChainedPlugins(
623 xmlConf.CredentialResolverManager, "CredentialResolver", CHAINING_CREDENTIAL_RESOLVER, _CredentialResolver, e, log
627 // Finally, load relying parties.
628 const DOMElement* child = XMLHelper::getFirstChildElement(e, RelyingParty);
630 if (child->hasAttributeNS(nullptr, saml2::Attribute::NAME_ATTRIB_NAME)) {
631 auto_ptr<DOMPropertySet> rp(new DOMPropertySet());
632 rp->load(child, nullptr, this);
634 m_partyMap[child->getAttributeNS(nullptr, saml2::Attribute::NAME_ATTRIB_NAME)] = rp.release();
636 child = XMLHelper::getNextSiblingElement(child, RelyingParty);
638 if (base && m_partyMap.empty() && !base->m_partyMap.empty()) {
639 // For inheritance of RPs to work, we have to pull them in to the override by cloning the DOM.
640 child = XMLHelper::getFirstChildElement(base->getElement(), RelyingParty);
642 if (child->hasAttributeNS(nullptr, saml2::Attribute::NAME_ATTRIB_NAME)) {
643 DOMElement* rpclone = static_cast<DOMElement*>(child->cloneNode(true));
644 auto_ptr<DOMPropertySet> rp(new DOMPropertySet());
645 rp->load(rpclone, nullptr, this);
647 m_partyMap[rpclone->getAttributeNS(nullptr, saml2::Attribute::NAME_ATTRIB_NAME)] = rp.release();
649 child = XMLHelper::getNextSiblingElement(child, RelyingParty);
654 // Out of process only, we register a listener endpoint.
655 if (!conf.isEnabled(SPConfig::InProcess)) {
656 ListenerService* listener = sp->getListenerService(false);
658 string addr=string(getId()) + "::getHeaders::Application";
659 listener->regListener(addr.c_str(),this);
662 log.info("no ListenerService available, Application remoting disabled");
678 template <class T> T* XMLApplication::doChainedPlugins(
679 PluginManager<T,string,const DOMElement*>& pluginMgr,
680 const char* pluginType,
681 const char* chainingType,
682 const XMLCh* localName,
688 DOMElement* child = XMLHelper::getFirstChildElement(e, localName);
690 // Check for multiple.
691 if (XMLHelper::getNextSiblingElement(child, localName)) {
692 log.info("multiple %s plugins, wrapping in a chain", pluginType);
693 DOMElement* chain = child->getOwnerDocument()->createElementNS(nullptr, localName);
695 chain->appendChild(child);
696 child = XMLHelper::getFirstChildElement(e, localName);
700 e->appendChild(chain);
703 // Only a single one.
704 t = XMLHelper::getAttrString(child, nullptr, _type);
709 log.info("building %s of type %s...", pluginType, t.c_str());
710 return pluginMgr.newPlugin(t.c_str(), child);
713 throw ConfigurationException("$1 element had no type attribute.", params(1, pluginType));
716 catch (exception& ex) {
717 log.crit("error building %s: %s", pluginType, ex.what());
724 void XMLApplication::doAttributeInfo()
726 // Populate prefix pair.
727 m_attributePrefix.second = "HTTP_";
728 pair<bool,const char*> prefix = getString("attributePrefix");
730 m_attributePrefix.first = prefix.second;
731 const char* pch = prefix.second;
733 m_attributePrefix.second += (isalnum(*pch) ? toupper(*pch) : '_');
738 // Load attribute ID lists for REMOTE_USER and header clearing.
739 if (SPConfig::getConfig().isEnabled(SPConfig::InProcess)) {
740 pair<bool,const char*> attributes = getString("REMOTE_USER");
741 if (attributes.first) {
742 char* dup = strdup(attributes.second);
745 while (start && *start) {
746 while (*start && isspace(*start))
750 pos = strchr(start,' ');
753 m_remoteUsers.push_back(start);
754 start = pos ? pos+1 : nullptr;
759 attributes = getString("unsetHeaders");
760 if (attributes.first) {
761 string transformedprefix(m_attributePrefix.second);
763 prefix = getString("metadataAttributePrefix");
767 transformedprefix += (isalnum(*pch) ? toupper(*pch) : '_');
771 char* dup = strdup(attributes.second);
774 while (start && *start) {
775 while (*start && isspace(*start))
779 pos = strchr(start,' ');
786 transformed += (isalnum(*pch) ? toupper(*pch) : '_');
790 m_unsetHeaders.push_back(pair<string,string>(m_attributePrefix.first + start, m_attributePrefix.second + transformed));
792 m_unsetHeaders.push_back(pair<string,string>(m_attributePrefix.first + prefix.second + start, transformedprefix + transformed));
793 start = pos ? pos+1 : nullptr;
796 m_unsetHeaders.push_back(pair<string,string>(m_attributePrefix.first + "Shib-Application-ID", m_attributePrefix.second + "SHIB_APPLICATION_ID"));
801 void XMLApplication::doHandlers(const ProtocolProvider* pp, const DOMElement* e, Category& log)
803 SPConfig& conf = SPConfig::getConfig();
805 Handler* handler = nullptr;
806 const PropertySet* sessions = getPropertySet("Sessions");
808 // Process assertion export handler.
809 pair<bool,const char*> location = sessions ? sessions->getString("exportLocation") : pair<bool,const char*>(false,nullptr);
810 if (location.first) {
812 DOMElement* exportElement = e->getOwnerDocument()->createElementNS(shibspconstants::SHIB2SPCONFIG_NS, _Handler);
813 exportElement->setAttributeNS(nullptr,Location,sessions->getXMLString("exportLocation").second);
814 pair<bool,const XMLCh*> exportACL = sessions->getXMLString("exportACL");
815 if (exportACL.first) {
816 static const XMLCh _acl[] = UNICODE_LITERAL_9(e,x,p,o,r,t,A,C,L);
817 exportElement->setAttributeNS(nullptr,_acl,exportACL.second);
819 handler = conf.HandlerManager.newPlugin(
820 samlconstants::SAML20_BINDING_URI, pair<const DOMElement*,const char*>(exportElement, getId())
822 m_handlers.push_back(handler);
824 // Insert into location map. If it contains the handlerURL, we skip past that part.
825 const char* hurl = sessions->getString("handlerURL").second;
827 hurl = "/Shibboleth.sso";
828 const char* pch = strstr(location.second, hurl);
830 location.second = pch + strlen(hurl);
831 if (*location.second == '/')
832 m_handlerMap[location.second]=handler;
834 m_handlerMap[string("/") + location.second]=handler;
836 catch (exception& ex) {
837 log.error("caught exception installing assertion lookup handler: %s", ex.what());
841 // Look for "shorthand" elements first.
842 set<string> protocols;
843 DOMElement* child = sessions ? XMLHelper::getFirstChildElement(sessions->getElement()) : nullptr;
845 if (XMLHelper::isNodeNamed(child, shibspconstants::SHIB2SPCONFIG_NS, SSO)) {
847 doSSO(*pp, protocols, child, log);
849 log.error("no ProtocolProvider, SSO auto-configure unsupported");
851 else if (XMLHelper::isNodeNamed(child, shibspconstants::SHIB2SPCONFIG_NS, Logout)) {
853 doLogout(*pp, protocols, child, log);
855 log.error("no ProtocolProvider, Logout auto-configure unsupported");
857 else if (XMLHelper::isNodeNamed(child, shibspconstants::SHIB2SPCONFIG_NS, NameIDMgmt)) {
859 doNameIDMgmt(*pp, protocols, child, log);
861 log.error("no ProtocolProvider, NameIDMgmt auto-configure unsupported");
864 break; // drop into next while loop
866 child = XMLHelper::getNextSiblingElement(child);
869 // Process other handlers.
870 bool hardACS=false, hardSessionInit=false, hardArt=false;
872 if (!child->hasAttributeNS(nullptr, Location)) {
873 auto_ptr_char hclass(child->getLocalName());
874 log.error("%s handler with no Location property cannot be processed", hclass.get());
875 child = XMLHelper::getNextSiblingElement(child);
879 if (XMLString::equals(child->getLocalName(), _AssertionConsumerService)) {
880 string bindprop(XMLHelper::getAttrString(child, nullptr, Binding));
881 if (bindprop.empty()) {
882 log.error("AssertionConsumerService element has no Binding attribute, skipping it...");
883 child = XMLHelper::getNextSiblingElement(child);
886 handler = conf.AssertionConsumerServiceManager.newPlugin(bindprop.c_str(), make_pair(child, getId()));
887 // Map by binding and protocol (may be > 1 per protocol and binding)
888 m_acsBindingMap[handler->getXMLString("Binding").second].push_back(handler);
889 const XMLCh* protfamily = handler->getProtocolFamily();
891 m_acsProtocolMap[protfamily].push_back(handler);
892 m_acsIndexMap[handler->getUnsignedInt("index").second] = handler;
895 pair<bool,bool> defprop = handler->getBool("isDefault");
897 if (defprop.second) {
899 m_acsDefault = handler;
902 else if (!m_acsDefault)
903 m_acsDefault = handler;
906 else if (XMLString::equals(child->getLocalName(), _SessionInitiator)) {
907 string t(XMLHelper::getAttrString(child, nullptr, _type));
909 log.error("SessionInitiator element has no type attribute, skipping it...");
910 child = XMLHelper::getNextSiblingElement(child);
913 SessionInitiator* sihandler = conf.SessionInitiatorManager.newPlugin(t.c_str(), make_pair(child, getId()));
915 pair<bool,const char*> si_id = handler->getString("id");
916 if (si_id.first && si_id.second)
917 m_sessionInitMap[si_id.second] = sihandler;
918 if (!hardSessionInit) {
919 pair<bool,bool> defprop = handler->getBool("isDefault");
921 if (defprop.second) {
922 hardSessionInit = true;
923 m_sessionInitDefault = sihandler;
926 else if (!m_sessionInitDefault) {
927 m_sessionInitDefault = sihandler;
931 else if (XMLString::equals(child->getLocalName(), _LogoutInitiator)) {
932 string t(XMLHelper::getAttrString(child, nullptr, _type));
934 log.error("LogoutInitiator element has no type attribute, skipping it...");
935 child = XMLHelper::getNextSiblingElement(child);
938 handler = conf.LogoutInitiatorManager.newPlugin(t.c_str(), make_pair(child, getId()));
940 else if (XMLString::equals(child->getLocalName(), _ArtifactResolutionService)) {
941 string bindprop(XMLHelper::getAttrString(child, nullptr, Binding));
942 if (bindprop.empty()) {
943 log.error("ArtifactResolutionService element has no Binding attribute, skipping it...");
944 child = XMLHelper::getNextSiblingElement(child);
947 handler = conf.ArtifactResolutionServiceManager.newPlugin(bindprop.c_str(), make_pair(child, getId()));
950 pair<bool,bool> defprop = handler->getBool("isDefault");
952 if (defprop.second) {
954 m_artifactResolutionDefault = handler;
957 else if (!m_artifactResolutionDefault)
958 m_artifactResolutionDefault = handler;
961 else if (XMLString::equals(child->getLocalName(), _SingleLogoutService)) {
962 string bindprop(XMLHelper::getAttrString(child, nullptr, Binding));
963 if (bindprop.empty()) {
964 log.error("SingleLogoutService element has no Binding attribute, skipping it...");
965 child = XMLHelper::getNextSiblingElement(child);
968 handler = conf.SingleLogoutServiceManager.newPlugin(bindprop.c_str(), make_pair(child, getId()));
970 else if (XMLString::equals(child->getLocalName(), _ManageNameIDService)) {
971 string bindprop(XMLHelper::getAttrString(child, nullptr, Binding));
972 if (bindprop.empty()) {
973 log.error("ManageNameIDService element has no Binding attribute, skipping it...");
974 child = XMLHelper::getNextSiblingElement(child);
977 handler = conf.ManageNameIDServiceManager.newPlugin(bindprop.c_str(), make_pair(child, getId()));
980 string t(XMLHelper::getAttrString(child, nullptr, _type));
982 log.error("Handler element has no type attribute, skipping it...");
983 child = XMLHelper::getNextSiblingElement(child);
986 handler = conf.HandlerManager.newPlugin(t.c_str(), make_pair(child, getId()));
989 m_handlers.push_back(handler);
991 // Insert into location map.
992 location = handler->getString("Location");
993 if (location.first && *location.second == '/')
994 m_handlerMap[location.second] = handler;
995 else if (location.first)
996 m_handlerMap[string("/") + location.second] = handler;
998 catch (exception& ex) {
999 log.error("caught exception processing handler element: %s", ex.what());
1002 child = XMLHelper::getNextSiblingElement(child);
1006 void XMLApplication::doSSO(const ProtocolProvider& pp, set<string>& protocols, DOMElement* e, Category& log)
1008 if (!e->hasChildNodes())
1011 SPConfig& conf = SPConfig::getConfig();
1013 // Tokenize the protocol list inside the element.
1014 const XMLCh* protlist = e->getFirstChild()->getNodeValue();
1015 XMLStringTokenizer prottokens(protlist);
1016 while (prottokens.hasMoreTokens()) {
1017 auto_ptr_char prot(prottokens.nextToken());
1019 // Look for initiator.
1020 const PropertySet* initiator = pp.getInitiator(prot.get(), "SSO");
1022 log.info("auto-configuring SSO initiation for protocol (%s)", prot.get());
1023 pair<bool,const XMLCh*> inittype = initiator->getXMLString("id");
1024 if (inittype.first) {
1025 // Append a session initiator element of the designated type to the root element.
1026 DOMElement* sidom = e->getOwnerDocument()->createElementNS(shibspconstants::SHIB2SPCONFIG_NS, _SessionInitiator);
1027 sidom->setAttributeNS(nullptr, _type, inittype.second);
1028 e->appendChild(sidom);
1029 log.info("adding SessionInitiator of type (%s) to chain (/Login)", initiator->getString("id").second);
1031 doArtifactResolution(pp, prot.get(), e, log);
1032 protocols.insert(prot.get());
1035 log.error("missing id property on Initiator element, check config for protocol (%s)", prot.get());
1039 // Look for incoming bindings.
1040 const vector<const PropertySet*>& bindings = pp.getBindings(prot.get(), "SSO");
1041 if (!bindings.empty()) {
1042 log.info("auto-configuring SSO endpoints for protocol (%s)", prot.get());
1044 pair<bool,const XMLCh*> idprop,pathprop;
1045 for (vector<const PropertySet*>::const_iterator b = bindings.begin(); b != bindings.end(); ++b, ++index) {
1046 idprop = (*b)->getXMLString("id");
1047 pathprop = (*b)->getXMLString("path");
1048 if (idprop.first && pathprop.first) {
1049 DOMElement* acsdom = e->getOwnerDocument()->createElementNS(samlconstants::SAML20MD_NS, _AssertionConsumerService);
1050 acsdom->setAttributeNS(nullptr, Binding, idprop.second);
1051 acsdom->setAttributeNS(nullptr, Location, pathprop.second);
1052 xstring indexbuf(chDigit_1 + (index % 10), 1);
1054 indexbuf = (XMLCh)(chDigit_1 + (index / 10)) + indexbuf;
1055 acsdom->setAttributeNS(nullptr, _index, indexbuf.c_str());
1057 log.info("adding AssertionConsumerService for Binding (%s) at (%s)", (*b)->getString("id").second, (*b)->getString("path").second);
1058 Handler* handler = conf.AssertionConsumerServiceManager.newPlugin((*b)->getString("id").second, make_pair(acsdom, getId()));
1059 m_handlers.push_back(handler);
1061 // Setup maps and defaults.
1062 m_acsBindingMap[handler->getXMLString("Binding").second].push_back(handler);
1063 const XMLCh* protfamily = handler->getProtocolFamily();
1065 m_acsProtocolMap[protfamily].push_back(handler);
1066 m_acsIndexMap[handler->getUnsignedInt("index").second] = handler;
1068 m_acsDefault = handler;
1070 // Insert into location map.
1071 pair<bool,const char*> location = handler->getString("Location");
1072 if (location.first && *location.second == '/')
1073 m_handlerMap[location.second] = handler;
1074 else if (location.first)
1075 m_handlerMap[string("/") + location.second] = handler;
1078 log.error("missing id or path property on Binding element, check config for protocol (%s)", prot.get());
1083 if (!initiator && bindings.empty()) {
1084 log.error("no SSO Initiator or Binding config for protocol (%s)", prot.get());
1088 // Handle discovery.
1089 static const XMLCh discoveryProtocol[] = UNICODE_LITERAL_17(d,i,s,c,o,v,e,r,y,P,r,o,t,o,c,o,l);
1090 static const XMLCh discoveryURL[] = UNICODE_LITERAL_12(d,i,s,c,o,v,e,r,y,U,R,L);
1091 static const XMLCh _URL[] = UNICODE_LITERAL_3(U,R,L);
1092 const XMLCh* discop = e->getAttributeNS(nullptr, discoveryProtocol);
1093 if (discop && *discop) {
1094 const XMLCh* discou = e->getAttributeNS(nullptr, discoveryURL);
1095 if (discou && *discou) {
1096 // Append a session initiator element of the designated type to the root element.
1097 DOMElement* sidom = e->getOwnerDocument()->createElementNS(shibspconstants::SHIB2SPCONFIG_NS, _SessionInitiator);
1098 sidom->setAttributeNS(nullptr, _type, discop);
1099 sidom->setAttributeNS(nullptr, _URL, discou);
1100 e->appendChild(sidom);
1101 if (log.isInfoEnabled()) {
1102 auto_ptr_char dp(discop);
1103 log.info("adding SessionInitiator of type (%s) to chain (/Login)", dp.get());
1107 log.error("SSO discoveryProtocol specified without discoveryURL");
1111 // Attach default Location to SSO element.
1112 static const XMLCh _loc[] = { chForwardSlash, chLatin_L, chLatin_o, chLatin_g, chLatin_i, chLatin_n, chNull };
1113 e->setAttributeNS(nullptr, Location, _loc);
1115 // Instantiate Chaining initiator around the SSO element.
1116 SessionInitiator* chain = conf.SessionInitiatorManager.newPlugin(CHAINING_SESSION_INITIATOR, make_pair(e, getId()));
1117 m_handlers.push_back(chain);
1118 m_sessionInitDefault = chain;
1119 m_handlerMap["/Login"] = chain;
1122 void XMLApplication::doLogout(const ProtocolProvider& pp, set<string>& protocols, DOMElement* e, Category& log)
1124 if (!e->hasChildNodes())
1127 SPConfig& conf = SPConfig::getConfig();
1129 // Tokenize the protocol list inside the element.
1130 const XMLCh* protlist = e->getFirstChild()->getNodeValue();
1131 XMLStringTokenizer prottokens(protlist);
1132 while (prottokens.hasMoreTokens()) {
1133 auto_ptr_char prot(prottokens.nextToken());
1135 // Look for initiator.
1136 const PropertySet* initiator = pp.getInitiator(prot.get(), "Logout");
1138 log.info("auto-configuring Logout initiation for protocol (%s)", prot.get());
1139 pair<bool,const XMLCh*> inittype = initiator->getXMLString("id");
1140 if (inittype.first) {
1141 // Append a logout initiator element of the designated type to the root element.
1142 DOMElement* lidom = e->getOwnerDocument()->createElementNS(shibspconstants::SHIB2SPCONFIG_NS, _LogoutInitiator);
1143 lidom->setAttributeNS(nullptr, _type, inittype.second);
1144 e->appendChild(lidom);
1145 log.info("adding LogoutInitiator of type (%s) to chain (/Logout)", initiator->getString("id").second);
1147 if (protocols.count(prot.get()) == 0) {
1148 doArtifactResolution(pp, prot.get(), e, log);
1149 protocols.insert(prot.get());
1153 log.error("missing id property on Initiator element, check config for protocol (%s)", prot.get());
1157 // Look for incoming bindings.
1158 const vector<const PropertySet*>& bindings = pp.getBindings(prot.get(), "Logout");
1159 if (!bindings.empty()) {
1160 log.info("auto-configuring Logout endpoints for protocol (%s)", prot.get());
1161 pair<bool,const XMLCh*> idprop,pathprop;
1162 for (vector<const PropertySet*>::const_iterator b = bindings.begin(); b != bindings.end(); ++b) {
1163 idprop = (*b)->getXMLString("id");
1164 pathprop = (*b)->getXMLString("path");
1165 if (idprop.first && pathprop.first) {
1166 DOMElement* slodom = e->getOwnerDocument()->createElementNS(samlconstants::SAML20MD_NS, _SingleLogoutService);
1167 slodom->setAttributeNS(nullptr, Binding, idprop.second);
1168 slodom->setAttributeNS(nullptr, Location, pathprop.second);
1170 log.info("adding SingleLogoutService for Binding (%s) at (%s)", (*b)->getString("id").second, (*b)->getString("path").second);
1171 Handler* handler = conf.SingleLogoutServiceManager.newPlugin((*b)->getString("id").second, make_pair(slodom, getId()));
1172 m_handlers.push_back(handler);
1174 // Insert into location map.
1175 pair<bool,const char*> location = handler->getString("Location");
1176 if (location.first && *location.second == '/')
1177 m_handlerMap[location.second] = handler;
1178 else if (location.first)
1179 m_handlerMap[string("/") + location.second] = handler;
1182 log.error("missing id or path property on Binding element, check config for protocol (%s)", prot.get());
1186 if (protocols.count(prot.get()) == 0) {
1187 doArtifactResolution(pp, prot.get(), e, log);
1188 protocols.insert(prot.get());
1192 if (!initiator && bindings.empty()) {
1193 log.error("no Logout Initiator or Binding config for protocol (%s)", prot.get());
1197 // Attach default Location to Logout element.
1198 static const XMLCh _loc[] = { chForwardSlash, chLatin_L, chLatin_o, chLatin_g, chLatin_o, chLatin_u, chLatin_t, chNull };
1199 e->setAttributeNS(nullptr, Location, _loc);
1201 // Instantiate Chaining initiator around the SSO element.
1202 Handler* chain = conf.LogoutInitiatorManager.newPlugin(CHAINING_LOGOUT_INITIATOR, make_pair(e, getId()));
1203 m_handlers.push_back(chain);
1204 m_handlerMap["/Logout"] = chain;
1207 void XMLApplication::doNameIDMgmt(const ProtocolProvider& pp, set<string>& protocols, DOMElement* e, Category& log)
1209 if (!e->hasChildNodes())
1212 SPConfig& conf = SPConfig::getConfig();
1214 // Tokenize the protocol list inside the element.
1215 const XMLCh* protlist = e->getFirstChild()->getNodeValue();
1216 XMLStringTokenizer prottokens(protlist);
1217 while (prottokens.hasMoreTokens()) {
1218 auto_ptr_char prot(prottokens.nextToken());
1220 // Look for incoming bindings.
1221 const vector<const PropertySet*>& bindings = pp.getBindings(prot.get(), "NameIDMgmt");
1222 if (!bindings.empty()) {
1223 log.info("auto-configuring NameIDMgmt endpoints for protocol (%s)", prot.get());
1224 pair<bool,const XMLCh*> idprop,pathprop;
1225 for (vector<const PropertySet*>::const_iterator b = bindings.begin(); b != bindings.end(); ++b) {
1226 idprop = (*b)->getXMLString("id");
1227 pathprop = (*b)->getXMLString("path");
1228 if (idprop.first && pathprop.first) {
1229 DOMElement* nimdom = e->getOwnerDocument()->createElementNS(samlconstants::SAML20MD_NS, _ManageNameIDService);
1230 nimdom->setAttributeNS(nullptr, Binding, idprop.second);
1231 nimdom->setAttributeNS(nullptr, Location, pathprop.second);
1233 log.info("adding ManageNameIDService for Binding (%s) at (%s)", (*b)->getString("id").second, (*b)->getString("path").second);
1234 Handler* handler = conf.ManageNameIDServiceManager.newPlugin((*b)->getString("id").second, make_pair(nimdom, getId()));
1235 m_handlers.push_back(handler);
1237 // Insert into location map.
1238 pair<bool,const char*> location = handler->getString("Location");
1239 if (location.first && *location.second == '/')
1240 m_handlerMap[location.second] = handler;
1241 else if (location.first)
1242 m_handlerMap[string("/") + location.second] = handler;
1245 log.error("missing id or path property on Binding element, check config for protocol (%s)", prot.get());
1249 if (protocols.count(prot.get()) == 0) {
1250 doArtifactResolution(pp, prot.get(), e, log);
1251 protocols.insert(prot.get());
1255 log.error("no NameIDMgmt Binding config for protocol (%s)", prot.get());
1260 void XMLApplication::doArtifactResolution(const ProtocolProvider& pp, const char* protocol, DOMElement* e, Category& log)
1262 SPConfig& conf = SPConfig::getConfig();
1264 // Look for incoming bindings.
1265 const vector<const PropertySet*>& bindings = pp.getBindings(protocol, "ArtifactResolution");
1266 if (!bindings.empty()) {
1267 log.info("auto-configuring ArtifactResolution endpoints for protocol (%s)", protocol);
1269 pair<bool,const XMLCh*> idprop,pathprop;
1270 for (vector<const PropertySet*>::const_iterator b = bindings.begin(); b != bindings.end(); ++b) {
1271 idprop = (*b)->getXMLString("id");
1272 pathprop = (*b)->getXMLString("path");
1273 if (idprop.first && pathprop.first) {
1274 DOMElement* artdom = e->getOwnerDocument()->createElementNS(samlconstants::SAML20MD_NS, _ArtifactResolutionService);
1275 artdom->setAttributeNS(nullptr, Binding, idprop.second);
1276 artdom->setAttributeNS(nullptr, Location, pathprop.second);
1277 xstring indexbuf(chDigit_1 + (index % 10), 1);
1279 indexbuf = (XMLCh)(chDigit_1 + (index / 10)) + indexbuf;
1280 artdom->setAttributeNS(nullptr, _index, indexbuf.c_str());
1282 log.info("adding ArtifactResolutionService for Binding (%s) at (%s)", (*b)->getString("id").second, (*b)->getString("path").second);
1283 Handler* handler = conf.ArtifactResolutionServiceManager.newPlugin((*b)->getString("id").second, make_pair(artdom, getId()));
1284 m_handlers.push_back(handler);
1286 if (!m_artifactResolutionDefault)
1287 m_artifactResolutionDefault = handler;
1289 // Insert into location map.
1290 pair<bool,const char*> location = handler->getString("Location");
1291 if (location.first && *location.second == '/')
1292 m_handlerMap[location.second] = handler;
1293 else if (location.first)
1294 m_handlerMap[string("/") + location.second] = handler;
1297 log.error("missing id or path property on Binding element, check config for protocol (%s)", protocol);
1304 void XMLApplication::doAttributePlugins(DOMElement* e, Category& log)
1306 SPConfig& conf = SPConfig::getConfig();
1309 doChainedPlugins(conf.AttributeExtractorManager, "AttributeExtractor", CHAINING_ATTRIBUTE_EXTRACTOR, _AttributeExtractor, e, log);
1312 doChainedPlugins(conf.AttributeFilterManager, "AttributeFilter", CHAINING_ATTRIBUTE_FILTER, _AttributeFilter, e, log);
1315 doChainedPlugins(conf.AttributeResolverManager, "AttributeResolver", CHAINING_ATTRIBUTE_RESOLVER, _AttributeResolver, e, log);
1317 if (m_unsetHeaders.empty()) {
1318 vector<string> unsetHeaders;
1319 if (m_attrExtractor) {
1320 Locker extlock(m_attrExtractor);
1321 m_attrExtractor->getAttributeIds(unsetHeaders);
1323 else if (m_base && m_base->m_attrExtractor) {
1324 Locker extlock(m_base->m_attrExtractor);
1325 m_base->m_attrExtractor->getAttributeIds(unsetHeaders);
1327 if (m_attrResolver) {
1328 Locker reslock(m_attrResolver);
1329 m_attrResolver->getAttributeIds(unsetHeaders);
1331 else if (m_base && m_base->m_attrResolver) {
1332 Locker extlock(m_base->m_attrResolver);
1333 m_base->m_attrResolver->getAttributeIds(unsetHeaders);
1335 if (!unsetHeaders.empty()) {
1336 string transformedprefix(m_attributePrefix.second);
1338 pair<bool,const char*> prefix = getString("metadataAttributePrefix");
1340 pch = prefix.second;
1342 transformedprefix += (isalnum(*pch) ? toupper(*pch) : '_');
1346 for (vector<string>::const_iterator hdr = unsetHeaders.begin(); hdr!=unsetHeaders.end(); ++hdr) {
1350 transformed += (isalnum(*pch) ? toupper(*pch) : '_');
1353 m_unsetHeaders.push_back(pair<string,string>(m_attributePrefix.first + *hdr, m_attributePrefix.second + transformed));
1355 m_unsetHeaders.push_back(pair<string,string>(m_attributePrefix.first + prefix.second + *hdr, transformedprefix + transformed));
1358 m_unsetHeaders.push_back(pair<string,string>(m_attributePrefix.first + "Shib-Application-ID", m_attributePrefix.second + "SHIB_APPLICATION_ID"));
1363 void XMLApplication::cleanup()
1365 ListenerService* listener=getServiceProvider().getListenerService(false);
1366 if (listener && SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess) && !SPConfig::getConfig().isEnabled(SPConfig::InProcess)) {
1367 string addr=string(getId()) + "::getHeaders::Application";
1368 listener->unregListener(addr.c_str(),this);
1370 for_each(m_handlers.begin(),m_handlers.end(),xmltooling::cleanup<Handler>());
1373 for_each(m_partyMap.begin(),m_partyMap.end(),cleanup_pair<xstring,PropertySet>());
1375 delete m_credResolver;
1376 m_credResolver = nullptr;
1377 delete m_attrResolver;
1378 m_attrResolver = nullptr;
1379 delete m_attrFilter;
1380 m_attrFilter = nullptr;
1381 delete m_attrExtractor;
1382 m_attrExtractor = nullptr;
1386 m_metadata = nullptr;
1390 #ifdef SHIBSP_XERCESC_SHORT_ACCEPTNODE
1393 DOMNodeFilter::FilterAction
1395 XMLApplication::acceptNode(const DOMNode* node) const
1397 const XMLCh* name=node->getLocalName();
1398 if (XMLString::equals(name,ApplicationOverride) ||
1399 XMLString::equals(name,_Audience) ||
1400 XMLString::equals(name,Notify) ||
1401 XMLString::equals(name,_Handler) ||
1402 XMLString::equals(name,_AssertionConsumerService) ||
1403 XMLString::equals(name,_ArtifactResolutionService) ||
1404 XMLString::equals(name,Logout) ||
1405 XMLString::equals(name,_LogoutInitiator) ||
1406 XMLString::equals(name,_ManageNameIDService) ||
1407 XMLString::equals(name,NameIDMgmt) ||
1408 XMLString::equals(name,_SessionInitiator) ||
1409 XMLString::equals(name,_SingleLogoutService) ||
1410 XMLString::equals(name,SSO) ||
1411 XMLString::equals(name,RelyingParty) ||
1412 XMLString::equals(name,_MetadataProvider) ||
1413 XMLString::equals(name,_TrustEngine) ||
1414 XMLString::equals(name,_CredentialResolver) ||
1415 XMLString::equals(name,_AttributeFilter) ||
1416 XMLString::equals(name,_AttributeExtractor) ||
1417 XMLString::equals(name,_AttributeResolver))
1418 return FILTER_REJECT;
1420 return FILTER_ACCEPT;
1425 const PropertySet* XMLApplication::getRelyingParty(const EntityDescriptor* provider) const
1430 map<xstring,PropertySet*>::const_iterator i=m_partyMap.find(provider->getEntityID());
1431 if (i!=m_partyMap.end())
1433 const EntitiesDescriptor* group=dynamic_cast<const EntitiesDescriptor*>(provider->getParent());
1435 if (group->getName()) {
1436 i=m_partyMap.find(group->getName());
1437 if (i!=m_partyMap.end())
1440 group=dynamic_cast<const EntitiesDescriptor*>(group->getParent());
1445 const PropertySet* XMLApplication::getRelyingParty(const XMLCh* entityID) const
1450 map<xstring,PropertySet*>::const_iterator i=m_partyMap.find(entityID);
1451 if (i!=m_partyMap.end())
1458 string XMLApplication::getNotificationURL(const char* resource, bool front, unsigned int index) const
1460 const vector<string>& locs = front ? m_frontLogout : m_backLogout;
1462 return m_base ? m_base->getNotificationURL(resource, front, index) : string();
1463 else if (index >= locs.size())
1466 #ifdef HAVE_STRCASECMP
1467 if (!resource || (strncasecmp(resource,"http://",7) && strncasecmp(resource,"https://",8)))
1469 if (!resource || (strnicmp(resource,"http://",7) && strnicmp(resource,"https://",8)))
1471 throw ConfigurationException("Request URL was not absolute.");
1473 const char* handler=locs[index].c_str();
1475 // Should never happen...
1476 if (!handler || (*handler!='/' && strncmp(handler,"http:",5) && strncmp(handler,"https:",6)))
1477 throw ConfigurationException(
1478 "Invalid Location property ($1) in Notify element for Application ($2)",
1479 params(2, handler ? handler : "null", getId())
1482 // The "Location" property can be in one of three formats:
1484 // 1) a full URI: http://host/foo/bar
1485 // 2) a hostless URI: http:///foo/bar
1486 // 3) a relative path: /foo/bar
1488 // # Protocol Host Path
1489 // 1 handler handler handler
1490 // 2 handler resource handler
1491 // 3 resource resource handler
1493 const char* path = nullptr;
1495 // Decide whether to use the handler or the resource for the "protocol"
1497 if (*handler != '/') {
1505 // break apart the "protocol" string into protocol, host, and "the rest"
1506 const char* colon=strchr(prot,':');
1508 const char* slash=strchr(colon,'/');
1512 // Compute the actual protocol and store.
1513 string notifyURL(prot, colon-prot);
1515 // create the "host" from either the colon/slash or from the target string
1516 // If prot == handler then we're in either #1 or #2, else #3.
1517 // If slash == colon then we're in #2.
1518 if (prot != handler || slash == colon) {
1519 colon = strchr(resource, ':');
1520 colon += 3; // Get past the ://
1521 slash = strchr(colon, '/');
1523 string host(colon, (slash ? slash-colon : strlen(colon)));
1526 notifyURL += host + path;
1530 void XMLApplication::clearHeader(SPRequest& request, const char* rawname, const char* cginame) const
1532 if (!m_attributePrefix.first.empty()) {
1533 string temp = m_attributePrefix.first + rawname;
1534 string temp2 = m_attributePrefix.second + (cginame + 5);
1535 request.clearHeader(temp.c_str(), temp2.c_str());
1538 m_base->clearHeader(request, rawname, cginame);
1541 request.clearHeader(rawname, cginame);
1545 void XMLApplication::setHeader(SPRequest& request, const char* name, const char* value) const
1547 if (!m_attributePrefix.first.empty()) {
1548 string temp = m_attributePrefix.first + name;
1549 request.setHeader(temp.c_str(), value);
1552 m_base->setHeader(request, name, value);
1555 request.setHeader(name, value);
1559 string XMLApplication::getSecureHeader(const SPRequest& request, const char* name) const
1561 if (!m_attributePrefix.first.empty()) {
1562 string temp = m_attributePrefix.first + name;
1563 return request.getSecureHeader(temp.c_str());
1566 return m_base->getSecureHeader(request,name);
1569 return request.getSecureHeader(name);
1573 const SessionInitiator* XMLApplication::getDefaultSessionInitiator() const
1575 if (m_sessionInitDefault) return m_sessionInitDefault;
1576 return m_base ? m_base->getDefaultSessionInitiator() : nullptr;
1579 const SessionInitiator* XMLApplication::getSessionInitiatorById(const char* id) const
1581 map<string,const SessionInitiator*>::const_iterator i=m_sessionInitMap.find(id);
1582 if (i!=m_sessionInitMap.end()) return i->second;
1583 return m_base ? m_base->getSessionInitiatorById(id) : nullptr;
1586 const Handler* XMLApplication::getDefaultAssertionConsumerService() const
1588 if (m_acsDefault) return m_acsDefault;
1589 return m_base ? m_base->getDefaultAssertionConsumerService() : nullptr;
1592 const Handler* XMLApplication::getAssertionConsumerServiceByIndex(unsigned short index) const
1594 map<unsigned int,const Handler*>::const_iterator i=m_acsIndexMap.find(index);
1595 if (i != m_acsIndexMap.end()) return i->second;
1596 return m_base ? m_base->getAssertionConsumerServiceByIndex(index) : nullptr;
1599 const Handler* XMLApplication::getAssertionConsumerServiceByProtocol(const XMLCh* protocol, const char* binding) const
1601 ACSProtocolMap::const_iterator i=m_acsProtocolMap.find(protocol);
1602 if (i != m_acsProtocolMap.end() && !i->second.empty()) {
1603 if (!binding || !*binding)
1604 return i->second.front();
1605 for (ACSProtocolMap::value_type::second_type::const_iterator j = i->second.begin(); j != i->second.end(); ++j) {
1606 if (!strcmp(binding, (*j)->getString("Binding").second))
1610 return m_base ? m_base->getAssertionConsumerServiceByProtocol(protocol) : nullptr;
1613 const vector<const Handler*>& XMLApplication::getAssertionConsumerServicesByBinding(const XMLCh* binding) const
1615 ACSBindingMap::const_iterator i=m_acsBindingMap.find(binding);
1616 if (i != m_acsBindingMap.end())
1618 return m_base ? m_base->getAssertionConsumerServicesByBinding(binding) : g_noHandlers;
1621 const Handler* XMLApplication::getHandler(const char* path) const
1624 wrap = wrap.substr(0,wrap.find(';'));
1625 map<string,const Handler*>::const_iterator i=m_handlerMap.find(wrap.substr(0,wrap.find('?')));
1626 if (i!=m_handlerMap.end())
1628 return m_base ? m_base->getHandler(path) : nullptr;
1631 void XMLApplication::getHandlers(vector<const Handler*>& handlers) const
1633 handlers.insert(handlers.end(), m_handlers.begin(), m_handlers.end());
1635 for (map<string,const Handler*>::const_iterator h = m_base->m_handlerMap.begin(); h != m_base->m_handlerMap.end(); ++h) {
1636 if (m_handlerMap.count(h->first) == 0)
1637 handlers.push_back(h->second);
1642 #ifdef SHIBSP_XERCESC_SHORT_ACCEPTNODE
1645 DOMNodeFilter::FilterAction
1647 XMLConfigImpl::acceptNode(const DOMNode* node) const
1649 if (!XMLString::equals(node->getNamespaceURI(),shibspconstants::SHIB2SPCONFIG_NS))
1650 return FILTER_ACCEPT;
1651 const XMLCh* name=node->getLocalName();
1652 if (XMLString::equals(name,ApplicationDefaults) ||
1653 XMLString::equals(name,_ArtifactMap) ||
1654 XMLString::equals(name,_Extensions) ||
1655 XMLString::equals(name,Listener) ||
1656 XMLString::equals(name,_ProtocolProvider) ||
1657 XMLString::equals(name,_RequestMapper) ||
1658 XMLString::equals(name,_ReplayCache) ||
1659 XMLString::equals(name,SecurityPolicies) ||
1660 XMLString::equals(name,_SecurityPolicyProvider) ||
1661 XMLString::equals(name,_SessionCache) ||
1662 XMLString::equals(name,Site) ||
1663 XMLString::equals(name,_StorageService) ||
1664 XMLString::equals(name,TCPListener) ||
1665 XMLString::equals(name,TransportOption) ||
1666 XMLString::equals(name,UnixListener))
1667 return FILTER_REJECT;
1669 return FILTER_ACCEPT;
1672 void XMLConfigImpl::doExtensions(const DOMElement* e, const char* label, Category& log)
1674 const DOMElement* exts = XMLHelper::getFirstChildElement(e, _Extensions);
1676 exts = XMLHelper::getFirstChildElement(exts, Library);
1678 string path(XMLHelper::getAttrString(exts, nullptr, _path));
1680 if (!path.empty()) {
1681 if (!XMLToolingConfig::getConfig().load_library(path.c_str(), (void*)exts))
1682 throw ConfigurationException("XMLToolingConfig::load_library failed.");
1683 log.debug("loaded %s extension library (%s)", label, path.c_str());
1686 catch (exception& e) {
1687 if (XMLHelper::getAttrBool(exts, false, _fatal)) {
1688 log.fatal("unable to load mandatory %s extension library %s: %s", label, path.c_str(), e.what());
1692 log.crit("unable to load optional %s extension library %s: %s", label, path.c_str(), e.what());
1695 exts = XMLHelper::getNextSiblingElement(exts, Library);
1700 void XMLConfigImpl::doListener(const DOMElement* e, XMLConfig* conf, Category& log)
1703 string plugtype(TCP_LISTENER_SERVICE);
1705 string plugtype(UNIX_LISTENER_SERVICE);
1707 DOMElement* child = XMLHelper::getFirstChildElement(e, UnixListener);
1709 plugtype = UNIX_LISTENER_SERVICE;
1711 child = XMLHelper::getFirstChildElement(e, TCPListener);
1713 plugtype = TCP_LISTENER_SERVICE;
1715 child = XMLHelper::getFirstChildElement(e, Listener);
1717 auto_ptr_char type(child->getAttributeNS(nullptr, _type));
1718 if (type.get() && *type.get())
1719 plugtype = type.get();
1724 log.info("building ListenerService of type %s...", plugtype.c_str());
1725 conf->m_listener = SPConfig::getConfig().ListenerServiceManager.newPlugin(plugtype.c_str(), child);
1728 void XMLConfigImpl::doCaching(const DOMElement* e, XMLConfig* conf, Category& log)
1730 SPConfig& spConf = SPConfig::getConfig();
1732 SAMLConfig& samlConf = SAMLConfig::getConfig();
1737 if (spConf.isEnabled(SPConfig::OutOfProcess)) {
1738 XMLToolingConfig& xmlConf = XMLToolingConfig::getConfig();
1739 // First build any StorageServices.
1740 child = XMLHelper::getFirstChildElement(e, _StorageService);
1742 string id(XMLHelper::getAttrString(child, nullptr, _id));
1743 string t(XMLHelper::getAttrString(child, nullptr, _type));
1746 log.info("building StorageService (%s) of type %s...", id.c_str(), t.c_str());
1747 conf->m_storage[id] = xmlConf.StorageServiceManager.newPlugin(t.c_str(), child);
1749 catch (exception& ex) {
1750 log.crit("failed to instantiate StorageService (%s): %s", id.c_str(), ex.what());
1753 child = XMLHelper::getNextSiblingElement(child, _StorageService);
1756 if (conf->m_storage.empty()) {
1757 log.info("no StorageService plugin(s) installed, using (mem) in-memory instance");
1758 conf->m_storage["mem"] = xmlConf.StorageServiceManager.newPlugin(MEMORY_STORAGE_SERVICE, nullptr);
1762 StorageService* replaySS = nullptr;
1763 child = XMLHelper::getFirstChildElement(e, _ReplayCache);
1765 string ssid(XMLHelper::getAttrString(child, nullptr, _StorageService));
1766 if (!ssid.empty()) {
1767 if (conf->m_storage.count(ssid)) {
1768 log.info("building ReplayCache on top of StorageService (%s)...", ssid.c_str());
1769 replaySS = conf->m_storage[ssid];
1772 log.error("unable to locate StorageService (%s), using arbitrary instance for ReplayCache", ssid.c_str());
1773 replaySS = conf->m_storage.begin()->second;
1777 log.info("no StorageService specified for ReplayCache, using arbitrary instance");
1778 replaySS = conf->m_storage.begin()->second;
1782 log.info("no ReplayCache specified, using arbitrary StorageService instance");
1783 replaySS = conf->m_storage.begin()->second;
1785 xmlConf.setReplayCache(new ReplayCache(replaySS));
1788 child = XMLHelper::getFirstChildElement(e, _ArtifactMap);
1790 string ssid(XMLHelper::getAttrString(child, nullptr, _StorageService));
1791 if (!ssid.empty()) {
1792 if (conf->m_storage.count(ssid)) {
1793 log.info("building ArtifactMap on top of StorageService (%s)...", ssid.c_str());
1794 samlConf.setArtifactMap(new ArtifactMap(child, conf->m_storage[ssid]));
1797 log.error("unable to locate StorageService (%s), using in-memory ArtifactMap", ssid.c_str());
1798 samlConf.setArtifactMap(new ArtifactMap(child));
1802 log.info("no StorageService specified, using in-memory ArtifactMap");
1803 samlConf.setArtifactMap(new ArtifactMap(child));
1807 log.info("no ArtifactMap specified, building in-memory ArtifactMap...");
1808 samlConf.setArtifactMap(new ArtifactMap(child));
1810 } // end of out of process caching components
1813 child = XMLHelper::getFirstChildElement(e, _SessionCache);
1815 string t(XMLHelper::getAttrString(child, nullptr, _type));
1817 log.info("building SessionCache of type %s...", t.c_str());
1818 conf->m_sessionCache = spConf.SessionCacheManager.newPlugin(t.c_str(), child);
1821 if (!conf->m_sessionCache) {
1822 log.info("no SessionCache specified, using StorageService-backed instance");
1823 conf->m_sessionCache = spConf.SessionCacheManager.newPlugin(STORAGESERVICE_SESSION_CACHE, nullptr);
1827 XMLConfigImpl::XMLConfigImpl(const DOMElement* e, bool first, XMLConfig* outer, Category& log)
1828 : m_requestMapper(nullptr),
1835 xmltooling::NDC ndc("XMLConfigImpl");
1839 SPConfig& conf=SPConfig::getConfig();
1840 XMLToolingConfig& xmlConf=XMLToolingConfig::getConfig();
1841 const DOMElement* SHAR=XMLHelper::getFirstChildElement(e, OutOfProcess);
1842 const DOMElement* SHIRE=XMLHelper::getFirstChildElement(e, InProcess);
1844 // Initialize logging manually in order to redirect log messages as soon as possible.
1845 if (conf.isEnabled(SPConfig::Logging)) {
1847 if (conf.isEnabled(SPConfig::OutOfProcess))
1848 logconf = XMLHelper::getAttrString(SHAR, nullptr, logger);
1849 else if (conf.isEnabled(SPConfig::InProcess))
1850 logconf = XMLHelper::getAttrString(SHIRE, nullptr, logger);
1851 if (logconf.empty())
1852 logconf = XMLHelper::getAttrString(e, nullptr, logger);
1853 if (logconf.empty() && !getenv("SHIBSP_LOGGING")) {
1854 // No properties found, so default them.
1855 if (conf.isEnabled(SPConfig::OutOfProcess) && !conf.isEnabled(SPConfig::InProcess))
1856 logconf = "shibd.logger";
1857 else if (!conf.isEnabled(SPConfig::OutOfProcess) && conf.isEnabled(SPConfig::InProcess))
1858 logconf = "native.logger";
1860 logconf = "shibboleth.logger";
1862 if (!logconf.empty()) {
1863 log.debug("loading new logging configuration from (%s), check log destination for status of configuration", logconf.c_str());
1864 if (!XMLToolingConfig::getConfig().log_config(logconf.c_str()))
1865 log.crit("failed to load new logging configuration from (%s)", logconf.c_str());
1870 outer->m_tranLog = new TransactionLog();
1874 // Re-log library versions now that logging is set up.
1875 log.info("Shibboleth SP Version %s", PACKAGE_VERSION);
1878 "Library versions: %s %s, Xerces-C %s, XML-Security-C %s, XMLTooling-C %s, OpenSAML-C %s, Shibboleth %s",
1879 # if defined(LOG4SHIB_VERSION)
1880 "log4shib", LOG4SHIB_VERSION,
1881 # elif defined(LOG4CPP_VERSION)
1882 "log4cpp", LOG4CPP_VERSION,
1886 XERCES_FULLVERSIONDOT, XSEC_FULLVERSIONDOT, XMLTOOLING_FULLVERSIONDOT, OPENSAML_FULLVERSIONDOT, SHIBSP_FULLVERSIONDOT
1890 "Library versions: %s %s, Xerces-C %s, XMLTooling-C %s, Shibboleth %s",
1891 # if defined(LOG4SHIB_VERSION)
1892 "log4shib", LOG4SHIB_VERSION,
1893 # elif defined(LOG4CPP_VERSION)
1894 "log4cpp", LOG4CPP_VERSION,
1898 XERCES_FULLVERSIONDOT, XMLTOOLING_FULLVERSIONDOT, SHIBSP_FULLVERSIONDOT
1902 // First load any property sets.
1903 load(e,nullptr,this);
1907 // Much of the processing can only occur on the first instantiation.
1910 pair<bool,unsigned int> skew=getUnsignedInt("clockSkew");
1912 xmlConf.clock_skew_secs=min(skew.second,(60*60*24*7*28));
1914 pair<bool,const char*> unsafe = getString("unsafeChars");
1916 TemplateEngine::unsafe_chars = unsafe.second;
1918 unsafe = getString("allowedSchemes");
1920 HTTPResponse::getAllowedSchemes().clear();
1921 string schemes=unsafe.second;
1922 unsigned int j_sch=0;
1923 for (unsigned int i_sch=0; i_sch < schemes.length(); i_sch++) {
1924 if (schemes.at(i_sch)==' ') {
1925 HTTPResponse::getAllowedSchemes().push_back(schemes.substr(j_sch, i_sch-j_sch));
1929 HTTPResponse::getAllowedSchemes().push_back(schemes.substr(j_sch, schemes.length()-j_sch));
1933 doExtensions(e, "global", log);
1934 if (conf.isEnabled(SPConfig::OutOfProcess))
1935 doExtensions(SHAR, "out of process", log);
1937 if (conf.isEnabled(SPConfig::InProcess))
1938 doExtensions(SHIRE, "in process", log);
1940 // Instantiate the ListenerService and SessionCache objects.
1941 if (conf.isEnabled(SPConfig::Listener))
1942 doListener(e, outer, log);
1945 if (outer->m_listener && conf.isEnabled(SPConfig::OutOfProcess) && !conf.isEnabled(SPConfig::InProcess)) {
1946 outer->m_listener->regListener("set::RelayState", outer);
1947 outer->m_listener->regListener("get::RelayState", outer);
1948 outer->m_listener->regListener("set::PostData", outer);
1949 outer->m_listener->regListener("get::PostData", outer);
1952 if (conf.isEnabled(SPConfig::Caching))
1953 doCaching(e, outer, log);
1954 } // end of first-time-only stuff
1956 // Back to the fully dynamic stuff...next up is the RequestMapper.
1957 if (conf.isEnabled(SPConfig::RequestMapping)) {
1958 if (child = XMLHelper::getFirstChildElement(e, _RequestMapper)) {
1959 string t(XMLHelper::getAttrString(child, nullptr, _type));
1961 log.info("building RequestMapper of type %s...", t.c_str());
1962 m_requestMapper = conf.RequestMapperManager.newPlugin(t.c_str(), child);
1965 if (!m_requestMapper) {
1966 log.info("no RequestMapper specified, using 'Native' plugin with empty/default map");
1967 child = e->getOwnerDocument()->createElementNS(nullptr, _RequestMapper);
1968 DOMElement* mapperDummy = e->getOwnerDocument()->createElementNS(shibspconstants::SHIB2SPCONFIG_NS, RequestMap);
1969 mapperDummy->setAttributeNS(nullptr, applicationId, _default);
1970 child->appendChild(mapperDummy);
1971 m_requestMapper = conf.RequestMapperManager.newPlugin(NATIVE_REQUEST_MAPPER, child);
1976 // Load security policies.
1977 if (child = XMLHelper::getLastChildElement(e, _SecurityPolicyProvider)) {
1978 string t(XMLHelper::getAttrString(child, nullptr, _type));
1980 log.info("building SecurityPolicyProvider of type %s...", t.c_str());
1981 m_policy = conf.SecurityPolicyProviderManager.newPlugin(t.c_str(), child);
1984 throw ConfigurationException("can't build SecurityPolicyProvider, no type specified");
1987 else if (child = XMLHelper::getLastChildElement(e, SecurityPolicies)) {
1988 // For backward compatibility, wrap in a plugin element.
1989 DOMElement* polwrapper = e->getOwnerDocument()->createElementNS(nullptr, _SecurityPolicyProvider);
1990 polwrapper->appendChild(child);
1991 log.info("building SecurityPolicyProvider of type %s...", XML_SECURITYPOLICY_PROVIDER);
1992 m_policy = conf.SecurityPolicyProviderManager.newPlugin(XML_SECURITYPOLICY_PROVIDER, polwrapper);
1995 log.fatal("can't build SecurityPolicyProvider, missing conf:SecurityPolicyProvider element?");
1996 throw ConfigurationException("Can't build SecurityPolicyProvider, missing conf:SecurityPolicyProvider element?");
2000 if (!m_policy->getAlgorithmBlacklist().empty()) {
2001 #ifdef SHIBSP_XMLSEC_WHITELISTING
2002 for (vector<xstring>::const_iterator alg = m_policy->getAlgorithmBlacklist().begin(); alg != m_policy->getAlgorithmBlacklist().end(); ++alg)
2003 XSECPlatformUtils::blacklistAlgorithm(alg->c_str());
2005 log.crit("XML-Security-C library prior to 1.6.0 does not support algorithm white/blacklists");
2008 else if (!m_policy->getAlgorithmWhitelist().empty()) {
2009 #ifdef SHIBSP_XMLSEC_WHITELISTING
2010 for (vector<xstring>::const_iterator alg = m_policy->getAlgorithmWhitelist().begin(); alg != m_policy->getAlgorithmWhitelist().end(); ++alg)
2011 XSECPlatformUtils::whitelistAlgorithm(alg->c_str());
2013 log.crit("XML-Security-C library prior to 1.6.0 does not support algorithm white/blacklists");
2018 // Process TransportOption elements.
2019 child = XMLHelper::getLastChildElement(e, TransportOption);
2021 if (child->hasChildNodes()) {
2022 string provider(XMLHelper::getAttrString(child, nullptr, _provider));
2023 string option(XMLHelper::getAttrString(child, nullptr, _option));
2024 auto_ptr_char value(child->getFirstChild()->getNodeValue());
2025 if (!provider.empty() && !option.empty() && value.get() && *value.get()) {
2026 m_transportOptions.push_back(make_pair(provider, make_pair(option, string(value.get()))));
2029 child = XMLHelper::getPreviousSiblingElement(child, TransportOption);
2033 ProtocolProvider* pp = nullptr;
2034 if (conf.isEnabled(SPConfig::Handlers)) {
2035 if (child = XMLHelper::getLastChildElement(e, _ProtocolProvider)) {
2036 string t(XMLHelper::getAttrString(child, nullptr, _type));
2038 log.info("building ProtocolProvider of type %s...", t.c_str());
2039 pp = conf.ProtocolProviderManager.newPlugin(t.c_str(), child);
2043 auto_ptr<ProtocolProvider> ppwrapper(pp);
2044 Locker pplocker(pp);
2046 // Load the default application.
2047 child = XMLHelper::getLastChildElement(e, ApplicationDefaults);
2049 log.fatal("can't build default Application object, missing conf:ApplicationDefaults element?");
2050 throw ConfigurationException("can't build default Application object, missing conf:ApplicationDefaults element?");
2052 XMLApplication* defapp = new XMLApplication(outer, pp, child);
2053 m_appmap[defapp->getId()] = defapp;
2055 // Load any overrides.
2056 child = XMLHelper::getFirstChildElement(child, ApplicationOverride);
2058 auto_ptr<XMLApplication> iapp(new XMLApplication(outer, pp, child, defapp));
2059 if (m_appmap.count(iapp->getId()))
2060 log.crit("found conf:ApplicationOverride element with duplicate id attribute (%s), skipping it", iapp->getId());
2062 const char* iappid=iapp->getId();
2063 m_appmap[iappid] = iapp.release();
2066 child = XMLHelper::getNextSiblingElement(child, ApplicationOverride);
2069 // Check for extra AuthTypes to recognize.
2070 if (conf.isEnabled(SPConfig::InProcess)) {
2071 const PropertySet* inprocs = getPropertySet("InProcess");
2073 pair<bool,const char*> extraAuthTypes = inprocs->getString("extraAuthTypes");
2074 if (extraAuthTypes.first) {
2075 string types=extraAuthTypes.second;
2076 unsigned int j_types=0;
2077 for (unsigned int i_types=0; i_types < types.length(); i_types++) {
2078 if (types.at(i_types) == ' ') {
2079 outer->m_authTypes.insert(types.substr(j_types, i_types - j_types));
2080 j_types = i_types + 1;
2083 outer->m_authTypes.insert(types.substr(j_types, types.length() - j_types));
2088 catch (exception&) {
2094 XMLConfigImpl::~XMLConfigImpl()
2099 void XMLConfigImpl::cleanup()
2101 for_each(m_appmap.begin(),m_appmap.end(),cleanup_pair<string,Application>());
2107 delete m_requestMapper;
2108 m_requestMapper = nullptr;
2110 m_document->release();
2111 m_document = nullptr;
2115 void XMLConfig::receive(DDF& in, ostream& out)
2117 if (!strcmp(in.name(), "get::RelayState")) {
2118 const char* id = in["id"].string();
2119 const char* key = in["key"].string();
2121 throw ListenerException("Required parameters missing for RelayState recovery.");
2124 StorageService* storage = getStorageService(id);
2126 if (storage->readString("RelayState",key,&relayState)>0) {
2127 if (in["clear"].integer())
2128 storage->deleteString("RelayState",key);
2132 Category::getInstance(SHIBSP_LOGCAT".ServiceProvider").error(
2133 "Storage-backed RelayState with invalid StorageService ID (%s)", id
2137 // Repack for return to caller.
2138 DDF ret=DDF(nullptr).unsafe_string(relayState.c_str());
2139 DDFJanitor jret(ret);
2142 else if (!strcmp(in.name(), "set::RelayState")) {
2143 const char* id = in["id"].string();
2144 const char* value = in["value"].string();
2146 throw ListenerException("Required parameters missing for RelayState creation.");
2149 StorageService* storage = getStorageService(id);
2151 SAMLConfig::getConfig().generateRandomBytes(rsKey,20);
2152 rsKey = SAMLArtifact::toHex(rsKey);
2153 storage->createString("RelayState", rsKey.c_str(), value, time(nullptr) + 600);
2156 Category::getInstance(SHIBSP_LOGCAT".ServiceProvider").error(
2157 "Storage-backed RelayState with invalid StorageService ID (%s)", id
2161 // Repack for return to caller.
2162 DDF ret=DDF(nullptr).string(rsKey.c_str());
2163 DDFJanitor jret(ret);
2166 else if (!strcmp(in.name(), "get::PostData")) {
2167 const char* id = in["id"].string();
2168 const char* key = in["key"].string();
2170 throw ListenerException("Required parameters missing for PostData recovery.");
2173 StorageService* storage = getStorageService(id);
2175 if (storage->readString("PostData",key,&postData) > 0) {
2176 storage->deleteString("PostData",key);
2180 Category::getInstance(SHIBSP_LOGCAT".ServiceProvider").error(
2181 "Storage-backed PostData with invalid StorageService ID (%s)", id
2184 // If the data's empty, we'll send nothing back.
2185 // If not, we don't need to round trip it, just send back the serialized DDF list.
2186 if (postData.empty()) {
2188 DDFJanitor jret(ret);
2195 else if (!strcmp(in.name(), "set::PostData")) {
2196 const char* id = in["id"].string();
2197 if (!id || !in["parameters"].islist())
2198 throw ListenerException("Required parameters missing for PostData creation.");
2201 StorageService* storage = getStorageService(id);
2203 SAMLConfig::getConfig().generateRandomBytes(rsKey,20);
2204 rsKey = SAMLArtifact::toHex(rsKey);
2205 ostringstream params;
2206 params << in["parameters"];
2207 storage->createString("PostData", rsKey.c_str(), params.str().c_str(), time(nullptr) + 600);
2210 Category::getInstance(SHIBSP_LOGCAT".ServiceProvider").error(
2211 "Storage-backed PostData with invalid StorageService ID (%s)", id
2215 // Repack for return to caller.
2216 DDF ret=DDF(nullptr).string(rsKey.c_str());
2217 DDFJanitor jret(ret);
2223 pair<bool,DOMElement*> XMLConfig::background_load()
2225 // Load from source using base class.
2226 pair<bool,DOMElement*> raw = ReloadableXMLFile::load();
2228 // If we own it, wrap it.
2229 XercesJanitor<DOMDocument> docjanitor(raw.first ? raw.second->getOwnerDocument() : nullptr);
2231 XMLConfigImpl* impl = new XMLConfigImpl(raw.second, (m_impl==nullptr), this, m_log);
2233 // If we held the document, transfer it to the impl. If we didn't, it's a no-op.
2234 impl->setDocument(docjanitor.release());
2236 // Perform the swap inside a lock.
2239 SharedLock locker(m_lock, false);
2243 return make_pair(false,(DOMElement*)nullptr);