2 * Copyright 2001-2010 Internet2
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
18 * XMLServiceProvider.cpp
20 * XML-based SP configuration and mgmt.
24 #include "exceptions.h"
26 #include "AccessControl.h"
27 #include "Application.h"
28 #include "RequestMapper.h"
29 #include "ServiceProvider.h"
30 #include "SessionCache.h"
32 #include "SPRequest.h"
33 #include "binding/ProtocolProvider.h"
34 #include "handler/LogoutInitiator.h"
35 #include "handler/SessionInitiator.h"
36 #include "remoting/ListenerService.h"
37 #include "util/DOMPropertySet.h"
38 #include "util/SPConstants.h"
40 #if defined(XMLTOOLING_LOG4SHIB)
41 # include <log4shib/PropertyConfigurator.hh>
42 #elif defined(XMLTOOLING_LOG4CPP)
43 # include <log4cpp/PropertyConfigurator.hh>
45 # error "Supported logging library not available."
48 #include <xercesc/util/XMLUniDefs.hpp>
49 #include <xercesc/util/XMLStringTokenizer.hpp>
50 #include <xmltooling/XMLToolingConfig.h>
51 #include <xmltooling/version.h>
52 #include <xmltooling/util/NDC.h>
53 #include <xmltooling/util/ReloadableXMLFile.h>
54 #include <xmltooling/util/TemplateEngine.h>
55 #include <xmltooling/util/Threads.h>
56 #include <xmltooling/util/XMLHelper.h>
59 # include "TransactionLog.h"
60 # include "attribute/filtering/AttributeFilter.h"
61 # include "attribute/resolver/AttributeExtractor.h"
62 # include "attribute/resolver/AttributeResolver.h"
63 # include "security/PKIXTrustEngine.h"
64 # include "security/SecurityPolicyProvider.h"
65 # include <saml/SAMLConfig.h>
66 # include <saml/version.h>
67 # include <saml/binding/ArtifactMap.h>
68 # include <saml/binding/SAMLArtifact.h>
69 # include <saml/saml1/core/Assertions.h>
70 # include <saml/saml2/core/Assertions.h>
71 # include <saml/saml2/binding/SAML2ArtifactType0004.h>
72 # include <saml/saml2/metadata/Metadata.h>
73 # include <saml/saml2/metadata/MetadataProvider.h>
74 # include <saml/util/SAMLConstants.h>
75 # include <xmltooling/security/ChainingTrustEngine.h>
76 # include <xmltooling/security/CredentialResolver.h>
77 # include <xmltooling/security/SecurityHelper.h>
78 # include <xmltooling/util/ReplayCache.h>
79 # include <xmltooling/util/StorageService.h>
80 # include <xsec/utils/XSECPlatformUtils.hpp>
81 using namespace opensaml::saml2;
82 using namespace opensaml::saml2p;
83 using namespace opensaml::saml2md;
84 using namespace opensaml;
86 # include "lite/SAMLConstants.h"
89 using namespace shibsp;
90 using namespace xmltooling;
94 # define min(a,b) (((a) < (b)) ? (a) : (b))
99 #if defined (_MSC_VER)
100 #pragma warning( push )
101 #pragma warning( disable : 4250 )
104 static vector<const Handler*> g_noHandlers;
106 // Application configuration wrapper
107 class SHIBSP_DLLLOCAL XMLApplication : public Application, public Remoted, public DOMPropertySet, public DOMNodeFilter
110 XMLApplication(const ServiceProvider*, const ProtocolProvider*, const DOMElement*, const XMLApplication* base=nullptr);
111 ~XMLApplication() { cleanup(); }
113 const char* getHash() const {return m_hash.c_str();}
116 SAMLArtifact* generateSAML1Artifact(const EntityDescriptor* relyingParty) const {
117 throw ConfigurationException("No support for SAML 1.x artifact generation.");
119 SAML2Artifact* generateSAML2Artifact(const EntityDescriptor* relyingParty) const {
120 pair<bool,int> index = make_pair(false,0);
121 const PropertySet* props = getRelyingParty(relyingParty);
122 index = props->getInt("artifactEndpointIndex");
124 index = getArtifactEndpointIndex();
125 pair<bool,const char*> entityID = props->getString("entityID");
126 return new SAML2ArtifactType0004(
127 SecurityHelper::doHash("SHA1", entityID.second, strlen(entityID.second), false),
128 index.first ? index.second : 1
132 MetadataProvider* getMetadataProvider(bool required=true) const {
133 if (required && !m_base && !m_metadata)
134 throw ConfigurationException("No MetadataProvider available.");
135 return (!m_metadata && m_base) ? m_base->getMetadataProvider() : m_metadata;
137 TrustEngine* getTrustEngine(bool required=true) const {
138 if (required && !m_base && !m_trust)
139 throw ConfigurationException("No TrustEngine available.");
140 return (!m_trust && m_base) ? m_base->getTrustEngine() : m_trust;
142 AttributeExtractor* getAttributeExtractor() const {
143 return (!m_attrExtractor && m_base) ? m_base->getAttributeExtractor() : m_attrExtractor;
145 AttributeFilter* getAttributeFilter() const {
146 return (!m_attrFilter && m_base) ? m_base->getAttributeFilter() : m_attrFilter;
148 AttributeResolver* getAttributeResolver() const {
149 return (!m_attrResolver && m_base) ? m_base->getAttributeResolver() : m_attrResolver;
151 CredentialResolver* getCredentialResolver() const {
152 return (!m_credResolver && m_base) ? m_base->getCredentialResolver() : m_credResolver;
154 const PropertySet* getRelyingParty(const EntityDescriptor* provider) const;
155 const PropertySet* getRelyingParty(const XMLCh* entityID) const;
156 const vector<const XMLCh*>* getAudiences() const {
157 return (m_audiences.empty() && m_base) ? m_base->getAudiences() : &m_audiences;
160 string getNotificationURL(const char* resource, bool front, unsigned int index) const;
162 const vector<string>& getRemoteUserAttributeIds() const {
163 return (m_remoteUsers.empty() && m_base) ? m_base->getRemoteUserAttributeIds() : m_remoteUsers;
166 void clearHeader(SPRequest& request, const char* rawname, const char* cginame) const;
167 void setHeader(SPRequest& request, const char* name, const char* value) const;
168 string getSecureHeader(const SPRequest& request, const char* name) const;
170 const SessionInitiator* getDefaultSessionInitiator() const;
171 const SessionInitiator* getSessionInitiatorById(const char* id) const;
172 const Handler* getDefaultAssertionConsumerService() const;
173 const Handler* getAssertionConsumerServiceByIndex(unsigned short index) const;
174 const Handler* getAssertionConsumerServiceByProtocol(const XMLCh* protocol, const char* binding=nullptr) const;
175 const vector<const Handler*>& getAssertionConsumerServicesByBinding(const XMLCh* binding) const;
176 const Handler* getHandler(const char* path) const;
177 void getHandlers(vector<const Handler*>& handlers) const;
179 void receive(DDF& in, ostream& out) {
180 // Only current function is to return the headers to clear.
182 DDF ret=DDF(nullptr).list();
183 DDFJanitor jret(ret);
184 for (vector< pair<string,string> >::const_iterator i = m_unsetHeaders.begin(); i!=m_unsetHeaders.end(); ++i) {
185 header = DDF(i->first.c_str()).string(i->second.c_str());
191 // Provides filter to exclude special config elements.
192 #ifdef SHIBSP_XERCESC_SHORT_ACCEPTNODE
197 acceptNode(const DOMNode* node) const;
200 void doAttributeInfo();
201 void doHandlers(const ProtocolProvider*, const DOMElement*, Category&);
202 void doSSO(const ProtocolProvider&, set<string>&, DOMElement*, Category&);
203 void doLogout(const ProtocolProvider&, set<string>&, DOMElement*, Category&);
204 void doNameIDMgmt(const ProtocolProvider&, set<string>&, DOMElement*, Category&);
205 void doArtifactResolution(const ProtocolProvider&, const char*, DOMElement*, Category&);
207 const XMLApplication* m_base;
209 std::pair<std::string,std::string> m_attributePrefix;
211 void doAttributePlugins(const DOMElement* e, Category& log);
212 MetadataProvider* m_metadata;
213 TrustEngine* m_trust;
214 AttributeExtractor* m_attrExtractor;
215 AttributeFilter* m_attrFilter;
216 AttributeResolver* m_attrResolver;
217 CredentialResolver* m_credResolver;
218 vector<const XMLCh*> m_audiences;
220 // RelyingParty properties
221 map<xstring,PropertySet*> m_partyMap;
223 vector<string> m_remoteUsers,m_frontLogout,m_backLogout;
225 // manage handler objects
226 vector<Handler*> m_handlers;
228 // maps location (path info) to applicable handlers
229 map<string,const Handler*> m_handlerMap;
231 // maps unique indexes to consumer services
232 map<unsigned int,const Handler*> m_acsIndexMap;
234 // pointer to default consumer service
235 const Handler* m_acsDefault;
237 // maps binding strings to supporting consumer service(s)
238 typedef map< xstring,vector<const Handler*> > ACSBindingMap;
239 ACSBindingMap m_acsBindingMap;
241 // maps protocol strings to supporting consumer service(s)
242 typedef map< xstring,vector<const Handler*> > ACSProtocolMap;
243 ACSProtocolMap m_acsProtocolMap;
245 // pointer to default session initiator
246 const SessionInitiator* m_sessionInitDefault;
248 // maps unique ID strings to session initiators
249 map<string,const SessionInitiator*> m_sessionInitMap;
251 // pointer to default artifact resolution service
252 const Handler* m_artifactResolutionDefault;
254 pair<bool,int> getArtifactEndpointIndex() const {
255 if (m_artifactResolutionDefault) return m_artifactResolutionDefault->getInt("index");
256 return m_base ? m_base->getArtifactEndpointIndex() : make_pair(false,0);
260 // Top-level configuration implementation
261 class SHIBSP_DLLLOCAL XMLConfig;
262 class SHIBSP_DLLLOCAL XMLConfigImpl : public DOMPropertySet, public DOMNodeFilter
265 XMLConfigImpl(const DOMElement* e, bool first, const XMLConfig* outer, Category& log);
268 RequestMapper* m_requestMapper;
269 map<string,Application*> m_appmap;
271 SecurityPolicyProvider* m_policy;
272 vector< pair< string, pair<string,string> > > m_transportOptions;
275 // Provides filter to exclude special config elements.
276 #ifdef SHIBSP_XERCESC_SHORT_ACCEPTNODE
281 acceptNode(const DOMNode* node) const;
283 void setDocument(DOMDocument* doc) {
288 void doExtensions(const DOMElement* e, const char* label, Category& log);
289 void doListener(const DOMElement* e, Category& log);
290 void doCaching(const DOMElement* e, Category& log);
293 const XMLConfig* m_outer;
294 DOMDocument* m_document;
297 class SHIBSP_DLLLOCAL XMLConfig : public ServiceProvider, public ReloadableXMLFile
303 XMLConfig(const DOMElement* e) : ReloadableXMLFile(e, Category::getInstance(SHIBSP_LOGCAT".Config")),
304 m_impl(nullptr), m_listener(nullptr), m_sessionCache(nullptr)
318 delete m_sessionCache;
322 SAMLConfig::getConfig().setArtifactMap(nullptr);
323 XMLToolingConfig::getConfig().setReplayCache(nullptr);
324 for_each(m_storage.begin(), m_storage.end(), cleanup_pair<string,StorageService>());
331 ReloadableXMLFile::lock();
332 if (m_impl->m_policy)
333 m_impl->m_policy->lock();
337 if (m_impl->m_policy)
338 m_impl->m_policy->unlock();
339 ReloadableXMLFile::unlock();
344 const PropertySet* getParent() const { return m_impl->getParent(); }
345 void setParent(const PropertySet* parent) {return m_impl->setParent(parent);}
346 pair<bool,bool> getBool(const char* name, const char* ns=nullptr) const {return m_impl->getBool(name,ns);}
347 pair<bool,const char*> getString(const char* name, const char* ns=nullptr) const {return m_impl->getString(name,ns);}
348 pair<bool,const XMLCh*> getXMLString(const char* name, const char* ns=nullptr) const {return m_impl->getXMLString(name,ns);}
349 pair<bool,unsigned int> getUnsignedInt(const char* name, const char* ns=nullptr) const {return m_impl->getUnsignedInt(name,ns);}
350 pair<bool,int> getInt(const char* name, const char* ns=nullptr) const {return m_impl->getInt(name,ns);}
351 void getAll(map<string,const char*>& properties) const {return m_impl->getAll(properties);}
352 const PropertySet* getPropertySet(const char* name, const char* ns="urn:mace:shibboleth:2.0:native:sp:config") const {return m_impl->getPropertySet(name,ns);}
353 const DOMElement* getElement() const {return m_impl->getElement();}
358 void receive(DDF& in, ostream& out);
360 TransactionLog* getTransactionLog() const {
363 throw ConfigurationException("No TransactionLog available.");
366 StorageService* getStorageService(const char* id) const {
368 map<string,StorageService*>::const_iterator i=m_storage.find(id);
369 if (i!=m_storage.end())
372 else if (!m_storage.empty())
373 return m_storage.begin()->second;
378 ListenerService* getListenerService(bool required=true) const {
379 if (required && !m_listener)
380 throw ConfigurationException("No ListenerService available.");
384 SessionCache* getSessionCache(bool required=true) const {
385 if (required && !m_sessionCache)
386 throw ConfigurationException("No SessionCache available.");
387 return m_sessionCache;
390 RequestMapper* getRequestMapper(bool required=true) const {
391 if (required && !m_impl->m_requestMapper)
392 throw ConfigurationException("No RequestMapper available.");
393 return m_impl->m_requestMapper;
396 const Application* getApplication(const char* applicationId) const {
397 map<string,Application*>::const_iterator i=m_impl->m_appmap.find(applicationId ? applicationId : "default");
398 return (i!=m_impl->m_appmap.end()) ? i->second : nullptr;
402 SecurityPolicyProvider* getSecurityPolicyProvider(bool required=true) const {
403 if (required && !m_impl->m_policy)
404 throw ConfigurationException("No SecurityPolicyProvider available.");
405 return m_impl->m_policy;
408 const PropertySet* getPolicySettings(const char* id) const {
409 return getSecurityPolicyProvider()->getPolicySettings(id);
412 const vector<const SecurityPolicyRule*>& getPolicyRules(const char* id) const {
413 return getSecurityPolicyProvider()->getPolicyRules(id);
416 bool setTransportOptions(SOAPTransport& transport) const {
418 vector< pair< string, pair<string,string> > >::const_iterator opt;
419 for (opt = m_impl->m_transportOptions.begin(); opt != m_impl->m_transportOptions.end(); ++opt) {
420 if (!transport.setProviderOption(opt->first.c_str(), opt->second.first.c_str(), opt->second.second.c_str())) {
421 m_log.error("failed to set SOAPTransport option (%s)", opt->second.first.c_str());
430 pair<bool,DOMElement*> background_load();
433 friend class XMLConfigImpl;
434 XMLConfigImpl* m_impl;
435 mutable ListenerService* m_listener;
436 mutable SessionCache* m_sessionCache;
438 mutable TransactionLog* m_tranLog;
439 mutable map<string,StorageService*> m_storage;
443 #if defined (_MSC_VER)
444 #pragma warning( pop )
447 static const XMLCh applicationId[] = UNICODE_LITERAL_13(a,p,p,l,i,c,a,t,i,o,n,I,d);
448 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);
449 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);
450 static const XMLCh _ArtifactMap[] = UNICODE_LITERAL_11(A,r,t,i,f,a,c,t,M,a,p);
451 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);
452 static const XMLCh _AttributeFilter[] = UNICODE_LITERAL_15(A,t,t,r,i,b,u,t,e,F,i,l,t,e,r);
453 static const XMLCh _AttributeResolver[] = UNICODE_LITERAL_17(A,t,t,r,i,b,u,t,e,R,e,s,o,l,v,e,r);
454 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);
455 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);
456 static const XMLCh _Audience[] = UNICODE_LITERAL_8(A,u,d,i,e,n,c,e);
457 static const XMLCh Binding[] = UNICODE_LITERAL_7(B,i,n,d,i,n,g);
458 static const XMLCh Channel[]= UNICODE_LITERAL_7(C,h,a,n,n,e,l);
459 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);
460 static const XMLCh _default[] = UNICODE_LITERAL_7(d,e,f,a,u,l,t);
461 static const XMLCh _Extensions[] = UNICODE_LITERAL_10(E,x,t,e,n,s,i,o,n,s);
462 static const XMLCh _fatal[] = UNICODE_LITERAL_5(f,a,t,a,l);
463 static const XMLCh _Handler[] = UNICODE_LITERAL_7(H,a,n,d,l,e,r);
464 static const XMLCh _id[] = UNICODE_LITERAL_2(i,d);
465 static const XMLCh _index[] = UNICODE_LITERAL_5(i,n,d,e,x);
466 static const XMLCh InProcess[] = UNICODE_LITERAL_9(I,n,P,r,o,c,e,s,s);
467 static const XMLCh Library[] = UNICODE_LITERAL_7(L,i,b,r,a,r,y);
468 static const XMLCh Listener[] = UNICODE_LITERAL_8(L,i,s,t,e,n,e,r);
469 static const XMLCh Location[] = UNICODE_LITERAL_8(L,o,c,a,t,i,o,n);
470 static const XMLCh logger[] = UNICODE_LITERAL_6(l,o,g,g,e,r);
471 static const XMLCh Logout[] = UNICODE_LITERAL_6(L,o,g,o,u,t);
472 static const XMLCh _LogoutInitiator[] = UNICODE_LITERAL_15(L,o,g,o,u,t,I,n,i,t,i,a,t,o,r);
473 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);
474 static const XMLCh _MetadataProvider[] = UNICODE_LITERAL_16(M,e,t,a,d,a,t,a,P,r,o,v,i,d,e,r);
475 static const XMLCh NameIDMgmt[] = UNICODE_LITERAL_10(N,a,m,e,I,D,M,g,m,t);
476 static const XMLCh Notify[] = UNICODE_LITERAL_6(N,o,t,i,f,y);
477 static const XMLCh _option[] = UNICODE_LITERAL_6(o,p,t,i,o,n);
478 static const XMLCh OutOfProcess[] = UNICODE_LITERAL_12(O,u,t,O,f,P,r,o,c,e,s,s);
479 static const XMLCh _path[] = UNICODE_LITERAL_4(p,a,t,h);
480 static const XMLCh _ProtocolProvider[] = UNICODE_LITERAL_16(P,r,o,t,o,c,o,l,P,r,o,v,i,d,e,r);
481 static const XMLCh _provider[] = UNICODE_LITERAL_8(p,r,o,v,i,d,e,r);
482 static const XMLCh RelyingParty[] = UNICODE_LITERAL_12(R,e,l,y,i,n,g,P,a,r,t,y);
483 static const XMLCh _ReplayCache[] = UNICODE_LITERAL_11(R,e,p,l,a,y,C,a,c,h,e);
484 static const XMLCh _RequestMapper[] = UNICODE_LITERAL_13(R,e,q,u,e,s,t,M,a,p,p,e,r);
485 static const XMLCh RequestMap[] = UNICODE_LITERAL_10(R,e,q,u,e,s,t,M,a,p);
486 static const XMLCh SecurityPolicies[] = UNICODE_LITERAL_16(S,e,c,u,r,i,t,y,P,o,l,i,c,i,e,s);
487 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);
488 static const XMLCh _SessionCache[] = UNICODE_LITERAL_12(S,e,s,s,i,o,n,C,a,c,h,e);
489 static const XMLCh _SessionInitiator[] = UNICODE_LITERAL_16(S,e,s,s,i,o,n,I,n,i,t,i,a,t,o,r);
490 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);
491 static const XMLCh Site[] = UNICODE_LITERAL_4(S,i,t,e);
492 static const XMLCh SSO[] = UNICODE_LITERAL_3(S,S,O);
493 static const XMLCh _StorageService[] = UNICODE_LITERAL_14(S,t,o,r,a,g,e,S,e,r,v,i,c,e);
494 static const XMLCh TCPListener[] = UNICODE_LITERAL_11(T,C,P,L,i,s,t,e,n,e,r);
495 static const XMLCh TransportOption[] = UNICODE_LITERAL_15(T,r,a,n,s,p,o,r,t,O,p,t,i,o,n);
496 static const XMLCh _TrustEngine[] = UNICODE_LITERAL_11(T,r,u,s,t,E,n,g,i,n,e);
497 static const XMLCh _type[] = UNICODE_LITERAL_4(t,y,p,e);
498 static const XMLCh UnixListener[] = UNICODE_LITERAL_12(U,n,i,x,L,i,s,t,e,n,e,r);
502 ServiceProvider* XMLServiceProviderFactory(const DOMElement* const & e)
504 return new XMLConfig(e);
508 XMLApplication::XMLApplication(
509 const ServiceProvider* sp,
510 const ProtocolProvider* pp,
512 const XMLApplication* base
513 ) : Application(sp), m_base(base),
515 m_metadata(nullptr), m_trust(nullptr),
516 m_attrExtractor(nullptr), m_attrFilter(nullptr), m_attrResolver(nullptr),
517 m_credResolver(nullptr),
519 m_acsDefault(nullptr), m_sessionInitDefault(nullptr), m_artifactResolutionDefault(nullptr)
522 xmltooling::NDC ndc("XMLApplication");
524 Category& log=Category::getInstance(SHIBSP_LOGCAT".Application");
527 // First load any property sets.
528 load(e,nullptr,this);
532 SPConfig& conf=SPConfig::getConfig();
534 SAMLConfig& samlConf=SAMLConfig::getConfig();
535 XMLToolingConfig& xmlConf=XMLToolingConfig::getConfig();
538 // This used to be an actual hash, but now it's just a hex-encode to avoid xmlsec dependency.
539 static char DIGITS[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
540 string tohash=getId();
541 tohash+=getString("entityID").second;
542 for (const char* ch = tohash.c_str(); *ch; ++ch) {
543 m_hash += (DIGITS[((unsigned char)(0xF0 & *ch)) >> 4 ]);
544 m_hash += (DIGITS[0x0F & *ch]);
549 if (conf.isEnabled(SPConfig::Handlers))
550 doHandlers(pp, e, log);
553 DOMNodeList* nlist = e->getElementsByTagNameNS(shibspconstants::SHIB2SPCONFIG_NS, Notify);
554 for (XMLSize_t i = 0; nlist && i < nlist->getLength(); ++i) {
555 if (nlist->item(i)->getParentNode()->isSameNode(e)) {
556 const XMLCh* channel = static_cast<DOMElement*>(nlist->item(i))->getAttributeNS(nullptr, Channel);
557 string loc(XMLHelper::getAttrString(static_cast<DOMElement*>(nlist->item(i)), nullptr, Location));
559 if (channel && *channel == chLatin_f)
560 m_frontLogout.push_back(loc);
562 m_backLogout.push_back(loc);
568 nlist = e->getElementsByTagNameNS(samlconstants::SAML20_NS, Audience::LOCAL_NAME);
569 if (nlist && nlist->getLength()) {
570 log.warn("use of <saml:Audience> elements outside of a Security Policy Rule is deprecated");
571 for (XMLSize_t i = 0; i < nlist->getLength(); ++i)
572 if (nlist->item(i)->getParentNode()->isSameNode(e) && nlist->item(i)->hasChildNodes())
573 m_audiences.push_back(nlist->item(i)->getFirstChild()->getNodeValue());
576 const DOMElement* child;
578 if (conf.isEnabled(SPConfig::Metadata)) {
579 child = XMLHelper::getFirstChildElement(e, _MetadataProvider);
581 string t(XMLHelper::getAttrString(child, nullptr, _type));
584 log.info("building MetadataProvider of type %s...", t.c_str());
585 auto_ptr<MetadataProvider> mp(samlConf.MetadataProviderManager.newPlugin(t.c_str(), child));
587 m_metadata = mp.release();
590 throw ConfigurationException("MetadataProvider element had no type attribute.");
593 catch (exception& ex) {
594 log.crit("error building/initializing MetadataProvider: %s", ex.what());
599 if (conf.isEnabled(SPConfig::Trust)) {
600 child = XMLHelper::getFirstChildElement(e, _TrustEngine);
602 string t(XMLHelper::getAttrString(child, nullptr, _type));
605 log.info("building TrustEngine of type %s...", t.c_str());
606 m_trust = xmlConf.TrustEngineManager.newPlugin(t.c_str(), child);
609 throw ConfigurationException("TrustEngine element had no type attribute.");
612 catch (exception& ex) {
613 log.crit("error building TrustEngine: %s", ex.what());
618 "no TrustEngine specified, using default chain {%s, %s}",
619 EXPLICIT_KEY_TRUSTENGINE, SHIBBOLETH_PKIX_TRUSTENGINE
621 m_trust = xmlConf.TrustEngineManager.newPlugin(CHAINING_TRUSTENGINE, nullptr);
622 ChainingTrustEngine* trustchain = dynamic_cast<ChainingTrustEngine*>(m_trust);
624 trustchain->addTrustEngine(xmlConf.TrustEngineManager.newPlugin(EXPLICIT_KEY_TRUSTENGINE, nullptr));
625 trustchain->addTrustEngine(xmlConf.TrustEngineManager.newPlugin(SHIBBOLETH_PKIX_TRUSTENGINE, nullptr));
630 if (conf.isEnabled(SPConfig::AttributeResolution))
631 doAttributePlugins(e, log);
633 if (conf.isEnabled(SPConfig::Credentials)) {
634 child = XMLHelper::getFirstChildElement(e,_CredentialResolver);
636 auto_ptr_char type(child->getAttributeNS(nullptr,_type));
637 log.info("building CredentialResolver of type %s...",type.get());
639 m_credResolver = xmlConf.CredentialResolverManager.newPlugin(type.get(),child);
641 catch (exception& ex) {
642 log.crit("error building CredentialResolver: %s", ex.what());
647 // Finally, load relying parties.
648 child = XMLHelper::getFirstChildElement(e,RelyingParty);
650 auto_ptr<DOMPropertySet> rp(new DOMPropertySet());
651 rp->load(child,nullptr,this);
653 m_partyMap[child->getAttributeNS(nullptr,saml2::Attribute::NAME_ATTRIB_NAME)]=rp.release();
654 child = XMLHelper::getNextSiblingElement(child,RelyingParty);
658 // Out of process only, we register a listener endpoint.
659 if (!conf.isEnabled(SPConfig::InProcess)) {
660 ListenerService* listener = sp->getListenerService(false);
662 string addr=string(getId()) + "::getHeaders::Application";
663 listener->regListener(addr.c_str(),this);
666 log.info("no ListenerService available, Application remoting disabled");
682 void XMLApplication::doAttributeInfo()
684 // Populate prefix pair.
685 m_attributePrefix.second = "HTTP_";
686 pair<bool,const char*> prefix = getString("attributePrefix");
688 m_attributePrefix.first = prefix.second;
689 const char* pch = prefix.second;
691 m_attributePrefix.second += (isalnum(*pch) ? toupper(*pch) : '_');
696 // Load attribute ID lists for REMOTE_USER and header clearing.
697 if (SPConfig::getConfig().isEnabled(SPConfig::InProcess)) {
698 pair<bool,const char*> attributes = getString("REMOTE_USER");
699 if (attributes.first) {
700 char* dup = strdup(attributes.second);
703 while (start && *start) {
704 while (*start && isspace(*start))
708 pos = strchr(start,' ');
711 m_remoteUsers.push_back(start);
712 start = pos ? pos+1 : nullptr;
717 attributes = getString("unsetHeaders");
718 if (attributes.first) {
719 string transformedprefix(m_attributePrefix.second);
721 prefix = getString("metadataAttributePrefix");
725 transformedprefix += (isalnum(*pch) ? toupper(*pch) : '_');
729 char* dup = strdup(attributes.second);
732 while (start && *start) {
733 while (*start && isspace(*start))
737 pos = strchr(start,' ');
744 transformed += (isalnum(*pch) ? toupper(*pch) : '_');
748 m_unsetHeaders.push_back(pair<string,string>(m_attributePrefix.first + start, m_attributePrefix.second + transformed));
750 m_unsetHeaders.push_back(pair<string,string>(m_attributePrefix.first + prefix.second + start, transformedprefix + transformed));
751 start = pos ? pos+1 : nullptr;
754 m_unsetHeaders.push_back(pair<string,string>(m_attributePrefix.first + "Shib-Application-ID", m_attributePrefix.second + "SHIB_APPLICATION_ID"));
759 void XMLApplication::doHandlers(const ProtocolProvider* pp, const DOMElement* e, Category& log)
761 SPConfig& conf = SPConfig::getConfig();
763 Handler* handler = nullptr;
764 const PropertySet* sessions = getPropertySet("Sessions");
766 // Process assertion export handler.
767 pair<bool,const char*> location = sessions ? sessions->getString("exportLocation") : pair<bool,const char*>(false,nullptr);
768 if (location.first) {
770 DOMElement* exportElement = e->getOwnerDocument()->createElementNS(shibspconstants::SHIB2SPCONFIG_NS, _Handler);
771 exportElement->setAttributeNS(nullptr,Location,sessions->getXMLString("exportLocation").second);
772 pair<bool,const XMLCh*> exportACL = sessions->getXMLString("exportACL");
773 if (exportACL.first) {
774 static const XMLCh _acl[] = UNICODE_LITERAL_9(e,x,p,o,r,t,A,C,L);
775 exportElement->setAttributeNS(nullptr,_acl,exportACL.second);
777 handler = conf.HandlerManager.newPlugin(
778 samlconstants::SAML20_BINDING_URI, pair<const DOMElement*,const char*>(exportElement, getId())
780 m_handlers.push_back(handler);
782 // Insert into location map. If it contains the handlerURL, we skip past that part.
783 const char* pch = strstr(location.second, sessions->getString("handlerURL").second);
785 location.second = pch + strlen(sessions->getString("handlerURL").second);
786 if (*location.second == '/')
787 m_handlerMap[location.second]=handler;
789 m_handlerMap[string("/") + location.second]=handler;
791 catch (exception& ex) {
792 log.error("caught exception installing assertion lookup handler: %s", ex.what());
796 // Look for "shorthand" elements first.
797 set<string> protocols;
798 DOMElement* child = sessions ? XMLHelper::getFirstChildElement(sessions->getElement()) : nullptr;
800 if (XMLHelper::isNodeNamed(child, shibspconstants::SHIB2SPCONFIG_NS, SSO)) {
802 doSSO(*pp, protocols, child, log);
804 log.error("no ProtocolProvider, SSO auto-configure unsupported");
806 else if (XMLHelper::isNodeNamed(child, shibspconstants::SHIB2SPCONFIG_NS, Logout)) {
808 doLogout(*pp, protocols, child, log);
810 log.error("no ProtocolProvider, Logout auto-configure unsupported");
812 else if (XMLHelper::isNodeNamed(child, shibspconstants::SHIB2SPCONFIG_NS, NameIDMgmt)) {
814 doNameIDMgmt(*pp, protocols, child, log);
816 log.error("no ProtocolProvider, NameIDMgmt auto-configure unsupported");
819 break; // drop into next while loop
821 child = XMLHelper::getNextSiblingElement(child);
824 // Process other handlers.
825 bool hardACS=false, hardSessionInit=false, hardArt=false;
827 if (!child->hasAttributeNS(nullptr, Location)) {
828 auto_ptr_char hclass(child->getLocalName());
829 log.error("%s handler with no Location property cannot be processed", hclass.get());
830 child = XMLHelper::getNextSiblingElement(child);
834 if (XMLString::equals(child->getLocalName(), _AssertionConsumerService)) {
835 string bindprop(XMLHelper::getAttrString(child, nullptr, Binding));
836 if (bindprop.empty()) {
837 log.error("AssertionConsumerService element has no Binding attribute, skipping it...");
838 child = XMLHelper::getNextSiblingElement(child);
841 handler = conf.AssertionConsumerServiceManager.newPlugin(bindprop.c_str(), make_pair(child, getId()));
842 // Map by binding and protocol (may be > 1 per protocol and binding)
843 m_acsBindingMap[handler->getXMLString("Binding").second].push_back(handler);
844 const XMLCh* protfamily = handler->getProtocolFamily();
846 m_acsProtocolMap[protfamily].push_back(handler);
847 m_acsIndexMap[handler->getUnsignedInt("index").second] = handler;
850 pair<bool,bool> defprop = handler->getBool("isDefault");
852 if (defprop.second) {
854 m_acsDefault = handler;
857 else if (!m_acsDefault)
858 m_acsDefault = handler;
861 else if (XMLString::equals(child->getLocalName(), _SessionInitiator)) {
862 string t(XMLHelper::getAttrString(child, nullptr, _type));
864 log.error("SessionInitiator element has no type attribute, skipping it...");
865 child = XMLHelper::getNextSiblingElement(child);
868 SessionInitiator* sihandler = conf.SessionInitiatorManager.newPlugin(t.c_str(), make_pair(child, getId()));
870 pair<bool,const char*> si_id = handler->getString("id");
871 if (si_id.first && si_id.second)
872 m_sessionInitMap[si_id.second] = sihandler;
873 if (!hardSessionInit) {
874 pair<bool,bool> defprop = handler->getBool("isDefault");
876 if (defprop.second) {
877 hardSessionInit = true;
878 m_sessionInitDefault = sihandler;
881 else if (!m_sessionInitDefault) {
882 m_sessionInitDefault = sihandler;
886 else if (XMLString::equals(child->getLocalName(), _LogoutInitiator)) {
887 string t(XMLHelper::getAttrString(child, nullptr, _type));
889 log.error("LogoutInitiator element has no type attribute, skipping it...");
890 child = XMLHelper::getNextSiblingElement(child);
893 handler = conf.LogoutInitiatorManager.newPlugin(t.c_str(), make_pair(child, getId()));
895 else if (XMLString::equals(child->getLocalName(), _ArtifactResolutionService)) {
896 string bindprop(XMLHelper::getAttrString(child, nullptr, Binding));
897 if (bindprop.empty()) {
898 log.error("ArtifactResolutionService element has no Binding attribute, skipping it...");
899 child = XMLHelper::getNextSiblingElement(child);
902 handler = conf.ArtifactResolutionServiceManager.newPlugin(bindprop.c_str(), make_pair(child, getId()));
905 pair<bool,bool> defprop = handler->getBool("isDefault");
907 if (defprop.second) {
909 m_artifactResolutionDefault = handler;
912 else if (!m_artifactResolutionDefault)
913 m_artifactResolutionDefault = handler;
916 else if (XMLString::equals(child->getLocalName(), _SingleLogoutService)) {
917 string bindprop(XMLHelper::getAttrString(child, nullptr, Binding));
918 if (bindprop.empty()) {
919 log.error("SingleLogoutService element has no Binding attribute, skipping it...");
920 child = XMLHelper::getNextSiblingElement(child);
923 handler = conf.SingleLogoutServiceManager.newPlugin(bindprop.c_str(), make_pair(child, getId()));
925 else if (XMLString::equals(child->getLocalName(), _ManageNameIDService)) {
926 string bindprop(XMLHelper::getAttrString(child, nullptr, Binding));
927 if (bindprop.empty()) {
928 log.error("ManageNameIDService element has no Binding attribute, skipping it...");
929 child = XMLHelper::getNextSiblingElement(child);
932 handler = conf.ManageNameIDServiceManager.newPlugin(bindprop.c_str(), make_pair(child, getId()));
935 string t(XMLHelper::getAttrString(child, nullptr, _type));
937 log.error("Handler element has no type attribute, skipping it...");
938 child = XMLHelper::getNextSiblingElement(child);
941 handler = conf.HandlerManager.newPlugin(t.c_str(), make_pair(child, getId()));
944 m_handlers.push_back(handler);
946 // Insert into location map.
947 location = handler->getString("Location");
948 if (location.first && *location.second == '/')
949 m_handlerMap[location.second] = handler;
950 else if (location.first)
951 m_handlerMap[string("/") + location.second] = handler;
953 catch (exception& ex) {
954 log.error("caught exception processing handler element: %s", ex.what());
957 child = XMLHelper::getNextSiblingElement(child);
961 void XMLApplication::doSSO(const ProtocolProvider& pp, set<string>& protocols, DOMElement* e, Category& log)
963 if (!e->hasChildNodes())
966 SPConfig& conf = SPConfig::getConfig();
968 // Tokenize the protocol list inside the element.
969 const XMLCh* protlist = e->getFirstChild()->getNodeValue();
970 XMLStringTokenizer prottokens(protlist);
971 while (prottokens.hasMoreTokens()) {
972 auto_ptr_char prot(prottokens.nextToken());
974 // Look for initiator.
975 const PropertySet* initiator = pp.getInitiator(prot.get(), "SSO");
977 log.info("auto-configuring SSO initiation for protocol (%s)", prot.get());
978 pair<bool,const XMLCh*> inittype = initiator->getXMLString("id");
979 if (inittype.first) {
980 // Append a session initiator element of the designated type to the root element.
981 DOMElement* sidom = e->getOwnerDocument()->createElementNS(shibspconstants::SHIB2SPCONFIG_NS, _SessionInitiator);
982 sidom->setAttributeNS(nullptr, _type, inittype.second);
983 e->appendChild(sidom);
984 log.info("adding SessionInitiator of type (%s) to chain (/Login)", initiator->getString("id").second);
986 doArtifactResolution(pp, prot.get(), e, log);
987 protocols.insert(prot.get());
990 log.error("missing id property on Initiator element, check config for protocol (%s)", prot.get());
994 // Look for incoming bindings.
995 const vector<const PropertySet*>& bindings = pp.getBindings(prot.get(), "SSO");
996 if (!bindings.empty()) {
997 log.info("auto-configuring SSO endpoints for protocol (%s)", prot.get());
999 pair<bool,const XMLCh*> idprop,pathprop;
1000 for (vector<const PropertySet*>::const_iterator b = bindings.begin(); b != bindings.end(); ++b, ++index) {
1001 idprop = (*b)->getXMLString("id");
1002 pathprop = (*b)->getXMLString("path");
1003 if (idprop.first && pathprop.first) {
1004 DOMElement* acsdom = e->getOwnerDocument()->createElementNS(samlconstants::SAML20MD_NS, _AssertionConsumerService);
1005 acsdom->setAttributeNS(nullptr, Binding, idprop.second);
1006 acsdom->setAttributeNS(nullptr, Location, pathprop.second);
1007 xstring indexbuf(chDigit_1 + (index % 10), 1);
1009 indexbuf = (XMLCh)(chDigit_1 + (index / 10)) + indexbuf;
1010 acsdom->setAttributeNS(nullptr, _index, indexbuf.c_str());
1012 log.info("adding AssertionConsumerService for Binding (%s) at (%s)", (*b)->getString("id").second, (*b)->getString("path").second);
1013 Handler* handler = conf.AssertionConsumerServiceManager.newPlugin((*b)->getString("id").second, make_pair(acsdom, getId()));
1014 m_handlers.push_back(handler);
1016 // Setup maps and defaults.
1017 m_acsBindingMap[handler->getXMLString("Binding").second].push_back(handler);
1018 const XMLCh* protfamily = handler->getProtocolFamily();
1020 m_acsProtocolMap[protfamily].push_back(handler);
1021 m_acsIndexMap[handler->getUnsignedInt("index").second] = handler;
1023 m_acsDefault = handler;
1025 // Insert into location map.
1026 pair<bool,const char*> location = handler->getString("Location");
1027 if (location.first && *location.second == '/')
1028 m_handlerMap[location.second] = handler;
1029 else if (location.first)
1030 m_handlerMap[string("/") + location.second] = handler;
1033 log.error("missing id or path property on Binding element, check config for protocol (%s)", prot.get());
1038 if (!initiator && bindings.empty()) {
1039 log.error("no SSO Initiator or Binding config for protocol (%s)", prot.get());
1043 // Handle discovery.
1044 static const XMLCh discoveryProtocol[] = UNICODE_LITERAL_17(d,i,s,c,o,v,e,r,y,P,r,o,t,o,c,o,l);
1045 static const XMLCh discoveryURL[] = UNICODE_LITERAL_12(d,i,s,c,o,v,e,r,y,U,R,L);
1046 static const XMLCh _URL[] = UNICODE_LITERAL_3(U,R,L);
1047 const XMLCh* discop = e->getAttributeNS(nullptr, discoveryProtocol);
1048 if (discop && *discop) {
1049 const XMLCh* discou = e->getAttributeNS(nullptr, discoveryURL);
1050 if (discou && *discou) {
1051 // Append a session initiator element of the designated type to the root element.
1052 DOMElement* sidom = e->getOwnerDocument()->createElementNS(shibspconstants::SHIB2SPCONFIG_NS, _SessionInitiator);
1053 sidom->setAttributeNS(nullptr, _type, discop);
1054 sidom->setAttributeNS(nullptr, _URL, discou);
1055 e->appendChild(sidom);
1056 if (log.isInfoEnabled()) {
1057 auto_ptr_char dp(discop);
1058 log.info("adding SessionInitiator of type (%s) to chain (/Login)", dp.get());
1062 log.error("SSO discoveryProtocol specified without discoveryURL");
1066 // Attach default Location to SSO element.
1067 static const XMLCh _loc[] = { chForwardSlash, chLatin_L, chLatin_o, chLatin_g, chLatin_i, chLatin_n, chNull };
1068 e->setAttributeNS(nullptr, Location, _loc);
1070 // Instantiate Chaining initiator around the SSO element.
1071 SessionInitiator* chain = conf.SessionInitiatorManager.newPlugin(CHAINING_SESSION_INITIATOR, make_pair(e, getId()));
1072 m_handlers.push_back(chain);
1073 m_sessionInitDefault = chain;
1074 m_handlerMap["/Login"] = chain;
1077 void XMLApplication::doLogout(const ProtocolProvider& pp, set<string>& protocols, DOMElement* e, Category& log)
1079 if (!e->hasChildNodes())
1082 SPConfig& conf = SPConfig::getConfig();
1084 // Tokenize the protocol list inside the element.
1085 const XMLCh* protlist = e->getFirstChild()->getNodeValue();
1086 XMLStringTokenizer prottokens(protlist);
1087 while (prottokens.hasMoreTokens()) {
1088 auto_ptr_char prot(prottokens.nextToken());
1090 // Look for initiator.
1091 const PropertySet* initiator = pp.getInitiator(prot.get(), "Logout");
1093 log.info("auto-configuring Logout initiation for protocol (%s)", prot.get());
1094 pair<bool,const XMLCh*> inittype = initiator->getXMLString("id");
1095 if (inittype.first) {
1096 // Append a logout initiator element of the designated type to the root element.
1097 DOMElement* lidom = e->getOwnerDocument()->createElementNS(shibspconstants::SHIB2SPCONFIG_NS, _LogoutInitiator);
1098 lidom->setAttributeNS(nullptr, _type, inittype.second);
1099 e->appendChild(lidom);
1100 log.info("adding LogoutInitiator of type (%s) to chain (/Logout)", initiator->getString("id").second);
1102 if (protocols.count(prot.get()) == 0) {
1103 doArtifactResolution(pp, prot.get(), e, log);
1104 protocols.insert(prot.get());
1108 log.error("missing id property on Initiator element, check config for protocol (%s)", prot.get());
1112 // Look for incoming bindings.
1113 const vector<const PropertySet*>& bindings = pp.getBindings(prot.get(), "Logout");
1114 if (!bindings.empty()) {
1115 log.info("auto-configuring Logout endpoints for protocol (%s)", prot.get());
1116 pair<bool,const XMLCh*> idprop,pathprop;
1117 for (vector<const PropertySet*>::const_iterator b = bindings.begin(); b != bindings.end(); ++b) {
1118 idprop = (*b)->getXMLString("id");
1119 pathprop = (*b)->getXMLString("path");
1120 if (idprop.first && pathprop.first) {
1121 DOMElement* slodom = e->getOwnerDocument()->createElementNS(samlconstants::SAML20MD_NS, _SingleLogoutService);
1122 slodom->setAttributeNS(nullptr, Binding, idprop.second);
1123 slodom->setAttributeNS(nullptr, Location, pathprop.second);
1125 log.info("adding SingleLogoutService for Binding (%s) at (%s)", (*b)->getString("id").second, (*b)->getString("path").second);
1126 Handler* handler = conf.SingleLogoutServiceManager.newPlugin((*b)->getString("id").second, make_pair(slodom, getId()));
1127 m_handlers.push_back(handler);
1129 // Insert into location map.
1130 pair<bool,const char*> location = handler->getString("Location");
1131 if (location.first && *location.second == '/')
1132 m_handlerMap[location.second] = handler;
1133 else if (location.first)
1134 m_handlerMap[string("/") + location.second] = handler;
1137 log.error("missing id or path property on Binding element, check config for protocol (%s)", prot.get());
1141 if (protocols.count(prot.get()) == 0) {
1142 doArtifactResolution(pp, prot.get(), e, log);
1143 protocols.insert(prot.get());
1147 if (!initiator && bindings.empty()) {
1148 log.error("no Logout Initiator or Binding config for protocol (%s)", prot.get());
1152 // Attach default Location to Logout element.
1153 static const XMLCh _loc[] = { chForwardSlash, chLatin_L, chLatin_o, chLatin_g, chLatin_o, chLatin_u, chLatin_t, chNull };
1154 e->setAttributeNS(nullptr, Location, _loc);
1156 // Instantiate Chaining initiator around the SSO element.
1157 Handler* chain = conf.LogoutInitiatorManager.newPlugin(CHAINING_LOGOUT_INITIATOR, make_pair(e, getId()));
1158 m_handlers.push_back(chain);
1159 m_handlerMap["/Logout"] = chain;
1162 void XMLApplication::doNameIDMgmt(const ProtocolProvider& pp, set<string>& protocols, DOMElement* e, Category& log)
1164 if (!e->hasChildNodes())
1167 SPConfig& conf = SPConfig::getConfig();
1169 // Tokenize the protocol list inside the element.
1170 const XMLCh* protlist = e->getFirstChild()->getNodeValue();
1171 XMLStringTokenizer prottokens(protlist);
1172 while (prottokens.hasMoreTokens()) {
1173 auto_ptr_char prot(prottokens.nextToken());
1175 // Look for incoming bindings.
1176 const vector<const PropertySet*>& bindings = pp.getBindings(prot.get(), "NameIDMgmt");
1177 if (!bindings.empty()) {
1178 log.info("auto-configuring NameIDMgmt endpoints for protocol (%s)", prot.get());
1179 pair<bool,const XMLCh*> idprop,pathprop;
1180 for (vector<const PropertySet*>::const_iterator b = bindings.begin(); b != bindings.end(); ++b) {
1181 idprop = (*b)->getXMLString("id");
1182 pathprop = (*b)->getXMLString("path");
1183 if (idprop.first && pathprop.first) {
1184 DOMElement* nimdom = e->getOwnerDocument()->createElementNS(samlconstants::SAML20MD_NS, _ManageNameIDService);
1185 nimdom->setAttributeNS(nullptr, Binding, idprop.second);
1186 nimdom->setAttributeNS(nullptr, Location, pathprop.second);
1188 log.info("adding ManageNameIDService for Binding (%s) at (%s)", (*b)->getString("id").second, (*b)->getString("path").second);
1189 Handler* handler = conf.ManageNameIDServiceManager.newPlugin((*b)->getString("id").second, make_pair(nimdom, getId()));
1190 m_handlers.push_back(handler);
1192 // Insert into location map.
1193 pair<bool,const char*> location = handler->getString("Location");
1194 if (location.first && *location.second == '/')
1195 m_handlerMap[location.second] = handler;
1196 else if (location.first)
1197 m_handlerMap[string("/") + location.second] = handler;
1200 log.error("missing id or path property on Binding element, check config for protocol (%s)", prot.get());
1204 if (protocols.count(prot.get()) == 0) {
1205 doArtifactResolution(pp, prot.get(), e, log);
1206 protocols.insert(prot.get());
1210 log.error("no NameIDMgmt Binding config for protocol (%s)", prot.get());
1215 void XMLApplication::doArtifactResolution(const ProtocolProvider& pp, const char* protocol, DOMElement* e, Category& log)
1217 SPConfig& conf = SPConfig::getConfig();
1219 // Look for incoming bindings.
1220 const vector<const PropertySet*>& bindings = pp.getBindings(protocol, "ArtifactResolution");
1221 if (!bindings.empty()) {
1222 log.info("auto-configuring ArtifactResolution endpoints for protocol (%s)", protocol);
1224 pair<bool,const XMLCh*> idprop,pathprop;
1225 for (vector<const PropertySet*>::const_iterator b = bindings.begin(); b != bindings.end(); ++b) {
1226 idprop = (*b)->getXMLString("id");
1227 pathprop = (*b)->getXMLString("path");
1228 if (idprop.first && pathprop.first) {
1229 DOMElement* artdom = e->getOwnerDocument()->createElementNS(samlconstants::SAML20MD_NS, _ArtifactResolutionService);
1230 artdom->setAttributeNS(nullptr, Binding, idprop.second);
1231 artdom->setAttributeNS(nullptr, Location, pathprop.second);
1232 xstring indexbuf(chDigit_1 + (index % 10), 1);
1234 indexbuf = (XMLCh)(chDigit_1 + (index / 10)) + indexbuf;
1235 artdom->setAttributeNS(nullptr, _index, indexbuf.c_str());
1237 log.info("adding ArtifactResolutionService for Binding (%s) at (%s)", (*b)->getString("id").second, (*b)->getString("path").second);
1238 Handler* handler = conf.ArtifactResolutionServiceManager.newPlugin((*b)->getString("id").second, make_pair(artdom, getId()));
1239 m_handlers.push_back(handler);
1241 if (!m_artifactResolutionDefault)
1242 m_artifactResolutionDefault = handler;
1244 // Insert into location map.
1245 pair<bool,const char*> location = handler->getString("Location");
1246 if (location.first && *location.second == '/')
1247 m_handlerMap[location.second] = handler;
1248 else if (location.first)
1249 m_handlerMap[string("/") + location.second] = handler;
1252 log.error("missing id or path property on Binding element, check config for protocol (%s)", protocol);
1259 void XMLApplication::doAttributePlugins(const DOMElement* e, Category& log)
1261 SPConfig& conf = SPConfig::getConfig();
1263 DOMElement* child = XMLHelper::getFirstChildElement(e, _AttributeExtractor);
1265 string t(XMLHelper::getAttrString(child, nullptr, _type));
1268 log.info("building AttributeExtractor of type %s...", t.c_str());
1269 m_attrExtractor = conf.AttributeExtractorManager.newPlugin(t.c_str(), child);
1272 throw ConfigurationException("AttributeExtractor element had no type attribute.");
1275 catch (exception& ex) {
1276 log.crit("error building AttributeExtractor: %s", ex.what());
1280 child = XMLHelper::getFirstChildElement(e, _AttributeFilter);
1282 string t(XMLHelper::getAttrString(child, nullptr, _type));
1285 log.info("building AttributeFilter of type %s...", t.c_str());
1286 m_attrFilter = conf.AttributeFilterManager.newPlugin(t.c_str(), child);
1289 throw ConfigurationException("AttributeFilter element had no type attribute.");
1292 catch (exception& ex) {
1293 log.crit("error building AttributeFilter: %s", ex.what());
1297 child = XMLHelper::getFirstChildElement(e, _AttributeResolver);
1299 string t(XMLHelper::getAttrString(child, nullptr, _type));
1302 log.info("building AttributeResolver of type %s...", t.c_str());
1303 m_attrResolver = conf.AttributeResolverManager.newPlugin(t.c_str(), child);
1306 throw ConfigurationException("AttributeResolver element had no type attribute.");
1309 catch (exception& ex) {
1310 log.crit("error building AttributeResolver: %s", ex.what());
1314 if (m_unsetHeaders.empty()) {
1315 vector<string> unsetHeaders;
1316 if (m_attrExtractor) {
1317 Locker extlock(m_attrExtractor);
1318 m_attrExtractor->getAttributeIds(unsetHeaders);
1320 else if (m_base && m_base->m_attrExtractor) {
1321 Locker extlock(m_base->m_attrExtractor);
1322 m_base->m_attrExtractor->getAttributeIds(unsetHeaders);
1324 if (m_attrResolver) {
1325 Locker reslock(m_attrResolver);
1326 m_attrResolver->getAttributeIds(unsetHeaders);
1328 else if (m_base && m_base->m_attrResolver) {
1329 Locker extlock(m_base->m_attrResolver);
1330 m_base->m_attrResolver->getAttributeIds(unsetHeaders);
1332 if (!unsetHeaders.empty()) {
1333 string transformedprefix(m_attributePrefix.second);
1335 pair<bool,const char*> prefix = getString("metadataAttributePrefix");
1337 pch = prefix.second;
1339 transformedprefix += (isalnum(*pch) ? toupper(*pch) : '_');
1343 for (vector<string>::const_iterator hdr = unsetHeaders.begin(); hdr!=unsetHeaders.end(); ++hdr) {
1347 transformed += (isalnum(*pch) ? toupper(*pch) : '_');
1350 m_unsetHeaders.push_back(pair<string,string>(m_attributePrefix.first + *hdr, m_attributePrefix.second + transformed));
1352 m_unsetHeaders.push_back(pair<string,string>(m_attributePrefix.first + prefix.second + *hdr, transformedprefix + transformed));
1355 m_unsetHeaders.push_back(pair<string,string>(m_attributePrefix.first + "Shib-Application-ID", m_attributePrefix.second + "SHIB_APPLICATION_ID"));
1360 void XMLApplication::cleanup()
1362 ListenerService* listener=getServiceProvider().getListenerService(false);
1363 if (listener && SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess) && !SPConfig::getConfig().isEnabled(SPConfig::InProcess)) {
1364 string addr=string(getId()) + "::getHeaders::Application";
1365 listener->unregListener(addr.c_str(),this);
1367 for_each(m_handlers.begin(),m_handlers.end(),xmltooling::cleanup<Handler>());
1370 for_each(m_partyMap.begin(),m_partyMap.end(),cleanup_pair<xstring,PropertySet>());
1372 delete m_credResolver;
1373 m_credResolver = nullptr;
1374 delete m_attrResolver;
1375 m_attrResolver = nullptr;
1376 delete m_attrFilter;
1377 m_attrFilter = nullptr;
1378 delete m_attrExtractor;
1379 m_attrExtractor = nullptr;
1383 m_metadata = nullptr;
1387 #ifdef SHIBSP_XERCESC_SHORT_ACCEPTNODE
1390 DOMNodeFilter::FilterAction
1392 XMLApplication::acceptNode(const DOMNode* node) const
1394 const XMLCh* name=node->getLocalName();
1395 if (XMLString::equals(name,ApplicationOverride) ||
1396 XMLString::equals(name,_Audience) ||
1397 XMLString::equals(name,Notify) ||
1398 XMLString::equals(name,_Handler) ||
1399 XMLString::equals(name,_AssertionConsumerService) ||
1400 XMLString::equals(name,_ArtifactResolutionService) ||
1401 XMLString::equals(name,Logout) ||
1402 XMLString::equals(name,_LogoutInitiator) ||
1403 XMLString::equals(name,_ManageNameIDService) ||
1404 XMLString::equals(name,NameIDMgmt) ||
1405 XMLString::equals(name,_SessionInitiator) ||
1406 XMLString::equals(name,_SingleLogoutService) ||
1407 XMLString::equals(name,SSO) ||
1408 XMLString::equals(name,RelyingParty) ||
1409 XMLString::equals(name,_MetadataProvider) ||
1410 XMLString::equals(name,_TrustEngine) ||
1411 XMLString::equals(name,_CredentialResolver) ||
1412 XMLString::equals(name,_AttributeFilter) ||
1413 XMLString::equals(name,_AttributeExtractor) ||
1414 XMLString::equals(name,_AttributeResolver))
1415 return FILTER_REJECT;
1417 return FILTER_ACCEPT;
1422 const PropertySet* XMLApplication::getRelyingParty(const EntityDescriptor* provider) const
1427 map<xstring,PropertySet*>::const_iterator i=m_partyMap.find(provider->getEntityID());
1428 if (i!=m_partyMap.end())
1430 const EntitiesDescriptor* group=dynamic_cast<const EntitiesDescriptor*>(provider->getParent());
1432 if (group->getName()) {
1433 i=m_partyMap.find(group->getName());
1434 if (i!=m_partyMap.end())
1437 group=dynamic_cast<const EntitiesDescriptor*>(group->getParent());
1442 const PropertySet* XMLApplication::getRelyingParty(const XMLCh* entityID) const
1447 map<xstring,PropertySet*>::const_iterator i=m_partyMap.find(entityID);
1448 if (i!=m_partyMap.end())
1455 string XMLApplication::getNotificationURL(const char* resource, bool front, unsigned int index) const
1457 const vector<string>& locs = front ? m_frontLogout : m_backLogout;
1459 return m_base ? m_base->getNotificationURL(resource, front, index) : string();
1460 else if (index >= locs.size())
1463 #ifdef HAVE_STRCASECMP
1464 if (!resource || (strncasecmp(resource,"http://",7) && strncasecmp(resource,"https://",8)))
1466 if (!resource || (strnicmp(resource,"http://",7) && strnicmp(resource,"https://",8)))
1468 throw ConfigurationException("Request URL was not absolute.");
1470 const char* handler=locs[index].c_str();
1472 // Should never happen...
1473 if (!handler || (*handler!='/' && strncmp(handler,"http:",5) && strncmp(handler,"https:",6)))
1474 throw ConfigurationException(
1475 "Invalid Location property ($1) in Notify element for Application ($2)",
1476 params(2, handler ? handler : "null", getId())
1479 // The "Location" property can be in one of three formats:
1481 // 1) a full URI: http://host/foo/bar
1482 // 2) a hostless URI: http:///foo/bar
1483 // 3) a relative path: /foo/bar
1485 // # Protocol Host Path
1486 // 1 handler handler handler
1487 // 2 handler resource handler
1488 // 3 resource resource handler
1490 const char* path = nullptr;
1492 // Decide whether to use the handler or the resource for the "protocol"
1494 if (*handler != '/') {
1502 // break apart the "protocol" string into protocol, host, and "the rest"
1503 const char* colon=strchr(prot,':');
1505 const char* slash=strchr(colon,'/');
1509 // Compute the actual protocol and store.
1510 string notifyURL(prot, colon-prot);
1512 // create the "host" from either the colon/slash or from the target string
1513 // If prot == handler then we're in either #1 or #2, else #3.
1514 // If slash == colon then we're in #2.
1515 if (prot != handler || slash == colon) {
1516 colon = strchr(resource, ':');
1517 colon += 3; // Get past the ://
1518 slash = strchr(colon, '/');
1520 string host(colon, (slash ? slash-colon : strlen(colon)));
1523 notifyURL += host + path;
1527 void XMLApplication::clearHeader(SPRequest& request, const char* rawname, const char* cginame) const
1529 if (!m_attributePrefix.first.empty()) {
1530 string temp = m_attributePrefix.first + rawname;
1531 string temp2 = m_attributePrefix.second + (cginame + 5);
1532 request.clearHeader(temp.c_str(), temp2.c_str());
1535 m_base->clearHeader(request, rawname, cginame);
1538 request.clearHeader(rawname, cginame);
1542 void XMLApplication::setHeader(SPRequest& request, const char* name, const char* value) const
1544 if (!m_attributePrefix.first.empty()) {
1545 string temp = m_attributePrefix.first + name;
1546 request.setHeader(temp.c_str(), value);
1549 m_base->setHeader(request, name, value);
1552 request.setHeader(name, value);
1556 string XMLApplication::getSecureHeader(const SPRequest& request, const char* name) const
1558 if (!m_attributePrefix.first.empty()) {
1559 string temp = m_attributePrefix.first + name;
1560 return request.getSecureHeader(temp.c_str());
1563 return m_base->getSecureHeader(request,name);
1566 return request.getSecureHeader(name);
1570 const SessionInitiator* XMLApplication::getDefaultSessionInitiator() const
1572 if (m_sessionInitDefault) return m_sessionInitDefault;
1573 return m_base ? m_base->getDefaultSessionInitiator() : nullptr;
1576 const SessionInitiator* XMLApplication::getSessionInitiatorById(const char* id) const
1578 map<string,const SessionInitiator*>::const_iterator i=m_sessionInitMap.find(id);
1579 if (i!=m_sessionInitMap.end()) return i->second;
1580 return m_base ? m_base->getSessionInitiatorById(id) : nullptr;
1583 const Handler* XMLApplication::getDefaultAssertionConsumerService() const
1585 if (m_acsDefault) return m_acsDefault;
1586 return m_base ? m_base->getDefaultAssertionConsumerService() : nullptr;
1589 const Handler* XMLApplication::getAssertionConsumerServiceByIndex(unsigned short index) const
1591 map<unsigned int,const Handler*>::const_iterator i=m_acsIndexMap.find(index);
1592 if (i != m_acsIndexMap.end()) return i->second;
1593 return m_base ? m_base->getAssertionConsumerServiceByIndex(index) : nullptr;
1596 const Handler* XMLApplication::getAssertionConsumerServiceByProtocol(const XMLCh* protocol, const char* binding) const
1598 ACSProtocolMap::const_iterator i=m_acsProtocolMap.find(protocol);
1599 if (i != m_acsProtocolMap.end() && !i->second.empty()) {
1600 if (!binding || !*binding)
1601 return i->second.front();
1602 for (ACSProtocolMap::value_type::second_type::const_iterator j = i->second.begin(); j != i->second.end(); ++j) {
1603 if (!strcmp(binding, (*j)->getString("Binding").second))
1607 return m_base ? m_base->getAssertionConsumerServiceByProtocol(protocol) : nullptr;
1610 const vector<const Handler*>& XMLApplication::getAssertionConsumerServicesByBinding(const XMLCh* binding) const
1612 ACSBindingMap::const_iterator i=m_acsBindingMap.find(binding);
1613 if (i != m_acsBindingMap.end())
1615 return m_base ? m_base->getAssertionConsumerServicesByBinding(binding) : g_noHandlers;
1618 const Handler* XMLApplication::getHandler(const char* path) const
1621 wrap = wrap.substr(0,wrap.find(';'));
1622 map<string,const Handler*>::const_iterator i=m_handlerMap.find(wrap.substr(0,wrap.find('?')));
1623 if (i!=m_handlerMap.end())
1625 return m_base ? m_base->getHandler(path) : nullptr;
1628 void XMLApplication::getHandlers(vector<const Handler*>& handlers) const
1630 handlers.insert(handlers.end(), m_handlers.begin(), m_handlers.end());
1632 for (map<string,const Handler*>::const_iterator h = m_base->m_handlerMap.begin(); h != m_base->m_handlerMap.end(); ++h) {
1633 if (m_handlerMap.count(h->first) == 0)
1634 handlers.push_back(h->second);
1639 #ifdef SHIBSP_XERCESC_SHORT_ACCEPTNODE
1642 DOMNodeFilter::FilterAction
1644 XMLConfigImpl::acceptNode(const DOMNode* node) const
1646 if (!XMLString::equals(node->getNamespaceURI(),shibspconstants::SHIB2SPCONFIG_NS))
1647 return FILTER_ACCEPT;
1648 const XMLCh* name=node->getLocalName();
1649 if (XMLString::equals(name,ApplicationDefaults) ||
1650 XMLString::equals(name,_ArtifactMap) ||
1651 XMLString::equals(name,_Extensions) ||
1652 XMLString::equals(name,Listener) ||
1653 XMLString::equals(name,_ProtocolProvider) ||
1654 XMLString::equals(name,_RequestMapper) ||
1655 XMLString::equals(name,_ReplayCache) ||
1656 XMLString::equals(name,SecurityPolicies) ||
1657 XMLString::equals(name,_SecurityPolicyProvider) ||
1658 XMLString::equals(name,_SessionCache) ||
1659 XMLString::equals(name,Site) ||
1660 XMLString::equals(name,_StorageService) ||
1661 XMLString::equals(name,TCPListener) ||
1662 XMLString::equals(name,TransportOption) ||
1663 XMLString::equals(name,UnixListener))
1664 return FILTER_REJECT;
1666 return FILTER_ACCEPT;
1669 void XMLConfigImpl::doExtensions(const DOMElement* e, const char* label, Category& log)
1671 const DOMElement* exts = XMLHelper::getFirstChildElement(e, _Extensions);
1673 exts = XMLHelper::getFirstChildElement(exts, Library);
1675 string path(XMLHelper::getAttrString(exts, nullptr, _path));
1677 if (!path.empty()) {
1678 if (!XMLToolingConfig::getConfig().load_library(path.c_str(), (void*)exts))
1679 throw ConfigurationException("XMLToolingConfig::load_library failed.");
1680 log.debug("loaded %s extension library (%s)", label, path.c_str());
1683 catch (exception& e) {
1684 if (XMLHelper::getAttrBool(exts, false, _fatal)) {
1685 log.fatal("unable to load mandatory %s extension library %s: %s", label, path.c_str(), e.what());
1689 log.crit("unable to load optional %s extension library %s: %s", label, path.c_str(), e.what());
1692 exts = XMLHelper::getNextSiblingElement(exts, Library);
1697 void XMLConfigImpl::doListener(const DOMElement* e, Category& log)
1700 string plugtype(TCP_LISTENER_SERVICE);
1702 string plugtype(UNIX_LISTENER_SERVICE);
1704 DOMElement* child = XMLHelper::getFirstChildElement(e, UnixListener);
1706 plugtype = UNIX_LISTENER_SERVICE;
1708 child = XMLHelper::getFirstChildElement(e, TCPListener);
1710 plugtype = TCP_LISTENER_SERVICE;
1712 child = XMLHelper::getFirstChildElement(e, Listener);
1714 auto_ptr_char type(child->getAttributeNS(nullptr, _type));
1715 if (type.get() && *type.get())
1716 plugtype = type.get();
1721 log.info("building ListenerService of type %s...", plugtype.c_str());
1722 m_outer->m_listener = SPConfig::getConfig().ListenerServiceManager.newPlugin(plugtype.c_str(), child);
1725 void XMLConfigImpl::doCaching(const DOMElement* e, Category& log)
1727 SPConfig& conf = SPConfig::getConfig();
1729 SAMLConfig& samlConf = SAMLConfig::getConfig();
1731 XMLToolingConfig& xmlConf = XMLToolingConfig::getConfig();
1735 if (conf.isEnabled(SPConfig::OutOfProcess)) {
1736 // First build any StorageServices.
1737 child = XMLHelper::getFirstChildElement(e, _StorageService);
1739 string id(XMLHelper::getAttrString(child, nullptr, _id));
1740 string t(XMLHelper::getAttrString(child, nullptr, _type));
1743 log.info("building StorageService (%s) of type %s...", id.c_str(), t.c_str());
1744 m_outer->m_storage[id] = xmlConf.StorageServiceManager.newPlugin(t.c_str(), child);
1746 catch (exception& ex) {
1747 log.crit("failed to instantiate StorageService (%s): %s", id.c_str(), ex.what());
1750 child = XMLHelper::getNextSiblingElement(child, _StorageService);
1753 if (m_outer->m_storage.empty()) {
1754 log.info("no StorageService plugin(s) installed, using (mem) in-memory instance");
1755 m_outer->m_storage["id"] = xmlConf.StorageServiceManager.newPlugin(MEMORY_STORAGE_SERVICE, nullptr);
1759 StorageService* replaySS = nullptr;
1760 child = XMLHelper::getFirstChildElement(e, _ReplayCache);
1762 string ssid(XMLHelper::getAttrString(child, nullptr, _StorageService));
1763 if (!ssid.empty()) {
1764 if (m_outer->m_storage.count(ssid)) {
1765 log.info("building ReplayCache on top of StorageService (%s)...", ssid.c_str());
1766 replaySS = m_outer->m_storage[ssid];
1769 log.error("unable to locate StorageService (%s), using arbitrary instance for ReplayCache", ssid.c_str());
1770 replaySS = m_outer->m_storage.begin()->second;
1774 log.info("no StorageService specified for ReplayCache, using arbitrary instance");
1775 replaySS = m_outer->m_storage.begin()->second;
1779 log.info("no ReplayCache specified, using arbitrary StorageService instance");
1780 replaySS = m_outer->m_storage.begin()->second;
1782 xmlConf.setReplayCache(new ReplayCache(replaySS));
1785 child = XMLHelper::getFirstChildElement(e, _ArtifactMap);
1787 string ssid(XMLHelper::getAttrString(child, nullptr, _StorageService));
1788 if (!ssid.empty()) {
1789 if (m_outer->m_storage.count(ssid)) {
1790 log.info("building ArtifactMap on top of StorageService (%s)...", ssid.c_str());
1791 samlConf.setArtifactMap(new ArtifactMap(child, m_outer->m_storage[ssid]));
1794 log.error("unable to locate StorageService (%s), using in-memory ArtifactMap", ssid.c_str());
1795 samlConf.setArtifactMap(new ArtifactMap(child));
1799 log.info("no StorageService specified, using in-memory ArtifactMap");
1800 samlConf.setArtifactMap(new ArtifactMap(child));
1804 log.info("no ArtifactMap specified, building in-memory ArtifactMap...");
1805 samlConf.setArtifactMap(new ArtifactMap(child));
1807 } // end of out of process caching components
1810 child = XMLHelper::getFirstChildElement(e, _SessionCache);
1812 string t(XMLHelper::getAttrString(child, nullptr, _type));
1814 log.info("building SessionCache of type %s...", t.c_str());
1815 m_outer->m_sessionCache = conf.SessionCacheManager.newPlugin(t.c_str(), child);
1818 if (!m_outer->m_sessionCache) {
1819 log.info("no SessionCache specified, using StorageService-backed instance");
1820 m_outer->m_sessionCache = conf.SessionCacheManager.newPlugin(STORAGESERVICE_SESSION_CACHE, nullptr);
1824 XMLConfigImpl::XMLConfigImpl(const DOMElement* e, bool first, const XMLConfig* outer, Category& log)
1825 : m_requestMapper(nullptr),
1829 m_outer(outer), m_document(nullptr)
1832 xmltooling::NDC ndc("XMLConfigImpl");
1836 SPConfig& conf=SPConfig::getConfig();
1838 SAMLConfig& samlConf=SAMLConfig::getConfig();
1840 XMLToolingConfig& xmlConf=XMLToolingConfig::getConfig();
1841 const DOMElement* SHAR=XMLHelper::getFirstChildElement(e, OutOfProcess);
1842 const DOMElement* SHIRE=XMLHelper::getFirstChildElement(e, InProcess);
1844 // Initialize logging manually in order to redirect log messages as soon as possible.
1845 if (conf.isEnabled(SPConfig::Logging)) {
1847 if (conf.isEnabled(SPConfig::OutOfProcess))
1848 logconf = XMLHelper::getAttrString(SHAR, nullptr, logger);
1849 else if (conf.isEnabled(SPConfig::InProcess))
1850 logconf = XMLHelper::getAttrString(SHIRE, nullptr, logger);
1851 if (logconf.empty())
1852 logconf = XMLHelper::getAttrString(e, nullptr, logger);
1853 if (logconf.empty() && !getenv("SHIBSP_LOGGING")) {
1854 // No properties found, so default them.
1855 if (conf.isEnabled(SPConfig::OutOfProcess) && !conf.isEnabled(SPConfig::InProcess))
1856 logconf = "shibd.logger";
1857 else if (!conf.isEnabled(SPConfig::OutOfProcess) && conf.isEnabled(SPConfig::InProcess))
1858 logconf = "native.logger";
1860 logconf = "shibboleth.logger";
1862 if (!logconf.empty()) {
1863 log.debug("loading new logging configuration from (%s), check log destination for status of configuration", logconf.c_str());
1864 if (!XMLToolingConfig::getConfig().log_config(logconf.c_str()))
1865 log.crit("failed to load new logging configuration from (%s)", logconf.c_str());
1870 m_outer->m_tranLog = new TransactionLog();
1874 // Re-log library versions now that logging is set up.
1875 log.info("Shibboleth SP Version %s", PACKAGE_VERSION);
1878 "Library versions: Xerces-C %s, XML-Security-C %s, XMLTooling-C %s, OpenSAML-C %s, Shibboleth %s",
1879 XERCES_FULLVERSIONDOT, XSEC_FULLVERSIONDOT, XMLTOOLING_FULLVERSIONDOT, OPENSAML_FULLVERSIONDOT, SHIBSP_FULLVERSIONDOT
1883 "Library versions: Xerces-C %s, XMLTooling-C %s, Shibboleth %s",
1884 XERCES_FULLVERSIONDOT, XMLTOOLING_FULLVERSIONDOT, SHIBSP_FULLVERSIONDOT
1888 // First load any property sets.
1889 load(e,nullptr,this);
1893 // Much of the processing can only occur on the first instantiation.
1896 pair<bool,unsigned int> skew=getUnsignedInt("clockSkew");
1898 xmlConf.clock_skew_secs=min(skew.second,(60*60*24*7*28));
1900 pair<bool,const char*> unsafe = getString("unsafeChars");
1902 TemplateEngine::unsafe_chars = unsafe.second;
1904 unsafe = getString("allowedSchemes");
1906 HTTPResponse::getAllowedSchemes().clear();
1907 string schemes=unsafe.second;
1908 unsigned int j_sch=0;
1909 for (unsigned int i_sch=0; i_sch < schemes.length(); i_sch++) {
1910 if (schemes.at(i_sch)==' ') {
1911 HTTPResponse::getAllowedSchemes().push_back(schemes.substr(j_sch, i_sch-j_sch));
1915 HTTPResponse::getAllowedSchemes().push_back(schemes.substr(j_sch, schemes.length()-j_sch));
1919 doExtensions(e, "global", log);
1920 if (conf.isEnabled(SPConfig::OutOfProcess))
1921 doExtensions(SHAR, "out of process", log);
1923 if (conf.isEnabled(SPConfig::InProcess))
1924 doExtensions(SHIRE, "in process", log);
1926 // Instantiate the ListenerService and SessionCache objects.
1927 if (conf.isEnabled(SPConfig::Listener))
1931 if (m_outer->m_listener && conf.isEnabled(SPConfig::OutOfProcess) && !conf.isEnabled(SPConfig::InProcess)) {
1932 m_outer->m_listener->regListener("set::RelayState", const_cast<XMLConfig*>(m_outer));
1933 m_outer->m_listener->regListener("get::RelayState", const_cast<XMLConfig*>(m_outer));
1934 m_outer->m_listener->regListener("set::PostData", const_cast<XMLConfig*>(m_outer));
1935 m_outer->m_listener->regListener("get::PostData", const_cast<XMLConfig*>(m_outer));
1938 if (conf.isEnabled(SPConfig::Caching))
1940 } // end of first-time-only stuff
1942 // Back to the fully dynamic stuff...next up is the RequestMapper.
1943 if (conf.isEnabled(SPConfig::RequestMapping)) {
1944 if (child = XMLHelper::getFirstChildElement(e, _RequestMapper)) {
1945 string t(XMLHelper::getAttrString(child, nullptr, _type));
1947 log.info("building RequestMapper of type %s...", t.c_str());
1948 m_requestMapper = conf.RequestMapperManager.newPlugin(t.c_str(), child);
1951 if (!m_requestMapper) {
1952 log.info("no RequestMapper specified, using 'Native' plugin with empty/default map");
1953 child = e->getOwnerDocument()->createElementNS(nullptr, _RequestMapper);
1954 DOMElement* mapperDummy = e->getOwnerDocument()->createElementNS(shibspconstants::SHIB2SPCONFIG_NS, RequestMap);
1955 mapperDummy->setAttributeNS(nullptr, applicationId, _default);
1956 child->appendChild(mapperDummy);
1957 m_requestMapper = conf.RequestMapperManager.newPlugin(NATIVE_REQUEST_MAPPER, child);
1962 // Load security policies.
1963 if (child = XMLHelper::getLastChildElement(e, _SecurityPolicyProvider)) {
1964 string t(XMLHelper::getAttrString(child, nullptr, _type));
1966 log.info("building SecurityPolicyProvider of type %s...", t.c_str());
1967 m_policy = conf.SecurityPolicyProviderManager.newPlugin(t.c_str(), child);
1970 throw ConfigurationException("can't build SecurityPolicyProvider, no type specified");
1973 else if (child = XMLHelper::getLastChildElement(e, SecurityPolicies)) {
1974 // For backward compatibility, wrap in a plugin element.
1975 DOMElement* polwrapper = e->getOwnerDocument()->createElementNS(nullptr, _SecurityPolicyProvider);
1976 polwrapper->appendChild(child);
1977 log.info("building SecurityPolicyProvider of type %s...", XML_SECURITYPOLICY_PROVIDER);
1978 m_policy = conf.SecurityPolicyProviderManager.newPlugin(XML_SECURITYPOLICY_PROVIDER, polwrapper);
1981 log.fatal("can't build SecurityPolicyProvider, missing conf:SecurityPolicyProvider element?");
1982 throw ConfigurationException("Can't build SecurityPolicyProvider, missing conf:SecurityPolicyProvider element?");
1986 #ifdef SHIBSP_XMLSEC_WHITELISTING
1987 vector<xstring>::const_iterator alg;
1988 if (!m_policy->getAlgorithmBlacklist().empty()) {
1989 for (alg = m_policy->getAlgorithmBlacklist().begin(); alg != m_policy->getAlgorithmBlacklist().end(); ++alg)
1990 XSECPlatformUtils::blacklistAlgorithm(alg->c_str());
1992 else if (!m_policy->getAlgorithmWhitelist().empty()) {
1993 for (alg = m_policy->getAlgorithmWhitelist().begin(); alg != m_policy->getAlgorithmWhitelist().end(); ++alg)
1994 XSECPlatformUtils::whitelistAlgorithm(alg->c_str());
1997 log.fatal("XML-Security-C library prior to 1.6.0 does not support algorithm white/blacklists");
1998 throw ConfigurationException("XML-Security-C library prior to 1.6.0 does not support algorithm white/blacklists.");
2002 // Process TransportOption elements.
2003 child = XMLHelper::getLastChildElement(e, TransportOption);
2005 if (child->hasChildNodes()) {
2006 string provider(XMLHelper::getAttrString(child, nullptr, _provider));
2007 string option(XMLHelper::getAttrString(child, nullptr, _option));
2008 auto_ptr_char value(child->getFirstChild()->getNodeValue());
2009 if (!provider.empty() && !option.empty() && value.get() && *value.get()) {
2010 m_transportOptions.push_back(make_pair(provider, make_pair(option, string(value.get()))));
2013 child = XMLHelper::getPreviousSiblingElement(child, TransportOption);
2017 ProtocolProvider* pp = nullptr;
2018 if (conf.isEnabled(SPConfig::Handlers)) {
2019 if (child = XMLHelper::getLastChildElement(e, _ProtocolProvider)) {
2020 string t(XMLHelper::getAttrString(child, nullptr, _type));
2022 log.info("building ProtocolProvider of type %s...", t.c_str());
2023 pp = conf.ProtocolProviderManager.newPlugin(t.c_str(), child);
2027 auto_ptr<ProtocolProvider> ppwrapper(pp);
2028 Locker pplocker(pp);
2030 // Load the default application.
2031 child = XMLHelper::getLastChildElement(e, ApplicationDefaults);
2033 log.fatal("can't build default Application object, missing conf:ApplicationDefaults element?");
2034 throw ConfigurationException("can't build default Application object, missing conf:ApplicationDefaults element?");
2036 XMLApplication* defapp = new XMLApplication(m_outer, pp, child);
2037 m_appmap[defapp->getId()] = defapp;
2039 // Load any overrides.
2040 child = XMLHelper::getFirstChildElement(child, ApplicationOverride);
2042 auto_ptr<XMLApplication> iapp(new XMLApplication(m_outer, pp, child, defapp));
2043 if (m_appmap.count(iapp->getId()))
2044 log.crit("found conf:ApplicationOverride element with duplicate id attribute (%s), skipping it", iapp->getId());
2046 const char* iappid=iapp->getId();
2047 m_appmap[iappid] = iapp.release();
2050 child = XMLHelper::getNextSiblingElement(child, ApplicationOverride);
2053 catch (exception&) {
2059 XMLConfigImpl::~XMLConfigImpl()
2064 void XMLConfigImpl::cleanup()
2066 for_each(m_appmap.begin(),m_appmap.end(),cleanup_pair<string,Application>());
2072 delete m_requestMapper;
2073 m_requestMapper = nullptr;
2075 m_document->release();
2076 m_document = nullptr;
2080 void XMLConfig::receive(DDF& in, ostream& out)
2082 if (!strcmp(in.name(), "get::RelayState")) {
2083 const char* id = in["id"].string();
2084 const char* key = in["key"].string();
2086 throw ListenerException("Required parameters missing for RelayState recovery.");
2089 StorageService* storage = getStorageService(id);
2091 if (storage->readString("RelayState",key,&relayState)>0) {
2092 if (in["clear"].integer())
2093 storage->deleteString("RelayState",key);
2097 Category::getInstance(SHIBSP_LOGCAT".ServiceProvider").error(
2098 "Storage-backed RelayState with invalid StorageService ID (%s)", id
2102 // Repack for return to caller.
2103 DDF ret=DDF(nullptr).unsafe_string(relayState.c_str());
2104 DDFJanitor jret(ret);
2107 else if (!strcmp(in.name(), "set::RelayState")) {
2108 const char* id = in["id"].string();
2109 const char* value = in["value"].string();
2111 throw ListenerException("Required parameters missing for RelayState creation.");
2114 StorageService* storage = getStorageService(id);
2116 SAMLConfig::getConfig().generateRandomBytes(rsKey,20);
2117 rsKey = SAMLArtifact::toHex(rsKey);
2118 storage->createString("RelayState", rsKey.c_str(), value, time(nullptr) + 600);
2121 Category::getInstance(SHIBSP_LOGCAT".ServiceProvider").error(
2122 "Storage-backed RelayState with invalid StorageService ID (%s)", id
2126 // Repack for return to caller.
2127 DDF ret=DDF(nullptr).string(rsKey.c_str());
2128 DDFJanitor jret(ret);
2131 else if (!strcmp(in.name(), "get::PostData")) {
2132 const char* id = in["id"].string();
2133 const char* key = in["key"].string();
2135 throw ListenerException("Required parameters missing for PostData recovery.");
2138 StorageService* storage = getStorageService(id);
2140 if (storage->readString("PostData",key,&postData) > 0) {
2141 storage->deleteString("PostData",key);
2145 Category::getInstance(SHIBSP_LOGCAT".ServiceProvider").error(
2146 "Storage-backed PostData with invalid StorageService ID (%s)", id
2149 // If the data's empty, we'll send nothing back.
2150 // If not, we don't need to round trip it, just send back the serialized DDF list.
2151 if (postData.empty()) {
2153 DDFJanitor jret(ret);
2160 else if (!strcmp(in.name(), "set::PostData")) {
2161 const char* id = in["id"].string();
2162 if (!id || !in["parameters"].islist())
2163 throw ListenerException("Required parameters missing for PostData creation.");
2166 StorageService* storage = getStorageService(id);
2168 SAMLConfig::getConfig().generateRandomBytes(rsKey,20);
2169 rsKey = SAMLArtifact::toHex(rsKey);
2170 ostringstream params;
2171 params << in["parameters"];
2172 storage->createString("PostData", rsKey.c_str(), params.str().c_str(), time(nullptr) + 600);
2175 Category::getInstance(SHIBSP_LOGCAT".ServiceProvider").error(
2176 "Storage-backed PostData with invalid StorageService ID (%s)", id
2180 // Repack for return to caller.
2181 DDF ret=DDF(nullptr).string(rsKey.c_str());
2182 DDFJanitor jret(ret);
2188 pair<bool,DOMElement*> XMLConfig::background_load()
2190 // Load from source using base class.
2191 pair<bool,DOMElement*> raw = ReloadableXMLFile::load();
2193 // If we own it, wrap it.
2194 XercesJanitor<DOMDocument> docjanitor(raw.first ? raw.second->getOwnerDocument() : nullptr);
2196 XMLConfigImpl* impl = new XMLConfigImpl(raw.second, (m_impl==nullptr), this, m_log);
2198 // If we held the document, transfer it to the impl. If we didn't, it's a no-op.
2199 impl->setDocument(docjanitor.release());
2201 // Perform the swap inside a lock.
2204 SharedLock locker(m_lock, false);
2208 return make_pair(false,(DOMElement*)nullptr);