2 * Copyright 2001-2009 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 "handler/SessionInitiator.h"
34 #include "remoting/ListenerService.h"
35 #include "util/DOMPropertySet.h"
36 #include "util/SPConstants.h"
38 #if defined(XMLTOOLING_LOG4SHIB)
39 # include <log4shib/PropertyConfigurator.hh>
40 #elif defined(XMLTOOLING_LOG4CPP)
41 # include <log4cpp/PropertyConfigurator.hh>
43 # error "Supported logging library not available."
46 #include <xercesc/util/XMLUniDefs.hpp>
47 #include <xmltooling/XMLToolingConfig.h>
48 #include <xmltooling/version.h>
49 #include <xmltooling/util/NDC.h>
50 #include <xmltooling/util/ReloadableXMLFile.h>
51 #include <xmltooling/util/TemplateEngine.h>
52 #include <xmltooling/util/XMLHelper.h>
55 # include "TransactionLog.h"
56 # include "attribute/filtering/AttributeFilter.h"
57 # include "attribute/resolver/AttributeExtractor.h"
58 # include "attribute/resolver/AttributeResolver.h"
59 # include "security/PKIXTrustEngine.h"
60 # include <saml/SAMLConfig.h>
61 # include <saml/version.h>
62 # include <saml/binding/ArtifactMap.h>
63 # include <saml/binding/SAMLArtifact.h>
64 # include <saml/binding/SecurityPolicyRule.h>
65 # include <saml/saml1/core/Assertions.h>
66 # include <saml/saml2/core/Assertions.h>
67 # include <saml/saml2/binding/SAML2ArtifactType0004.h>
68 # include <saml/saml2/metadata/Metadata.h>
69 # include <saml/saml2/metadata/MetadataProvider.h>
70 # include <saml/util/SAMLConstants.h>
71 # include <xmltooling/security/CredentialResolver.h>
72 # include <xmltooling/security/TrustEngine.h>
73 # include <xmltooling/util/ReplayCache.h>
74 # include <xmltooling/util/StorageService.h>
75 using namespace opensaml::saml2;
76 using namespace opensaml::saml2p;
77 using namespace opensaml::saml2md;
78 using namespace opensaml;
80 # include "lite/SAMLConstants.h"
83 using namespace shibsp;
84 using namespace xmltooling;
88 # define min(a,b) (((a) < (b)) ? (a) : (b))
93 #if defined (_MSC_VER)
94 #pragma warning( push )
95 #pragma warning( disable : 4250 )
98 static vector<const Handler*> g_noHandlers;
100 // Application configuration wrapper
101 class SHIBSP_DLLLOCAL XMLApplication : public Application, public Remoted, public DOMPropertySet, public DOMNodeFilter
104 XMLApplication(const ServiceProvider*, const DOMElement* e, const XMLApplication* base=NULL);
105 ~XMLApplication() { cleanup(); }
107 const char* getHash() const {return m_hash.c_str();}
110 SAMLArtifact* generateSAML1Artifact(const EntityDescriptor* relyingParty) const {
111 throw ConfigurationException("No support for SAML 1.x artifact generation.");
113 SAML2Artifact* generateSAML2Artifact(const EntityDescriptor* relyingParty) const {
114 pair<bool,int> index = make_pair(false,0);
115 const PropertySet* props = getRelyingParty(relyingParty);
116 index = props->getInt("artifactEndpointIndex");
118 index = getArtifactEndpointIndex();
119 return new SAML2ArtifactType0004(SAMLConfig::getConfig().hashSHA1(props->getString("entityID").second),index.first ? index.second : 1);
122 MetadataProvider* getMetadataProvider(bool required=true) const {
123 if (required && !m_base && !m_metadata)
124 throw ConfigurationException("No MetadataProvider available.");
125 return (!m_metadata && m_base) ? m_base->getMetadataProvider() : m_metadata;
127 TrustEngine* getTrustEngine(bool required=true) const {
128 if (required && !m_base && !m_trust)
129 throw ConfigurationException("No TrustEngine available.");
130 return (!m_trust && m_base) ? m_base->getTrustEngine() : m_trust;
132 AttributeExtractor* getAttributeExtractor() const {
133 return (!m_attrExtractor && m_base) ? m_base->getAttributeExtractor() : m_attrExtractor;
135 AttributeFilter* getAttributeFilter() const {
136 return (!m_attrFilter && m_base) ? m_base->getAttributeFilter() : m_attrFilter;
138 AttributeResolver* getAttributeResolver() const {
139 return (!m_attrResolver && m_base) ? m_base->getAttributeResolver() : m_attrResolver;
141 CredentialResolver* getCredentialResolver() const {
142 return (!m_credResolver && m_base) ? m_base->getCredentialResolver() : m_credResolver;
144 const PropertySet* getRelyingParty(const EntityDescriptor* provider) const;
145 const PropertySet* getRelyingParty(const XMLCh* entityID) const;
146 const vector<const XMLCh*>* getAudiences() const {
147 return (m_audiences.empty() && m_base) ? m_base->getAudiences() : &m_audiences;
150 string getNotificationURL(const char* resource, bool front, unsigned int index) const;
152 const vector<string>& getRemoteUserAttributeIds() const {
153 return (m_remoteUsers.empty() && m_base) ? m_base->getRemoteUserAttributeIds() : m_remoteUsers;
156 void clearHeader(SPRequest& request, const char* rawname, const char* cginame) const;
157 void setHeader(SPRequest& request, const char* name, const char* value) const;
158 string getSecureHeader(const SPRequest& request, const char* name) const;
160 const SessionInitiator* getDefaultSessionInitiator() const;
161 const SessionInitiator* getSessionInitiatorById(const char* id) const;
162 const Handler* getDefaultAssertionConsumerService() const;
163 const Handler* getAssertionConsumerServiceByIndex(unsigned short index) const;
164 const vector<const Handler*>& getAssertionConsumerServicesByBinding(const XMLCh* binding) const;
165 const Handler* getHandler(const char* path) const;
166 void getHandlers(vector<const Handler*>& handlers) const;
168 void receive(DDF& in, ostream& out) {
169 // Only current function is to return the headers to clear.
171 DDF ret=DDF(NULL).list();
172 DDFJanitor jret(ret);
173 for (vector< pair<string,string> >::const_iterator i = m_unsetHeaders.begin(); i!=m_unsetHeaders.end(); ++i) {
174 header = DDF(i->first.c_str()).string(i->second.c_str());
180 // Provides filter to exclude special config elements.
181 #ifdef SHIBSP_XERCESC_SHORT_ACCEPTNODE
186 acceptNode(const DOMNode* node) const;
190 const XMLApplication* m_base;
192 std::pair<std::string,std::string> m_attributePrefix;
194 MetadataProvider* m_metadata;
195 TrustEngine* m_trust;
196 AttributeExtractor* m_attrExtractor;
197 AttributeFilter* m_attrFilter;
198 AttributeResolver* m_attrResolver;
199 CredentialResolver* m_credResolver;
200 vector<const XMLCh*> m_audiences;
202 // RelyingParty properties
203 map<xstring,PropertySet*> m_partyMap;
205 vector<string> m_remoteUsers,m_frontLogout,m_backLogout;
207 // manage handler objects
208 vector<Handler*> m_handlers;
210 // maps location (path info) to applicable handlers
211 map<string,const Handler*> m_handlerMap;
213 // maps unique indexes to consumer services
214 map<unsigned int,const Handler*> m_acsIndexMap;
216 // pointer to default consumer service
217 const Handler* m_acsDefault;
219 // maps binding strings to supporting consumer service(s)
220 typedef map<xstring,vector<const Handler*> > ACSBindingMap;
221 ACSBindingMap m_acsBindingMap;
223 // pointer to default session initiator
224 const SessionInitiator* m_sessionInitDefault;
226 // maps unique ID strings to session initiators
227 map<string,const SessionInitiator*> m_sessionInitMap;
229 // pointer to default artifact resolution service
230 const Handler* m_artifactResolutionDefault;
232 pair<bool,int> getArtifactEndpointIndex() const {
233 if (m_artifactResolutionDefault) return m_artifactResolutionDefault->getInt("index");
234 return m_base ? m_base->getArtifactEndpointIndex() : make_pair(false,0);
238 // Top-level configuration implementation
239 class SHIBSP_DLLLOCAL XMLConfig;
240 class SHIBSP_DLLLOCAL XMLConfigImpl : public DOMPropertySet, public DOMNodeFilter
243 XMLConfigImpl(const DOMElement* e, bool first, const XMLConfig* outer, Category& log);
246 RequestMapper* m_requestMapper;
247 map<string,Application*> m_appmap;
249 map< string,pair< PropertySet*,vector<const SecurityPolicyRule*> > > m_policyMap;
250 vector< pair< string, pair<string,string> > > m_transportOptions;
253 // Provides filter to exclude special config elements.
254 #ifdef SHIBSP_XERCESC_SHORT_ACCEPTNODE
259 acceptNode(const DOMNode* node) const;
261 void setDocument(DOMDocument* doc) {
266 void doExtensions(const DOMElement* e, const char* label, Category& log);
269 const XMLConfig* m_outer;
270 DOMDocument* m_document;
273 class SHIBSP_DLLLOCAL XMLConfig : public ServiceProvider, public ReloadableXMLFile
279 XMLConfig(const DOMElement* e) : ReloadableXMLFile(e, Category::getInstance(SHIBSP_LOGCAT".Config")),
280 m_impl(NULL), m_listener(NULL), m_sessionCache(NULL)
293 delete m_sessionCache;
297 SAMLConfig::getConfig().setArtifactMap(NULL);
298 XMLToolingConfig::getConfig().setReplayCache(NULL);
299 for_each(m_storage.begin(), m_storage.end(), cleanup_pair<string,StorageService>());
304 const PropertySet* getParent() const { return m_impl->getParent(); }
305 void setParent(const PropertySet* parent) {return m_impl->setParent(parent);}
306 pair<bool,bool> getBool(const char* name, const char* ns=NULL) const {return m_impl->getBool(name,ns);}
307 pair<bool,const char*> getString(const char* name, const char* ns=NULL) const {return m_impl->getString(name,ns);}
308 pair<bool,const XMLCh*> getXMLString(const char* name, const char* ns=NULL) const {return m_impl->getXMLString(name,ns);}
309 pair<bool,unsigned int> getUnsignedInt(const char* name, const char* ns=NULL) const {return m_impl->getUnsignedInt(name,ns);}
310 pair<bool,int> getInt(const char* name, const char* ns=NULL) const {return m_impl->getInt(name,ns);}
311 void getAll(map<string,const char*>& properties) const {return m_impl->getAll(properties);}
312 const PropertySet* getPropertySet(const char* name, const char* ns="urn:mace:shibboleth:2.0:native:sp:config") const {return m_impl->getPropertySet(name,ns);}
313 const DOMElement* getElement() const {return m_impl->getElement();}
318 void receive(DDF& in, ostream& out);
320 TransactionLog* getTransactionLog() const {
323 throw ConfigurationException("No TransactionLog available.");
326 StorageService* getStorageService(const char* id) const {
328 map<string,StorageService*>::const_iterator i=m_storage.find(id);
329 if (i!=m_storage.end())
336 ListenerService* getListenerService(bool required=true) const {
337 if (required && !m_listener)
338 throw ConfigurationException("No ListenerService available.");
342 SessionCache* getSessionCache(bool required=true) const {
343 if (required && !m_sessionCache)
344 throw ConfigurationException("No SessionCache available.");
345 return m_sessionCache;
348 RequestMapper* getRequestMapper(bool required=true) const {
349 if (required && !m_impl->m_requestMapper)
350 throw ConfigurationException("No RequestMapper available.");
351 return m_impl->m_requestMapper;
354 const Application* getApplication(const char* applicationId) const {
355 map<string,Application*>::const_iterator i=m_impl->m_appmap.find(applicationId);
356 return (i!=m_impl->m_appmap.end()) ? i->second : NULL;
360 const PropertySet* getPolicySettings(const char* id) const {
361 map<string,pair<PropertySet*,vector<const SecurityPolicyRule*> > >::const_iterator i = m_impl->m_policyMap.find(id);
362 if (i!=m_impl->m_policyMap.end())
363 return i->second.first;
364 throw ConfigurationException("Security Policy ($1) not found, check <SecurityPolicies> element.", params(1,id));
367 const vector<const SecurityPolicyRule*>& getPolicyRules(const char* id) const {
368 map<string,pair<PropertySet*,vector<const SecurityPolicyRule*> > >::const_iterator i = m_impl->m_policyMap.find(id);
369 if (i!=m_impl->m_policyMap.end())
370 return i->second.second;
371 throw ConfigurationException("Security Policy ($1) not found, check <SecurityPolicies> element.", params(1,id));
374 bool setTransportOptions(SOAPTransport& transport) const {
376 vector< pair< string, pair<string,string> > >::const_iterator opt;
377 for (opt = m_impl->m_transportOptions.begin(); opt != m_impl->m_transportOptions.end(); ++opt) {
378 if (!transport.setProviderOption(opt->first.c_str(), opt->second.first.c_str(), opt->second.second.c_str())) {
379 m_log.error("failed to set SOAPTransport option (%s)", opt->second.first.c_str());
388 pair<bool,DOMElement*> load();
391 friend class XMLConfigImpl;
392 XMLConfigImpl* m_impl;
393 mutable ListenerService* m_listener;
394 mutable SessionCache* m_sessionCache;
396 mutable TransactionLog* m_tranLog;
397 mutable map<string,StorageService*> m_storage;
401 #if defined (_MSC_VER)
402 #pragma warning( pop )
405 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);
406 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);
407 static const XMLCh _ArtifactMap[] = UNICODE_LITERAL_11(A,r,t,i,f,a,c,t,M,a,p);
408 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);
409 static const XMLCh _AttributeFilter[] = UNICODE_LITERAL_15(A,t,t,r,i,b,u,t,e,F,i,l,t,e,r);
410 static const XMLCh _AttributeResolver[] = UNICODE_LITERAL_17(A,t,t,r,i,b,u,t,e,R,e,s,o,l,v,e,r);
411 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);
412 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);
413 static const XMLCh _Audience[] = UNICODE_LITERAL_8(A,u,d,i,e,n,c,e);
414 static const XMLCh Binding[] = UNICODE_LITERAL_7(B,i,n,d,i,n,g);
415 static const XMLCh Channel[]= UNICODE_LITERAL_7(C,h,a,n,n,e,l);
416 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);
417 static const XMLCh _Extensions[] = UNICODE_LITERAL_10(E,x,t,e,n,s,i,o,n,s);
418 static const XMLCh _fatal[] = UNICODE_LITERAL_5(f,a,t,a,l);
419 static const XMLCh _Handler[] = UNICODE_LITERAL_7(H,a,n,d,l,e,r);
420 static const XMLCh _id[] = UNICODE_LITERAL_2(i,d);
421 static const XMLCh InProcess[] = UNICODE_LITERAL_9(I,n,P,r,o,c,e,s,s);
422 static const XMLCh Library[] = UNICODE_LITERAL_7(L,i,b,r,a,r,y);
423 static const XMLCh Listener[] = UNICODE_LITERAL_8(L,i,s,t,e,n,e,r);
424 static const XMLCh Location[] = UNICODE_LITERAL_8(L,o,c,a,t,i,o,n);
425 static const XMLCh logger[] = UNICODE_LITERAL_6(l,o,g,g,e,r);
426 static const XMLCh _LogoutInitiator[] = UNICODE_LITERAL_15(L,o,g,o,u,t,I,n,i,t,i,a,t,o,r);
427 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);
428 static const XMLCh _MetadataProvider[] = UNICODE_LITERAL_16(M,e,t,a,d,a,t,a,P,r,o,v,i,d,e,r);
429 static const XMLCh Notify[] = UNICODE_LITERAL_6(N,o,t,i,f,y);
430 static const XMLCh _option[] = UNICODE_LITERAL_6(o,p,t,i,o,n);
431 static const XMLCh OutOfProcess[] = UNICODE_LITERAL_12(O,u,t,O,f,P,r,o,c,e,s,s);
432 static const XMLCh _path[] = UNICODE_LITERAL_4(p,a,t,h);
433 static const XMLCh Policy[] = UNICODE_LITERAL_6(P,o,l,i,c,y);
434 static const XMLCh PolicyRule[] = UNICODE_LITERAL_10(P,o,l,i,c,y,R,u,l,e);
435 static const XMLCh _provider[] = UNICODE_LITERAL_8(p,r,o,v,i,d,e,r);
436 static const XMLCh RelyingParty[] = UNICODE_LITERAL_12(R,e,l,y,i,n,g,P,a,r,t,y);
437 static const XMLCh _ReplayCache[] = UNICODE_LITERAL_11(R,e,p,l,a,y,C,a,c,h,e);
438 static const XMLCh _RequestMapper[] = UNICODE_LITERAL_13(R,e,q,u,e,s,t,M,a,p,p,e,r);
439 static const XMLCh Rule[] = UNICODE_LITERAL_4(R,u,l,e);
440 static const XMLCh SecurityPolicies[] = UNICODE_LITERAL_16(S,e,c,u,r,i,t,y,P,o,l,i,c,i,e,s);
441 static const XMLCh _SessionCache[] = UNICODE_LITERAL_12(S,e,s,s,i,o,n,C,a,c,h,e);
442 static const XMLCh _SessionInitiator[] = UNICODE_LITERAL_16(S,e,s,s,i,o,n,I,n,i,t,i,a,t,o,r);
443 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);
444 static const XMLCh Site[] = UNICODE_LITERAL_4(S,i,t,e);
445 static const XMLCh _StorageService[] = UNICODE_LITERAL_14(S,t,o,r,a,g,e,S,e,r,v,i,c,e);
446 static const XMLCh TCPListener[] = UNICODE_LITERAL_11(T,C,P,L,i,s,t,e,n,e,r);
447 static const XMLCh TransportOption[] = UNICODE_LITERAL_15(T,r,a,n,s,p,o,r,t,O,p,t,i,o,n);
448 static const XMLCh _TrustEngine[] = UNICODE_LITERAL_11(T,r,u,s,t,E,n,g,i,n,e);
449 static const XMLCh _type[] = UNICODE_LITERAL_4(t,y,p,e);
450 static const XMLCh UnixListener[] = UNICODE_LITERAL_12(U,n,i,x,L,i,s,t,e,n,e,r);
453 class SHIBSP_DLLLOCAL PolicyNodeFilter : public DOMNodeFilter
456 #ifdef SHIBSP_XERCESC_SHORT_ACCEPTNODE
461 acceptNode(const DOMNode* node) const {
462 return FILTER_REJECT;
469 ServiceProvider* XMLServiceProviderFactory(const DOMElement* const & e)
471 return new XMLConfig(e);
475 XMLApplication::XMLApplication(
476 const ServiceProvider* sp,
478 const XMLApplication* base
479 ) : Application(sp), m_base(base),
481 m_metadata(NULL), m_trust(NULL),
482 m_attrExtractor(NULL), m_attrFilter(NULL), m_attrResolver(NULL),
483 m_credResolver(NULL),
485 m_acsDefault(NULL), m_sessionInitDefault(NULL), m_artifactResolutionDefault(NULL)
488 xmltooling::NDC ndc("XMLApplication");
490 Category& log=Category::getInstance(SHIBSP_LOGCAT".Application");
493 // First load any property sets.
498 SPConfig& conf=SPConfig::getConfig();
500 SAMLConfig& samlConf=SAMLConfig::getConfig();
501 XMLToolingConfig& xmlConf=XMLToolingConfig::getConfig();
504 // This used to be an actual hash, but now it's just a hex-encode to avoid xmlsec.
505 static char DIGITS[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
506 string tohash=getId();
507 tohash+=getString("entityID").second;
508 for (const char* ch = tohash.c_str(); *ch; ++ch) {
509 m_hash += (DIGITS[((unsigned char)(0xF0 & *ch)) >> 4 ]);
510 m_hash += (DIGITS[0x0F & *ch]);
513 // Populate prefix pair.
514 m_attributePrefix.second = "HTTP_";
515 pair<bool,const char*> prefix = getString("attributePrefix");
517 m_attributePrefix.first = prefix.second;
518 const char* pch = prefix.second;
520 m_attributePrefix.second += (isalnum(*pch) ? toupper(*pch) : '_');
525 // Load attribute ID lists for REMOTE_USER and header clearing.
526 if (conf.isEnabled(SPConfig::InProcess)) {
527 pair<bool,const char*> attributes = getString("REMOTE_USER");
528 if (attributes.first) {
529 char* dup = strdup(attributes.second);
532 while (start && *start) {
533 while (*start && isspace(*start))
537 pos = strchr(start,' ');
540 m_remoteUsers.push_back(start);
541 start = pos ? pos+1 : NULL;
546 attributes = getString("unsetHeaders");
547 if (attributes.first) {
548 string transformedprefix(m_attributePrefix.second);
550 prefix = getString("metadataAttributePrefix");
554 transformedprefix += (isalnum(*pch) ? toupper(*pch) : '_');
558 char* dup = strdup(attributes.second);
561 while (start && *start) {
562 while (*start && isspace(*start))
566 pos = strchr(start,' ');
573 transformed += (isalnum(*pch) ? toupper(*pch) : '_');
577 m_unsetHeaders.push_back(pair<string,string>(m_attributePrefix.first + start, m_attributePrefix.second + transformed));
579 m_unsetHeaders.push_back(pair<string,string>(m_attributePrefix.first + prefix.second + start, transformedprefix + transformed));
580 start = pos ? pos+1 : NULL;
583 m_unsetHeaders.push_back(pair<string,string>(m_attributePrefix.first + "Shib-Application-ID", m_attributePrefix.second + "SHIB_APPLICATION_ID"));
587 Handler* handler=NULL;
588 const PropertySet* sessions = getPropertySet("Sessions");
590 // Process assertion export handler.
591 pair<bool,const char*> location = sessions ? sessions->getString("exportLocation") : pair<bool,const char*>(false,NULL);
592 if (location.first) {
594 DOMElement* exportElement = e->getOwnerDocument()->createElementNS(shibspconstants::SHIB2SPCONFIG_NS,_Handler);
595 exportElement->setAttributeNS(NULL,Location,sessions->getXMLString("exportLocation").second);
596 pair<bool,const XMLCh*> exportACL = sessions->getXMLString("exportACL");
597 if (exportACL.first) {
598 static const XMLCh _acl[] = UNICODE_LITERAL_9(e,x,p,o,r,t,A,C,L);
599 exportElement->setAttributeNS(NULL,_acl,exportACL.second);
601 handler = conf.HandlerManager.newPlugin(
602 samlconstants::SAML20_BINDING_URI, pair<const DOMElement*,const char*>(exportElement, getId())
604 m_handlers.push_back(handler);
606 // Insert into location map. If it contains the handlerURL, we skip past that part.
607 const char* pch = strstr(location.second, sessions->getString("handlerURL").second);
609 location.second = pch + strlen(sessions->getString("handlerURL").second);
610 if (*location.second == '/')
611 m_handlerMap[location.second]=handler;
613 m_handlerMap[string("/") + location.second]=handler;
615 catch (exception& ex) {
616 log.error("caught exception installing assertion lookup handler: %s", ex.what());
620 // Process other handlers.
621 bool hardACS=false, hardSessionInit=false, hardArt=false;
622 const DOMElement* child = sessions ? XMLHelper::getFirstChildElement(sessions->getElement()) : NULL;
625 // A handler is based on the Binding property in conjunction with the element name.
626 // If it's an ACS or SI, also handle index/id mappings and defaulting.
627 if (XMLString::equals(child->getLocalName(),_AssertionConsumerService)) {
628 auto_ptr_char bindprop(child->getAttributeNS(NULL,Binding));
629 if (!bindprop.get() || !*(bindprop.get())) {
630 log.warn("md:AssertionConsumerService element has no Binding attribute, skipping it...");
631 child = XMLHelper::getNextSiblingElement(child);
634 handler=conf.AssertionConsumerServiceManager.newPlugin(bindprop.get(),make_pair(child, getId()));
635 // Map by binding (may be > 1 per binding, e.g. SAML 1.0 vs 1.1)
636 m_acsBindingMap[handler->getXMLString("Binding").second].push_back(handler);
637 m_acsIndexMap[handler->getUnsignedInt("index").second]=handler;
640 pair<bool,bool> defprop=handler->getBool("isDefault");
642 if (defprop.second) {
644 m_acsDefault=handler;
647 else if (!m_acsDefault)
648 m_acsDefault=handler;
651 else if (XMLString::equals(child->getLocalName(),_SessionInitiator)) {
652 auto_ptr_char type(child->getAttributeNS(NULL,_type));
653 if (!type.get() || !*(type.get())) {
654 log.warn("SessionInitiator element has no type attribute, skipping it...");
655 child = XMLHelper::getNextSiblingElement(child);
658 SessionInitiator* sihandler=conf.SessionInitiatorManager.newPlugin(type.get(),make_pair(child, getId()));
660 pair<bool,const char*> si_id=handler->getString("id");
661 if (si_id.first && si_id.second)
662 m_sessionInitMap[si_id.second]=sihandler;
663 if (!hardSessionInit) {
664 pair<bool,bool> defprop=handler->getBool("isDefault");
666 if (defprop.second) {
667 hardSessionInit=true;
668 m_sessionInitDefault=sihandler;
671 else if (!m_sessionInitDefault)
672 m_sessionInitDefault=sihandler;
675 else if (XMLString::equals(child->getLocalName(),_LogoutInitiator)) {
676 auto_ptr_char type(child->getAttributeNS(NULL,_type));
677 if (!type.get() || !*(type.get())) {
678 log.warn("LogoutInitiator element has no type attribute, skipping it...");
679 child = XMLHelper::getNextSiblingElement(child);
682 handler=conf.LogoutInitiatorManager.newPlugin(type.get(),make_pair(child, getId()));
684 else if (XMLString::equals(child->getLocalName(),_ArtifactResolutionService)) {
685 auto_ptr_char bindprop(child->getAttributeNS(NULL,Binding));
686 if (!bindprop.get() || !*(bindprop.get())) {
687 log.warn("md:ArtifactResolutionService element has no Binding attribute, skipping it...");
688 child = XMLHelper::getNextSiblingElement(child);
691 handler=conf.ArtifactResolutionServiceManager.newPlugin(bindprop.get(),make_pair(child, getId()));
694 pair<bool,bool> defprop=handler->getBool("isDefault");
696 if (defprop.second) {
698 m_artifactResolutionDefault=handler;
701 else if (!m_artifactResolutionDefault)
702 m_artifactResolutionDefault=handler;
705 else if (XMLString::equals(child->getLocalName(),_SingleLogoutService)) {
706 auto_ptr_char bindprop(child->getAttributeNS(NULL,Binding));
707 if (!bindprop.get() || !*(bindprop.get())) {
708 log.warn("md:SingleLogoutService element has no Binding attribute, skipping it...");
709 child = XMLHelper::getNextSiblingElement(child);
712 handler=conf.SingleLogoutServiceManager.newPlugin(bindprop.get(),make_pair(child, getId()));
714 else if (XMLString::equals(child->getLocalName(),_ManageNameIDService)) {
715 auto_ptr_char bindprop(child->getAttributeNS(NULL,Binding));
716 if (!bindprop.get() || !*(bindprop.get())) {
717 log.warn("md:ManageNameIDService element has no Binding attribute, skipping it...");
718 child = XMLHelper::getNextSiblingElement(child);
721 handler=conf.ManageNameIDServiceManager.newPlugin(bindprop.get(),make_pair(child, getId()));
724 auto_ptr_char type(child->getAttributeNS(NULL,_type));
725 if (!type.get() || !*(type.get())) {
726 log.warn("Handler element has no type attribute, skipping it...");
727 child = XMLHelper::getNextSiblingElement(child);
730 handler=conf.HandlerManager.newPlugin(type.get(),make_pair(child, getId()));
733 m_handlers.push_back(handler);
735 // Insert into location map.
736 location=handler->getString("Location");
737 if (location.first && *location.second == '/')
738 m_handlerMap[location.second]=handler;
739 else if (location.first)
740 m_handlerMap[string("/") + location.second]=handler;
743 catch (exception& ex) {
744 log.error("caught exception processing handler element: %s", ex.what());
747 child = XMLHelper::getNextSiblingElement(child);
751 DOMNodeList* nlist=e->getElementsByTagNameNS(shibspconstants::SHIB2SPCONFIG_NS,Notify);
752 for (XMLSize_t i=0; nlist && i<nlist->getLength(); i++) {
753 if (nlist->item(i)->getParentNode()->isSameNode(e)) {
754 const XMLCh* channel = static_cast<DOMElement*>(nlist->item(i))->getAttributeNS(NULL,Channel);
755 auto_ptr_char loc(static_cast<DOMElement*>(nlist->item(i))->getAttributeNS(NULL,Location));
756 if (loc.get() && *loc.get()) {
757 if (channel && *channel == chLatin_f)
758 m_frontLogout.push_back(loc.get());
760 m_backLogout.push_back(loc.get());
766 nlist=e->getElementsByTagNameNS(samlconstants::SAML20_NS,Audience::LOCAL_NAME);
767 if (nlist && nlist->getLength()) {
768 log.warn("use of <saml:Audience> elements outside of a Security Policy Rule is deprecated");
769 for (XMLSize_t i=0; i<nlist->getLength(); i++)
770 if (nlist->item(i)->getParentNode()->isSameNode(e) && nlist->item(i)->hasChildNodes())
771 m_audiences.push_back(nlist->item(i)->getFirstChild()->getNodeValue());
774 if (conf.isEnabled(SPConfig::Metadata)) {
775 child = XMLHelper::getFirstChildElement(e,_MetadataProvider);
777 auto_ptr_char type(child->getAttributeNS(NULL,_type));
778 log.info("building MetadataProvider of type %s...",type.get());
780 auto_ptr<MetadataProvider> mp(samlConf.MetadataProviderManager.newPlugin(type.get(),child));
782 m_metadata = mp.release();
784 catch (exception& ex) {
785 log.crit("error building/initializing MetadataProvider: %s", ex.what());
790 if (conf.isEnabled(SPConfig::Trust)) {
791 child = XMLHelper::getFirstChildElement(e,_TrustEngine);
793 auto_ptr_char type(child->getAttributeNS(NULL,_type));
794 log.info("building TrustEngine of type %s...",type.get());
796 m_trust = xmlConf.TrustEngineManager.newPlugin(type.get(),child);
798 catch (exception& ex) {
799 log.crit("error building TrustEngine: %s", ex.what());
804 if (conf.isEnabled(SPConfig::AttributeResolution)) {
805 child = XMLHelper::getFirstChildElement(e,_AttributeExtractor);
807 auto_ptr_char type(child->getAttributeNS(NULL,_type));
808 log.info("building AttributeExtractor of type %s...",type.get());
810 m_attrExtractor = conf.AttributeExtractorManager.newPlugin(type.get(),child);
812 catch (exception& ex) {
813 log.crit("error building AttributeExtractor: %s", ex.what());
817 child = XMLHelper::getFirstChildElement(e,_AttributeFilter);
819 auto_ptr_char type(child->getAttributeNS(NULL,_type));
820 log.info("building AttributeFilter of type %s...",type.get());
822 m_attrFilter = conf.AttributeFilterManager.newPlugin(type.get(),child);
824 catch (exception& ex) {
825 log.crit("error building AttributeFilter: %s", ex.what());
829 child = XMLHelper::getFirstChildElement(e,_AttributeResolver);
831 auto_ptr_char type(child->getAttributeNS(NULL,_type));
832 log.info("building AttributeResolver of type %s...",type.get());
834 m_attrResolver = conf.AttributeResolverManager.newPlugin(type.get(),child);
836 catch (exception& ex) {
837 log.crit("error building AttributeResolver: %s", ex.what());
841 if (m_unsetHeaders.empty()) {
842 vector<string> unsetHeaders;
843 if (m_attrExtractor) {
844 Locker extlock(m_attrExtractor);
845 m_attrExtractor->getAttributeIds(unsetHeaders);
847 else if (m_base && m_base->m_attrExtractor) {
848 Locker extlock(m_base->m_attrExtractor);
849 m_base->m_attrExtractor->getAttributeIds(unsetHeaders);
851 if (m_attrResolver) {
852 Locker reslock(m_attrResolver);
853 m_attrResolver->getAttributeIds(unsetHeaders);
855 else if (m_base && m_base->m_attrResolver) {
856 Locker extlock(m_base->m_attrResolver);
857 m_base->m_attrResolver->getAttributeIds(unsetHeaders);
859 if (!unsetHeaders.empty()) {
860 string transformedprefix(m_attributePrefix.second);
862 pair<bool,const char*> prefix = getString("metadataAttributePrefix");
866 transformedprefix += (isalnum(*pch) ? toupper(*pch) : '_');
870 for (vector<string>::const_iterator hdr = unsetHeaders.begin(); hdr!=unsetHeaders.end(); ++hdr) {
874 transformed += (isalnum(*pch) ? toupper(*pch) : '_');
877 m_unsetHeaders.push_back(pair<string,string>(m_attributePrefix.first + *hdr, m_attributePrefix.second + transformed));
879 m_unsetHeaders.push_back(pair<string,string>(m_attributePrefix.first + prefix.second + *hdr, transformedprefix + transformed));
882 m_unsetHeaders.push_back(pair<string,string>(m_attributePrefix.first + "Shib-Application-ID", m_attributePrefix.second + "SHIB_APPLICATION_ID"));
886 if (conf.isEnabled(SPConfig::Credentials)) {
887 child = XMLHelper::getFirstChildElement(e,_CredentialResolver);
889 auto_ptr_char type(child->getAttributeNS(NULL,_type));
890 log.info("building CredentialResolver of type %s...",type.get());
892 m_credResolver = xmlConf.CredentialResolverManager.newPlugin(type.get(),child);
894 catch (exception& ex) {
895 log.crit("error building CredentialResolver: %s", ex.what());
900 // Finally, load relying parties.
901 child = XMLHelper::getFirstChildElement(e,RelyingParty);
903 auto_ptr<DOMPropertySet> rp(new DOMPropertySet());
904 rp->load(child,NULL,this);
906 m_partyMap[child->getAttributeNS(NULL,saml2::Attribute::NAME_ATTRIB_NAME)]=rp.release();
907 child = XMLHelper::getNextSiblingElement(child,RelyingParty);
911 // Out of process only, we register a listener endpoint.
912 if (!conf.isEnabled(SPConfig::InProcess)) {
913 ListenerService* listener = sp->getListenerService(false);
915 string addr=string(getId()) + "::getHeaders::Application";
916 listener->regListener(addr.c_str(),this);
919 log.info("no ListenerService available, Application remoting disabled");
934 void XMLApplication::cleanup()
936 ListenerService* listener=getServiceProvider().getListenerService(false);
937 if (listener && SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess) && !SPConfig::getConfig().isEnabled(SPConfig::InProcess)) {
938 string addr=string(getId()) + "::getHeaders::Application";
939 listener->unregListener(addr.c_str(),this);
941 for_each(m_handlers.begin(),m_handlers.end(),xmltooling::cleanup<Handler>());
944 for_each(m_partyMap.begin(),m_partyMap.end(),cleanup_pair<xstring,PropertySet>());
946 delete m_credResolver;
947 m_credResolver = NULL;
948 delete m_attrResolver;
949 m_attrResolver = NULL;
952 delete m_attrExtractor;
953 m_attrExtractor = NULL;
961 #ifdef SHIBSP_XERCESC_SHORT_ACCEPTNODE
964 DOMNodeFilter::FilterAction
966 XMLApplication::acceptNode(const DOMNode* node) const
968 const XMLCh* name=node->getLocalName();
969 if (XMLString::equals(name,ApplicationOverride) ||
970 XMLString::equals(name,_Audience) ||
971 XMLString::equals(name,Notify) ||
972 XMLString::equals(name,_Handler) ||
973 XMLString::equals(name,_AssertionConsumerService) ||
974 XMLString::equals(name,_ArtifactResolutionService) ||
975 XMLString::equals(name,_LogoutInitiator) ||
976 XMLString::equals(name,_ManageNameIDService) ||
977 XMLString::equals(name,_SessionInitiator) ||
978 XMLString::equals(name,_SingleLogoutService) ||
979 XMLString::equals(name,RelyingParty) ||
980 XMLString::equals(name,_MetadataProvider) ||
981 XMLString::equals(name,_TrustEngine) ||
982 XMLString::equals(name,_CredentialResolver) ||
983 XMLString::equals(name,_AttributeFilter) ||
984 XMLString::equals(name,_AttributeExtractor) ||
985 XMLString::equals(name,_AttributeResolver))
986 return FILTER_REJECT;
988 return FILTER_ACCEPT;
993 const PropertySet* XMLApplication::getRelyingParty(const EntityDescriptor* provider) const
998 map<xstring,PropertySet*>::const_iterator i=m_partyMap.find(provider->getEntityID());
999 if (i!=m_partyMap.end())
1001 const EntitiesDescriptor* group=dynamic_cast<const EntitiesDescriptor*>(provider->getParent());
1003 if (group->getName()) {
1004 i=m_partyMap.find(group->getName());
1005 if (i!=m_partyMap.end())
1008 group=dynamic_cast<const EntitiesDescriptor*>(group->getParent());
1013 const PropertySet* XMLApplication::getRelyingParty(const XMLCh* entityID) const
1018 map<xstring,PropertySet*>::const_iterator i=m_partyMap.find(entityID);
1019 if (i!=m_partyMap.end())
1026 string XMLApplication::getNotificationURL(const char* resource, bool front, unsigned int index) const
1028 const vector<string>& locs = front ? m_frontLogout : m_backLogout;
1030 return m_base ? m_base->getNotificationURL(resource, front, index) : string();
1031 else if (index >= locs.size())
1034 #ifdef HAVE_STRCASECMP
1035 if (!resource || (strncasecmp(resource,"http://",7) && strncasecmp(resource,"https://",8)))
1037 if (!resource || (strnicmp(resource,"http://",7) && strnicmp(resource,"https://",8)))
1039 throw ConfigurationException("Request URL was not absolute.");
1041 const char* handler=locs[index].c_str();
1043 // Should never happen...
1044 if (!handler || (*handler!='/' && strncmp(handler,"http:",5) && strncmp(handler,"https:",6)))
1045 throw ConfigurationException(
1046 "Invalid Location property ($1) in Notify element for Application ($2)",
1047 params(2, handler ? handler : "null", getId())
1050 // The "Location" property can be in one of three formats:
1052 // 1) a full URI: http://host/foo/bar
1053 // 2) a hostless URI: http:///foo/bar
1054 // 3) a relative path: /foo/bar
1056 // # Protocol Host Path
1057 // 1 handler handler handler
1058 // 2 handler resource handler
1059 // 3 resource resource handler
1061 const char* path = NULL;
1063 // Decide whether to use the handler or the resource for the "protocol"
1065 if (*handler != '/') {
1073 // break apart the "protocol" string into protocol, host, and "the rest"
1074 const char* colon=strchr(prot,':');
1076 const char* slash=strchr(colon,'/');
1080 // Compute the actual protocol and store.
1081 string notifyURL(prot, colon-prot);
1083 // create the "host" from either the colon/slash or from the target string
1084 // If prot == handler then we're in either #1 or #2, else #3.
1085 // If slash == colon then we're in #2.
1086 if (prot != handler || slash == colon) {
1087 colon = strchr(resource, ':');
1088 colon += 3; // Get past the ://
1089 slash = strchr(colon, '/');
1091 string host(colon, (slash ? slash-colon : strlen(colon)));
1094 notifyURL += host + path;
1098 void XMLApplication::clearHeader(SPRequest& request, const char* rawname, const char* cginame) const
1100 if (!m_attributePrefix.first.empty()) {
1101 string temp = m_attributePrefix.first + rawname;
1102 string temp2 = m_attributePrefix.second + (cginame + 5);
1103 request.clearHeader(temp.c_str(), temp2.c_str());
1106 m_base->clearHeader(request, rawname, cginame);
1109 request.clearHeader(rawname, cginame);
1113 void XMLApplication::setHeader(SPRequest& request, const char* name, const char* value) const
1115 if (!m_attributePrefix.first.empty()) {
1116 string temp = m_attributePrefix.first + name;
1117 request.setHeader(temp.c_str(), value);
1120 m_base->setHeader(request, name, value);
1123 request.setHeader(name, value);
1127 string XMLApplication::getSecureHeader(const SPRequest& request, const char* name) const
1129 if (!m_attributePrefix.first.empty()) {
1130 string temp = m_attributePrefix.first + name;
1131 return request.getSecureHeader(temp.c_str());
1134 return m_base->getSecureHeader(request,name);
1137 return request.getSecureHeader(name);
1141 const SessionInitiator* XMLApplication::getDefaultSessionInitiator() const
1143 if (m_sessionInitDefault) return m_sessionInitDefault;
1144 return m_base ? m_base->getDefaultSessionInitiator() : NULL;
1147 const SessionInitiator* XMLApplication::getSessionInitiatorById(const char* id) const
1149 map<string,const SessionInitiator*>::const_iterator i=m_sessionInitMap.find(id);
1150 if (i!=m_sessionInitMap.end()) return i->second;
1151 return m_base ? m_base->getSessionInitiatorById(id) : NULL;
1154 const Handler* XMLApplication::getDefaultAssertionConsumerService() const
1156 if (m_acsDefault) return m_acsDefault;
1157 return m_base ? m_base->getDefaultAssertionConsumerService() : NULL;
1160 const Handler* XMLApplication::getAssertionConsumerServiceByIndex(unsigned short index) const
1162 map<unsigned int,const Handler*>::const_iterator i=m_acsIndexMap.find(index);
1163 if (i!=m_acsIndexMap.end()) return i->second;
1164 return m_base ? m_base->getAssertionConsumerServiceByIndex(index) : NULL;
1167 const vector<const Handler*>& XMLApplication::getAssertionConsumerServicesByBinding(const XMLCh* binding) const
1169 ACSBindingMap::const_iterator i=m_acsBindingMap.find(binding);
1170 if (i!=m_acsBindingMap.end())
1172 return m_base ? m_base->getAssertionConsumerServicesByBinding(binding) : g_noHandlers;
1175 const Handler* XMLApplication::getHandler(const char* path) const
1178 wrap = wrap.substr(0,wrap.find(';'));
1179 map<string,const Handler*>::const_iterator i=m_handlerMap.find(wrap.substr(0,wrap.find('?')));
1180 if (i!=m_handlerMap.end())
1182 return m_base ? m_base->getHandler(path) : NULL;
1185 void XMLApplication::getHandlers(vector<const Handler*>& handlers) const
1187 handlers.insert(handlers.end(), m_handlers.begin(), m_handlers.end());
1189 for (map<string,const Handler*>::const_iterator h = m_base->m_handlerMap.begin(); h != m_base->m_handlerMap.end(); ++h) {
1190 if (m_handlerMap.count(h->first) == 0)
1191 handlers.push_back(h->second);
1196 #ifdef SHIBSP_XERCESC_SHORT_ACCEPTNODE
1199 DOMNodeFilter::FilterAction
1201 XMLConfigImpl::acceptNode(const DOMNode* node) const
1203 if (!XMLString::equals(node->getNamespaceURI(),shibspconstants::SHIB2SPCONFIG_NS))
1204 return FILTER_ACCEPT;
1205 const XMLCh* name=node->getLocalName();
1206 if (XMLString::equals(name,ApplicationDefaults) ||
1207 XMLString::equals(name,_ArtifactMap) ||
1208 XMLString::equals(name,_Extensions) ||
1209 XMLString::equals(name,Listener) ||
1210 XMLString::equals(name,_RequestMapper) ||
1211 XMLString::equals(name,_ReplayCache) ||
1212 XMLString::equals(name,SecurityPolicies) ||
1213 XMLString::equals(name,_SessionCache) ||
1214 XMLString::equals(name,Site) ||
1215 XMLString::equals(name,_StorageService) ||
1216 XMLString::equals(name,TCPListener) ||
1217 XMLString::equals(name,TransportOption) ||
1218 XMLString::equals(name,UnixListener))
1219 return FILTER_REJECT;
1221 return FILTER_ACCEPT;
1224 void XMLConfigImpl::doExtensions(const DOMElement* e, const char* label, Category& log)
1226 const DOMElement* exts=XMLHelper::getFirstChildElement(e,_Extensions);
1228 exts=XMLHelper::getFirstChildElement(exts,Library);
1230 auto_ptr_char path(exts->getAttributeNS(NULL,_path));
1233 if (!XMLToolingConfig::getConfig().load_library(path.get(),(void*)exts))
1234 throw ConfigurationException("XMLToolingConfig::load_library failed.");
1235 log.debug("loaded %s extension library (%s)", label, path.get());
1238 catch (exception& e) {
1239 const XMLCh* fatal=exts->getAttributeNS(NULL,_fatal);
1240 if (fatal && (*fatal==chLatin_t || *fatal==chDigit_1)) {
1241 log.fatal("unable to load mandatory %s extension library %s: %s", label, path.get(), e.what());
1245 log.crit("unable to load optional %s extension library %s: %s", label, path.get(), e.what());
1248 exts=XMLHelper::getNextSiblingElement(exts,Library);
1253 XMLConfigImpl::XMLConfigImpl(const DOMElement* e, bool first, const XMLConfig* outer, Category& log)
1254 : m_requestMapper(NULL), m_outer(outer), m_document(NULL)
1257 xmltooling::NDC ndc("XMLConfigImpl");
1261 SPConfig& conf=SPConfig::getConfig();
1263 SAMLConfig& samlConf=SAMLConfig::getConfig();
1265 XMLToolingConfig& xmlConf=XMLToolingConfig::getConfig();
1266 const DOMElement* SHAR=XMLHelper::getFirstChildElement(e,OutOfProcess);
1267 const DOMElement* SHIRE=XMLHelper::getFirstChildElement(e,InProcess);
1269 // Initialize log4cpp manually in order to redirect log messages as soon as possible.
1270 if (conf.isEnabled(SPConfig::Logging)) {
1271 const XMLCh* logconf=NULL;
1272 if (conf.isEnabled(SPConfig::OutOfProcess))
1273 logconf=SHAR->getAttributeNS(NULL,logger);
1274 else if (conf.isEnabled(SPConfig::InProcess))
1275 logconf=SHIRE->getAttributeNS(NULL,logger);
1276 if (!logconf || !*logconf)
1277 logconf=e->getAttributeNS(NULL,logger);
1278 if (logconf && *logconf) {
1279 auto_ptr_char logpath(logconf);
1280 log.debug("loading new logging configuration from (%s), check log destination for status of configuration",logpath.get());
1281 if (!XMLToolingConfig::getConfig().log_config(logpath.get()))
1282 log.crit("failed to load new logging configuration from (%s)", logpath.get());
1287 m_outer->m_tranLog = new TransactionLog();
1291 // Re-log library versions now that logging is set up.
1294 "Library versions: Xerces-C %s, XML-Security-C %s, XMLTooling-C %s, OpenSAML-C %s, Shibboleth %s",
1295 XERCES_FULLVERSIONDOT, XSEC_FULLVERSIONDOT, XMLTOOLING_FULLVERSIONDOT, OPENSAML_FULLVERSIONDOT, SHIBSP_FULLVERSIONDOT
1299 "Library versions: Xerces-C %s, XMLTooling-C %s, Shibboleth %s",
1300 XERCES_FULLVERSIONDOT, XMLTOOLING_FULLVERSIONDOT, SHIBSP_FULLVERSIONDOT
1304 // First load any property sets.
1307 const DOMElement* child;
1310 // Much of the processing can only occur on the first instantiation.
1313 pair<bool,unsigned int> skew=getUnsignedInt("clockSkew");
1315 xmlConf.clock_skew_secs=min(skew.second,(60*60*24*7*28));
1317 pair<bool,const char*> unsafe = getString("unsafeChars");
1319 TemplateEngine::unsafe_chars = unsafe.second;
1322 doExtensions(e, "global", log);
1323 if (conf.isEnabled(SPConfig::OutOfProcess))
1324 doExtensions(SHAR, "out of process", log);
1326 if (conf.isEnabled(SPConfig::InProcess))
1327 doExtensions(SHIRE, "in process", log);
1329 // Instantiate the ListenerService and SessionCache objects.
1330 if (conf.isEnabled(SPConfig::Listener)) {
1331 child=XMLHelper::getFirstChildElement(e,UnixListener);
1333 plugtype=UNIX_LISTENER_SERVICE;
1335 child=XMLHelper::getFirstChildElement(e,TCPListener);
1337 plugtype=TCP_LISTENER_SERVICE;
1339 child=XMLHelper::getFirstChildElement(e,Listener);
1341 auto_ptr_char type(child->getAttributeNS(NULL,_type));
1343 plugtype=type.get();
1348 log.info("building ListenerService of type %s...", plugtype.c_str());
1349 m_outer->m_listener = conf.ListenerServiceManager.newPlugin(plugtype.c_str(), child);
1352 log.fatal("can't build ListenerService, missing conf:Listener element?");
1353 throw ConfigurationException("Can't build ListenerService, missing conf:Listener element?");
1358 if (m_outer->m_listener && conf.isEnabled(SPConfig::OutOfProcess) && !conf.isEnabled(SPConfig::InProcess)) {
1359 m_outer->m_listener->regListener("set::RelayState", const_cast<XMLConfig*>(m_outer));
1360 m_outer->m_listener->regListener("get::RelayState", const_cast<XMLConfig*>(m_outer));
1361 m_outer->m_listener->regListener("set::PostData", const_cast<XMLConfig*>(m_outer));
1362 m_outer->m_listener->regListener("get::PostData", const_cast<XMLConfig*>(m_outer));
1366 if (conf.isEnabled(SPConfig::Caching)) {
1367 if (conf.isEnabled(SPConfig::OutOfProcess)) {
1369 // First build any StorageServices.
1370 child=XMLHelper::getFirstChildElement(e,_StorageService);
1372 auto_ptr_char id(child->getAttributeNS(NULL,_id));
1373 auto_ptr_char type(child->getAttributeNS(NULL,_type));
1375 log.info("building StorageService (%s) of type %s...", id.get(), type.get());
1376 m_outer->m_storage[id.get()] = xmlConf.StorageServiceManager.newPlugin(type.get(),child);
1378 catch (exception& ex) {
1379 log.crit("failed to instantiate StorageService (%s): %s", id.get(), ex.what());
1381 child=XMLHelper::getNextSiblingElement(child,_StorageService);
1385 StorageService* replaySS=NULL;
1386 child=XMLHelper::getFirstChildElement(e,_ReplayCache);
1388 auto_ptr_char ssid(child->getAttributeNS(NULL,_StorageService));
1389 if (ssid.get() && *ssid.get()) {
1390 if (m_outer->m_storage.count(ssid.get()))
1391 replaySS = m_outer->m_storage[ssid.get()];
1393 log.info("building ReplayCache on top of StorageService (%s)...", ssid.get());
1395 log.warn("unable to locate StorageService (%s) for ReplayCache, using dedicated in-memory instance", ssid.get());
1397 xmlConf.setReplayCache(new ReplayCache(replaySS));
1400 log.warn("no ReplayCache built, missing conf:ReplayCache element?");
1404 child=XMLHelper::getFirstChildElement(e,_ArtifactMap);
1406 auto_ptr_char ssid(child->getAttributeNS(NULL,_StorageService));
1407 if (ssid.get() && *ssid.get() && m_outer->m_storage.count(ssid.get())) {
1408 log.info("building ArtifactMap on top of StorageService (%s)...", ssid.get());
1409 samlConf.setArtifactMap(new ArtifactMap(child, m_outer->m_storage[ssid.get()]));
1412 if (samlConf.getArtifactMap()==NULL) {
1413 log.info("building in-memory ArtifactMap...");
1414 samlConf.setArtifactMap(new ArtifactMap(child));
1418 child=XMLHelper::getFirstChildElement(e,_SessionCache);
1420 auto_ptr_char type(child->getAttributeNS(NULL,_type));
1421 log.info("building SessionCache of type %s...",type.get());
1422 m_outer->m_sessionCache=conf.SessionCacheManager.newPlugin(type.get(), child);
1425 log.fatal("can't build SessionCache, missing conf:SessionCache element?");
1426 throw ConfigurationException("Can't build SessionCache, missing conf:SessionCache element?");
1429 } // end of first-time-only stuff
1431 // Back to the fully dynamic stuff...next up is the RequestMapper.
1432 if (conf.isEnabled(SPConfig::RequestMapping)) {
1433 child=XMLHelper::getFirstChildElement(e,_RequestMapper);
1435 auto_ptr_char type(child->getAttributeNS(NULL,_type));
1436 log.info("building RequestMapper of type %s...",type.get());
1437 m_requestMapper=conf.RequestMapperManager.newPlugin(type.get(),child);
1440 log.fatal("can't build RequestMapper, missing conf:RequestMapper element?");
1441 throw ConfigurationException("Can't build RequestMapper, missing conf:RequestMapper element?");
1446 // Load security policies.
1447 child = XMLHelper::getLastChildElement(e,SecurityPolicies);
1449 PolicyNodeFilter filter;
1450 child = XMLHelper::getFirstChildElement(child,Policy);
1452 auto_ptr_char id(child->getAttributeNS(NULL,_id));
1453 pair< PropertySet*,vector<const SecurityPolicyRule*> >& rules = m_policyMap[id.get()];
1455 auto_ptr<DOMPropertySet> settings(new DOMPropertySet());
1456 settings->load(child, NULL, &filter);
1457 rules.first = settings.release();
1459 // Process PolicyRule elements.
1460 const DOMElement* rule = XMLHelper::getFirstChildElement(child,PolicyRule);
1462 auto_ptr_char type(rule->getAttributeNS(NULL,_type));
1464 rules.second.push_back(samlConf.SecurityPolicyRuleManager.newPlugin(type.get(),rule));
1466 catch (exception& ex) {
1467 log.crit("error instantiating policy rule (%s) in policy (%s): %s", type.get(), id.get(), ex.what());
1469 rule = XMLHelper::getNextSiblingElement(rule,PolicyRule);
1472 if (rules.second.size() == 0) {
1473 // Process Rule elements.
1474 log.warn("detected legacy Policy configuration, please convert to new PolicyRule syntax");
1475 rule = XMLHelper::getFirstChildElement(child,Rule);
1477 auto_ptr_char type(rule->getAttributeNS(NULL,_type));
1479 rules.second.push_back(samlConf.SecurityPolicyRuleManager.newPlugin(type.get(),rule));
1481 catch (exception& ex) {
1482 log.crit("error instantiating policy rule (%s) in policy (%s): %s", type.get(), id.get(), ex.what());
1484 rule = XMLHelper::getNextSiblingElement(rule,Rule);
1487 // Manually add a basic Conditions rule.
1488 log.info("installing a default Conditions rule in policy (%s) for compatibility with legacy configuration", id.get());
1489 rules.second.push_back(samlConf.SecurityPolicyRuleManager.newPlugin(CONDITIONS_POLICY_RULE, NULL));
1492 child = XMLHelper::getNextSiblingElement(child,Policy);
1496 // Process TransportOption elements.
1497 child = XMLHelper::getLastChildElement(e,TransportOption);
1499 if (child->hasChildNodes()) {
1500 auto_ptr_char provider(child->getAttributeNS(NULL,_provider));
1501 auto_ptr_char option(child->getAttributeNS(NULL,_option));
1502 auto_ptr_char value(child->getFirstChild()->getNodeValue());
1503 if (provider.get() && *provider.get() && option.get() && *option.get() && value.get() && *value.get()) {
1504 m_transportOptions.push_back(make_pair(string(provider.get()), make_pair(string(option.get()), string(value.get()))));
1507 child = XMLHelper::getPreviousSiblingElement(child,TransportOption);
1511 // Load the default application. This actually has a fixed ID of "default". ;-)
1512 child=XMLHelper::getLastChildElement(e,ApplicationDefaults);
1514 log.fatal("can't build default Application object, missing conf:ApplicationDefaults element?");
1515 throw ConfigurationException("can't build default Application object, missing conf:ApplicationDefaults element?");
1517 XMLApplication* defapp=new XMLApplication(m_outer,child);
1518 m_appmap[defapp->getId()]=defapp;
1520 // Load any overrides.
1521 child = XMLHelper::getFirstChildElement(child,ApplicationOverride);
1523 auto_ptr<XMLApplication> iapp(new XMLApplication(m_outer,child,defapp));
1524 if (m_appmap.count(iapp->getId()))
1525 log.crit("found conf:ApplicationOverride element with duplicate id attribute (%s), skipping it", iapp->getId());
1527 const char* iappid=iapp->getId();
1528 m_appmap[iappid]=iapp.release();
1531 child = XMLHelper::getNextSiblingElement(child,ApplicationOverride);
1534 catch (exception&) {
1540 XMLConfigImpl::~XMLConfigImpl()
1545 void XMLConfigImpl::cleanup()
1547 for_each(m_appmap.begin(),m_appmap.end(),cleanup_pair<string,Application>());
1550 for (map< string,pair<PropertySet*,vector<const SecurityPolicyRule*> > >::iterator i=m_policyMap.begin(); i!=m_policyMap.end(); ++i) {
1551 delete i->second.first;
1552 for_each(i->second.second.begin(), i->second.second.end(), xmltooling::cleanup<SecurityPolicyRule>());
1554 m_policyMap.clear();
1556 delete m_requestMapper;
1557 m_requestMapper = NULL;
1559 m_document->release();
1564 void XMLConfig::receive(DDF& in, ostream& out)
1566 if (!strcmp(in.name(), "get::RelayState")) {
1567 const char* id = in["id"].string();
1568 const char* key = in["key"].string();
1570 throw ListenerException("Required parameters missing for RelayState recovery.");
1573 StorageService* storage = getStorageService(id);
1575 if (storage->readString("RelayState",key,&relayState)>0) {
1576 if (in["clear"].integer())
1577 storage->deleteString("RelayState",key);
1581 Category::getInstance(SHIBSP_LOGCAT".ServiceProvider").error(
1582 "Storage-backed RelayState with invalid StorageService ID (%s)", id
1586 // Repack for return to caller.
1587 DDF ret=DDF(NULL).unsafe_string(relayState.c_str());
1588 DDFJanitor jret(ret);
1591 else if (!strcmp(in.name(), "set::RelayState")) {
1592 const char* id = in["id"].string();
1593 const char* value = in["value"].string();
1595 throw ListenerException("Required parameters missing for RelayState creation.");
1598 StorageService* storage = getStorageService(id);
1600 SAMLConfig::getConfig().generateRandomBytes(rsKey,20);
1601 rsKey = SAMLArtifact::toHex(rsKey);
1602 storage->createString("RelayState", rsKey.c_str(), value, time(NULL) + 600);
1605 Category::getInstance(SHIBSP_LOGCAT".ServiceProvider").error(
1606 "Storage-backed RelayState with invalid StorageService ID (%s)", id
1610 // Repack for return to caller.
1611 DDF ret=DDF(NULL).string(rsKey.c_str());
1612 DDFJanitor jret(ret);
1615 else if (!strcmp(in.name(), "get::PostData")) {
1616 const char* id = in["id"].string();
1617 const char* key = in["key"].string();
1619 throw ListenerException("Required parameters missing for PostData recovery.");
1622 StorageService* storage = getStorageService(id);
1624 if (storage->readString("PostData",key,&postData) > 0) {
1625 storage->deleteString("PostData",key);
1629 Category::getInstance(SHIBSP_LOGCAT".ServiceProvider").error(
1630 "Storage-backed PostData with invalid StorageService ID (%s)", id
1633 // If the data's empty, we'll send nothing back.
1634 // If not, we don't need to round trip it, just send back the serialized DDF list.
1635 if (postData.empty()) {
1637 DDFJanitor jret(ret);
1644 else if (!strcmp(in.name(), "set::PostData")) {
1645 const char* id = in["id"].string();
1646 if (!id || !in["parameters"].islist())
1647 throw ListenerException("Required parameters missing for PostData creation.");
1650 StorageService* storage = getStorageService(id);
1652 SAMLConfig::getConfig().generateRandomBytes(rsKey,20);
1653 rsKey = SAMLArtifact::toHex(rsKey);
1654 ostringstream params;
1655 params << in["parameters"];
1656 storage->createString("PostData", rsKey.c_str(), params.str().c_str(), time(NULL) + 600);
1659 Category::getInstance(SHIBSP_LOGCAT".ServiceProvider").error(
1660 "Storage-backed PostData with invalid StorageService ID (%s)", id
1664 // Repack for return to caller.
1665 DDF ret=DDF(NULL).string(rsKey.c_str());
1666 DDFJanitor jret(ret);
1672 pair<bool,DOMElement*> XMLConfig::load()
1674 // Load from source using base class.
1675 pair<bool,DOMElement*> raw = ReloadableXMLFile::load();
1677 // If we own it, wrap it.
1678 XercesJanitor<DOMDocument> docjanitor(raw.first ? raw.second->getOwnerDocument() : NULL);
1680 XMLConfigImpl* impl = new XMLConfigImpl(raw.second,(m_impl==NULL),this,m_log);
1682 // If we held the document, transfer it to the impl. If we didn't, it's a no-op.
1683 impl->setDocument(docjanitor.release());
1688 return make_pair(false,(DOMElement*)NULL);