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/lexical_cast.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/exceptions.h>
74 # include <saml/version.h>
75 # include <saml/SAMLConfig.h>
76 # include <saml/binding/ArtifactMap.h>
77 # include <saml/binding/SAMLArtifact.h>
78 # include <saml/saml1/core/Assertions.h>
79 # include <saml/saml2/core/Assertions.h>
80 # include <saml/saml2/binding/SAML2ArtifactType0004.h>
81 # include <saml/saml2/metadata/Metadata.h>
82 # include <saml/saml2/metadata/MetadataProvider.h>
83 # include <saml/util/SAMLConstants.h>
84 # include <xmltooling/security/ChainingTrustEngine.h>
85 # include <xmltooling/security/CredentialResolver.h>
86 # include <xmltooling/security/SecurityHelper.h>
87 # include <xmltooling/util/ReplayCache.h>
88 # include <xmltooling/util/StorageService.h>
89 # include <xsec/utils/XSECPlatformUtils.hpp>
90 using namespace opensaml::saml2;
91 using namespace opensaml::saml2p;
92 using namespace opensaml::saml2md;
93 using namespace opensaml;
95 # include "lite/SAMLConstants.h"
98 using namespace shibsp;
99 using namespace xmltooling;
100 using namespace boost;
104 # define min(a,b) (((a) < (b)) ? (a) : (b))
109 #if defined (_MSC_VER)
110 #pragma warning( push )
111 #pragma warning( disable : 4250 )
114 static vector<const Handler*> g_noHandlers;
116 // Application configuration wrapper
117 class SHIBSP_DLLLOCAL XMLApplication : public Application, public Remoted, public DOMPropertySet, public DOMNodeFilter
120 XMLApplication(const ServiceProvider*, const ProtocolProvider*, DOMElement*, const XMLApplication* base=nullptr);
123 const char* getHash() const {return m_hash.c_str();}
126 SAMLArtifact* generateSAML1Artifact(const EntityDescriptor* relyingParty) const {
127 throw ConfigurationException("No support for SAML 1.x artifact generation.");
129 SAML2Artifact* generateSAML2Artifact(const EntityDescriptor* relyingParty) const {
130 pair<bool,int> index = make_pair(false,0);
131 const PropertySet* props = getRelyingParty(relyingParty);
132 index = props->getInt("artifactEndpointIndex");
134 index = getArtifactEndpointIndex();
135 pair<bool,const char*> entityID = props->getString("entityID");
136 return new SAML2ArtifactType0004(
137 SecurityHelper::doHash("SHA1", entityID.second, strlen(entityID.second), false),
138 index.first ? index.second : 1
142 MetadataProvider* getMetadataProvider(bool required=true) const {
143 if (required && !m_base && !m_metadata)
144 throw ConfigurationException("No MetadataProvider available.");
145 return (!m_metadata && m_base) ? m_base->getMetadataProvider(required) : m_metadata.get();
147 TrustEngine* getTrustEngine(bool required=true) const {
148 if (required && !m_base && !m_trust)
149 throw ConfigurationException("No TrustEngine available.");
150 return (!m_trust && m_base) ? m_base->getTrustEngine(required) : m_trust.get();
152 AttributeExtractor* getAttributeExtractor() const {
153 return (!m_attrExtractor && m_base) ? m_base->getAttributeExtractor() : m_attrExtractor.get();
155 AttributeFilter* getAttributeFilter() const {
156 return (!m_attrFilter && m_base) ? m_base->getAttributeFilter() : m_attrFilter.get();
158 AttributeResolver* getAttributeResolver() const {
159 return (!m_attrResolver && m_base) ? m_base->getAttributeResolver() : m_attrResolver.get();
161 CredentialResolver* getCredentialResolver() const {
162 return (!m_credResolver && m_base) ? m_base->getCredentialResolver() : m_credResolver.get();
164 const PropertySet* getRelyingParty(const EntityDescriptor* provider) const;
165 const PropertySet* getRelyingParty(const XMLCh* entityID) const;
166 const vector<const XMLCh*>* getAudiences() const {
167 return (m_audiences.empty() && m_base) ? m_base->getAudiences() : &m_audiences;
170 string getNotificationURL(const char* resource, bool front, unsigned int index) const;
172 const vector<string>& getRemoteUserAttributeIds() const {
173 return (m_remoteUsers.empty() && m_base) ? m_base->getRemoteUserAttributeIds() : m_remoteUsers;
176 void clearHeader(SPRequest& request, const char* rawname, const char* cginame) const;
177 void setHeader(SPRequest& request, const char* name, const char* value) const;
178 string getSecureHeader(const SPRequest& request, const char* name) const;
180 const SessionInitiator* getDefaultSessionInitiator() const;
181 const SessionInitiator* getSessionInitiatorById(const char* id) const;
182 const Handler* getDefaultAssertionConsumerService() const;
183 const Handler* getAssertionConsumerServiceByIndex(unsigned short index) const;
184 const Handler* getAssertionConsumerServiceByProtocol(const XMLCh* protocol, const char* binding=nullptr) const;
185 const vector<const Handler*>& getAssertionConsumerServicesByBinding(const XMLCh* binding) const;
186 const Handler* getHandler(const char* path) const;
187 void getHandlers(vector<const Handler*>& handlers) const;
188 void limitRedirect(const GenericRequest& request, const char* url) const;
190 void receive(DDF& in, ostream& out) {
191 // Only current function is to return the headers to clear.
193 DDF ret=DDF(nullptr).list();
194 DDFJanitor jret(ret);
195 for (vector< pair<string,string> >::const_iterator i = m_unsetHeaders.begin(); i!=m_unsetHeaders.end(); ++i) {
196 header = DDF(i->first.c_str()).string(i->second.c_str());
202 // Provides filter to exclude special config elements.
203 #ifdef SHIBSP_XERCESC_SHORT_ACCEPTNODE
208 acceptNode(const DOMNode* node) const;
211 template <class T> T* doChainedPlugins(
212 PluginManager<T,string,const DOMElement*>& pluginMgr,
213 const char* pluginType,
214 const char* chainingType,
215 const XMLCh* localName,
218 const char* dummyType=nullptr
220 void doAttributeInfo();
221 void doHandlers(const ProtocolProvider*, const DOMElement*, Category&);
222 void doSSO(const ProtocolProvider&, set<string>&, DOMElement*, Category&);
223 void doLogout(const ProtocolProvider&, set<string>&, DOMElement*, Category&);
224 void doNameIDMgmt(const ProtocolProvider&, set<string>&, DOMElement*, Category&);
225 void doArtifactResolution(const ProtocolProvider&, const char*, DOMElement*, Category&);
226 const XMLApplication* m_base;
228 std::pair<std::string,std::string> m_attributePrefix;
230 void doAttributePlugins(DOMElement*, Category&);
231 scoped_ptr<MetadataProvider> m_metadata;
232 scoped_ptr<TrustEngine> m_trust;
233 scoped_ptr<AttributeExtractor> m_attrExtractor;
234 scoped_ptr<AttributeFilter> m_attrFilter;
235 scoped_ptr<AttributeResolver> m_attrResolver;
236 scoped_ptr<CredentialResolver> m_credResolver;
237 vector<const XMLCh*> m_audiences;
239 // RelyingParty properties
240 map< xstring,boost::shared_ptr<PropertySet> > m_partyMap;
242 vector<string> m_remoteUsers,m_frontLogout,m_backLogout;
244 // manage handler objects
245 vector< boost::shared_ptr<Handler> > m_handlers;
247 // maps location (path info) to applicable handlers
248 map<string,const Handler*> m_handlerMap;
250 // maps unique indexes to consumer services
251 map<unsigned int,const Handler*> m_acsIndexMap;
253 // pointer to default consumer service
254 const Handler* m_acsDefault;
256 // maps binding strings to supporting consumer service(s)
257 typedef map< xstring,vector<const Handler*> > ACSBindingMap;
258 ACSBindingMap m_acsBindingMap;
260 // maps protocol strings to supporting consumer service(s)
261 typedef map< xstring,vector<const Handler*> > ACSProtocolMap;
262 ACSProtocolMap m_acsProtocolMap;
264 // pointer to default session initiator
265 const SessionInitiator* m_sessionInitDefault;
267 // maps unique ID strings to session initiators
268 map<string,const SessionInitiator*> m_sessionInitMap;
270 // pointer to default artifact resolution service
271 const Handler* m_artifactResolutionDefault;
273 pair<bool,int> getArtifactEndpointIndex() const {
274 if (m_artifactResolutionDefault) return m_artifactResolutionDefault->getInt("index");
275 return m_base ? m_base->getArtifactEndpointIndex() : make_pair(false,0);
279 REDIRECT_LIMIT_INHERIT,
281 REDIRECT_LIMIT_EXACT,
283 REDIRECT_LIMIT_WHITELIST,
284 REDIRECT_LIMIT_EXACT_WHITELIST,
285 REDIRECT_LIMIT_HOST_WHITELIST
287 vector<string> m_redirectWhitelist;
290 // Top-level configuration implementation
291 class SHIBSP_DLLLOCAL XMLConfig;
292 class SHIBSP_DLLLOCAL XMLConfigImpl : public DOMPropertySet, public DOMNodeFilter
295 XMLConfigImpl(const DOMElement* e, bool first, XMLConfig* outer, Category& log);
298 m_document->release();
302 scoped_ptr<TransactionLog> m_tranLog;
303 scoped_ptr<SecurityPolicyProvider> m_policy;
304 vector< tuple<string,string,string> > m_transportOptions;
306 scoped_ptr<RequestMapper> m_requestMapper;
307 map< string,boost::shared_ptr<Application> > m_appmap;
309 // Provides filter to exclude special config elements.
310 #ifdef SHIBSP_XERCESC_SHORT_ACCEPTNODE
315 acceptNode(const DOMNode* node) const;
317 void setDocument(DOMDocument* doc) {
322 void doExtensions(const DOMElement*, const char*, Category&);
323 void doListener(const DOMElement*, XMLConfig*, Category&);
324 void doCaching(const DOMElement*, XMLConfig*, Category&);
326 DOMDocument* m_document;
329 class SHIBSP_DLLLOCAL XMLConfig : public ServiceProvider, public ReloadableXMLFile
335 XMLConfig(const DOMElement* e) : ReloadableXMLFile(e, Category::getInstance(SHIBSP_LOGCAT".Config")) {}
344 SAMLConfig::getConfig().setArtifactMap(nullptr);
345 XMLToolingConfig::getConfig().setReplayCache(nullptr);
352 ReloadableXMLFile::lock();
353 if (m_impl->m_policy)
354 m_impl->m_policy->lock();
358 if (m_impl->m_policy)
359 m_impl->m_policy->unlock();
360 ReloadableXMLFile::unlock();
365 const PropertySet* getParent() const { return m_impl->getParent(); }
366 void setParent(const PropertySet* parent) {return m_impl->setParent(parent);}
367 pair<bool,bool> getBool(const char* name, const char* ns=nullptr) const {return m_impl->getBool(name,ns);}
368 pair<bool,const char*> getString(const char* name, const char* ns=nullptr) const {return m_impl->getString(name,ns);}
369 pair<bool,const XMLCh*> getXMLString(const char* name, const char* ns=nullptr) const {return m_impl->getXMLString(name,ns);}
370 pair<bool,unsigned int> getUnsignedInt(const char* name, const char* ns=nullptr) const {return m_impl->getUnsignedInt(name,ns);}
371 pair<bool,int> getInt(const char* name, const char* ns=nullptr) const {return m_impl->getInt(name,ns);}
372 void getAll(map<string,const char*>& properties) const {return m_impl->getAll(properties);}
373 const PropertySet* getPropertySet(const char* name, const char* ns="urn:mace:shibboleth:2.0:native:sp:config") const {return m_impl->getPropertySet(name,ns);}
374 const DOMElement* getElement() const {return m_impl->getElement();}
379 void receive(DDF& in, ostream& out);
381 TransactionLog* getTransactionLog() const {
382 if (m_impl->m_tranLog)
383 return m_impl->m_tranLog.get();
384 throw ConfigurationException("No TransactionLog available.");
387 StorageService* getStorageService(const char* id) const {
389 map< string,boost::shared_ptr<StorageService> >::const_iterator i = m_storage.find(id);
390 if (i != m_storage.end())
391 return i->second.get();
393 else if (!m_storage.empty())
394 return m_storage.begin()->second.get();
399 ListenerService* getListenerService(bool required=true) const {
400 if (required && !m_listener)
401 throw ConfigurationException("No ListenerService available.");
402 return m_listener.get();
405 SessionCache* getSessionCache(bool required=true) const {
406 if (required && !m_sessionCache)
407 throw ConfigurationException("No SessionCache available.");
408 return m_sessionCache.get();
411 RequestMapper* getRequestMapper(bool required=true) const {
412 if (required && !m_impl->m_requestMapper)
413 throw ConfigurationException("No RequestMapper available.");
414 return m_impl->m_requestMapper.get();
417 const Application* getApplication(const char* applicationId) const {
418 map< string,boost::shared_ptr<Application> >::const_iterator i = m_impl->m_appmap.find(applicationId ? applicationId : "default");
419 return (i != m_impl->m_appmap.end()) ? i->second.get() : nullptr;
423 SecurityPolicyProvider* getSecurityPolicyProvider(bool required=true) const {
424 if (required && !m_impl->m_policy)
425 throw ConfigurationException("No SecurityPolicyProvider available.");
426 return m_impl->m_policy.get();
429 const PropertySet* getPolicySettings(const char* id) const {
430 return getSecurityPolicyProvider()->getPolicySettings(id);
433 const vector<const SecurityPolicyRule*>& getPolicyRules(const char* id) const {
434 return getSecurityPolicyProvider()->getPolicyRules(id);
437 bool setTransportOptions(SOAPTransport& transport) const {
439 for (vector< tuple<string,string,string> >::const_iterator opt = m_impl->m_transportOptions.begin();
440 opt != m_impl->m_transportOptions.end(); ++opt) {
441 if (!transport.setProviderOption(opt->get<0>().c_str(), opt->get<1>().c_str(), opt->get<2>().c_str())) {
442 m_log.error("failed to set SOAPTransport option (%s)", opt->get<1>().c_str());
451 pair<bool,DOMElement*> background_load();
454 friend class XMLConfigImpl;
455 // The order of these members actually matters. If we want to rely on auto-destruction, then
456 // anything dependent on anything else has to come later in the object so it will pop first.
457 // Storage is the lowest, then remoting, then the cache, and finally the rest.
459 map< string,boost::shared_ptr<StorageService> > m_storage;
461 scoped_ptr<ListenerService> m_listener;
462 scoped_ptr<SessionCache> m_sessionCache;
463 scoped_ptr<XMLConfigImpl> m_impl;
466 #if defined (_MSC_VER)
467 #pragma warning( pop )
470 static const XMLCh applicationId[] = UNICODE_LITERAL_13(a,p,p,l,i,c,a,t,i,o,n,I,d);
471 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);
472 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);
473 static const XMLCh _ArtifactMap[] = UNICODE_LITERAL_11(A,r,t,i,f,a,c,t,M,a,p);
474 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);
475 static const XMLCh _AttributeFilter[] = UNICODE_LITERAL_15(A,t,t,r,i,b,u,t,e,F,i,l,t,e,r);
476 static const XMLCh _AttributeResolver[] = UNICODE_LITERAL_17(A,t,t,r,i,b,u,t,e,R,e,s,o,l,v,e,r);
477 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);
478 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);
479 static const XMLCh _Audience[] = UNICODE_LITERAL_8(A,u,d,i,e,n,c,e);
480 static const XMLCh Binding[] = UNICODE_LITERAL_7(B,i,n,d,i,n,g);
481 static const XMLCh Channel[]= UNICODE_LITERAL_7(C,h,a,n,n,e,l);
482 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);
483 static const XMLCh _default[] = UNICODE_LITERAL_7(d,e,f,a,u,l,t);
484 static const XMLCh _Extensions[] = UNICODE_LITERAL_10(E,x,t,e,n,s,i,o,n,s);
485 static const XMLCh _fatal[] = UNICODE_LITERAL_5(f,a,t,a,l);
486 static const XMLCh _Handler[] = UNICODE_LITERAL_7(H,a,n,d,l,e,r);
487 static const XMLCh _id[] = UNICODE_LITERAL_2(i,d);
488 static const XMLCh _index[] = UNICODE_LITERAL_5(i,n,d,e,x);
489 static const XMLCh InProcess[] = UNICODE_LITERAL_9(I,n,P,r,o,c,e,s,s);
490 static const XMLCh Library[] = UNICODE_LITERAL_7(L,i,b,r,a,r,y);
491 static const XMLCh Listener[] = UNICODE_LITERAL_8(L,i,s,t,e,n,e,r);
492 static const XMLCh Location[] = UNICODE_LITERAL_8(L,o,c,a,t,i,o,n);
493 static const XMLCh logger[] = UNICODE_LITERAL_6(l,o,g,g,e,r);
494 static const XMLCh Logout[] = UNICODE_LITERAL_6(L,o,g,o,u,t);
495 static const XMLCh _LogoutInitiator[] = UNICODE_LITERAL_15(L,o,g,o,u,t,I,n,i,t,i,a,t,o,r);
496 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);
497 static const XMLCh _MetadataProvider[] = UNICODE_LITERAL_16(M,e,t,a,d,a,t,a,P,r,o,v,i,d,e,r);
498 static const XMLCh NameIDMgmt[] = UNICODE_LITERAL_10(N,a,m,e,I,D,M,g,m,t);
499 static const XMLCh Notify[] = UNICODE_LITERAL_6(N,o,t,i,f,y);
500 static const XMLCh _option[] = UNICODE_LITERAL_6(o,p,t,i,o,n);
501 static const XMLCh OutOfProcess[] = UNICODE_LITERAL_12(O,u,t,O,f,P,r,o,c,e,s,s);
502 static const XMLCh _path[] = UNICODE_LITERAL_4(p,a,t,h);
503 static const XMLCh _ProtocolProvider[] = UNICODE_LITERAL_16(P,r,o,t,o,c,o,l,P,r,o,v,i,d,e,r);
504 static const XMLCh _provider[] = UNICODE_LITERAL_8(p,r,o,v,i,d,e,r);
505 static const XMLCh RelyingParty[] = UNICODE_LITERAL_12(R,e,l,y,i,n,g,P,a,r,t,y);
506 static const XMLCh _ReplayCache[] = UNICODE_LITERAL_11(R,e,p,l,a,y,C,a,c,h,e);
507 static const XMLCh _RequestMapper[] = UNICODE_LITERAL_13(R,e,q,u,e,s,t,M,a,p,p,e,r);
508 static const XMLCh RequestMap[] = UNICODE_LITERAL_10(R,e,q,u,e,s,t,M,a,p);
509 static const XMLCh SecurityPolicies[] = UNICODE_LITERAL_16(S,e,c,u,r,i,t,y,P,o,l,i,c,i,e,s);
510 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);
511 static const XMLCh _SessionCache[] = UNICODE_LITERAL_12(S,e,s,s,i,o,n,C,a,c,h,e);
512 static const XMLCh _SessionInitiator[] = UNICODE_LITERAL_16(S,e,s,s,i,o,n,I,n,i,t,i,a,t,o,r);
513 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);
514 static const XMLCh Site[] = UNICODE_LITERAL_4(S,i,t,e);
515 static const XMLCh SSO[] = UNICODE_LITERAL_3(S,S,O);
516 static const XMLCh _StorageService[] = UNICODE_LITERAL_14(S,t,o,r,a,g,e,S,e,r,v,i,c,e);
517 static const XMLCh TCPListener[] = UNICODE_LITERAL_11(T,C,P,L,i,s,t,e,n,e,r);
518 static const XMLCh tranLogFiller[] = UNICODE_LITERAL_13(t,r,a,n,L,o,g,F,i,l,l,e,r);
519 static const XMLCh tranLogFormat[] = UNICODE_LITERAL_13(t,r,a,n,L,o,g,F,o,r,m,a,t);
520 static const XMLCh TransportOption[] = UNICODE_LITERAL_15(T,r,a,n,s,p,o,r,t,O,p,t,i,o,n);
521 static const XMLCh _TrustEngine[] = UNICODE_LITERAL_11(T,r,u,s,t,E,n,g,i,n,e);
522 static const XMLCh _type[] = UNICODE_LITERAL_4(t,y,p,e);
523 static const XMLCh UnixListener[] = UNICODE_LITERAL_12(U,n,i,x,L,i,s,t,e,n,e,r);
527 ServiceProvider* XMLServiceProviderFactory(const DOMElement* const & e)
529 return new XMLConfig(e);
533 XMLApplication::XMLApplication(
534 const ServiceProvider* sp,
535 const ProtocolProvider* pp,
537 const XMLApplication* base
538 ) : Application(sp), m_base(base), m_acsDefault(nullptr), m_sessionInitDefault(nullptr), m_artifactResolutionDefault(nullptr)
541 xmltooling::NDC ndc("XMLApplication");
543 Category& log = Category::getInstance(SHIBSP_LOGCAT".Application");
545 // First load any property sets.
546 map<string,string> remapper;
547 remapper["relayStateLimit"] = "redirectLimit";
548 remapper["relayStateWhitelist"] = "redirectWhitelist";
549 load(e, nullptr, this, &remapper);
551 // Process redirect limit policy. Do this before assigning the parent pointer
552 // to ensure we get only our Sessions element.
553 const PropertySet* sessionProps = getPropertySet("Sessions");
555 pair<bool,const char*> redirectLimit = sessionProps->getString("redirectLimit");
556 if (redirectLimit.first) {
557 if (!strcmp(redirectLimit.second, "none"))
558 m_redirectLimit = REDIRECT_LIMIT_NONE;
559 else if (!strcmp(redirectLimit.second, "exact"))
560 m_redirectLimit = REDIRECT_LIMIT_EXACT;
561 else if (!strcmp(redirectLimit.second, "host"))
562 m_redirectLimit = REDIRECT_LIMIT_HOST;
564 if (!strcmp(redirectLimit.second, "exact+whitelist"))
565 m_redirectLimit = REDIRECT_LIMIT_EXACT_WHITELIST;
566 else if (!strcmp(redirectLimit.second, "exact+host"))
567 m_redirectLimit = REDIRECT_LIMIT_HOST_WHITELIST;
568 else if (!strcmp(redirectLimit.second, "exact+host"))
569 m_redirectLimit = REDIRECT_LIMIT_WHITELIST;
571 throw ConfigurationException("Unrecognized redirectLimit setting ($1)", params(1, redirectLimit.second));
572 redirectLimit = sessionProps->getString("redirectWhitelist");
573 if (redirectLimit.first) {
574 string dup(redirectLimit.second);
575 split(m_redirectWhitelist, dup, is_space(), algorithm::token_compress_on);
580 m_redirectLimit = base ? REDIRECT_LIMIT_INHERIT : REDIRECT_LIMIT_NONE;
584 m_redirectLimit = base ? REDIRECT_LIMIT_INHERIT : REDIRECT_LIMIT_NONE;
591 SPConfig& conf=SPConfig::getConfig();
593 XMLToolingConfig& xmlConf=XMLToolingConfig::getConfig();
596 // This used to be an actual hash, but now it's just a hex-encode to avoid xmlsec dependency.
597 static char DIGITS[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
598 string tohash=getId();
599 tohash+=getString("entityID").second;
600 for (const char* ch = tohash.c_str(); *ch; ++ch) {
601 m_hash += (DIGITS[((unsigned char)(0xF0 & *ch)) >> 4 ]);
602 m_hash += (DIGITS[0x0F & *ch]);
607 if (conf.isEnabled(SPConfig::Handlers))
608 doHandlers(pp, e, log);
611 DOMNodeList* nlist = e->getElementsByTagNameNS(shibspconstants::SHIB2SPCONFIG_NS, Notify);
612 for (XMLSize_t i = 0; nlist && i < nlist->getLength(); ++i) {
613 if (nlist->item(i)->getParentNode()->isSameNode(e)) {
614 const XMLCh* channel = static_cast<DOMElement*>(nlist->item(i))->getAttributeNS(nullptr, Channel);
615 string loc(XMLHelper::getAttrString(static_cast<DOMElement*>(nlist->item(i)), nullptr, Location));
617 if (channel && *channel == chLatin_f)
618 m_frontLogout.push_back(loc);
620 m_backLogout.push_back(loc);
626 nlist = e->getElementsByTagNameNS(samlconstants::SAML20_NS, Audience::LOCAL_NAME);
627 if (nlist && nlist->getLength()) {
628 log.warn("use of <saml:Audience> elements outside of a Security Policy Rule is deprecated");
629 for (XMLSize_t i = 0; i < nlist->getLength(); ++i)
630 if (nlist->item(i)->getParentNode()->isSameNode(e) && nlist->item(i)->hasChildNodes())
631 m_audiences.push_back(nlist->item(i)->getFirstChild()->getNodeValue());
634 if (conf.isEnabled(SPConfig::Metadata)) {
637 SAMLConfig::getConfig().MetadataProviderManager, "MetadataProvider", CHAINING_METADATA_PROVIDER, _MetadataProvider, e, log
644 log.crit("no MetadataProvider available, configuration is probably unusable");
646 catch (std::exception& ex) {
647 log.crit("error initializing MetadataProvider: %s", ex.what());
651 if (conf.isEnabled(SPConfig::Trust)) {
652 m_trust.reset(doChainedPlugins(xmlConf.TrustEngineManager, "TrustEngine", CHAINING_TRUSTENGINE, _TrustEngine, e, log));
653 if (!m_trust && !m_base) {
655 "no TrustEngine specified or installed, using default chain {%s, %s}",
656 EXPLICIT_KEY_TRUSTENGINE, SHIBBOLETH_PKIX_TRUSTENGINE
658 m_trust.reset(xmlConf.TrustEngineManager.newPlugin(CHAINING_TRUSTENGINE, nullptr));
659 ChainingTrustEngine* trustchain = dynamic_cast<ChainingTrustEngine*>(m_trust.get());
661 trustchain->addTrustEngine(xmlConf.TrustEngineManager.newPlugin(EXPLICIT_KEY_TRUSTENGINE, nullptr));
662 trustchain->addTrustEngine(xmlConf.TrustEngineManager.newPlugin(SHIBBOLETH_PKIX_TRUSTENGINE, nullptr));
667 if (conf.isEnabled(SPConfig::AttributeResolution)) {
668 doAttributePlugins(e, log);
671 if (conf.isEnabled(SPConfig::Credentials)) {
672 m_credResolver.reset(
673 doChainedPlugins(xmlConf.CredentialResolverManager, "CredentialResolver", CHAINING_CREDENTIAL_RESOLVER, _CredentialResolver, e, log)
677 // Finally, load relying parties.
678 const DOMElement* child = XMLHelper::getFirstChildElement(e, RelyingParty);
680 if (child->hasAttributeNS(nullptr, saml2::Attribute::NAME_ATTRIB_NAME)) {
681 boost::shared_ptr<DOMPropertySet> rp(new DOMPropertySet());
682 rp->load(child, nullptr, this);
684 m_partyMap[child->getAttributeNS(nullptr, saml2::Attribute::NAME_ATTRIB_NAME)] = rp;
686 child = XMLHelper::getNextSiblingElement(child, RelyingParty);
688 if (base && m_partyMap.empty() && !base->m_partyMap.empty()) {
689 // For inheritance of RPs to work, we have to pull them in to the override by cloning the DOM.
690 child = XMLHelper::getFirstChildElement(base->getElement(), RelyingParty);
692 if (child->hasAttributeNS(nullptr, saml2::Attribute::NAME_ATTRIB_NAME)) {
693 DOMElement* rpclone = static_cast<DOMElement*>(child->cloneNode(true));
694 boost::shared_ptr<DOMPropertySet> rp(new DOMPropertySet());
695 rp->load(rpclone, nullptr, this);
697 m_partyMap[rpclone->getAttributeNS(nullptr, saml2::Attribute::NAME_ATTRIB_NAME)] = rp;
699 child = XMLHelper::getNextSiblingElement(child, RelyingParty);
704 // Out of process only, we register a listener endpoint.
705 if (!conf.isEnabled(SPConfig::InProcess)) {
706 ListenerService* listener = sp->getListenerService(false);
708 string addr=string(getId()) + "::getHeaders::Application";
709 listener->regListener(addr.c_str(), this);
712 log.info("no ListenerService available, Application remoting disabled");
717 XMLApplication::~XMLApplication()
719 ListenerService* listener=getServiceProvider().getListenerService(false);
720 if (listener && SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess) && !SPConfig::getConfig().isEnabled(SPConfig::InProcess)) {
721 string addr=string(getId()) + "::getHeaders::Application";
722 listener->unregListener(addr.c_str(), this);
726 template <class T> T* XMLApplication::doChainedPlugins(
727 PluginManager<T,string,const DOMElement*>& pluginMgr,
728 const char* pluginType,
729 const char* chainingType,
730 const XMLCh* localName,
733 const char* dummyType
737 DOMElement* child = XMLHelper::getFirstChildElement(e, localName);
739 // Check for multiple.
740 if (XMLHelper::getNextSiblingElement(child, localName)) {
741 log.info("multiple %s plugins, wrapping in a chain", pluginType);
742 DOMElement* chain = child->getOwnerDocument()->createElementNS(nullptr, localName);
744 chain->appendChild(child);
745 child = XMLHelper::getFirstChildElement(e, localName);
749 e->appendChild(chain);
752 // Only a single one.
753 t = XMLHelper::getAttrString(child, nullptr, _type);
758 log.info("building %s of type %s...", pluginType, t.c_str());
759 return pluginMgr.newPlugin(t.c_str(), child);
762 throw ConfigurationException("$1 element had no type attribute.", params(1, pluginType));
765 catch (std::exception& ex) {
766 log.crit("error building %s: %s", pluginType, ex.what());
768 // Install a dummy version as a safety valve.
769 log.crit("installing safe %s in place of failed version", pluginType);
770 return pluginMgr.newPlugin(dummyType, nullptr);
778 void XMLApplication::doAttributeInfo()
780 // Populate prefix pair.
781 m_attributePrefix.second = "HTTP_";
782 pair<bool,const char*> prefix = getString("attributePrefix");
784 m_attributePrefix.first = prefix.second;
785 const char* pch = prefix.second;
787 m_attributePrefix.second += (isalnum(*pch) ? toupper(*pch) : '_');
792 pair<bool,const char*> attributes = getString("REMOTE_USER");
793 if (attributes.first) {
794 string dup(attributes.second);
795 split(m_remoteUsers, dup, is_space(), algorithm::token_compress_on);
798 // Load attribute ID lists for REMOTE_USER and header clearing.
799 if (SPConfig::getConfig().isEnabled(SPConfig::InProcess)) {
800 attributes = getString("unsetHeaders");
801 if (attributes.first) {
802 string transformedprefix(m_attributePrefix.second);
804 prefix = getString("metadataAttributePrefix");
808 transformedprefix += (isalnum(*pch) ? toupper(*pch) : '_');
813 string dup(attributes.second);
814 vector<string> headerNames;
815 split(headerNames, dup, is_space(), algorithm::token_compress_on);
816 for (vector<string>::const_iterator h = headerNames.begin(); h != headerNames.end(); ++h) {
818 const char* pch = h->c_str();
820 transformed += (isalnum(*pch) ? toupper(*pch) : '_');
823 m_unsetHeaders.push_back(pair<string,string>(m_attributePrefix.first + *h, m_attributePrefix.second + transformed));
825 m_unsetHeaders.push_back(pair<string,string>(m_attributePrefix.first + prefix.second + *h, transformedprefix + transformed));
827 m_unsetHeaders.push_back(pair<string,string>(m_attributePrefix.first + "Shib-Application-ID", m_attributePrefix.second + "SHIB_APPLICATION_ID"));
832 void XMLApplication::doHandlers(const ProtocolProvider* pp, const DOMElement* e, Category& log)
834 SPConfig& conf = SPConfig::getConfig();
836 const PropertySet* sessions = getPropertySet("Sessions");
838 // Process assertion export handler.
839 pair<bool,const char*> location = sessions ? sessions->getString("exportLocation") : pair<bool,const char*>(false,nullptr);
840 if (location.first) {
842 DOMElement* exportElement = e->getOwnerDocument()->createElementNS(shibspconstants::SHIB2SPCONFIG_NS, _Handler);
843 exportElement->setAttributeNS(nullptr,Location,sessions->getXMLString("exportLocation").second);
844 pair<bool,const XMLCh*> exportACL = sessions->getXMLString("exportACL");
845 if (exportACL.first) {
846 static const XMLCh _acl[] = UNICODE_LITERAL_9(e,x,p,o,r,t,A,C,L);
847 exportElement->setAttributeNS(nullptr,_acl,exportACL.second);
849 boost::shared_ptr<Handler> exportHandler(
850 conf.HandlerManager.newPlugin(samlconstants::SAML20_BINDING_URI, pair<const DOMElement*,const char*>(exportElement, getId()))
852 m_handlers.push_back(exportHandler);
854 // Insert into location map. If it contains the handlerURL, we skip past that part.
855 const char* hurl = sessions->getString("handlerURL").second;
857 hurl = "/Shibboleth.sso";
858 const char* pch = strstr(location.second, hurl);
860 location.second = pch + strlen(hurl);
861 if (*location.second == '/')
862 m_handlerMap[location.second] = exportHandler.get();
864 m_handlerMap[string("/") + location.second] = exportHandler.get();
866 catch (std::exception& ex) {
867 log.error("caught exception installing assertion lookup handler: %s", ex.what());
871 // Look for "shorthand" elements first.
872 set<string> protocols;
873 DOMElement* child = sessions ? XMLHelper::getFirstChildElement(sessions->getElement()) : nullptr;
875 if (XMLHelper::isNodeNamed(child, shibspconstants::SHIB2SPCONFIG_NS, SSO)) {
877 doSSO(*pp, protocols, child, log);
879 log.error("no ProtocolProvider, SSO auto-configure unsupported");
881 else if (XMLHelper::isNodeNamed(child, shibspconstants::SHIB2SPCONFIG_NS, Logout)) {
883 doLogout(*pp, protocols, child, log);
885 log.error("no ProtocolProvider, Logout auto-configure unsupported");
887 else if (XMLHelper::isNodeNamed(child, shibspconstants::SHIB2SPCONFIG_NS, NameIDMgmt)) {
889 doNameIDMgmt(*pp, protocols, child, log);
891 log.error("no ProtocolProvider, NameIDMgmt auto-configure unsupported");
894 break; // drop into next while loop
896 child = XMLHelper::getNextSiblingElement(child);
899 // Process other handlers.
900 bool hardACS=false, hardSessionInit=false, hardArt=false;
902 if (!child->hasAttributeNS(nullptr, Location)) {
903 auto_ptr_char hclass(child->getLocalName());
904 log.error("%s handler with no Location property cannot be processed", hclass.get());
905 child = XMLHelper::getNextSiblingElement(child);
909 boost::shared_ptr<Handler> handler;
910 if (XMLString::equals(child->getLocalName(), _AssertionConsumerService)) {
911 string bindprop(XMLHelper::getAttrString(child, nullptr, Binding));
912 if (bindprop.empty()) {
913 log.error("AssertionConsumerService element has no Binding attribute, skipping it...");
914 child = XMLHelper::getNextSiblingElement(child);
917 handler.reset(conf.AssertionConsumerServiceManager.newPlugin(bindprop.c_str(), pair<const DOMElement*,const char*>(child, getId())));
918 // Map by binding and protocol (may be > 1 per protocol and binding)
919 m_acsBindingMap[handler->getXMLString("Binding").second].push_back(handler.get());
920 const XMLCh* protfamily = handler->getProtocolFamily();
922 m_acsProtocolMap[protfamily].push_back(handler.get());
923 m_acsIndexMap[handler->getUnsignedInt("index").second] = handler.get();
926 pair<bool,bool> defprop = handler->getBool("isDefault");
928 if (defprop.second) {
930 m_acsDefault = handler.get();
933 else if (!m_acsDefault)
934 m_acsDefault = handler.get();
937 else if (XMLString::equals(child->getLocalName(), _SessionInitiator)) {
938 string t(XMLHelper::getAttrString(child, nullptr, _type));
940 log.error("SessionInitiator element has no type attribute, skipping it...");
941 child = XMLHelper::getNextSiblingElement(child);
944 boost::shared_ptr<SessionInitiator> sihandler(
945 conf.SessionInitiatorManager.newPlugin(t.c_str(), pair<const DOMElement*,const char*>(child, getId()))
948 pair<bool,const char*> si_id = handler->getString("id");
949 if (si_id.first && si_id.second)
950 m_sessionInitMap[si_id.second] = sihandler.get();
951 if (!hardSessionInit) {
952 pair<bool,bool> defprop = handler->getBool("isDefault");
954 if (defprop.second) {
955 hardSessionInit = true;
956 m_sessionInitDefault = sihandler.get();
959 else if (!m_sessionInitDefault) {
960 m_sessionInitDefault = sihandler.get();
964 else if (XMLString::equals(child->getLocalName(), _LogoutInitiator)) {
965 string t(XMLHelper::getAttrString(child, nullptr, _type));
967 log.error("LogoutInitiator element has no type attribute, skipping it...");
968 child = XMLHelper::getNextSiblingElement(child);
971 handler.reset(conf.LogoutInitiatorManager.newPlugin(t.c_str(), pair<const DOMElement*,const char*>(child, getId())));
973 else if (XMLString::equals(child->getLocalName(), _ArtifactResolutionService)) {
974 string bindprop(XMLHelper::getAttrString(child, nullptr, Binding));
975 if (bindprop.empty()) {
976 log.error("ArtifactResolutionService element has no Binding attribute, skipping it...");
977 child = XMLHelper::getNextSiblingElement(child);
980 handler.reset(conf.ArtifactResolutionServiceManager.newPlugin(bindprop.c_str(), pair<const DOMElement*,const char*>(child, getId())));
983 pair<bool,bool> defprop = handler->getBool("isDefault");
985 if (defprop.second) {
987 m_artifactResolutionDefault = handler.get();
990 else if (!m_artifactResolutionDefault)
991 m_artifactResolutionDefault = handler.get();
994 else if (XMLString::equals(child->getLocalName(), _SingleLogoutService)) {
995 string bindprop(XMLHelper::getAttrString(child, nullptr, Binding));
996 if (bindprop.empty()) {
997 log.error("SingleLogoutService element has no Binding attribute, skipping it...");
998 child = XMLHelper::getNextSiblingElement(child);
1001 handler.reset(conf.SingleLogoutServiceManager.newPlugin(bindprop.c_str(), pair<const DOMElement*,const char*>(child, getId())));
1003 else if (XMLString::equals(child->getLocalName(), _ManageNameIDService)) {
1004 string bindprop(XMLHelper::getAttrString(child, nullptr, Binding));
1005 if (bindprop.empty()) {
1006 log.error("ManageNameIDService element has no Binding attribute, skipping it...");
1007 child = XMLHelper::getNextSiblingElement(child);
1010 handler.reset(conf.ManageNameIDServiceManager.newPlugin(bindprop.c_str(), pair<const DOMElement*,const char*>(child, getId())));
1013 string t(XMLHelper::getAttrString(child, nullptr, _type));
1015 log.error("Handler element has no type attribute, skipping it...");
1016 child = XMLHelper::getNextSiblingElement(child);
1019 handler.reset(conf.HandlerManager.newPlugin(t.c_str(), pair<const DOMElement*,const char*>(child, getId())));
1022 m_handlers.push_back(handler);
1024 // Insert into location map.
1025 location = handler->getString("Location");
1026 if (location.first && *location.second == '/')
1027 m_handlerMap[location.second] = handler.get();
1028 else if (location.first)
1029 m_handlerMap[string("/") + location.second] = handler.get();
1031 catch (std::exception& ex) {
1032 log.error("caught exception processing handler element: %s", ex.what());
1035 child = XMLHelper::getNextSiblingElement(child);
1039 void XMLApplication::doSSO(const ProtocolProvider& pp, set<string>& protocols, DOMElement* e, Category& log)
1041 if (!e->hasChildNodes())
1044 SPConfig& conf = SPConfig::getConfig();
1046 // Tokenize the protocol list inside the element.
1047 XMLStringTokenizer prottokens(e->getTextContent());
1048 while (prottokens.hasMoreTokens()) {
1049 auto_ptr_char prot(prottokens.nextToken());
1051 // Look for initiator.
1052 const PropertySet* initiator = pp.getInitiator(prot.get(), "SSO");
1054 log.info("auto-configuring SSO initiation for protocol (%s)", prot.get());
1055 pair<bool,const XMLCh*> inittype = initiator->getXMLString("id");
1056 if (inittype.first) {
1057 // Append a session initiator element of the designated type to the root element.
1058 DOMElement* sidom = e->getOwnerDocument()->createElementNS(shibspconstants::SHIB2SPCONFIG_NS, _SessionInitiator);
1059 sidom->setAttributeNS(nullptr, _type, inittype.second);
1060 e->appendChild(sidom);
1061 log.info("adding SessionInitiator of type (%s) to chain (/Login)", initiator->getString("id").second);
1063 doArtifactResolution(pp, prot.get(), e, log);
1064 protocols.insert(prot.get());
1067 log.error("missing id property on Initiator element, check config for protocol (%s)", prot.get());
1071 // Look for incoming bindings.
1072 const vector<const PropertySet*>& bindings = pp.getBindings(prot.get(), "SSO");
1073 if (!bindings.empty()) {
1074 log.info("auto-configuring SSO endpoints for protocol (%s)", prot.get());
1076 pair<bool,const XMLCh*> idprop,pathprop;
1077 for (vector<const PropertySet*>::const_iterator b = bindings.begin(); b != bindings.end(); ++b, ++index) {
1078 idprop = (*b)->getXMLString("id");
1079 pathprop = (*b)->getXMLString("path");
1080 if (idprop.first && pathprop.first) {
1081 DOMElement* acsdom = e->getOwnerDocument()->createElementNS(samlconstants::SAML20MD_NS, _AssertionConsumerService);
1082 acsdom->setAttributeNS(nullptr, Binding, idprop.second);
1083 acsdom->setAttributeNS(nullptr, Location, pathprop.second);
1084 xstring indexbuf(chDigit_1 + (index % 10), 1);
1086 indexbuf = (XMLCh)(chDigit_1 + (index / 10)) + indexbuf;
1087 acsdom->setAttributeNS(nullptr, _index, indexbuf.c_str());
1089 log.info("adding AssertionConsumerService for Binding (%s) at (%s)", (*b)->getString("id").second, (*b)->getString("path").second);
1090 boost::shared_ptr<Handler> handler(
1091 conf.AssertionConsumerServiceManager.newPlugin(
1092 (*b)->getString("id").second, pair<const DOMElement*,const char*>(acsdom, getId())
1095 m_handlers.push_back(handler);
1097 // Setup maps and defaults.
1098 m_acsBindingMap[handler->getXMLString("Binding").second].push_back(handler.get());
1099 const XMLCh* protfamily = handler->getProtocolFamily();
1101 m_acsProtocolMap[protfamily].push_back(handler.get());
1102 m_acsIndexMap[handler->getUnsignedInt("index").second] = handler.get();
1104 m_acsDefault = handler.get();
1106 // Insert into location map.
1107 pair<bool,const char*> location = handler->getString("Location");
1108 if (location.first && *location.second == '/')
1109 m_handlerMap[location.second] = handler.get();
1110 else if (location.first)
1111 m_handlerMap[string("/") + location.second] = handler.get();
1114 log.error("missing id or path property on Binding element, check config for protocol (%s)", prot.get());
1119 if (!initiator && bindings.empty()) {
1120 log.error("no SSO Initiator or Binding config for protocol (%s)", prot.get());
1124 // Handle discovery.
1125 static const XMLCh discoveryProtocol[] = UNICODE_LITERAL_17(d,i,s,c,o,v,e,r,y,P,r,o,t,o,c,o,l);
1126 static const XMLCh discoveryURL[] = UNICODE_LITERAL_12(d,i,s,c,o,v,e,r,y,U,R,L);
1127 static const XMLCh _URL[] = UNICODE_LITERAL_3(U,R,L);
1128 const XMLCh* discop = e->getAttributeNS(nullptr, discoveryProtocol);
1129 if (discop && *discop) {
1130 const XMLCh* discou = e->getAttributeNS(nullptr, discoveryURL);
1131 if (discou && *discou) {
1132 // Append a session initiator element of the designated type to the root element.
1133 DOMElement* sidom = e->getOwnerDocument()->createElementNS(shibspconstants::SHIB2SPCONFIG_NS, _SessionInitiator);
1134 sidom->setAttributeNS(nullptr, _type, discop);
1135 sidom->setAttributeNS(nullptr, _URL, discou);
1136 e->appendChild(sidom);
1137 if (log.isInfoEnabled()) {
1138 auto_ptr_char dp(discop);
1139 log.info("adding SessionInitiator of type (%s) to chain (/Login)", dp.get());
1143 log.error("SSO discoveryProtocol specified without discoveryURL");
1147 // Attach default Location to SSO element.
1148 static const XMLCh _loc[] = { chForwardSlash, chLatin_L, chLatin_o, chLatin_g, chLatin_i, chLatin_n, chNull };
1149 e->setAttributeNS(nullptr, Location, _loc);
1151 // Instantiate Chaining initiator around the SSO element.
1152 boost::shared_ptr<SessionInitiator> chain(
1153 conf.SessionInitiatorManager.newPlugin(CHAINING_SESSION_INITIATOR, pair<const DOMElement*,const char*>(e, getId()))
1155 m_handlers.push_back(chain);
1156 m_sessionInitDefault = chain.get();
1157 m_handlerMap["/Login"] = chain.get();
1160 void XMLApplication::doLogout(const ProtocolProvider& pp, set<string>& protocols, DOMElement* e, Category& log)
1162 if (!e->hasChildNodes())
1165 SPConfig& conf = SPConfig::getConfig();
1167 // Tokenize the protocol list inside the element.
1168 XMLStringTokenizer prottokens(e->getTextContent());
1169 while (prottokens.hasMoreTokens()) {
1170 auto_ptr_char prot(prottokens.nextToken());
1172 // Look for initiator.
1173 const PropertySet* initiator = pp.getInitiator(prot.get(), "Logout");
1175 log.info("auto-configuring Logout initiation for protocol (%s)", prot.get());
1176 pair<bool,const XMLCh*> inittype = initiator->getXMLString("id");
1177 if (inittype.first) {
1178 // Append a logout initiator element of the designated type to the root element.
1179 DOMElement* lidom = e->getOwnerDocument()->createElementNS(shibspconstants::SHIB2SPCONFIG_NS, _LogoutInitiator);
1180 lidom->setAttributeNS(nullptr, _type, inittype.second);
1181 e->appendChild(lidom);
1182 log.info("adding LogoutInitiator of type (%s) to chain (/Logout)", initiator->getString("id").second);
1184 if (protocols.count(prot.get()) == 0) {
1185 doArtifactResolution(pp, prot.get(), e, log);
1186 protocols.insert(prot.get());
1190 log.error("missing id property on Initiator element, check config for protocol (%s)", prot.get());
1194 // Look for incoming bindings.
1195 const vector<const PropertySet*>& bindings = pp.getBindings(prot.get(), "Logout");
1196 if (!bindings.empty()) {
1197 log.info("auto-configuring Logout endpoints for protocol (%s)", prot.get());
1198 pair<bool,const XMLCh*> idprop,pathprop;
1199 for (vector<const PropertySet*>::const_iterator b = bindings.begin(); b != bindings.end(); ++b) {
1200 idprop = (*b)->getXMLString("id");
1201 pathprop = (*b)->getXMLString("path");
1202 if (idprop.first && pathprop.first) {
1203 DOMElement* slodom = e->getOwnerDocument()->createElementNS(samlconstants::SAML20MD_NS, _SingleLogoutService);
1204 slodom->setAttributeNS(nullptr, Binding, idprop.second);
1205 slodom->setAttributeNS(nullptr, Location, pathprop.second);
1207 log.info("adding SingleLogoutService for Binding (%s) at (%s)", (*b)->getString("id").second, (*b)->getString("path").second);
1208 boost::shared_ptr<Handler> handler(
1209 conf.SingleLogoutServiceManager.newPlugin((*b)->getString("id").second, pair<const DOMElement*,const char*>(slodom, getId()))
1211 m_handlers.push_back(handler);
1213 // Insert into location map.
1214 pair<bool,const char*> location = handler->getString("Location");
1215 if (location.first && *location.second == '/')
1216 m_handlerMap[location.second] = handler.get();
1217 else if (location.first)
1218 m_handlerMap[string("/") + location.second] = handler.get();
1221 log.error("missing id or path property on Binding element, check config for protocol (%s)", prot.get());
1225 if (protocols.count(prot.get()) == 0) {
1226 doArtifactResolution(pp, prot.get(), e, log);
1227 protocols.insert(prot.get());
1231 if (!initiator && bindings.empty()) {
1232 log.error("no Logout Initiator or Binding config for protocol (%s)", prot.get());
1236 // Attach default Location to Logout element.
1237 static const XMLCh _loc[] = { chForwardSlash, chLatin_L, chLatin_o, chLatin_g, chLatin_o, chLatin_u, chLatin_t, chNull };
1238 e->setAttributeNS(nullptr, Location, _loc);
1240 // Instantiate Chaining initiator around the SSO element.
1241 boost::shared_ptr<Handler> chain(
1242 conf.LogoutInitiatorManager.newPlugin(CHAINING_LOGOUT_INITIATOR, pair<const DOMElement*,const char*>(e, getId()))
1244 m_handlers.push_back(chain);
1245 m_handlerMap["/Logout"] = chain.get();
1248 void XMLApplication::doNameIDMgmt(const ProtocolProvider& pp, set<string>& protocols, DOMElement* e, Category& log)
1250 if (!e->hasChildNodes())
1253 SPConfig& conf = SPConfig::getConfig();
1255 // Tokenize the protocol list inside the element.
1256 XMLStringTokenizer prottokens(e->getTextContent());
1257 while (prottokens.hasMoreTokens()) {
1258 auto_ptr_char prot(prottokens.nextToken());
1260 // Look for incoming bindings.
1261 const vector<const PropertySet*>& bindings = pp.getBindings(prot.get(), "NameIDMgmt");
1262 if (!bindings.empty()) {
1263 log.info("auto-configuring NameIDMgmt endpoints for protocol (%s)", prot.get());
1264 pair<bool,const XMLCh*> idprop,pathprop;
1265 for (vector<const PropertySet*>::const_iterator b = bindings.begin(); b != bindings.end(); ++b) {
1266 idprop = (*b)->getXMLString("id");
1267 pathprop = (*b)->getXMLString("path");
1268 if (idprop.first && pathprop.first) {
1269 DOMElement* nimdom = e->getOwnerDocument()->createElementNS(samlconstants::SAML20MD_NS, _ManageNameIDService);
1270 nimdom->setAttributeNS(nullptr, Binding, idprop.second);
1271 nimdom->setAttributeNS(nullptr, Location, pathprop.second);
1273 log.info("adding ManageNameIDService for Binding (%s) at (%s)", (*b)->getString("id").second, (*b)->getString("path").second);
1274 boost::shared_ptr<Handler> handler(
1275 conf.ManageNameIDServiceManager.newPlugin((*b)->getString("id").second, pair<const DOMElement*,const char*>(nimdom, getId()))
1277 m_handlers.push_back(handler);
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)", prot.get());
1291 if (protocols.count(prot.get()) == 0) {
1292 doArtifactResolution(pp, prot.get(), e, log);
1293 protocols.insert(prot.get());
1297 log.error("no NameIDMgmt Binding config for protocol (%s)", prot.get());
1302 void XMLApplication::doArtifactResolution(const ProtocolProvider& pp, const char* protocol, DOMElement* e, Category& log)
1304 SPConfig& conf = SPConfig::getConfig();
1306 // Look for incoming bindings.
1307 const vector<const PropertySet*>& bindings = pp.getBindings(protocol, "ArtifactResolution");
1308 if (!bindings.empty()) {
1309 log.info("auto-configuring ArtifactResolution endpoints for protocol (%s)", protocol);
1311 pair<bool,const XMLCh*> idprop,pathprop;
1312 for (vector<const PropertySet*>::const_iterator b = bindings.begin(); b != bindings.end(); ++b) {
1313 idprop = (*b)->getXMLString("id");
1314 pathprop = (*b)->getXMLString("path");
1315 if (idprop.first && pathprop.first) {
1316 DOMElement* artdom = e->getOwnerDocument()->createElementNS(samlconstants::SAML20MD_NS, _ArtifactResolutionService);
1317 artdom->setAttributeNS(nullptr, Binding, idprop.second);
1318 artdom->setAttributeNS(nullptr, Location, pathprop.second);
1319 xstring indexbuf(chDigit_1 + (index % 10), 1);
1321 indexbuf = (XMLCh)(chDigit_1 + (index / 10)) + indexbuf;
1322 artdom->setAttributeNS(nullptr, _index, indexbuf.c_str());
1324 log.info("adding ArtifactResolutionService for Binding (%s) at (%s)", (*b)->getString("id").second, (*b)->getString("path").second);
1325 boost::shared_ptr<Handler> handler(
1326 conf.ArtifactResolutionServiceManager.newPlugin((*b)->getString("id").second, pair<const DOMElement*,const char*>(artdom, getId()))
1328 m_handlers.push_back(handler);
1330 if (!m_artifactResolutionDefault)
1331 m_artifactResolutionDefault = handler.get();
1333 // Insert into location map.
1334 pair<bool,const char*> location = handler->getString("Location");
1335 if (location.first && *location.second == '/')
1336 m_handlerMap[location.second] = handler.get();
1337 else if (location.first)
1338 m_handlerMap[string("/") + location.second] = handler.get();
1341 log.error("missing id or path property on Binding element, check config for protocol (%s)", protocol);
1348 void XMLApplication::doAttributePlugins(DOMElement* e, Category& log)
1350 SPConfig& conf = SPConfig::getConfig();
1352 m_attrExtractor.reset(
1353 doChainedPlugins(conf.AttributeExtractorManager, "AttributeExtractor", CHAINING_ATTRIBUTE_EXTRACTOR, _AttributeExtractor, e, log)
1357 doChainedPlugins(conf.AttributeFilterManager, "AttributeFilter", CHAINING_ATTRIBUTE_FILTER, _AttributeFilter, e, log, DUMMY_ATTRIBUTE_FILTER)
1360 m_attrResolver.reset(
1361 doChainedPlugins(conf.AttributeResolverManager, "AttributeResolver", CHAINING_ATTRIBUTE_RESOLVER, _AttributeResolver, e, log)
1364 if (m_unsetHeaders.empty()) {
1365 vector<string> unsetHeaders;
1366 if (m_attrExtractor) {
1367 Locker extlock(m_attrExtractor.get());
1368 m_attrExtractor->getAttributeIds(unsetHeaders);
1370 else if (m_base && m_base->m_attrExtractor) {
1371 Locker extlock(m_base->m_attrExtractor.get());
1372 m_base->m_attrExtractor->getAttributeIds(unsetHeaders);
1374 if (m_attrResolver) {
1375 Locker reslock(m_attrResolver.get());
1376 m_attrResolver->getAttributeIds(unsetHeaders);
1378 else if (m_base && m_base->m_attrResolver) {
1379 Locker extlock(m_base->m_attrResolver.get());
1380 m_base->m_attrResolver->getAttributeIds(unsetHeaders);
1382 if (!unsetHeaders.empty()) {
1383 string transformedprefix(m_attributePrefix.second);
1385 pair<bool,const char*> prefix = getString("metadataAttributePrefix");
1387 pch = prefix.second;
1389 transformedprefix += (isalnum(*pch) ? toupper(*pch) : '_');
1393 for (vector<string>::const_iterator hdr = unsetHeaders.begin(); hdr!=unsetHeaders.end(); ++hdr) {
1397 transformed += (isalnum(*pch) ? toupper(*pch) : '_');
1400 m_unsetHeaders.push_back(make_pair(m_attributePrefix.first + *hdr, m_attributePrefix.second + transformed));
1402 m_unsetHeaders.push_back(make_pair(m_attributePrefix.first + prefix.second + *hdr, transformedprefix + transformed));
1405 m_unsetHeaders.push_back(make_pair(m_attributePrefix.first + "Shib-Application-ID", m_attributePrefix.second + "SHIB_APPLICATION_ID"));
1410 #ifdef SHIBSP_XERCESC_SHORT_ACCEPTNODE
1413 DOMNodeFilter::FilterAction
1415 XMLApplication::acceptNode(const DOMNode* node) const
1417 const XMLCh* name=node->getLocalName();
1418 if (XMLString::equals(name,ApplicationOverride) ||
1419 XMLString::equals(name,_Audience) ||
1420 XMLString::equals(name,Notify) ||
1421 XMLString::equals(name,_Handler) ||
1422 XMLString::equals(name,_AssertionConsumerService) ||
1423 XMLString::equals(name,_ArtifactResolutionService) ||
1424 XMLString::equals(name,Logout) ||
1425 XMLString::equals(name,_LogoutInitiator) ||
1426 XMLString::equals(name,_ManageNameIDService) ||
1427 XMLString::equals(name,NameIDMgmt) ||
1428 XMLString::equals(name,_SessionInitiator) ||
1429 XMLString::equals(name,_SingleLogoutService) ||
1430 XMLString::equals(name,SSO) ||
1431 XMLString::equals(name,RelyingParty) ||
1432 XMLString::equals(name,_MetadataProvider) ||
1433 XMLString::equals(name,_TrustEngine) ||
1434 XMLString::equals(name,_CredentialResolver) ||
1435 XMLString::equals(name,_AttributeFilter) ||
1436 XMLString::equals(name,_AttributeExtractor) ||
1437 XMLString::equals(name,_AttributeResolver))
1438 return FILTER_REJECT;
1440 return FILTER_ACCEPT;
1445 const PropertySet* XMLApplication::getRelyingParty(const EntityDescriptor* provider) const
1450 map< xstring,boost::shared_ptr<PropertySet> >::const_iterator i = m_partyMap.find(provider->getEntityID());
1451 if (i != m_partyMap.end())
1452 return i->second.get();
1453 const EntitiesDescriptor* group = dynamic_cast<const EntitiesDescriptor*>(provider->getParent());
1455 if (group->getName()) {
1456 i = m_partyMap.find(group->getName());
1457 if (i != m_partyMap.end())
1458 return i->second.get();
1460 group = dynamic_cast<const EntitiesDescriptor*>(group->getParent());
1465 const PropertySet* XMLApplication::getRelyingParty(const XMLCh* entityID) const
1469 map< xstring,boost::shared_ptr<PropertySet> >::const_iterator i = m_partyMap.find(entityID);
1470 return (i != m_partyMap.end()) ? i->second.get() : this;
1475 string XMLApplication::getNotificationURL(const char* resource, bool front, unsigned int index) const
1477 const vector<string>& locs = front ? m_frontLogout : m_backLogout;
1479 return m_base ? m_base->getNotificationURL(resource, front, index) : string();
1480 else if (index >= locs.size())
1483 #ifdef HAVE_STRCASECMP
1484 if (!resource || (strncasecmp(resource,"http://",7) && strncasecmp(resource,"https://",8)))
1486 if (!resource || (strnicmp(resource,"http://",7) && strnicmp(resource,"https://",8)))
1488 throw ConfigurationException("Request URL was not absolute.");
1490 const char* handler = locs[index].c_str();
1492 // Should never happen...
1493 if (!handler || (*handler!='/' && strncmp(handler,"http:",5) && strncmp(handler,"https:",6)))
1494 throw ConfigurationException(
1495 "Invalid Location property ($1) in Notify element for Application ($2)",
1496 params(2, handler ? handler : "null", getId())
1499 // The "Location" property can be in one of three formats:
1501 // 1) a full URI: http://host/foo/bar
1502 // 2) a hostless URI: http:///foo/bar
1503 // 3) a relative path: /foo/bar
1505 // # Protocol Host Path
1506 // 1 handler handler handler
1507 // 2 handler resource handler
1508 // 3 resource resource handler
1510 const char* path = nullptr;
1512 // Decide whether to use the handler or the resource for the "protocol"
1514 if (*handler != '/') {
1522 // break apart the "protocol" string into protocol, host, and "the rest"
1523 const char* colon=strchr(prot,':');
1525 const char* slash=strchr(colon,'/');
1529 // Compute the actual protocol and store.
1530 string notifyURL(prot, colon-prot);
1532 // create the "host" from either the colon/slash or from the target string
1533 // If prot == handler then we're in either #1 or #2, else #3.
1534 // If slash == colon then we're in #2.
1535 if (prot != handler || slash == colon) {
1536 colon = strchr(resource, ':');
1537 colon += 3; // Get past the ://
1538 slash = strchr(colon, '/');
1540 string host(colon, (slash ? slash-colon : strlen(colon)));
1543 notifyURL += host + path;
1547 void XMLApplication::clearHeader(SPRequest& request, const char* rawname, const char* cginame) const
1549 if (!m_attributePrefix.first.empty()) {
1550 string temp = m_attributePrefix.first + rawname;
1551 string temp2 = m_attributePrefix.second + (cginame + 5);
1552 request.clearHeader(temp.c_str(), temp2.c_str());
1555 m_base->clearHeader(request, rawname, cginame);
1558 request.clearHeader(rawname, cginame);
1562 void XMLApplication::setHeader(SPRequest& request, const char* name, const char* value) const
1564 if (!m_attributePrefix.first.empty()) {
1565 string temp = m_attributePrefix.first + name;
1566 request.setHeader(temp.c_str(), value);
1569 m_base->setHeader(request, name, value);
1572 request.setHeader(name, value);
1576 string XMLApplication::getSecureHeader(const SPRequest& request, const char* name) const
1578 if (!m_attributePrefix.first.empty()) {
1579 string temp = m_attributePrefix.first + name;
1580 return request.getSecureHeader(temp.c_str());
1583 return m_base->getSecureHeader(request,name);
1586 return request.getSecureHeader(name);
1590 const SessionInitiator* XMLApplication::getDefaultSessionInitiator() const
1592 if (m_sessionInitDefault) return m_sessionInitDefault;
1593 return m_base ? m_base->getDefaultSessionInitiator() : nullptr;
1596 const SessionInitiator* XMLApplication::getSessionInitiatorById(const char* id) const
1598 map<string,const SessionInitiator*>::const_iterator i = m_sessionInitMap.find(id);
1599 if (i != m_sessionInitMap.end()) return i->second;
1600 return m_base ? m_base->getSessionInitiatorById(id) : nullptr;
1603 const Handler* XMLApplication::getDefaultAssertionConsumerService() const
1605 if (m_acsDefault) return m_acsDefault;
1606 return m_base ? m_base->getDefaultAssertionConsumerService() : nullptr;
1609 const Handler* XMLApplication::getAssertionConsumerServiceByIndex(unsigned short index) const
1611 map<unsigned int,const Handler*>::const_iterator i = m_acsIndexMap.find(index);
1612 if (i != m_acsIndexMap.end()) return i->second;
1613 return m_base ? m_base->getAssertionConsumerServiceByIndex(index) : nullptr;
1616 const Handler* XMLApplication::getAssertionConsumerServiceByProtocol(const XMLCh* protocol, const char* binding) const
1618 ACSProtocolMap::const_iterator i = m_acsProtocolMap.find(protocol);
1619 if (i != m_acsProtocolMap.end() && !i->second.empty()) {
1620 if (!binding || !*binding)
1621 return i->second.front();
1622 for (ACSProtocolMap::value_type::second_type::const_iterator j = i->second.begin(); j != i->second.end(); ++j) {
1623 if (!strcmp(binding, (*j)->getString("Binding").second))
1627 return m_base ? m_base->getAssertionConsumerServiceByProtocol(protocol, binding) : nullptr;
1630 const vector<const Handler*>& XMLApplication::getAssertionConsumerServicesByBinding(const XMLCh* binding) const
1632 ACSBindingMap::const_iterator i = m_acsBindingMap.find(binding);
1633 if (i != m_acsBindingMap.end())
1635 return m_base ? m_base->getAssertionConsumerServicesByBinding(binding) : g_noHandlers;
1638 const Handler* XMLApplication::getHandler(const char* path) const
1641 wrap = wrap.substr(0, wrap.find(';'));
1642 map<string,const Handler*>::const_iterator i = m_handlerMap.find(wrap.substr(0, wrap.find('?')));
1643 if (i != m_handlerMap.end())
1645 return m_base ? m_base->getHandler(path) : nullptr;
1648 void XMLApplication::getHandlers(vector<const Handler*>& handlers) const
1650 static void (vector<const Handler*>::* pb)(const Handler* const&) = &vector<const Handler*>::push_back;
1651 for_each(m_handlers.begin(), m_handlers.end(), boost::bind(pb, boost::ref(handlers), boost::bind(&boost::shared_ptr<Handler>::get, _1)));
1653 for (map<string,const Handler*>::const_iterator h = m_base->m_handlerMap.begin(); h != m_base->m_handlerMap.end(); ++h) {
1654 if (m_handlerMap.count(h->first) == 0)
1655 handlers.push_back(h->second);
1660 void XMLApplication::limitRedirect(const GenericRequest& request, const char* url) const
1662 if (!url || *url == '/')
1664 if (m_redirectLimit == REDIRECT_LIMIT_INHERIT)
1665 return m_base->limitRedirect(request, url);
1666 if (m_redirectLimit != REDIRECT_LIMIT_NONE) {
1667 vector<string> whitelist;
1668 if (m_redirectLimit == REDIRECT_LIMIT_EXACT || m_redirectLimit == REDIRECT_LIMIT_EXACT_WHITELIST) {
1669 // Scheme and hostname have to match.
1670 if (request.isDefaultPort()) {
1671 whitelist.push_back(string(request.getScheme()) + "://" + request.getHostname() + '/');
1673 whitelist.push_back(string(request.getScheme()) + "://" + request.getHostname() + ':' + lexical_cast<string>(request.getPort()) + '/');
1675 else if (m_redirectLimit == REDIRECT_LIMIT_HOST || m_redirectLimit == REDIRECT_LIMIT_HOST_WHITELIST) {
1676 // Allow any scheme or port.
1677 whitelist.push_back(string("https://") + request.getHostname() + '/');
1678 whitelist.push_back(string("http://") + request.getHostname() + '/');
1679 whitelist.push_back(string("https://") + request.getHostname() + ':');
1680 whitelist.push_back(string("http://") + request.getHostname() + ':');
1683 static bool (*startsWithI)(const char*,const char*) = XMLString::startsWithI;
1684 if (!whitelist.empty() && find_if(whitelist.begin(), whitelist.end(),
1685 boost::bind(startsWithI, url, boost::bind(&string::c_str, _1))) != whitelist.end()) {
1688 else if (!m_redirectWhitelist.empty() && find_if(m_redirectWhitelist.begin(), m_redirectWhitelist.end(),
1689 boost::bind(startsWithI, url, boost::bind(&string::c_str, _1))) != m_redirectWhitelist.end()) {
1692 Category::getInstance(SHIBSP_LOGCAT".Application").warn("redirectLimit policy enforced, blocked redirect to (%s)", url);
1693 throw opensaml::SecurityPolicyException("Blocked unacceptable redirect location.");
1697 #ifdef SHIBSP_XERCESC_SHORT_ACCEPTNODE
1700 DOMNodeFilter::FilterAction
1702 XMLConfigImpl::acceptNode(const DOMNode* node) const
1704 if (!XMLString::equals(node->getNamespaceURI(),shibspconstants::SHIB2SPCONFIG_NS))
1705 return FILTER_ACCEPT;
1706 const XMLCh* name=node->getLocalName();
1707 if (XMLString::equals(name,ApplicationDefaults) ||
1708 XMLString::equals(name,_ArtifactMap) ||
1709 XMLString::equals(name,_Extensions) ||
1710 XMLString::equals(name,Listener) ||
1711 XMLString::equals(name,_ProtocolProvider) ||
1712 XMLString::equals(name,_RequestMapper) ||
1713 XMLString::equals(name,_ReplayCache) ||
1714 XMLString::equals(name,SecurityPolicies) ||
1715 XMLString::equals(name,_SecurityPolicyProvider) ||
1716 XMLString::equals(name,_SessionCache) ||
1717 XMLString::equals(name,Site) ||
1718 XMLString::equals(name,_StorageService) ||
1719 XMLString::equals(name,TCPListener) ||
1720 XMLString::equals(name,TransportOption) ||
1721 XMLString::equals(name,UnixListener))
1722 return FILTER_REJECT;
1724 return FILTER_ACCEPT;
1727 void XMLConfigImpl::doExtensions(const DOMElement* e, const char* label, Category& log)
1729 const DOMElement* exts = XMLHelper::getFirstChildElement(e, _Extensions);
1731 exts = XMLHelper::getFirstChildElement(exts, Library);
1733 string path(XMLHelper::getAttrString(exts, nullptr, _path));
1735 if (!path.empty()) {
1736 if (!XMLToolingConfig::getConfig().load_library(path.c_str(), (void*)exts))
1737 throw ConfigurationException("XMLToolingConfig::load_library failed.");
1738 log.debug("loaded %s extension library (%s)", label, path.c_str());
1741 catch (std::exception& e) {
1742 if (XMLHelper::getAttrBool(exts, false, _fatal)) {
1743 log.fatal("unable to load mandatory %s extension library %s: %s", label, path.c_str(), e.what());
1747 log.crit("unable to load optional %s extension library %s: %s", label, path.c_str(), e.what());
1750 exts = XMLHelper::getNextSiblingElement(exts, Library);
1755 void XMLConfigImpl::doListener(const DOMElement* e, XMLConfig* conf, Category& log)
1758 string plugtype(TCP_LISTENER_SERVICE);
1760 string plugtype(UNIX_LISTENER_SERVICE);
1762 DOMElement* child = XMLHelper::getFirstChildElement(e, UnixListener);
1764 plugtype = UNIX_LISTENER_SERVICE;
1766 child = XMLHelper::getFirstChildElement(e, TCPListener);
1768 plugtype = TCP_LISTENER_SERVICE;
1770 child = XMLHelper::getFirstChildElement(e, Listener);
1772 auto_ptr_char type(child->getAttributeNS(nullptr, _type));
1773 if (type.get() && *type.get())
1774 plugtype = type.get();
1779 log.info("building ListenerService of type %s...", plugtype.c_str());
1780 conf->m_listener.reset(SPConfig::getConfig().ListenerServiceManager.newPlugin(plugtype.c_str(), child));
1783 void XMLConfigImpl::doCaching(const DOMElement* e, XMLConfig* conf, Category& log)
1785 SPConfig& spConf = SPConfig::getConfig();
1787 SAMLConfig& samlConf = SAMLConfig::getConfig();
1792 if (spConf.isEnabled(SPConfig::OutOfProcess)) {
1793 XMLToolingConfig& xmlConf = XMLToolingConfig::getConfig();
1794 // First build any StorageServices.
1795 child = XMLHelper::getFirstChildElement(e, _StorageService);
1797 string id(XMLHelper::getAttrString(child, nullptr, _id));
1798 string t(XMLHelper::getAttrString(child, nullptr, _type));
1801 log.info("building StorageService (%s) of type %s...", id.c_str(), t.c_str());
1802 conf->m_storage[id] = boost::shared_ptr<StorageService>(xmlConf.StorageServiceManager.newPlugin(t.c_str(), child));
1804 catch (std::exception& ex) {
1805 log.crit("failed to instantiate StorageService (%s): %s", id.c_str(), ex.what());
1808 child = XMLHelper::getNextSiblingElement(child, _StorageService);
1811 if (conf->m_storage.empty()) {
1812 log.info("no StorageService plugin(s) installed, using (mem) in-memory instance");
1813 conf->m_storage["mem"] = boost::shared_ptr<StorageService>(xmlConf.StorageServiceManager.newPlugin(MEMORY_STORAGE_SERVICE, nullptr));
1817 StorageService* replaySS = nullptr;
1818 child = XMLHelper::getFirstChildElement(e, _ReplayCache);
1820 string ssid(XMLHelper::getAttrString(child, nullptr, _StorageService));
1821 if (!ssid.empty()) {
1822 if (conf->m_storage.count(ssid)) {
1823 log.info("building ReplayCache on top of StorageService (%s)...", ssid.c_str());
1824 replaySS = conf->m_storage[ssid].get();
1827 log.error("unable to locate StorageService (%s), using arbitrary instance for ReplayCache", ssid.c_str());
1828 replaySS = conf->m_storage.begin()->second.get();
1832 log.info("no StorageService specified for ReplayCache, using arbitrary instance");
1833 replaySS = conf->m_storage.begin()->second.get();
1837 log.info("no ReplayCache specified, using arbitrary StorageService instance");
1838 replaySS = conf->m_storage.begin()->second.get();
1840 xmlConf.setReplayCache(new ReplayCache(replaySS));
1843 child = XMLHelper::getFirstChildElement(e, _ArtifactMap);
1845 string ssid(XMLHelper::getAttrString(child, nullptr, _StorageService));
1846 if (!ssid.empty()) {
1847 if (conf->m_storage.count(ssid)) {
1848 log.info("building ArtifactMap on top of StorageService (%s)...", ssid.c_str());
1849 samlConf.setArtifactMap(new ArtifactMap(child, conf->m_storage[ssid].get()));
1852 log.error("unable to locate StorageService (%s), using in-memory ArtifactMap", ssid.c_str());
1853 samlConf.setArtifactMap(new ArtifactMap(child));
1857 log.info("no StorageService specified, using in-memory ArtifactMap");
1858 samlConf.setArtifactMap(new ArtifactMap(child));
1862 log.info("no ArtifactMap specified, building in-memory ArtifactMap...");
1863 samlConf.setArtifactMap(new ArtifactMap(child));
1865 } // end of out of process caching components
1868 child = XMLHelper::getFirstChildElement(e, _SessionCache);
1870 string t(XMLHelper::getAttrString(child, nullptr, _type));
1872 log.info("building SessionCache of type %s...", t.c_str());
1873 conf->m_sessionCache.reset(spConf.SessionCacheManager.newPlugin(t.c_str(), child));
1876 if (!conf->m_sessionCache) {
1877 log.info("no SessionCache specified, using StorageService-backed instance");
1878 conf->m_sessionCache.reset(spConf.SessionCacheManager.newPlugin(STORAGESERVICE_SESSION_CACHE, nullptr));
1882 XMLConfigImpl::XMLConfigImpl(const DOMElement* e, bool first, XMLConfig* outer, Category& log) : m_document(nullptr)
1885 xmltooling::NDC ndc("XMLConfigImpl");
1887 SPConfig& conf=SPConfig::getConfig();
1888 XMLToolingConfig& xmlConf=XMLToolingConfig::getConfig();
1889 const DOMElement* SHAR=XMLHelper::getFirstChildElement(e, OutOfProcess);
1890 const DOMElement* SHIRE=XMLHelper::getFirstChildElement(e, InProcess);
1892 // Initialize logging manually in order to redirect log messages as soon as possible.
1893 if (conf.isEnabled(SPConfig::Logging)) {
1895 if (conf.isEnabled(SPConfig::OutOfProcess))
1896 logconf = XMLHelper::getAttrString(SHAR, nullptr, logger);
1897 else if (conf.isEnabled(SPConfig::InProcess))
1898 logconf = XMLHelper::getAttrString(SHIRE, nullptr, logger);
1899 if (logconf.empty())
1900 logconf = XMLHelper::getAttrString(e, nullptr, logger);
1901 if (logconf.empty() && !getenv("SHIBSP_LOGGING")) {
1902 // No properties found, so default them.
1903 if (conf.isEnabled(SPConfig::OutOfProcess) && !conf.isEnabled(SPConfig::InProcess))
1904 logconf = "shibd.logger";
1905 else if (!conf.isEnabled(SPConfig::OutOfProcess) && conf.isEnabled(SPConfig::InProcess))
1906 logconf = "native.logger";
1908 logconf = "shibboleth.logger";
1910 if (!logconf.empty()) {
1911 log.debug("loading new logging configuration from (%s), check log destination for status of configuration", logconf.c_str());
1912 if (!XMLToolingConfig::getConfig().log_config(logconf.c_str()))
1913 log.crit("failed to load new logging configuration from (%s)", logconf.c_str());
1919 XMLHelper::getAttrString(SHAR, nullptr, tranLogFormat).c_str(),
1920 XMLHelper::getAttrString(SHAR, nullptr, tranLogFiller).c_str()
1926 // Re-log library versions now that logging is set up.
1927 log.info("Shibboleth SP Version %s", PACKAGE_VERSION);
1930 "Library versions: %s %s, Xerces-C %s, XML-Security-C %s, XMLTooling-C %s, OpenSAML-C %s, Shibboleth %s",
1931 # if defined(LOG4SHIB_VERSION)
1932 "log4shib", LOG4SHIB_VERSION,
1933 # elif defined(LOG4CPP_VERSION)
1934 "log4cpp", LOG4CPP_VERSION,
1938 XERCES_FULLVERSIONDOT, XSEC_FULLVERSIONDOT, gXMLToolingDotVersionStr, gOpenSAMLDotVersionStr, gShibSPDotVersionStr
1942 "Library versions: %s %s, Xerces-C %s, XMLTooling-C %s, Shibboleth %s",
1943 # if defined(LOG4SHIB_VERSION)
1944 "log4shib", LOG4SHIB_VERSION,
1945 # elif defined(LOG4CPP_VERSION)
1946 "log4cpp", LOG4CPP_VERSION,
1950 XERCES_FULLVERSIONDOT, gXMLToolingDotVersionStr, gShibSPDotVersionStr
1954 // First load any property sets.
1955 load(e, nullptr, this);
1959 // Much of the processing can only occur on the first instantiation.
1962 pair<bool,unsigned int> skew=getUnsignedInt("clockSkew");
1964 xmlConf.clock_skew_secs=min(skew.second,(60*60*24*7*28));
1966 pair<bool,const char*> unsafe = getString("unsafeChars");
1968 TemplateEngine::unsafe_chars = unsafe.second;
1970 unsafe = getString("allowedSchemes");
1972 HTTPResponse::getAllowedSchemes().clear();
1973 string schemes(unsafe.second);
1974 split(HTTPResponse::getAllowedSchemes(), schemes, is_space(), algorithm::token_compress_on);
1977 // Default language handling.
1978 pair<bool,bool> langFromClient = getBool("langFromClient");
1979 pair<bool,const XMLCh*> langPriority = getXMLString("langPriority");
1980 GenericRequest::setLangDefaults(!langFromClient.first || langFromClient.second, langPriority.second);
1983 langPriority = getXMLString("contactPriority");
1984 if (langPriority.first)
1985 SAMLConfig::getConfig().setContactPriority(langPriority.second);
1989 doExtensions(e, "global", log);
1990 if (conf.isEnabled(SPConfig::OutOfProcess))
1991 doExtensions(SHAR, "out of process", log);
1993 if (conf.isEnabled(SPConfig::InProcess))
1994 doExtensions(SHIRE, "in process", log);
1996 // Instantiate the ListenerService and SessionCache objects.
1997 if (conf.isEnabled(SPConfig::Listener))
1998 doListener(e, outer, log);
2001 if (outer->m_listener && conf.isEnabled(SPConfig::OutOfProcess) && !conf.isEnabled(SPConfig::InProcess)) {
2002 outer->m_listener->regListener("set::RelayState", outer);
2003 outer->m_listener->regListener("get::RelayState", outer);
2004 outer->m_listener->regListener("set::PostData", outer);
2005 outer->m_listener->regListener("get::PostData", outer);
2008 if (conf.isEnabled(SPConfig::Caching))
2009 doCaching(e, outer, log);
2010 } // end of first-time-only stuff
2012 // Back to the fully dynamic stuff...next up is the RequestMapper.
2013 if (conf.isEnabled(SPConfig::RequestMapping)) {
2014 if (child = XMLHelper::getFirstChildElement(e, _RequestMapper)) {
2015 string t(XMLHelper::getAttrString(child, nullptr, _type));
2017 log.info("building RequestMapper of type %s...", t.c_str());
2018 m_requestMapper.reset(conf.RequestMapperManager.newPlugin(t.c_str(), child));
2021 if (!m_requestMapper) {
2022 log.info("no RequestMapper specified, using 'Native' plugin with empty/default map");
2023 child = e->getOwnerDocument()->createElementNS(nullptr, _RequestMapper);
2024 DOMElement* mapperDummy = e->getOwnerDocument()->createElementNS(shibspconstants::SHIB2SPCONFIG_NS, RequestMap);
2025 mapperDummy->setAttributeNS(nullptr, applicationId, _default);
2026 child->appendChild(mapperDummy);
2027 m_requestMapper.reset(conf.RequestMapperManager.newPlugin(NATIVE_REQUEST_MAPPER, child));
2032 // Load security policies.
2033 if (child = XMLHelper::getLastChildElement(e, _SecurityPolicyProvider)) {
2034 string t(XMLHelper::getAttrString(child, nullptr, _type));
2036 log.info("building SecurityPolicyProvider of type %s...", t.c_str());
2037 m_policy.reset(conf.SecurityPolicyProviderManager.newPlugin(t.c_str(), child));
2040 throw ConfigurationException("can't build SecurityPolicyProvider, no type specified");
2043 else if (child = XMLHelper::getLastChildElement(e, SecurityPolicies)) {
2044 // For backward compatibility, wrap in a plugin element.
2045 DOMElement* polwrapper = e->getOwnerDocument()->createElementNS(nullptr, _SecurityPolicyProvider);
2046 polwrapper->appendChild(child);
2047 log.info("building SecurityPolicyProvider of type %s...", XML_SECURITYPOLICY_PROVIDER);
2048 m_policy.reset(conf.SecurityPolicyProviderManager.newPlugin(XML_SECURITYPOLICY_PROVIDER, polwrapper));
2051 log.fatal("can't build SecurityPolicyProvider, missing conf:SecurityPolicyProvider element?");
2052 throw ConfigurationException("Can't build SecurityPolicyProvider, missing conf:SecurityPolicyProvider element?");
2056 if (!m_policy->getAlgorithmBlacklist().empty()) {
2057 #ifdef SHIBSP_XMLSEC_WHITELISTING
2059 m_policy->getAlgorithmBlacklist().begin(), m_policy->getAlgorithmBlacklist().end(),
2060 boost::bind(&XSECPlatformUtils::blacklistAlgorithm, boost::bind(&xstring::c_str, _1))
2063 log.crit("XML-Security-C library prior to 1.6.0 does not support algorithm white/blacklists");
2066 else if (!m_policy->getAlgorithmWhitelist().empty()) {
2067 #ifdef SHIBSP_XMLSEC_WHITELISTING
2069 m_policy->getAlgorithmWhitelist().begin(), m_policy->getAlgorithmWhitelist().end(),
2070 boost::bind(&XSECPlatformUtils::whitelistAlgorithm, boost::bind(&xstring::c_str, _1))
2073 log.crit("XML-Security-C library prior to 1.6.0 does not support algorithm white/blacklists");
2078 // Process TransportOption elements.
2079 child = XMLHelper::getLastChildElement(e, TransportOption);
2081 if (child->hasChildNodes()) {
2082 string provider(XMLHelper::getAttrString(child, nullptr, _provider));
2083 string option(XMLHelper::getAttrString(child, nullptr, _option));
2084 auto_ptr_char value(child->getFirstChild()->getNodeValue());
2085 if (!provider.empty() && !option.empty() && value.get() && *value.get()) {
2086 m_transportOptions.push_back(make_tuple(provider, option, string(value.get())));
2089 child = XMLHelper::getPreviousSiblingElement(child, TransportOption);
2093 scoped_ptr<ProtocolProvider> pp;
2094 if (conf.isEnabled(SPConfig::Handlers)) {
2095 if (child = XMLHelper::getLastChildElement(e, _ProtocolProvider)) {
2096 string t(XMLHelper::getAttrString(child, nullptr, _type));
2098 log.info("building ProtocolProvider of type %s...", t.c_str());
2099 pp.reset(conf.ProtocolProviderManager.newPlugin(t.c_str(), child));
2103 Locker pplocker(pp.get());
2105 // Load the default application.
2106 child = XMLHelper::getLastChildElement(e, ApplicationDefaults);
2108 log.fatal("can't build default Application object, missing conf:ApplicationDefaults element?");
2109 throw ConfigurationException("can't build default Application object, missing conf:ApplicationDefaults element?");
2111 boost::shared_ptr<XMLApplication> defapp(new XMLApplication(outer, pp.get(), child));
2112 m_appmap[defapp->getId()] = defapp;
2114 // Load any overrides.
2115 child = XMLHelper::getFirstChildElement(child, ApplicationOverride);
2117 boost::shared_ptr<XMLApplication> iapp(new XMLApplication(outer, pp.get(), child, defapp.get()));
2118 if (m_appmap.count(iapp->getId()))
2119 log.crit("found conf:ApplicationOverride element with duplicate id attribute (%s), skipping it", iapp->getId());
2121 m_appmap[iapp->getId()] = iapp;
2123 child = XMLHelper::getNextSiblingElement(child, ApplicationOverride);
2126 // Check for extra AuthTypes to recognize.
2127 if (conf.isEnabled(SPConfig::InProcess)) {
2128 const PropertySet* inprocs = getPropertySet("InProcess");
2130 pair<bool,const char*> extraAuthTypes = inprocs->getString("extraAuthTypes");
2131 if (extraAuthTypes.first) {
2132 string types(extraAuthTypes.second);
2133 split(outer->m_authTypes, types, is_space(), algorithm::token_compress_on);
2140 void XMLConfig::receive(DDF& in, ostream& out)
2142 if (!strcmp(in.name(), "get::RelayState")) {
2143 const char* id = in["id"].string();
2144 const char* key = in["key"].string();
2146 throw ListenerException("Required parameters missing for RelayState recovery.");
2149 StorageService* storage = getStorageService(id);
2151 if (storage->readString("RelayState",key,&relayState)>0) {
2152 if (in["clear"].integer())
2153 storage->deleteString("RelayState",key);
2155 else if (storage->readText("RelayState",key,&relayState)>0) {
2156 if (in["clear"].integer())
2157 storage->deleteText("RelayState",key);
2161 Category::getInstance(SHIBSP_LOGCAT".ServiceProvider").error(
2162 "Storage-backed RelayState with invalid StorageService ID (%s)", id
2166 // Repack for return to caller.
2167 DDF ret=DDF(nullptr).unsafe_string(relayState.c_str());
2168 DDFJanitor jret(ret);
2171 else if (!strcmp(in.name(), "set::RelayState")) {
2172 const char* id = in["id"].string();
2173 const char* value = in["value"].string();
2175 throw ListenerException("Required parameters missing for RelayState creation.");
2178 StorageService* storage = getStorageService(id);
2180 SAMLConfig::getConfig().generateRandomBytes(rsKey,32);
2181 rsKey = SAMLArtifact::toHex(rsKey);
2182 if (strlen(value) <= storage->getCapabilities().getStringSize())
2183 storage->createString("RelayState", rsKey.c_str(), value, time(nullptr) + 600);
2185 storage->createText("RelayState", rsKey.c_str(), value, time(nullptr) + 600);
2188 Category::getInstance(SHIBSP_LOGCAT".ServiceProvider").error(
2189 "Storage-backed RelayState with invalid StorageService ID (%s)", id
2193 // Repack for return to caller.
2194 DDF ret=DDF(nullptr).string(rsKey.c_str());
2195 DDFJanitor jret(ret);
2198 else if (!strcmp(in.name(), "get::PostData")) {
2199 const char* id = in["id"].string();
2200 const char* key = in["key"].string();
2202 throw ListenerException("Required parameters missing for PostData recovery.");
2205 StorageService* storage = getStorageService(id);
2207 if (storage->readText("PostData",key,&postData) > 0) {
2208 storage->deleteText("PostData",key);
2212 Category::getInstance(SHIBSP_LOGCAT".ServiceProvider").error(
2213 "Storage-backed PostData with invalid StorageService ID (%s)", id
2216 // If the data's empty, we'll send nothing back.
2217 // If not, we don't need to round trip it, just send back the serialized DDF list.
2218 if (postData.empty()) {
2220 DDFJanitor jret(ret);
2227 else if (!strcmp(in.name(), "set::PostData")) {
2228 const char* id = in["id"].string();
2229 if (!id || !in["parameters"].islist())
2230 throw ListenerException("Required parameters missing for PostData creation.");
2233 StorageService* storage = getStorageService(id);
2235 SAMLConfig::getConfig().generateRandomBytes(rsKey,32);
2236 rsKey = SAMLArtifact::toHex(rsKey);
2237 ostringstream params;
2238 params << in["parameters"];
2239 storage->createText("PostData", rsKey.c_str(), params.str().c_str(), time(nullptr) + 600);
2242 Category::getInstance(SHIBSP_LOGCAT".ServiceProvider").error(
2243 "Storage-backed PostData with invalid StorageService ID (%s)", id
2247 // Repack for return to caller.
2248 DDF ret=DDF(nullptr).string(rsKey.c_str());
2249 DDFJanitor jret(ret);
2255 pair<bool,DOMElement*> XMLConfig::background_load()
2257 // Load from source using base class.
2258 pair<bool,DOMElement*> raw = ReloadableXMLFile::load();
2260 // If we own it, wrap it.
2261 XercesJanitor<DOMDocument> docjanitor(raw.first ? raw.second->getOwnerDocument() : nullptr);
2263 scoped_ptr<XMLConfigImpl> impl(new XMLConfigImpl(raw.second, (m_impl==nullptr), this, m_log));
2265 // If we held the document, transfer it to the impl. If we didn't, it's a no-op.
2266 impl->setDocument(docjanitor.release());
2268 // Perform the swap inside a lock.
2271 SharedLock locker(m_lock, false);
2274 return make_pair(false,(DOMElement*)nullptr);