2 * Licensed to the University Corporation for Advanced Internet
3 * Development, Inc. (UCAID) under one or more contributor license
4 * agreements. See the NOTICE file distributed with this work for
5 * additional information regarding copyright ownership.
7 * UCAID licenses this file to you under the Apache License,
8 * Version 2.0 (the "License"); you may not use this file except
9 * in compliance with the License. You may obtain a copy of the
12 * http://www.apache.org/licenses/LICENSE-2.0
14 * Unless required by applicable law or agreed to in writing,
15 * software distributed under the License is distributed on an
16 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
17 * either express or implied. See the License for the specific
18 * language governing permissions and limitations under the License.
22 * XMLServiceProvider.cpp
24 * XML-based SP configuration and mgmt.
28 #include "exceptions.h"
30 #include "AccessControl.h"
31 #include "Application.h"
32 #include "RequestMapper.h"
33 #include "ServiceProvider.h"
34 #include "SessionCache.h"
36 #include "SPRequest.h"
37 #include "binding/ProtocolProvider.h"
38 #include "handler/LogoutInitiator.h"
39 #include "handler/SessionInitiator.h"
40 #include "remoting/ListenerService.h"
41 #include "util/DOMPropertySet.h"
42 #include "util/SPConstants.h"
44 #if defined(XMLTOOLING_LOG4SHIB)
45 # include <log4shib/PropertyConfigurator.hh>
46 #elif defined(XMLTOOLING_LOG4CPP)
47 # include <log4cpp/PropertyConfigurator.hh>
49 # error "Supported logging library not available."
52 #include <boost/bind.hpp>
53 #include <boost/scoped_ptr.hpp>
54 #include <boost/shared_ptr.hpp>
55 #include <boost/algorithm/string.hpp>
56 #include <boost/tuple/tuple.hpp>
57 #include <xercesc/util/XMLUniDefs.hpp>
58 #include <xercesc/util/XMLStringTokenizer.hpp>
59 #include <xmltooling/XMLToolingConfig.h>
60 #include <xmltooling/version.h>
61 #include <xmltooling/util/NDC.h>
62 #include <xmltooling/util/ReloadableXMLFile.h>
63 #include <xmltooling/util/TemplateEngine.h>
64 #include <xmltooling/util/Threads.h>
65 #include <xmltooling/util/XMLHelper.h>
68 # include "attribute/filtering/AttributeFilter.h"
69 # include "attribute/resolver/AttributeExtractor.h"
70 # include "attribute/resolver/AttributeResolver.h"
71 # include "security/PKIXTrustEngine.h"
72 # include "security/SecurityPolicyProvider.h"
73 # include <saml/SAMLConfig.h>
74 # include <saml/version.h>
75 # include <saml/binding/ArtifactMap.h>
76 # include <saml/binding/SAMLArtifact.h>
77 # include <saml/saml1/core/Assertions.h>
78 # include <saml/saml2/core/Assertions.h>
79 # include <saml/saml2/binding/SAML2ArtifactType0004.h>
80 # include <saml/saml2/metadata/Metadata.h>
81 # include <saml/saml2/metadata/MetadataProvider.h>
82 # include <saml/util/SAMLConstants.h>
83 # include <xmltooling/security/ChainingTrustEngine.h>
84 # include <xmltooling/security/CredentialResolver.h>
85 # include <xmltooling/security/SecurityHelper.h>
86 # include <xmltooling/util/ReplayCache.h>
87 # include <xmltooling/util/StorageService.h>
88 # include <xsec/utils/XSECPlatformUtils.hpp>
89 using namespace opensaml::saml2;
90 using namespace opensaml::saml2p;
91 using namespace opensaml::saml2md;
92 using namespace opensaml;
94 # include "lite/SAMLConstants.h"
97 using namespace shibsp;
98 using namespace xmltooling;
99 using namespace boost;
103 # define min(a,b) (((a) < (b)) ? (a) : (b))
108 #if defined (_MSC_VER)
109 #pragma warning( push )
110 #pragma warning( disable : 4250 )
113 static vector<const Handler*> g_noHandlers;
115 // Application configuration wrapper
116 class SHIBSP_DLLLOCAL XMLApplication : public Application, public Remoted, public DOMPropertySet, public DOMNodeFilter
119 XMLApplication(const ServiceProvider*, const ProtocolProvider*, DOMElement*, const XMLApplication* base=nullptr);
122 const char* getHash() const {return m_hash.c_str();}
125 SAMLArtifact* generateSAML1Artifact(const EntityDescriptor* relyingParty) const {
126 throw ConfigurationException("No support for SAML 1.x artifact generation.");
128 SAML2Artifact* generateSAML2Artifact(const EntityDescriptor* relyingParty) const {
129 pair<bool,int> index = make_pair(false,0);
130 const PropertySet* props = getRelyingParty(relyingParty);
131 index = props->getInt("artifactEndpointIndex");
133 index = getArtifactEndpointIndex();
134 pair<bool,const char*> entityID = props->getString("entityID");
135 return new SAML2ArtifactType0004(
136 SecurityHelper::doHash("SHA1", entityID.second, strlen(entityID.second), false),
137 index.first ? index.second : 1
141 MetadataProvider* getMetadataProvider(bool required=true) const {
142 if (required && !m_base && !m_metadata)
143 throw ConfigurationException("No MetadataProvider available.");
144 return (!m_metadata && m_base) ? m_base->getMetadataProvider(required) : m_metadata.get();
146 TrustEngine* getTrustEngine(bool required=true) const {
147 if (required && !m_base && !m_trust)
148 throw ConfigurationException("No TrustEngine available.");
149 return (!m_trust && m_base) ? m_base->getTrustEngine(required) : m_trust.get();
151 AttributeExtractor* getAttributeExtractor() const {
152 return (!m_attrExtractor && m_base) ? m_base->getAttributeExtractor() : m_attrExtractor.get();
154 AttributeFilter* getAttributeFilter() const {
155 return (!m_attrFilter && m_base) ? m_base->getAttributeFilter() : m_attrFilter.get();
157 AttributeResolver* getAttributeResolver() const {
158 return (!m_attrResolver && m_base) ? m_base->getAttributeResolver() : m_attrResolver.get();
160 CredentialResolver* getCredentialResolver() const {
161 return (!m_credResolver && m_base) ? m_base->getCredentialResolver() : m_credResolver.get();
163 const PropertySet* getRelyingParty(const EntityDescriptor* provider) const;
164 const PropertySet* getRelyingParty(const XMLCh* entityID) const;
165 const vector<const XMLCh*>* getAudiences() const {
166 return (m_audiences.empty() && m_base) ? m_base->getAudiences() : &m_audiences;
169 string getNotificationURL(const char* resource, bool front, unsigned int index) const;
171 const vector<string>& getRemoteUserAttributeIds() const {
172 return (m_remoteUsers.empty() && m_base) ? m_base->getRemoteUserAttributeIds() : m_remoteUsers;
175 void clearHeader(SPRequest& request, const char* rawname, const char* cginame) const;
176 void setHeader(SPRequest& request, const char* name, const char* value) const;
177 string getSecureHeader(const SPRequest& request, const char* name) const;
179 const SessionInitiator* getDefaultSessionInitiator() const;
180 const SessionInitiator* getSessionInitiatorById(const char* id) const;
181 const Handler* getDefaultAssertionConsumerService() const;
182 const Handler* getAssertionConsumerServiceByIndex(unsigned short index) const;
183 const Handler* getAssertionConsumerServiceByProtocol(const XMLCh* protocol, const char* binding=nullptr) const;
184 const vector<const Handler*>& getAssertionConsumerServicesByBinding(const XMLCh* binding) const;
185 const Handler* getHandler(const char* path) const;
186 void getHandlers(vector<const Handler*>& handlers) const;
188 void receive(DDF& in, ostream& out) {
189 // Only current function is to return the headers to clear.
191 DDF ret=DDF(nullptr).list();
192 DDFJanitor jret(ret);
193 for (vector< pair<string,string> >::const_iterator i = m_unsetHeaders.begin(); i!=m_unsetHeaders.end(); ++i) {
194 header = DDF(i->first.c_str()).string(i->second.c_str());
200 // Provides filter to exclude special config elements.
201 #ifdef SHIBSP_XERCESC_SHORT_ACCEPTNODE
206 acceptNode(const DOMNode* node) const;
209 template <class T> T* doChainedPlugins(
210 PluginManager<T,string,const DOMElement*>& pluginMgr,
211 const char* pluginType,
212 const char* chainingType,
213 const XMLCh* localName,
216 const char* dummyType=nullptr
218 void doAttributeInfo();
219 void doHandlers(const ProtocolProvider*, const DOMElement*, Category&);
220 void doSSO(const ProtocolProvider&, set<string>&, DOMElement*, Category&);
221 void doLogout(const ProtocolProvider&, set<string>&, DOMElement*, Category&);
222 void doNameIDMgmt(const ProtocolProvider&, set<string>&, DOMElement*, Category&);
223 void doArtifactResolution(const ProtocolProvider&, const char*, DOMElement*, Category&);
224 const XMLApplication* m_base;
226 std::pair<std::string,std::string> m_attributePrefix;
228 void doAttributePlugins(DOMElement*, Category&);
229 scoped_ptr<MetadataProvider> m_metadata;
230 scoped_ptr<TrustEngine> m_trust;
231 scoped_ptr<AttributeExtractor> m_attrExtractor;
232 scoped_ptr<AttributeFilter> m_attrFilter;
233 scoped_ptr<AttributeResolver> m_attrResolver;
234 scoped_ptr<CredentialResolver> m_credResolver;
235 vector<const XMLCh*> m_audiences;
237 // RelyingParty properties
238 map< xstring,boost::shared_ptr<PropertySet> > m_partyMap;
240 vector<string> m_remoteUsers,m_frontLogout,m_backLogout;
242 // manage handler objects
243 vector< boost::shared_ptr<Handler> > m_handlers;
245 // maps location (path info) to applicable handlers
246 map<string,const Handler*> m_handlerMap;
248 // maps unique indexes to consumer services
249 map<unsigned int,const Handler*> m_acsIndexMap;
251 // pointer to default consumer service
252 const Handler* m_acsDefault;
254 // maps binding strings to supporting consumer service(s)
255 typedef map< xstring,vector<const Handler*> > ACSBindingMap;
256 ACSBindingMap m_acsBindingMap;
258 // maps protocol strings to supporting consumer service(s)
259 typedef map< xstring,vector<const Handler*> > ACSProtocolMap;
260 ACSProtocolMap m_acsProtocolMap;
262 // pointer to default session initiator
263 const SessionInitiator* m_sessionInitDefault;
265 // maps unique ID strings to session initiators
266 map<string,const SessionInitiator*> m_sessionInitMap;
268 // pointer to default artifact resolution service
269 const Handler* m_artifactResolutionDefault;
271 pair<bool,int> getArtifactEndpointIndex() const {
272 if (m_artifactResolutionDefault) return m_artifactResolutionDefault->getInt("index");
273 return m_base ? m_base->getArtifactEndpointIndex() : make_pair(false,0);
277 // Top-level configuration implementation
278 class SHIBSP_DLLLOCAL XMLConfig;
279 class SHIBSP_DLLLOCAL XMLConfigImpl : public DOMPropertySet, public DOMNodeFilter
282 XMLConfigImpl(const DOMElement* e, bool first, XMLConfig* outer, Category& log);
285 m_document->release();
289 scoped_ptr<TransactionLog> m_tranLog;
290 scoped_ptr<SecurityPolicyProvider> m_policy;
291 vector< tuple<string,string,string> > m_transportOptions;
293 scoped_ptr<RequestMapper> m_requestMapper;
294 map< string,boost::shared_ptr<Application> > m_appmap;
296 // Provides filter to exclude special config elements.
297 #ifdef SHIBSP_XERCESC_SHORT_ACCEPTNODE
302 acceptNode(const DOMNode* node) const;
304 void setDocument(DOMDocument* doc) {
309 void doExtensions(const DOMElement*, const char*, Category&);
310 void doListener(const DOMElement*, XMLConfig*, Category&);
311 void doCaching(const DOMElement*, XMLConfig*, Category&);
313 DOMDocument* m_document;
316 class SHIBSP_DLLLOCAL XMLConfig : public ServiceProvider, public ReloadableXMLFile
322 XMLConfig(const DOMElement* e) : ReloadableXMLFile(e, Category::getInstance(SHIBSP_LOGCAT".Config")) {}
331 SAMLConfig::getConfig().setArtifactMap(nullptr);
332 XMLToolingConfig::getConfig().setReplayCache(nullptr);
339 ReloadableXMLFile::lock();
340 if (m_impl->m_policy)
341 m_impl->m_policy->lock();
345 if (m_impl->m_policy)
346 m_impl->m_policy->unlock();
347 ReloadableXMLFile::unlock();
352 const PropertySet* getParent() const { return m_impl->getParent(); }
353 void setParent(const PropertySet* parent) {return m_impl->setParent(parent);}
354 pair<bool,bool> getBool(const char* name, const char* ns=nullptr) const {return m_impl->getBool(name,ns);}
355 pair<bool,const char*> getString(const char* name, const char* ns=nullptr) const {return m_impl->getString(name,ns);}
356 pair<bool,const XMLCh*> getXMLString(const char* name, const char* ns=nullptr) const {return m_impl->getXMLString(name,ns);}
357 pair<bool,unsigned int> getUnsignedInt(const char* name, const char* ns=nullptr) const {return m_impl->getUnsignedInt(name,ns);}
358 pair<bool,int> getInt(const char* name, const char* ns=nullptr) const {return m_impl->getInt(name,ns);}
359 void getAll(map<string,const char*>& properties) const {return m_impl->getAll(properties);}
360 const PropertySet* getPropertySet(const char* name, const char* ns="urn:mace:shibboleth:2.0:native:sp:config") const {return m_impl->getPropertySet(name,ns);}
361 const DOMElement* getElement() const {return m_impl->getElement();}
366 void receive(DDF& in, ostream& out);
368 TransactionLog* getTransactionLog() const {
369 if (m_impl->m_tranLog)
370 return m_impl->m_tranLog.get();
371 throw ConfigurationException("No TransactionLog available.");
374 StorageService* getStorageService(const char* id) const {
376 map< string,boost::shared_ptr<StorageService> >::const_iterator i = m_storage.find(id);
377 if (i != m_storage.end())
378 return i->second.get();
380 else if (!m_storage.empty())
381 return m_storage.begin()->second.get();
386 ListenerService* getListenerService(bool required=true) const {
387 if (required && !m_listener)
388 throw ConfigurationException("No ListenerService available.");
389 return m_listener.get();
392 SessionCache* getSessionCache(bool required=true) const {
393 if (required && !m_sessionCache)
394 throw ConfigurationException("No SessionCache available.");
395 return m_sessionCache.get();
398 RequestMapper* getRequestMapper(bool required=true) const {
399 if (required && !m_impl->m_requestMapper)
400 throw ConfigurationException("No RequestMapper available.");
401 return m_impl->m_requestMapper.get();
404 const Application* getApplication(const char* applicationId) const {
405 map< string,boost::shared_ptr<Application> >::const_iterator i = m_impl->m_appmap.find(applicationId ? applicationId : "default");
406 return (i != m_impl->m_appmap.end()) ? i->second.get() : nullptr;
410 SecurityPolicyProvider* getSecurityPolicyProvider(bool required=true) const {
411 if (required && !m_impl->m_policy)
412 throw ConfigurationException("No SecurityPolicyProvider available.");
413 return m_impl->m_policy.get();
416 const PropertySet* getPolicySettings(const char* id) const {
417 return getSecurityPolicyProvider()->getPolicySettings(id);
420 const vector<const SecurityPolicyRule*>& getPolicyRules(const char* id) const {
421 return getSecurityPolicyProvider()->getPolicyRules(id);
424 bool setTransportOptions(SOAPTransport& transport) const {
426 for (vector< tuple<string,string,string> >::const_iterator opt = m_impl->m_transportOptions.begin();
427 opt != m_impl->m_transportOptions.end(); ++opt) {
428 if (!transport.setProviderOption(opt->get<0>().c_str(), opt->get<1>().c_str(), opt->get<2>().c_str())) {
429 m_log.error("failed to set SOAPTransport option (%s)", opt->get<1>().c_str());
438 pair<bool,DOMElement*> background_load();
441 friend class XMLConfigImpl;
442 // The order of these members actually matters. If we want to rely on auto-destruction, then
443 // anything dependent on anything else has to come later in the object so it will pop first.
444 // Storage is the lowest, then remoting, then the cache, and finally the rest.
446 map< string,boost::shared_ptr<StorageService> > m_storage;
448 scoped_ptr<ListenerService> m_listener;
449 scoped_ptr<SessionCache> m_sessionCache;
450 scoped_ptr<XMLConfigImpl> m_impl;
453 #if defined (_MSC_VER)
454 #pragma warning( pop )
457 static const XMLCh applicationId[] = UNICODE_LITERAL_13(a,p,p,l,i,c,a,t,i,o,n,I,d);
458 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);
459 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);
460 static const XMLCh _ArtifactMap[] = UNICODE_LITERAL_11(A,r,t,i,f,a,c,t,M,a,p);
461 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);
462 static const XMLCh _AttributeFilter[] = UNICODE_LITERAL_15(A,t,t,r,i,b,u,t,e,F,i,l,t,e,r);
463 static const XMLCh _AttributeResolver[] = UNICODE_LITERAL_17(A,t,t,r,i,b,u,t,e,R,e,s,o,l,v,e,r);
464 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);
465 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);
466 static const XMLCh _Audience[] = UNICODE_LITERAL_8(A,u,d,i,e,n,c,e);
467 static const XMLCh Binding[] = UNICODE_LITERAL_7(B,i,n,d,i,n,g);
468 static const XMLCh Channel[]= UNICODE_LITERAL_7(C,h,a,n,n,e,l);
469 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);
470 static const XMLCh _default[] = UNICODE_LITERAL_7(d,e,f,a,u,l,t);
471 static const XMLCh _Extensions[] = UNICODE_LITERAL_10(E,x,t,e,n,s,i,o,n,s);
472 static const XMLCh _fatal[] = UNICODE_LITERAL_5(f,a,t,a,l);
473 static const XMLCh _Handler[] = UNICODE_LITERAL_7(H,a,n,d,l,e,r);
474 static const XMLCh _id[] = UNICODE_LITERAL_2(i,d);
475 static const XMLCh _index[] = UNICODE_LITERAL_5(i,n,d,e,x);
476 static const XMLCh InProcess[] = UNICODE_LITERAL_9(I,n,P,r,o,c,e,s,s);
477 static const XMLCh Library[] = UNICODE_LITERAL_7(L,i,b,r,a,r,y);
478 static const XMLCh Listener[] = UNICODE_LITERAL_8(L,i,s,t,e,n,e,r);
479 static const XMLCh Location[] = UNICODE_LITERAL_8(L,o,c,a,t,i,o,n);
480 static const XMLCh logger[] = UNICODE_LITERAL_6(l,o,g,g,e,r);
481 static const XMLCh Logout[] = UNICODE_LITERAL_6(L,o,g,o,u,t);
482 static const XMLCh _LogoutInitiator[] = UNICODE_LITERAL_15(L,o,g,o,u,t,I,n,i,t,i,a,t,o,r);
483 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);
484 static const XMLCh _MetadataProvider[] = UNICODE_LITERAL_16(M,e,t,a,d,a,t,a,P,r,o,v,i,d,e,r);
485 static const XMLCh NameIDMgmt[] = UNICODE_LITERAL_10(N,a,m,e,I,D,M,g,m,t);
486 static const XMLCh Notify[] = UNICODE_LITERAL_6(N,o,t,i,f,y);
487 static const XMLCh _option[] = UNICODE_LITERAL_6(o,p,t,i,o,n);
488 static const XMLCh OutOfProcess[] = UNICODE_LITERAL_12(O,u,t,O,f,P,r,o,c,e,s,s);
489 static const XMLCh _path[] = UNICODE_LITERAL_4(p,a,t,h);
490 static const XMLCh _ProtocolProvider[] = UNICODE_LITERAL_16(P,r,o,t,o,c,o,l,P,r,o,v,i,d,e,r);
491 static const XMLCh _provider[] = UNICODE_LITERAL_8(p,r,o,v,i,d,e,r);
492 static const XMLCh RelyingParty[] = UNICODE_LITERAL_12(R,e,l,y,i,n,g,P,a,r,t,y);
493 static const XMLCh _ReplayCache[] = UNICODE_LITERAL_11(R,e,p,l,a,y,C,a,c,h,e);
494 static const XMLCh _RequestMapper[] = UNICODE_LITERAL_13(R,e,q,u,e,s,t,M,a,p,p,e,r);
495 static const XMLCh RequestMap[] = UNICODE_LITERAL_10(R,e,q,u,e,s,t,M,a,p);
496 static const XMLCh SecurityPolicies[] = UNICODE_LITERAL_16(S,e,c,u,r,i,t,y,P,o,l,i,c,i,e,s);
497 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);
498 static const XMLCh _SessionCache[] = UNICODE_LITERAL_12(S,e,s,s,i,o,n,C,a,c,h,e);
499 static const XMLCh _SessionInitiator[] = UNICODE_LITERAL_16(S,e,s,s,i,o,n,I,n,i,t,i,a,t,o,r);
500 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);
501 static const XMLCh Site[] = UNICODE_LITERAL_4(S,i,t,e);
502 static const XMLCh SSO[] = UNICODE_LITERAL_3(S,S,O);
503 static const XMLCh _StorageService[] = UNICODE_LITERAL_14(S,t,o,r,a,g,e,S,e,r,v,i,c,e);
504 static const XMLCh TCPListener[] = UNICODE_LITERAL_11(T,C,P,L,i,s,t,e,n,e,r);
505 static const XMLCh tranLogFiller[] = UNICODE_LITERAL_13(t,r,a,n,L,o,g,F,i,l,l,e,r);
506 static const XMLCh tranLogFormat[] = UNICODE_LITERAL_13(t,r,a,n,L,o,g,F,o,r,m,a,t);
507 static const XMLCh TransportOption[] = UNICODE_LITERAL_15(T,r,a,n,s,p,o,r,t,O,p,t,i,o,n);
508 static const XMLCh _TrustEngine[] = UNICODE_LITERAL_11(T,r,u,s,t,E,n,g,i,n,e);
509 static const XMLCh _type[] = UNICODE_LITERAL_4(t,y,p,e);
510 static const XMLCh UnixListener[] = UNICODE_LITERAL_12(U,n,i,x,L,i,s,t,e,n,e,r);
514 ServiceProvider* XMLServiceProviderFactory(const DOMElement* const & e)
516 return new XMLConfig(e);
520 XMLApplication::XMLApplication(
521 const ServiceProvider* sp,
522 const ProtocolProvider* pp,
524 const XMLApplication* base
525 ) : Application(sp), m_base(base), m_acsDefault(nullptr), m_sessionInitDefault(nullptr), m_artifactResolutionDefault(nullptr)
528 xmltooling::NDC ndc("XMLApplication");
530 Category& log=Category::getInstance(SHIBSP_LOGCAT".Application");
532 // First load any property sets.
533 load(e, nullptr, this);
537 SPConfig& conf=SPConfig::getConfig();
539 XMLToolingConfig& xmlConf=XMLToolingConfig::getConfig();
542 // This used to be an actual hash, but now it's just a hex-encode to avoid xmlsec dependency.
543 static char DIGITS[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
544 string tohash=getId();
545 tohash+=getString("entityID").second;
546 for (const char* ch = tohash.c_str(); *ch; ++ch) {
547 m_hash += (DIGITS[((unsigned char)(0xF0 & *ch)) >> 4 ]);
548 m_hash += (DIGITS[0x0F & *ch]);
553 if (conf.isEnabled(SPConfig::Handlers))
554 doHandlers(pp, e, log);
557 DOMNodeList* nlist = e->getElementsByTagNameNS(shibspconstants::SHIB2SPCONFIG_NS, Notify);
558 for (XMLSize_t i = 0; nlist && i < nlist->getLength(); ++i) {
559 if (nlist->item(i)->getParentNode()->isSameNode(e)) {
560 const XMLCh* channel = static_cast<DOMElement*>(nlist->item(i))->getAttributeNS(nullptr, Channel);
561 string loc(XMLHelper::getAttrString(static_cast<DOMElement*>(nlist->item(i)), nullptr, Location));
563 if (channel && *channel == chLatin_f)
564 m_frontLogout.push_back(loc);
566 m_backLogout.push_back(loc);
572 nlist = e->getElementsByTagNameNS(samlconstants::SAML20_NS, Audience::LOCAL_NAME);
573 if (nlist && nlist->getLength()) {
574 log.warn("use of <saml:Audience> elements outside of a Security Policy Rule is deprecated");
575 for (XMLSize_t i = 0; i < nlist->getLength(); ++i)
576 if (nlist->item(i)->getParentNode()->isSameNode(e) && nlist->item(i)->hasChildNodes())
577 m_audiences.push_back(nlist->item(i)->getFirstChild()->getNodeValue());
580 if (conf.isEnabled(SPConfig::Metadata)) {
583 SAMLConfig::getConfig().MetadataProviderManager, "MetadataProvider", CHAINING_METADATA_PROVIDER, _MetadataProvider, e, log
590 log.crit("no MetadataProvider available, configuration is probably unusable");
592 catch (std::exception& ex) {
593 log.crit("error initializing MetadataProvider: %s", ex.what());
597 if (conf.isEnabled(SPConfig::Trust)) {
598 m_trust.reset(doChainedPlugins(xmlConf.TrustEngineManager, "TrustEngine", CHAINING_TRUSTENGINE, _TrustEngine, e, log));
599 if (!m_trust && !m_base) {
601 "no TrustEngine specified or installed, using default chain {%s, %s}",
602 EXPLICIT_KEY_TRUSTENGINE, SHIBBOLETH_PKIX_TRUSTENGINE
604 m_trust.reset(xmlConf.TrustEngineManager.newPlugin(CHAINING_TRUSTENGINE, nullptr));
605 ChainingTrustEngine* trustchain = dynamic_cast<ChainingTrustEngine*>(m_trust.get());
607 trustchain->addTrustEngine(xmlConf.TrustEngineManager.newPlugin(EXPLICIT_KEY_TRUSTENGINE, nullptr));
608 trustchain->addTrustEngine(xmlConf.TrustEngineManager.newPlugin(SHIBBOLETH_PKIX_TRUSTENGINE, nullptr));
613 if (conf.isEnabled(SPConfig::AttributeResolution)) {
614 doAttributePlugins(e, log);
617 if (conf.isEnabled(SPConfig::Credentials)) {
618 m_credResolver.reset(
619 doChainedPlugins(xmlConf.CredentialResolverManager, "CredentialResolver", CHAINING_CREDENTIAL_RESOLVER, _CredentialResolver, e, log)
623 // Finally, load relying parties.
624 const DOMElement* child = XMLHelper::getFirstChildElement(e, RelyingParty);
626 if (child->hasAttributeNS(nullptr, saml2::Attribute::NAME_ATTRIB_NAME)) {
627 boost::shared_ptr<DOMPropertySet> rp(new DOMPropertySet());
628 rp->load(child, nullptr, this);
630 m_partyMap[child->getAttributeNS(nullptr, saml2::Attribute::NAME_ATTRIB_NAME)] = rp;
632 child = XMLHelper::getNextSiblingElement(child, RelyingParty);
634 if (base && m_partyMap.empty() && !base->m_partyMap.empty()) {
635 // For inheritance of RPs to work, we have to pull them in to the override by cloning the DOM.
636 child = XMLHelper::getFirstChildElement(base->getElement(), RelyingParty);
638 if (child->hasAttributeNS(nullptr, saml2::Attribute::NAME_ATTRIB_NAME)) {
639 DOMElement* rpclone = static_cast<DOMElement*>(child->cloneNode(true));
640 boost::shared_ptr<DOMPropertySet> rp(new DOMPropertySet());
641 rp->load(rpclone, nullptr, this);
643 m_partyMap[rpclone->getAttributeNS(nullptr, saml2::Attribute::NAME_ATTRIB_NAME)] = rp;
645 child = XMLHelper::getNextSiblingElement(child, RelyingParty);
650 // Out of process only, we register a listener endpoint.
651 if (!conf.isEnabled(SPConfig::InProcess)) {
652 ListenerService* listener = sp->getListenerService(false);
654 string addr=string(getId()) + "::getHeaders::Application";
655 listener->regListener(addr.c_str(), this);
658 log.info("no ListenerService available, Application remoting disabled");
663 XMLApplication::~XMLApplication()
665 ListenerService* listener=getServiceProvider().getListenerService(false);
666 if (listener && SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess) && !SPConfig::getConfig().isEnabled(SPConfig::InProcess)) {
667 string addr=string(getId()) + "::getHeaders::Application";
668 listener->unregListener(addr.c_str(), this);
672 template <class T> T* XMLApplication::doChainedPlugins(
673 PluginManager<T,string,const DOMElement*>& pluginMgr,
674 const char* pluginType,
675 const char* chainingType,
676 const XMLCh* localName,
679 const char* dummyType
683 DOMElement* child = XMLHelper::getFirstChildElement(e, localName);
685 // Check for multiple.
686 if (XMLHelper::getNextSiblingElement(child, localName)) {
687 log.info("multiple %s plugins, wrapping in a chain", pluginType);
688 DOMElement* chain = child->getOwnerDocument()->createElementNS(nullptr, localName);
690 chain->appendChild(child);
691 child = XMLHelper::getFirstChildElement(e, localName);
695 e->appendChild(chain);
698 // Only a single one.
699 t = XMLHelper::getAttrString(child, nullptr, _type);
704 log.info("building %s of type %s...", pluginType, t.c_str());
705 return pluginMgr.newPlugin(t.c_str(), child);
708 throw ConfigurationException("$1 element had no type attribute.", params(1, pluginType));
711 catch (std::exception& ex) {
712 log.crit("error building %s: %s", pluginType, ex.what());
714 // Install a dummy version as a safety valve.
715 log.crit("installing safe %s in place of failed version", pluginType);
716 return pluginMgr.newPlugin(dummyType, nullptr);
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 pair<bool,const char*> attributes = getString("REMOTE_USER");
739 if (attributes.first) {
740 string dup(attributes.second);
741 split(m_remoteUsers, dup, is_space(), algorithm::token_compress_on);
744 // Load attribute ID lists for REMOTE_USER and header clearing.
745 if (SPConfig::getConfig().isEnabled(SPConfig::InProcess)) {
746 attributes = getString("unsetHeaders");
747 if (attributes.first) {
748 string transformedprefix(m_attributePrefix.second);
750 prefix = getString("metadataAttributePrefix");
754 transformedprefix += (isalnum(*pch) ? toupper(*pch) : '_');
759 string dup(attributes.second);
760 vector<string> headerNames;
761 split(headerNames, dup, is_space(), algorithm::token_compress_on);
762 for (vector<string>::const_iterator h = headerNames.begin(); h != headerNames.end(); ++h) {
764 const char* pch = h->c_str();
766 transformed += (isalnum(*pch) ? toupper(*pch) : '_');
769 m_unsetHeaders.push_back(pair<string,string>(m_attributePrefix.first + *h, m_attributePrefix.second + transformed));
771 m_unsetHeaders.push_back(pair<string,string>(m_attributePrefix.first + prefix.second + *h, transformedprefix + transformed));
773 m_unsetHeaders.push_back(pair<string,string>(m_attributePrefix.first + "Shib-Application-ID", m_attributePrefix.second + "SHIB_APPLICATION_ID"));
778 void XMLApplication::doHandlers(const ProtocolProvider* pp, const DOMElement* e, Category& log)
780 SPConfig& conf = SPConfig::getConfig();
782 const PropertySet* sessions = getPropertySet("Sessions");
784 // Process assertion export handler.
785 pair<bool,const char*> location = sessions ? sessions->getString("exportLocation") : pair<bool,const char*>(false,nullptr);
786 if (location.first) {
788 DOMElement* exportElement = e->getOwnerDocument()->createElementNS(shibspconstants::SHIB2SPCONFIG_NS, _Handler);
789 exportElement->setAttributeNS(nullptr,Location,sessions->getXMLString("exportLocation").second);
790 pair<bool,const XMLCh*> exportACL = sessions->getXMLString("exportACL");
791 if (exportACL.first) {
792 static const XMLCh _acl[] = UNICODE_LITERAL_9(e,x,p,o,r,t,A,C,L);
793 exportElement->setAttributeNS(nullptr,_acl,exportACL.second);
795 boost::shared_ptr<Handler> exportHandler(
796 conf.HandlerManager.newPlugin(samlconstants::SAML20_BINDING_URI, pair<const DOMElement*,const char*>(exportElement, getId()))
798 m_handlers.push_back(exportHandler);
800 // Insert into location map. If it contains the handlerURL, we skip past that part.
801 const char* hurl = sessions->getString("handlerURL").second;
803 hurl = "/Shibboleth.sso";
804 const char* pch = strstr(location.second, hurl);
806 location.second = pch + strlen(hurl);
807 if (*location.second == '/')
808 m_handlerMap[location.second] = exportHandler.get();
810 m_handlerMap[string("/") + location.second] = exportHandler.get();
812 catch (std::exception& ex) {
813 log.error("caught exception installing assertion lookup handler: %s", ex.what());
817 // Look for "shorthand" elements first.
818 set<string> protocols;
819 DOMElement* child = sessions ? XMLHelper::getFirstChildElement(sessions->getElement()) : nullptr;
821 if (XMLHelper::isNodeNamed(child, shibspconstants::SHIB2SPCONFIG_NS, SSO)) {
823 doSSO(*pp, protocols, child, log);
825 log.error("no ProtocolProvider, SSO auto-configure unsupported");
827 else if (XMLHelper::isNodeNamed(child, shibspconstants::SHIB2SPCONFIG_NS, Logout)) {
829 doLogout(*pp, protocols, child, log);
831 log.error("no ProtocolProvider, Logout auto-configure unsupported");
833 else if (XMLHelper::isNodeNamed(child, shibspconstants::SHIB2SPCONFIG_NS, NameIDMgmt)) {
835 doNameIDMgmt(*pp, protocols, child, log);
837 log.error("no ProtocolProvider, NameIDMgmt auto-configure unsupported");
840 break; // drop into next while loop
842 child = XMLHelper::getNextSiblingElement(child);
845 // Process other handlers.
846 bool hardACS=false, hardSessionInit=false, hardArt=false;
848 if (!child->hasAttributeNS(nullptr, Location)) {
849 auto_ptr_char hclass(child->getLocalName());
850 log.error("%s handler with no Location property cannot be processed", hclass.get());
851 child = XMLHelper::getNextSiblingElement(child);
855 boost::shared_ptr<Handler> handler;
856 if (XMLString::equals(child->getLocalName(), _AssertionConsumerService)) {
857 string bindprop(XMLHelper::getAttrString(child, nullptr, Binding));
858 if (bindprop.empty()) {
859 log.error("AssertionConsumerService element has no Binding attribute, skipping it...");
860 child = XMLHelper::getNextSiblingElement(child);
863 handler.reset(conf.AssertionConsumerServiceManager.newPlugin(bindprop.c_str(), pair<const DOMElement*,const char*>(child, getId())));
864 // Map by binding and protocol (may be > 1 per protocol and binding)
865 m_acsBindingMap[handler->getXMLString("Binding").second].push_back(handler.get());
866 const XMLCh* protfamily = handler->getProtocolFamily();
868 m_acsProtocolMap[protfamily].push_back(handler.get());
869 m_acsIndexMap[handler->getUnsignedInt("index").second] = handler.get();
872 pair<bool,bool> defprop = handler->getBool("isDefault");
874 if (defprop.second) {
876 m_acsDefault = handler.get();
879 else if (!m_acsDefault)
880 m_acsDefault = handler.get();
883 else if (XMLString::equals(child->getLocalName(), _SessionInitiator)) {
884 string t(XMLHelper::getAttrString(child, nullptr, _type));
886 log.error("SessionInitiator element has no type attribute, skipping it...");
887 child = XMLHelper::getNextSiblingElement(child);
890 boost::shared_ptr<SessionInitiator> sihandler(
891 conf.SessionInitiatorManager.newPlugin(t.c_str(), pair<const DOMElement*,const char*>(child, getId()))
894 pair<bool,const char*> si_id = handler->getString("id");
895 if (si_id.first && si_id.second)
896 m_sessionInitMap[si_id.second] = sihandler.get();
897 if (!hardSessionInit) {
898 pair<bool,bool> defprop = handler->getBool("isDefault");
900 if (defprop.second) {
901 hardSessionInit = true;
902 m_sessionInitDefault = sihandler.get();
905 else if (!m_sessionInitDefault) {
906 m_sessionInitDefault = sihandler.get();
910 else if (XMLString::equals(child->getLocalName(), _LogoutInitiator)) {
911 string t(XMLHelper::getAttrString(child, nullptr, _type));
913 log.error("LogoutInitiator element has no type attribute, skipping it...");
914 child = XMLHelper::getNextSiblingElement(child);
917 handler.reset(conf.LogoutInitiatorManager.newPlugin(t.c_str(), pair<const DOMElement*,const char*>(child, getId())));
919 else if (XMLString::equals(child->getLocalName(), _ArtifactResolutionService)) {
920 string bindprop(XMLHelper::getAttrString(child, nullptr, Binding));
921 if (bindprop.empty()) {
922 log.error("ArtifactResolutionService element has no Binding attribute, skipping it...");
923 child = XMLHelper::getNextSiblingElement(child);
926 handler.reset(conf.ArtifactResolutionServiceManager.newPlugin(bindprop.c_str(), pair<const DOMElement*,const char*>(child, getId())));
929 pair<bool,bool> defprop = handler->getBool("isDefault");
931 if (defprop.second) {
933 m_artifactResolutionDefault = handler.get();
936 else if (!m_artifactResolutionDefault)
937 m_artifactResolutionDefault = handler.get();
940 else if (XMLString::equals(child->getLocalName(), _SingleLogoutService)) {
941 string bindprop(XMLHelper::getAttrString(child, nullptr, Binding));
942 if (bindprop.empty()) {
943 log.error("SingleLogoutService element has no Binding attribute, skipping it...");
944 child = XMLHelper::getNextSiblingElement(child);
947 handler.reset(conf.SingleLogoutServiceManager.newPlugin(bindprop.c_str(), pair<const DOMElement*,const char*>(child, getId())));
949 else if (XMLString::equals(child->getLocalName(), _ManageNameIDService)) {
950 string bindprop(XMLHelper::getAttrString(child, nullptr, Binding));
951 if (bindprop.empty()) {
952 log.error("ManageNameIDService element has no Binding attribute, skipping it...");
953 child = XMLHelper::getNextSiblingElement(child);
956 handler.reset(conf.ManageNameIDServiceManager.newPlugin(bindprop.c_str(), pair<const DOMElement*,const char*>(child, getId())));
959 string t(XMLHelper::getAttrString(child, nullptr, _type));
961 log.error("Handler element has no type attribute, skipping it...");
962 child = XMLHelper::getNextSiblingElement(child);
965 handler.reset(conf.HandlerManager.newPlugin(t.c_str(), pair<const DOMElement*,const char*>(child, getId())));
968 m_handlers.push_back(handler);
970 // Insert into location map.
971 location = handler->getString("Location");
972 if (location.first && *location.second == '/')
973 m_handlerMap[location.second] = handler.get();
974 else if (location.first)
975 m_handlerMap[string("/") + location.second] = handler.get();
977 catch (std::exception& ex) {
978 log.error("caught exception processing handler element: %s", ex.what());
981 child = XMLHelper::getNextSiblingElement(child);
985 void XMLApplication::doSSO(const ProtocolProvider& pp, set<string>& protocols, DOMElement* e, Category& log)
987 if (!e->hasChildNodes())
990 SPConfig& conf = SPConfig::getConfig();
992 // Tokenize the protocol list inside the element.
993 XMLStringTokenizer prottokens(e->getTextContent());
994 while (prottokens.hasMoreTokens()) {
995 auto_ptr_char prot(prottokens.nextToken());
997 // Look for initiator.
998 const PropertySet* initiator = pp.getInitiator(prot.get(), "SSO");
1000 log.info("auto-configuring SSO initiation for protocol (%s)", prot.get());
1001 pair<bool,const XMLCh*> inittype = initiator->getXMLString("id");
1002 if (inittype.first) {
1003 // Append a session initiator element of the designated type to the root element.
1004 DOMElement* sidom = e->getOwnerDocument()->createElementNS(shibspconstants::SHIB2SPCONFIG_NS, _SessionInitiator);
1005 sidom->setAttributeNS(nullptr, _type, inittype.second);
1006 e->appendChild(sidom);
1007 log.info("adding SessionInitiator of type (%s) to chain (/Login)", initiator->getString("id").second);
1009 doArtifactResolution(pp, prot.get(), e, log);
1010 protocols.insert(prot.get());
1013 log.error("missing id property on Initiator element, check config for protocol (%s)", prot.get());
1017 // Look for incoming bindings.
1018 const vector<const PropertySet*>& bindings = pp.getBindings(prot.get(), "SSO");
1019 if (!bindings.empty()) {
1020 log.info("auto-configuring SSO endpoints for protocol (%s)", prot.get());
1022 pair<bool,const XMLCh*> idprop,pathprop;
1023 for (vector<const PropertySet*>::const_iterator b = bindings.begin(); b != bindings.end(); ++b, ++index) {
1024 idprop = (*b)->getXMLString("id");
1025 pathprop = (*b)->getXMLString("path");
1026 if (idprop.first && pathprop.first) {
1027 DOMElement* acsdom = e->getOwnerDocument()->createElementNS(samlconstants::SAML20MD_NS, _AssertionConsumerService);
1028 acsdom->setAttributeNS(nullptr, Binding, idprop.second);
1029 acsdom->setAttributeNS(nullptr, Location, pathprop.second);
1030 xstring indexbuf(chDigit_1 + (index % 10), 1);
1032 indexbuf = (XMLCh)(chDigit_1 + (index / 10)) + indexbuf;
1033 acsdom->setAttributeNS(nullptr, _index, indexbuf.c_str());
1035 log.info("adding AssertionConsumerService for Binding (%s) at (%s)", (*b)->getString("id").second, (*b)->getString("path").second);
1036 boost::shared_ptr<Handler> handler(
1037 conf.AssertionConsumerServiceManager.newPlugin(
1038 (*b)->getString("id").second, pair<const DOMElement*,const char*>(acsdom, getId())
1041 m_handlers.push_back(handler);
1043 // Setup maps and defaults.
1044 m_acsBindingMap[handler->getXMLString("Binding").second].push_back(handler.get());
1045 const XMLCh* protfamily = handler->getProtocolFamily();
1047 m_acsProtocolMap[protfamily].push_back(handler.get());
1048 m_acsIndexMap[handler->getUnsignedInt("index").second] = handler.get();
1050 m_acsDefault = handler.get();
1052 // Insert into location map.
1053 pair<bool,const char*> location = handler->getString("Location");
1054 if (location.first && *location.second == '/')
1055 m_handlerMap[location.second] = handler.get();
1056 else if (location.first)
1057 m_handlerMap[string("/") + location.second] = handler.get();
1060 log.error("missing id or path property on Binding element, check config for protocol (%s)", prot.get());
1065 if (!initiator && bindings.empty()) {
1066 log.error("no SSO Initiator or Binding config for protocol (%s)", prot.get());
1070 // Handle discovery.
1071 static const XMLCh discoveryProtocol[] = UNICODE_LITERAL_17(d,i,s,c,o,v,e,r,y,P,r,o,t,o,c,o,l);
1072 static const XMLCh discoveryURL[] = UNICODE_LITERAL_12(d,i,s,c,o,v,e,r,y,U,R,L);
1073 static const XMLCh _URL[] = UNICODE_LITERAL_3(U,R,L);
1074 const XMLCh* discop = e->getAttributeNS(nullptr, discoveryProtocol);
1075 if (discop && *discop) {
1076 const XMLCh* discou = e->getAttributeNS(nullptr, discoveryURL);
1077 if (discou && *discou) {
1078 // Append a session initiator element of the designated type to the root element.
1079 DOMElement* sidom = e->getOwnerDocument()->createElementNS(shibspconstants::SHIB2SPCONFIG_NS, _SessionInitiator);
1080 sidom->setAttributeNS(nullptr, _type, discop);
1081 sidom->setAttributeNS(nullptr, _URL, discou);
1082 e->appendChild(sidom);
1083 if (log.isInfoEnabled()) {
1084 auto_ptr_char dp(discop);
1085 log.info("adding SessionInitiator of type (%s) to chain (/Login)", dp.get());
1089 log.error("SSO discoveryProtocol specified without discoveryURL");
1093 // Attach default Location to SSO element.
1094 static const XMLCh _loc[] = { chForwardSlash, chLatin_L, chLatin_o, chLatin_g, chLatin_i, chLatin_n, chNull };
1095 e->setAttributeNS(nullptr, Location, _loc);
1097 // Instantiate Chaining initiator around the SSO element.
1098 boost::shared_ptr<SessionInitiator> chain(
1099 conf.SessionInitiatorManager.newPlugin(CHAINING_SESSION_INITIATOR, pair<const DOMElement*,const char*>(e, getId()))
1101 m_handlers.push_back(chain);
1102 m_sessionInitDefault = chain.get();
1103 m_handlerMap["/Login"] = chain.get();
1106 void XMLApplication::doLogout(const ProtocolProvider& pp, set<string>& protocols, DOMElement* e, Category& log)
1108 if (!e->hasChildNodes())
1111 SPConfig& conf = SPConfig::getConfig();
1113 // Tokenize the protocol list inside the element.
1114 XMLStringTokenizer prottokens(e->getTextContent());
1115 while (prottokens.hasMoreTokens()) {
1116 auto_ptr_char prot(prottokens.nextToken());
1118 // Look for initiator.
1119 const PropertySet* initiator = pp.getInitiator(prot.get(), "Logout");
1121 log.info("auto-configuring Logout initiation for protocol (%s)", prot.get());
1122 pair<bool,const XMLCh*> inittype = initiator->getXMLString("id");
1123 if (inittype.first) {
1124 // Append a logout initiator element of the designated type to the root element.
1125 DOMElement* lidom = e->getOwnerDocument()->createElementNS(shibspconstants::SHIB2SPCONFIG_NS, _LogoutInitiator);
1126 lidom->setAttributeNS(nullptr, _type, inittype.second);
1127 e->appendChild(lidom);
1128 log.info("adding LogoutInitiator of type (%s) to chain (/Logout)", initiator->getString("id").second);
1130 if (protocols.count(prot.get()) == 0) {
1131 doArtifactResolution(pp, prot.get(), e, log);
1132 protocols.insert(prot.get());
1136 log.error("missing id property on Initiator element, check config for protocol (%s)", prot.get());
1140 // Look for incoming bindings.
1141 const vector<const PropertySet*>& bindings = pp.getBindings(prot.get(), "Logout");
1142 if (!bindings.empty()) {
1143 log.info("auto-configuring Logout endpoints for protocol (%s)", prot.get());
1144 pair<bool,const XMLCh*> idprop,pathprop;
1145 for (vector<const PropertySet*>::const_iterator b = bindings.begin(); b != bindings.end(); ++b) {
1146 idprop = (*b)->getXMLString("id");
1147 pathprop = (*b)->getXMLString("path");
1148 if (idprop.first && pathprop.first) {
1149 DOMElement* slodom = e->getOwnerDocument()->createElementNS(samlconstants::SAML20MD_NS, _SingleLogoutService);
1150 slodom->setAttributeNS(nullptr, Binding, idprop.second);
1151 slodom->setAttributeNS(nullptr, Location, pathprop.second);
1153 log.info("adding SingleLogoutService for Binding (%s) at (%s)", (*b)->getString("id").second, (*b)->getString("path").second);
1154 boost::shared_ptr<Handler> handler(
1155 conf.SingleLogoutServiceManager.newPlugin((*b)->getString("id").second, pair<const DOMElement*,const char*>(slodom, getId()))
1157 m_handlers.push_back(handler);
1159 // Insert into location map.
1160 pair<bool,const char*> location = handler->getString("Location");
1161 if (location.first && *location.second == '/')
1162 m_handlerMap[location.second] = handler.get();
1163 else if (location.first)
1164 m_handlerMap[string("/") + location.second] = handler.get();
1167 log.error("missing id or path property on Binding element, check config for protocol (%s)", prot.get());
1171 if (protocols.count(prot.get()) == 0) {
1172 doArtifactResolution(pp, prot.get(), e, log);
1173 protocols.insert(prot.get());
1177 if (!initiator && bindings.empty()) {
1178 log.error("no Logout Initiator or Binding config for protocol (%s)", prot.get());
1182 // Attach default Location to Logout element.
1183 static const XMLCh _loc[] = { chForwardSlash, chLatin_L, chLatin_o, chLatin_g, chLatin_o, chLatin_u, chLatin_t, chNull };
1184 e->setAttributeNS(nullptr, Location, _loc);
1186 // Instantiate Chaining initiator around the SSO element.
1187 boost::shared_ptr<Handler> chain(
1188 conf.LogoutInitiatorManager.newPlugin(CHAINING_LOGOUT_INITIATOR, pair<const DOMElement*,const char*>(e, getId()))
1190 m_handlers.push_back(chain);
1191 m_handlerMap["/Logout"] = chain.get();
1194 void XMLApplication::doNameIDMgmt(const ProtocolProvider& pp, set<string>& protocols, DOMElement* e, Category& log)
1196 if (!e->hasChildNodes())
1199 SPConfig& conf = SPConfig::getConfig();
1201 // Tokenize the protocol list inside the element.
1202 XMLStringTokenizer prottokens(e->getTextContent());
1203 while (prottokens.hasMoreTokens()) {
1204 auto_ptr_char prot(prottokens.nextToken());
1206 // Look for incoming bindings.
1207 const vector<const PropertySet*>& bindings = pp.getBindings(prot.get(), "NameIDMgmt");
1208 if (!bindings.empty()) {
1209 log.info("auto-configuring NameIDMgmt endpoints for protocol (%s)", prot.get());
1210 pair<bool,const XMLCh*> idprop,pathprop;
1211 for (vector<const PropertySet*>::const_iterator b = bindings.begin(); b != bindings.end(); ++b) {
1212 idprop = (*b)->getXMLString("id");
1213 pathprop = (*b)->getXMLString("path");
1214 if (idprop.first && pathprop.first) {
1215 DOMElement* nimdom = e->getOwnerDocument()->createElementNS(samlconstants::SAML20MD_NS, _ManageNameIDService);
1216 nimdom->setAttributeNS(nullptr, Binding, idprop.second);
1217 nimdom->setAttributeNS(nullptr, Location, pathprop.second);
1219 log.info("adding ManageNameIDService for Binding (%s) at (%s)", (*b)->getString("id").second, (*b)->getString("path").second);
1220 boost::shared_ptr<Handler> handler(
1221 conf.ManageNameIDServiceManager.newPlugin((*b)->getString("id").second, pair<const DOMElement*,const char*>(nimdom, getId()))
1223 m_handlers.push_back(handler);
1225 // Insert into location map.
1226 pair<bool,const char*> location = handler->getString("Location");
1227 if (location.first && *location.second == '/')
1228 m_handlerMap[location.second] = handler.get();
1229 else if (location.first)
1230 m_handlerMap[string("/") + location.second] = handler.get();
1233 log.error("missing id or path property on Binding element, check config for protocol (%s)", prot.get());
1237 if (protocols.count(prot.get()) == 0) {
1238 doArtifactResolution(pp, prot.get(), e, log);
1239 protocols.insert(prot.get());
1243 log.error("no NameIDMgmt Binding config for protocol (%s)", prot.get());
1248 void XMLApplication::doArtifactResolution(const ProtocolProvider& pp, const char* protocol, DOMElement* e, Category& log)
1250 SPConfig& conf = SPConfig::getConfig();
1252 // Look for incoming bindings.
1253 const vector<const PropertySet*>& bindings = pp.getBindings(protocol, "ArtifactResolution");
1254 if (!bindings.empty()) {
1255 log.info("auto-configuring ArtifactResolution endpoints for protocol (%s)", protocol);
1257 pair<bool,const XMLCh*> idprop,pathprop;
1258 for (vector<const PropertySet*>::const_iterator b = bindings.begin(); b != bindings.end(); ++b) {
1259 idprop = (*b)->getXMLString("id");
1260 pathprop = (*b)->getXMLString("path");
1261 if (idprop.first && pathprop.first) {
1262 DOMElement* artdom = e->getOwnerDocument()->createElementNS(samlconstants::SAML20MD_NS, _ArtifactResolutionService);
1263 artdom->setAttributeNS(nullptr, Binding, idprop.second);
1264 artdom->setAttributeNS(nullptr, Location, pathprop.second);
1265 xstring indexbuf(chDigit_1 + (index % 10), 1);
1267 indexbuf = (XMLCh)(chDigit_1 + (index / 10)) + indexbuf;
1268 artdom->setAttributeNS(nullptr, _index, indexbuf.c_str());
1270 log.info("adding ArtifactResolutionService for Binding (%s) at (%s)", (*b)->getString("id").second, (*b)->getString("path").second);
1271 boost::shared_ptr<Handler> handler(
1272 conf.ArtifactResolutionServiceManager.newPlugin((*b)->getString("id").second, pair<const DOMElement*,const char*>(artdom, getId()))
1274 m_handlers.push_back(handler);
1276 if (!m_artifactResolutionDefault)
1277 m_artifactResolutionDefault = handler.get();
1279 // Insert into location map.
1280 pair<bool,const char*> location = handler->getString("Location");
1281 if (location.first && *location.second == '/')
1282 m_handlerMap[location.second] = handler.get();
1283 else if (location.first)
1284 m_handlerMap[string("/") + location.second] = handler.get();
1287 log.error("missing id or path property on Binding element, check config for protocol (%s)", protocol);
1294 void XMLApplication::doAttributePlugins(DOMElement* e, Category& log)
1296 SPConfig& conf = SPConfig::getConfig();
1298 m_attrExtractor.reset(
1299 doChainedPlugins(conf.AttributeExtractorManager, "AttributeExtractor", CHAINING_ATTRIBUTE_EXTRACTOR, _AttributeExtractor, e, log)
1303 doChainedPlugins(conf.AttributeFilterManager, "AttributeFilter", CHAINING_ATTRIBUTE_FILTER, _AttributeFilter, e, log, DUMMY_ATTRIBUTE_FILTER)
1306 m_attrResolver.reset(
1307 doChainedPlugins(conf.AttributeResolverManager, "AttributeResolver", CHAINING_ATTRIBUTE_RESOLVER, _AttributeResolver, e, log)
1310 if (m_unsetHeaders.empty()) {
1311 vector<string> unsetHeaders;
1312 if (m_attrExtractor) {
1313 Locker extlock(m_attrExtractor.get());
1314 m_attrExtractor->getAttributeIds(unsetHeaders);
1316 else if (m_base && m_base->m_attrExtractor) {
1317 Locker extlock(m_base->m_attrExtractor.get());
1318 m_base->m_attrExtractor->getAttributeIds(unsetHeaders);
1320 if (m_attrResolver) {
1321 Locker reslock(m_attrResolver.get());
1322 m_attrResolver->getAttributeIds(unsetHeaders);
1324 else if (m_base && m_base->m_attrResolver) {
1325 Locker extlock(m_base->m_attrResolver.get());
1326 m_base->m_attrResolver->getAttributeIds(unsetHeaders);
1328 if (!unsetHeaders.empty()) {
1329 string transformedprefix(m_attributePrefix.second);
1331 pair<bool,const char*> prefix = getString("metadataAttributePrefix");
1333 pch = prefix.second;
1335 transformedprefix += (isalnum(*pch) ? toupper(*pch) : '_');
1339 for (vector<string>::const_iterator hdr = unsetHeaders.begin(); hdr!=unsetHeaders.end(); ++hdr) {
1343 transformed += (isalnum(*pch) ? toupper(*pch) : '_');
1346 m_unsetHeaders.push_back(make_pair(m_attributePrefix.first + *hdr, m_attributePrefix.second + transformed));
1348 m_unsetHeaders.push_back(make_pair(m_attributePrefix.first + prefix.second + *hdr, transformedprefix + transformed));
1351 m_unsetHeaders.push_back(make_pair(m_attributePrefix.first + "Shib-Application-ID", m_attributePrefix.second + "SHIB_APPLICATION_ID"));
1356 #ifdef SHIBSP_XERCESC_SHORT_ACCEPTNODE
1359 DOMNodeFilter::FilterAction
1361 XMLApplication::acceptNode(const DOMNode* node) const
1363 const XMLCh* name=node->getLocalName();
1364 if (XMLString::equals(name,ApplicationOverride) ||
1365 XMLString::equals(name,_Audience) ||
1366 XMLString::equals(name,Notify) ||
1367 XMLString::equals(name,_Handler) ||
1368 XMLString::equals(name,_AssertionConsumerService) ||
1369 XMLString::equals(name,_ArtifactResolutionService) ||
1370 XMLString::equals(name,Logout) ||
1371 XMLString::equals(name,_LogoutInitiator) ||
1372 XMLString::equals(name,_ManageNameIDService) ||
1373 XMLString::equals(name,NameIDMgmt) ||
1374 XMLString::equals(name,_SessionInitiator) ||
1375 XMLString::equals(name,_SingleLogoutService) ||
1376 XMLString::equals(name,SSO) ||
1377 XMLString::equals(name,RelyingParty) ||
1378 XMLString::equals(name,_MetadataProvider) ||
1379 XMLString::equals(name,_TrustEngine) ||
1380 XMLString::equals(name,_CredentialResolver) ||
1381 XMLString::equals(name,_AttributeFilter) ||
1382 XMLString::equals(name,_AttributeExtractor) ||
1383 XMLString::equals(name,_AttributeResolver))
1384 return FILTER_REJECT;
1386 return FILTER_ACCEPT;
1391 const PropertySet* XMLApplication::getRelyingParty(const EntityDescriptor* provider) const
1396 map< xstring,boost::shared_ptr<PropertySet> >::const_iterator i = m_partyMap.find(provider->getEntityID());
1397 if (i != m_partyMap.end())
1398 return i->second.get();
1399 const EntitiesDescriptor* group = dynamic_cast<const EntitiesDescriptor*>(provider->getParent());
1401 if (group->getName()) {
1402 i = m_partyMap.find(group->getName());
1403 if (i != m_partyMap.end())
1404 return i->second.get();
1406 group = dynamic_cast<const EntitiesDescriptor*>(group->getParent());
1411 const PropertySet* XMLApplication::getRelyingParty(const XMLCh* entityID) const
1415 map< xstring,boost::shared_ptr<PropertySet> >::const_iterator i = m_partyMap.find(entityID);
1416 return (i != m_partyMap.end()) ? i->second.get() : this;
1421 string XMLApplication::getNotificationURL(const char* resource, bool front, unsigned int index) const
1423 const vector<string>& locs = front ? m_frontLogout : m_backLogout;
1425 return m_base ? m_base->getNotificationURL(resource, front, index) : string();
1426 else if (index >= locs.size())
1429 #ifdef HAVE_STRCASECMP
1430 if (!resource || (strncasecmp(resource,"http://",7) && strncasecmp(resource,"https://",8)))
1432 if (!resource || (strnicmp(resource,"http://",7) && strnicmp(resource,"https://",8)))
1434 throw ConfigurationException("Request URL was not absolute.");
1436 const char* handler = locs[index].c_str();
1438 // Should never happen...
1439 if (!handler || (*handler!='/' && strncmp(handler,"http:",5) && strncmp(handler,"https:",6)))
1440 throw ConfigurationException(
1441 "Invalid Location property ($1) in Notify element for Application ($2)",
1442 params(2, handler ? handler : "null", getId())
1445 // The "Location" property can be in one of three formats:
1447 // 1) a full URI: http://host/foo/bar
1448 // 2) a hostless URI: http:///foo/bar
1449 // 3) a relative path: /foo/bar
1451 // # Protocol Host Path
1452 // 1 handler handler handler
1453 // 2 handler resource handler
1454 // 3 resource resource handler
1456 const char* path = nullptr;
1458 // Decide whether to use the handler or the resource for the "protocol"
1460 if (*handler != '/') {
1468 // break apart the "protocol" string into protocol, host, and "the rest"
1469 const char* colon=strchr(prot,':');
1471 const char* slash=strchr(colon,'/');
1475 // Compute the actual protocol and store.
1476 string notifyURL(prot, colon-prot);
1478 // create the "host" from either the colon/slash or from the target string
1479 // If prot == handler then we're in either #1 or #2, else #3.
1480 // If slash == colon then we're in #2.
1481 if (prot != handler || slash == colon) {
1482 colon = strchr(resource, ':');
1483 colon += 3; // Get past the ://
1484 slash = strchr(colon, '/');
1486 string host(colon, (slash ? slash-colon : strlen(colon)));
1489 notifyURL += host + path;
1493 void XMLApplication::clearHeader(SPRequest& request, const char* rawname, const char* cginame) const
1495 if (!m_attributePrefix.first.empty()) {
1496 string temp = m_attributePrefix.first + rawname;
1497 string temp2 = m_attributePrefix.second + (cginame + 5);
1498 request.clearHeader(temp.c_str(), temp2.c_str());
1501 m_base->clearHeader(request, rawname, cginame);
1504 request.clearHeader(rawname, cginame);
1508 void XMLApplication::setHeader(SPRequest& request, const char* name, const char* value) const
1510 if (!m_attributePrefix.first.empty()) {
1511 string temp = m_attributePrefix.first + name;
1512 request.setHeader(temp.c_str(), value);
1515 m_base->setHeader(request, name, value);
1518 request.setHeader(name, value);
1522 string XMLApplication::getSecureHeader(const SPRequest& request, const char* name) const
1524 if (!m_attributePrefix.first.empty()) {
1525 string temp = m_attributePrefix.first + name;
1526 return request.getSecureHeader(temp.c_str());
1529 return m_base->getSecureHeader(request,name);
1532 return request.getSecureHeader(name);
1536 const SessionInitiator* XMLApplication::getDefaultSessionInitiator() const
1538 if (m_sessionInitDefault) return m_sessionInitDefault;
1539 return m_base ? m_base->getDefaultSessionInitiator() : nullptr;
1542 const SessionInitiator* XMLApplication::getSessionInitiatorById(const char* id) const
1544 map<string,const SessionInitiator*>::const_iterator i = m_sessionInitMap.find(id);
1545 if (i != m_sessionInitMap.end()) return i->second;
1546 return m_base ? m_base->getSessionInitiatorById(id) : nullptr;
1549 const Handler* XMLApplication::getDefaultAssertionConsumerService() const
1551 if (m_acsDefault) return m_acsDefault;
1552 return m_base ? m_base->getDefaultAssertionConsumerService() : nullptr;
1555 const Handler* XMLApplication::getAssertionConsumerServiceByIndex(unsigned short index) const
1557 map<unsigned int,const Handler*>::const_iterator i = m_acsIndexMap.find(index);
1558 if (i != m_acsIndexMap.end()) return i->second;
1559 return m_base ? m_base->getAssertionConsumerServiceByIndex(index) : nullptr;
1562 const Handler* XMLApplication::getAssertionConsumerServiceByProtocol(const XMLCh* protocol, const char* binding) const
1564 ACSProtocolMap::const_iterator i = m_acsProtocolMap.find(protocol);
1565 if (i != m_acsProtocolMap.end() && !i->second.empty()) {
1566 if (!binding || !*binding)
1567 return i->second.front();
1568 for (ACSProtocolMap::value_type::second_type::const_iterator j = i->second.begin(); j != i->second.end(); ++j) {
1569 if (!strcmp(binding, (*j)->getString("Binding").second))
1573 return m_base ? m_base->getAssertionConsumerServiceByProtocol(protocol, binding) : nullptr;
1576 const vector<const Handler*>& XMLApplication::getAssertionConsumerServicesByBinding(const XMLCh* binding) const
1578 ACSBindingMap::const_iterator i = m_acsBindingMap.find(binding);
1579 if (i != m_acsBindingMap.end())
1581 return m_base ? m_base->getAssertionConsumerServicesByBinding(binding) : g_noHandlers;
1584 const Handler* XMLApplication::getHandler(const char* path) const
1587 wrap = wrap.substr(0, wrap.find(';'));
1588 map<string,const Handler*>::const_iterator i = m_handlerMap.find(wrap.substr(0, wrap.find('?')));
1589 if (i != m_handlerMap.end())
1591 return m_base ? m_base->getHandler(path) : nullptr;
1594 void XMLApplication::getHandlers(vector<const Handler*>& handlers) const
1596 static void (vector<const Handler*>::* pb)(const Handler* const&) = &vector<const Handler*>::push_back;
1597 for_each(m_handlers.begin(), m_handlers.end(), boost::bind(pb, boost::ref(handlers), boost::bind(&boost::shared_ptr<Handler>::get, _1)));
1599 for (map<string,const Handler*>::const_iterator h = m_base->m_handlerMap.begin(); h != m_base->m_handlerMap.end(); ++h) {
1600 if (m_handlerMap.count(h->first) == 0)
1601 handlers.push_back(h->second);
1606 #ifdef SHIBSP_XERCESC_SHORT_ACCEPTNODE
1609 DOMNodeFilter::FilterAction
1611 XMLConfigImpl::acceptNode(const DOMNode* node) const
1613 if (!XMLString::equals(node->getNamespaceURI(),shibspconstants::SHIB2SPCONFIG_NS))
1614 return FILTER_ACCEPT;
1615 const XMLCh* name=node->getLocalName();
1616 if (XMLString::equals(name,ApplicationDefaults) ||
1617 XMLString::equals(name,_ArtifactMap) ||
1618 XMLString::equals(name,_Extensions) ||
1619 XMLString::equals(name,Listener) ||
1620 XMLString::equals(name,_ProtocolProvider) ||
1621 XMLString::equals(name,_RequestMapper) ||
1622 XMLString::equals(name,_ReplayCache) ||
1623 XMLString::equals(name,SecurityPolicies) ||
1624 XMLString::equals(name,_SecurityPolicyProvider) ||
1625 XMLString::equals(name,_SessionCache) ||
1626 XMLString::equals(name,Site) ||
1627 XMLString::equals(name,_StorageService) ||
1628 XMLString::equals(name,TCPListener) ||
1629 XMLString::equals(name,TransportOption) ||
1630 XMLString::equals(name,UnixListener))
1631 return FILTER_REJECT;
1633 return FILTER_ACCEPT;
1636 void XMLConfigImpl::doExtensions(const DOMElement* e, const char* label, Category& log)
1638 const DOMElement* exts = XMLHelper::getFirstChildElement(e, _Extensions);
1640 exts = XMLHelper::getFirstChildElement(exts, Library);
1642 string path(XMLHelper::getAttrString(exts, nullptr, _path));
1644 if (!path.empty()) {
1645 if (!XMLToolingConfig::getConfig().load_library(path.c_str(), (void*)exts))
1646 throw ConfigurationException("XMLToolingConfig::load_library failed.");
1647 log.debug("loaded %s extension library (%s)", label, path.c_str());
1650 catch (std::exception& e) {
1651 if (XMLHelper::getAttrBool(exts, false, _fatal)) {
1652 log.fatal("unable to load mandatory %s extension library %s: %s", label, path.c_str(), e.what());
1656 log.crit("unable to load optional %s extension library %s: %s", label, path.c_str(), e.what());
1659 exts = XMLHelper::getNextSiblingElement(exts, Library);
1664 void XMLConfigImpl::doListener(const DOMElement* e, XMLConfig* conf, Category& log)
1667 string plugtype(TCP_LISTENER_SERVICE);
1669 string plugtype(UNIX_LISTENER_SERVICE);
1671 DOMElement* child = XMLHelper::getFirstChildElement(e, UnixListener);
1673 plugtype = UNIX_LISTENER_SERVICE;
1675 child = XMLHelper::getFirstChildElement(e, TCPListener);
1677 plugtype = TCP_LISTENER_SERVICE;
1679 child = XMLHelper::getFirstChildElement(e, Listener);
1681 auto_ptr_char type(child->getAttributeNS(nullptr, _type));
1682 if (type.get() && *type.get())
1683 plugtype = type.get();
1688 log.info("building ListenerService of type %s...", plugtype.c_str());
1689 conf->m_listener.reset(SPConfig::getConfig().ListenerServiceManager.newPlugin(plugtype.c_str(), child));
1692 void XMLConfigImpl::doCaching(const DOMElement* e, XMLConfig* conf, Category& log)
1694 SPConfig& spConf = SPConfig::getConfig();
1696 SAMLConfig& samlConf = SAMLConfig::getConfig();
1701 if (spConf.isEnabled(SPConfig::OutOfProcess)) {
1702 XMLToolingConfig& xmlConf = XMLToolingConfig::getConfig();
1703 // First build any StorageServices.
1704 child = XMLHelper::getFirstChildElement(e, _StorageService);
1706 string id(XMLHelper::getAttrString(child, nullptr, _id));
1707 string t(XMLHelper::getAttrString(child, nullptr, _type));
1710 log.info("building StorageService (%s) of type %s...", id.c_str(), t.c_str());
1711 conf->m_storage[id] = boost::shared_ptr<StorageService>(xmlConf.StorageServiceManager.newPlugin(t.c_str(), child));
1713 catch (std::exception& ex) {
1714 log.crit("failed to instantiate StorageService (%s): %s", id.c_str(), ex.what());
1717 child = XMLHelper::getNextSiblingElement(child, _StorageService);
1720 if (conf->m_storage.empty()) {
1721 log.info("no StorageService plugin(s) installed, using (mem) in-memory instance");
1722 conf->m_storage["mem"] = boost::shared_ptr<StorageService>(xmlConf.StorageServiceManager.newPlugin(MEMORY_STORAGE_SERVICE, nullptr));
1726 StorageService* replaySS = nullptr;
1727 child = XMLHelper::getFirstChildElement(e, _ReplayCache);
1729 string ssid(XMLHelper::getAttrString(child, nullptr, _StorageService));
1730 if (!ssid.empty()) {
1731 if (conf->m_storage.count(ssid)) {
1732 log.info("building ReplayCache on top of StorageService (%s)...", ssid.c_str());
1733 replaySS = conf->m_storage[ssid].get();
1736 log.error("unable to locate StorageService (%s), using arbitrary instance for ReplayCache", ssid.c_str());
1737 replaySS = conf->m_storage.begin()->second.get();
1741 log.info("no StorageService specified for ReplayCache, using arbitrary instance");
1742 replaySS = conf->m_storage.begin()->second.get();
1746 log.info("no ReplayCache specified, using arbitrary StorageService instance");
1747 replaySS = conf->m_storage.begin()->second.get();
1749 xmlConf.setReplayCache(new ReplayCache(replaySS));
1752 child = XMLHelper::getFirstChildElement(e, _ArtifactMap);
1754 string ssid(XMLHelper::getAttrString(child, nullptr, _StorageService));
1755 if (!ssid.empty()) {
1756 if (conf->m_storage.count(ssid)) {
1757 log.info("building ArtifactMap on top of StorageService (%s)...", ssid.c_str());
1758 samlConf.setArtifactMap(new ArtifactMap(child, conf->m_storage[ssid].get()));
1761 log.error("unable to locate StorageService (%s), using in-memory ArtifactMap", ssid.c_str());
1762 samlConf.setArtifactMap(new ArtifactMap(child));
1766 log.info("no StorageService specified, using in-memory ArtifactMap");
1767 samlConf.setArtifactMap(new ArtifactMap(child));
1771 log.info("no ArtifactMap specified, building in-memory ArtifactMap...");
1772 samlConf.setArtifactMap(new ArtifactMap(child));
1774 } // end of out of process caching components
1777 child = XMLHelper::getFirstChildElement(e, _SessionCache);
1779 string t(XMLHelper::getAttrString(child, nullptr, _type));
1781 log.info("building SessionCache of type %s...", t.c_str());
1782 conf->m_sessionCache.reset(spConf.SessionCacheManager.newPlugin(t.c_str(), child));
1785 if (!conf->m_sessionCache) {
1786 log.info("no SessionCache specified, using StorageService-backed instance");
1787 conf->m_sessionCache.reset(spConf.SessionCacheManager.newPlugin(STORAGESERVICE_SESSION_CACHE, nullptr));
1791 XMLConfigImpl::XMLConfigImpl(const DOMElement* e, bool first, XMLConfig* outer, Category& log) : m_document(nullptr)
1794 xmltooling::NDC ndc("XMLConfigImpl");
1796 SPConfig& conf=SPConfig::getConfig();
1797 XMLToolingConfig& xmlConf=XMLToolingConfig::getConfig();
1798 const DOMElement* SHAR=XMLHelper::getFirstChildElement(e, OutOfProcess);
1799 const DOMElement* SHIRE=XMLHelper::getFirstChildElement(e, InProcess);
1801 // Initialize logging manually in order to redirect log messages as soon as possible.
1802 if (conf.isEnabled(SPConfig::Logging)) {
1804 if (conf.isEnabled(SPConfig::OutOfProcess))
1805 logconf = XMLHelper::getAttrString(SHAR, nullptr, logger);
1806 else if (conf.isEnabled(SPConfig::InProcess))
1807 logconf = XMLHelper::getAttrString(SHIRE, nullptr, logger);
1808 if (logconf.empty())
1809 logconf = XMLHelper::getAttrString(e, nullptr, logger);
1810 if (logconf.empty() && !getenv("SHIBSP_LOGGING")) {
1811 // No properties found, so default them.
1812 if (conf.isEnabled(SPConfig::OutOfProcess) && !conf.isEnabled(SPConfig::InProcess))
1813 logconf = "shibd.logger";
1814 else if (!conf.isEnabled(SPConfig::OutOfProcess) && conf.isEnabled(SPConfig::InProcess))
1815 logconf = "native.logger";
1817 logconf = "shibboleth.logger";
1819 if (!logconf.empty()) {
1820 log.debug("loading new logging configuration from (%s), check log destination for status of configuration", logconf.c_str());
1821 if (!XMLToolingConfig::getConfig().log_config(logconf.c_str()))
1822 log.crit("failed to load new logging configuration from (%s)", logconf.c_str());
1828 XMLHelper::getAttrString(SHAR, nullptr, tranLogFormat).c_str(),
1829 XMLHelper::getAttrString(SHAR, nullptr, tranLogFiller).c_str()
1835 // Re-log library versions now that logging is set up.
1836 log.info("Shibboleth SP Version %s", PACKAGE_VERSION);
1839 "Library versions: %s %s, Xerces-C %s, XML-Security-C %s, XMLTooling-C %s, OpenSAML-C %s, Shibboleth %s",
1840 # if defined(LOG4SHIB_VERSION)
1841 "log4shib", LOG4SHIB_VERSION,
1842 # elif defined(LOG4CPP_VERSION)
1843 "log4cpp", LOG4CPP_VERSION,
1847 XERCES_FULLVERSIONDOT, XSEC_FULLVERSIONDOT, gXMLToolingDotVersionStr, gOpenSAMLDotVersionStr, gShibSPDotVersionStr
1851 "Library versions: %s %s, Xerces-C %s, XMLTooling-C %s, Shibboleth %s",
1852 # if defined(LOG4SHIB_VERSION)
1853 "log4shib", LOG4SHIB_VERSION,
1854 # elif defined(LOG4CPP_VERSION)
1855 "log4cpp", LOG4CPP_VERSION,
1859 XERCES_FULLVERSIONDOT, gXMLToolingDotVersionStr, gShibSPDotVersionStr
1863 // First load any property sets.
1864 load(e, nullptr, this);
1868 // Much of the processing can only occur on the first instantiation.
1871 pair<bool,unsigned int> skew=getUnsignedInt("clockSkew");
1873 xmlConf.clock_skew_secs=min(skew.second,(60*60*24*7*28));
1875 pair<bool,const char*> unsafe = getString("unsafeChars");
1877 TemplateEngine::unsafe_chars = unsafe.second;
1879 unsafe = getString("allowedSchemes");
1881 HTTPResponse::getAllowedSchemes().clear();
1882 string schemes(unsafe.second);
1883 split(HTTPResponse::getAllowedSchemes(), schemes, is_space(), algorithm::token_compress_on);
1886 // Default language handling.
1887 pair<bool,bool> langFromClient = getBool("langFromClient");
1888 pair<bool,const XMLCh*> langPriority = getXMLString("langPriority");
1889 GenericRequest::setLangDefaults(!langFromClient.first || langFromClient.second, langPriority.second);
1892 doExtensions(e, "global", log);
1893 if (conf.isEnabled(SPConfig::OutOfProcess))
1894 doExtensions(SHAR, "out of process", log);
1896 if (conf.isEnabled(SPConfig::InProcess))
1897 doExtensions(SHIRE, "in process", log);
1899 // Instantiate the ListenerService and SessionCache objects.
1900 if (conf.isEnabled(SPConfig::Listener))
1901 doListener(e, outer, log);
1904 if (outer->m_listener && conf.isEnabled(SPConfig::OutOfProcess) && !conf.isEnabled(SPConfig::InProcess)) {
1905 outer->m_listener->regListener("set::RelayState", outer);
1906 outer->m_listener->regListener("get::RelayState", outer);
1907 outer->m_listener->regListener("set::PostData", outer);
1908 outer->m_listener->regListener("get::PostData", outer);
1911 if (conf.isEnabled(SPConfig::Caching))
1912 doCaching(e, outer, log);
1913 } // end of first-time-only stuff
1915 // Back to the fully dynamic stuff...next up is the RequestMapper.
1916 if (conf.isEnabled(SPConfig::RequestMapping)) {
1917 if (child = XMLHelper::getFirstChildElement(e, _RequestMapper)) {
1918 string t(XMLHelper::getAttrString(child, nullptr, _type));
1920 log.info("building RequestMapper of type %s...", t.c_str());
1921 m_requestMapper.reset(conf.RequestMapperManager.newPlugin(t.c_str(), child));
1924 if (!m_requestMapper) {
1925 log.info("no RequestMapper specified, using 'Native' plugin with empty/default map");
1926 child = e->getOwnerDocument()->createElementNS(nullptr, _RequestMapper);
1927 DOMElement* mapperDummy = e->getOwnerDocument()->createElementNS(shibspconstants::SHIB2SPCONFIG_NS, RequestMap);
1928 mapperDummy->setAttributeNS(nullptr, applicationId, _default);
1929 child->appendChild(mapperDummy);
1930 m_requestMapper.reset(conf.RequestMapperManager.newPlugin(NATIVE_REQUEST_MAPPER, child));
1935 // Load security policies.
1936 if (child = XMLHelper::getLastChildElement(e, _SecurityPolicyProvider)) {
1937 string t(XMLHelper::getAttrString(child, nullptr, _type));
1939 log.info("building SecurityPolicyProvider of type %s...", t.c_str());
1940 m_policy.reset(conf.SecurityPolicyProviderManager.newPlugin(t.c_str(), child));
1943 throw ConfigurationException("can't build SecurityPolicyProvider, no type specified");
1946 else if (child = XMLHelper::getLastChildElement(e, SecurityPolicies)) {
1947 // For backward compatibility, wrap in a plugin element.
1948 DOMElement* polwrapper = e->getOwnerDocument()->createElementNS(nullptr, _SecurityPolicyProvider);
1949 polwrapper->appendChild(child);
1950 log.info("building SecurityPolicyProvider of type %s...", XML_SECURITYPOLICY_PROVIDER);
1951 m_policy.reset(conf.SecurityPolicyProviderManager.newPlugin(XML_SECURITYPOLICY_PROVIDER, polwrapper));
1954 log.fatal("can't build SecurityPolicyProvider, missing conf:SecurityPolicyProvider element?");
1955 throw ConfigurationException("Can't build SecurityPolicyProvider, missing conf:SecurityPolicyProvider element?");
1959 if (!m_policy->getAlgorithmBlacklist().empty()) {
1960 #ifdef SHIBSP_XMLSEC_WHITELISTING
1962 m_policy->getAlgorithmBlacklist().begin(), m_policy->getAlgorithmBlacklist().end(),
1963 boost::bind(&XSECPlatformUtils::blacklistAlgorithm, boost::bind(&xstring::c_str, _1))
1966 log.crit("XML-Security-C library prior to 1.6.0 does not support algorithm white/blacklists");
1969 else if (!m_policy->getAlgorithmWhitelist().empty()) {
1970 #ifdef SHIBSP_XMLSEC_WHITELISTING
1972 m_policy->getAlgorithmWhitelist().begin(), m_policy->getAlgorithmWhitelist().end(),
1973 boost::bind(&XSECPlatformUtils::whitelistAlgorithm, boost::bind(&xstring::c_str, _1))
1976 log.crit("XML-Security-C library prior to 1.6.0 does not support algorithm white/blacklists");
1981 // Process TransportOption elements.
1982 child = XMLHelper::getLastChildElement(e, TransportOption);
1984 if (child->hasChildNodes()) {
1985 string provider(XMLHelper::getAttrString(child, nullptr, _provider));
1986 string option(XMLHelper::getAttrString(child, nullptr, _option));
1987 auto_ptr_char value(child->getFirstChild()->getNodeValue());
1988 if (!provider.empty() && !option.empty() && value.get() && *value.get()) {
1989 m_transportOptions.push_back(make_tuple(provider, option, string(value.get())));
1992 child = XMLHelper::getPreviousSiblingElement(child, TransportOption);
1996 scoped_ptr<ProtocolProvider> pp;
1997 if (conf.isEnabled(SPConfig::Handlers)) {
1998 if (child = XMLHelper::getLastChildElement(e, _ProtocolProvider)) {
1999 string t(XMLHelper::getAttrString(child, nullptr, _type));
2001 log.info("building ProtocolProvider of type %s...", t.c_str());
2002 pp.reset(conf.ProtocolProviderManager.newPlugin(t.c_str(), child));
2006 Locker pplocker(pp.get());
2008 // Load the default application.
2009 child = XMLHelper::getLastChildElement(e, ApplicationDefaults);
2011 log.fatal("can't build default Application object, missing conf:ApplicationDefaults element?");
2012 throw ConfigurationException("can't build default Application object, missing conf:ApplicationDefaults element?");
2014 boost::shared_ptr<XMLApplication> defapp(new XMLApplication(outer, pp.get(), child));
2015 m_appmap[defapp->getId()] = defapp;
2017 // Load any overrides.
2018 child = XMLHelper::getFirstChildElement(child, ApplicationOverride);
2020 boost::shared_ptr<XMLApplication> iapp(new XMLApplication(outer, pp.get(), child, defapp.get()));
2021 if (m_appmap.count(iapp->getId()))
2022 log.crit("found conf:ApplicationOverride element with duplicate id attribute (%s), skipping it", iapp->getId());
2024 m_appmap[iapp->getId()] = iapp;
2026 child = XMLHelper::getNextSiblingElement(child, ApplicationOverride);
2029 // Check for extra AuthTypes to recognize.
2030 if (conf.isEnabled(SPConfig::InProcess)) {
2031 const PropertySet* inprocs = getPropertySet("InProcess");
2033 pair<bool,const char*> extraAuthTypes = inprocs->getString("extraAuthTypes");
2034 if (extraAuthTypes.first) {
2035 string types(extraAuthTypes.second);
2036 split(outer->m_authTypes, types, is_space(), algorithm::token_compress_on);
2043 void XMLConfig::receive(DDF& in, ostream& out)
2045 if (!strcmp(in.name(), "get::RelayState")) {
2046 const char* id = in["id"].string();
2047 const char* key = in["key"].string();
2049 throw ListenerException("Required parameters missing for RelayState recovery.");
2052 StorageService* storage = getStorageService(id);
2054 if (storage->readString("RelayState",key,&relayState)>0) {
2055 if (in["clear"].integer())
2056 storage->deleteString("RelayState",key);
2058 else if (storage->readText("RelayState",key,&relayState)>0) {
2059 if (in["clear"].integer())
2060 storage->deleteText("RelayState",key);
2064 Category::getInstance(SHIBSP_LOGCAT".ServiceProvider").error(
2065 "Storage-backed RelayState with invalid StorageService ID (%s)", id
2069 // Repack for return to caller.
2070 DDF ret=DDF(nullptr).unsafe_string(relayState.c_str());
2071 DDFJanitor jret(ret);
2074 else if (!strcmp(in.name(), "set::RelayState")) {
2075 const char* id = in["id"].string();
2076 const char* value = in["value"].string();
2078 throw ListenerException("Required parameters missing for RelayState creation.");
2081 StorageService* storage = getStorageService(id);
2083 SAMLConfig::getConfig().generateRandomBytes(rsKey,32);
2084 rsKey = SAMLArtifact::toHex(rsKey);
2085 if (strlen(value) <= storage->getCapabilities().getStringSize())
2086 storage->createString("RelayState", rsKey.c_str(), value, time(nullptr) + 600);
2088 storage->createText("RelayState", rsKey.c_str(), value, time(nullptr) + 600);
2091 Category::getInstance(SHIBSP_LOGCAT".ServiceProvider").error(
2092 "Storage-backed RelayState with invalid StorageService ID (%s)", id
2096 // Repack for return to caller.
2097 DDF ret=DDF(nullptr).string(rsKey.c_str());
2098 DDFJanitor jret(ret);
2101 else if (!strcmp(in.name(), "get::PostData")) {
2102 const char* id = in["id"].string();
2103 const char* key = in["key"].string();
2105 throw ListenerException("Required parameters missing for PostData recovery.");
2108 StorageService* storage = getStorageService(id);
2110 if (storage->readText("PostData",key,&postData) > 0) {
2111 storage->deleteText("PostData",key);
2115 Category::getInstance(SHIBSP_LOGCAT".ServiceProvider").error(
2116 "Storage-backed PostData with invalid StorageService ID (%s)", id
2119 // If the data's empty, we'll send nothing back.
2120 // If not, we don't need to round trip it, just send back the serialized DDF list.
2121 if (postData.empty()) {
2123 DDFJanitor jret(ret);
2130 else if (!strcmp(in.name(), "set::PostData")) {
2131 const char* id = in["id"].string();
2132 if (!id || !in["parameters"].islist())
2133 throw ListenerException("Required parameters missing for PostData creation.");
2136 StorageService* storage = getStorageService(id);
2138 SAMLConfig::getConfig().generateRandomBytes(rsKey,32);
2139 rsKey = SAMLArtifact::toHex(rsKey);
2140 ostringstream params;
2141 params << in["parameters"];
2142 storage->createText("PostData", rsKey.c_str(), params.str().c_str(), time(nullptr) + 600);
2145 Category::getInstance(SHIBSP_LOGCAT".ServiceProvider").error(
2146 "Storage-backed PostData with invalid StorageService ID (%s)", id
2150 // Repack for return to caller.
2151 DDF ret=DDF(nullptr).string(rsKey.c_str());
2152 DDFJanitor jret(ret);
2158 pair<bool,DOMElement*> XMLConfig::background_load()
2160 // Load from source using base class.
2161 pair<bool,DOMElement*> raw = ReloadableXMLFile::load();
2163 // If we own it, wrap it.
2164 XercesJanitor<DOMDocument> docjanitor(raw.first ? raw.second->getOwnerDocument() : nullptr);
2166 scoped_ptr<XMLConfigImpl> impl(new XMLConfigImpl(raw.second, (m_impl==nullptr), this, m_log));
2168 // If we held the document, transfer it to the impl. If we didn't, it's a no-op.
2169 impl->setDocument(docjanitor.release());
2171 // Perform the swap inside a lock.
2174 SharedLock locker(m_lock, false);
2177 return make_pair(false,(DOMElement*)nullptr);