https://issues.shibboleth.net/jira/browse/SSPCPP-470
[shibboleth/cpp-sp.git] / shibsp / impl / XMLServiceProvider.cpp
1 /**
2  * Licensed to the University Corporation for Advanced Internet
3  * Development, Inc. (UCAID) under one or more contributor license
4  * agreements. See the NOTICE file distributed with this work for
5  * additional information regarding copyright ownership.
6  *
7  * UCAID licenses this file to you under the Apache License,
8  * Version 2.0 (the "License"); you may not use this file except
9  * in compliance with the License. You may obtain a copy of the
10  * License at
11  *
12  * http://www.apache.org/licenses/LICENSE-2.0
13  *
14  * Unless required by applicable law or agreed to in writing,
15  * software distributed under the License is distributed on an
16  * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
17  * either express or implied. See the License for the specific
18  * language governing permissions and limitations under the License.
19  */
20
21 /**
22  * XMLServiceProvider.cpp
23  *
24  * XML-based SP configuration and mgmt.
25  */
26
27 #include "internal.h"
28 #include "exceptions.h"
29 #include "version.h"
30 #include "AccessControl.h"
31 #include "Application.h"
32 #include "RequestMapper.h"
33 #include "ServiceProvider.h"
34 #include "SessionCache.h"
35 #include "SPConfig.h"
36 #include "SPRequest.h"
37 #include "binding/ProtocolProvider.h"
38 #include "handler/LogoutInitiator.h"
39 #include "handler/SessionInitiator.h"
40 #include "remoting/ListenerService.h"
41 #include "util/DOMPropertySet.h"
42 #include "util/SPConstants.h"
43
44 #if defined(XMLTOOLING_LOG4SHIB)
45 # include <log4shib/PropertyConfigurator.hh>
46 #elif defined(XMLTOOLING_LOG4CPP)
47 # include <log4cpp/PropertyConfigurator.hh>
48 #else
49 # error "Supported logging library not available."
50 #endif
51 #include <algorithm>
52 #include <boost/bind.hpp>
53 #include <boost/lexical_cast.hpp>
54 #include <boost/shared_ptr.hpp>
55 #include <boost/algorithm/string.hpp>
56 #include <boost/tuple/tuple.hpp>
57 #include <xercesc/util/XMLUniDefs.hpp>
58 #include <xercesc/util/XMLStringTokenizer.hpp>
59 #include <xmltooling/XMLToolingConfig.h>
60 #include <xmltooling/version.h>
61 #include <xmltooling/util/NDC.h>
62 #include <xmltooling/util/ReloadableXMLFile.h>
63 #include <xmltooling/util/TemplateEngine.h>
64 #include <xmltooling/util/Threads.h>
65 #include <xmltooling/util/XMLHelper.h>
66
67 #ifndef SHIBSP_LITE
68 # include "attribute/filtering/AttributeFilter.h"
69 # include "attribute/resolver/AttributeExtractor.h"
70 # include "attribute/resolver/AttributeResolver.h"
71 # include "security/PKIXTrustEngine.h"
72 # include "security/SecurityPolicyProvider.h"
73 # include <saml/exceptions.h>
74 # include <saml/version.h>
75 # include <saml/SAMLConfig.h>
76 # include <saml/binding/ArtifactMap.h>
77 # include <saml/binding/SAMLArtifact.h>
78 # include <saml/saml1/core/Assertions.h>
79 # include <saml/saml2/core/Assertions.h>
80 # include <saml/saml2/binding/SAML2ArtifactType0004.h>
81 # include <saml/saml2/metadata/EntityMatcher.h>
82 # include <saml/saml2/metadata/Metadata.h>
83 # include <saml/saml2/metadata/MetadataProvider.h>
84 # include <saml/util/SAMLConstants.h>
85 # include <xmltooling/security/ChainingTrustEngine.h>
86 # include <xmltooling/security/CredentialResolver.h>
87 # include <xmltooling/security/SecurityHelper.h>
88 # include <xmltooling/util/ReplayCache.h>
89 # include <xmltooling/util/StorageService.h>
90 # include <xsec/utils/XSECPlatformUtils.hpp>
91 using namespace opensaml::saml2;
92 using namespace opensaml::saml2p;
93 using namespace opensaml::saml2md;
94 using namespace opensaml;
95 #else
96 # include "lite/SAMLConstants.h"
97 #endif
98
99 using namespace shibsp;
100 using namespace xmltooling;
101 using namespace boost;
102 using namespace std;
103
104 #ifndef min
105 # define min(a,b)            (((a) < (b)) ? (a) : (b))
106 #endif
107
108 namespace {
109
110 #if defined (_MSC_VER)
111     #pragma warning( push )
112     #pragma warning( disable : 4250 )
113 #endif
114
115     static vector<const Handler*> g_noHandlers;
116
117     // Application configuration wrapper
118     class SHIBSP_DLLLOCAL XMLApplication : public Application, public Remoted, public DOMPropertySet, public DOMNodeFilter
119     {
120     public:
121         XMLApplication(const ServiceProvider*, const ProtocolProvider*, DOMElement*, const XMLApplication* base=nullptr);
122         ~XMLApplication();
123
124         const char* getHash() const {return m_hash.c_str();}
125
126 #ifndef SHIBSP_LITE
127         SAMLArtifact* generateSAML1Artifact(const EntityDescriptor* relyingParty) const {
128             throw ConfigurationException("No support for SAML 1.x artifact generation.");
129         }
130         SAML2Artifact* generateSAML2Artifact(const EntityDescriptor* relyingParty) const {
131             pair<bool,int> index = make_pair(false,0);
132             const PropertySet* props = getRelyingParty(relyingParty);
133             index = props->getInt("artifactEndpointIndex");
134             if (!index.first)
135                 index = getArtifactEndpointIndex();
136             pair<bool,const char*> entityID = props->getString("entityID");
137             return new SAML2ArtifactType0004(
138                 SecurityHelper::doHash("SHA1", entityID.second, strlen(entityID.second), false),
139                 index.first ? index.second : 1
140                 );
141         }
142
143         MetadataProvider* getMetadataProvider(bool required=true) const {
144             if (required && !m_base && !m_metadata)
145                 throw ConfigurationException("No MetadataProvider available.");
146             return (!m_metadata && m_base) ? m_base->getMetadataProvider(required) : m_metadata.get();
147         }
148         TrustEngine* getTrustEngine(bool required=true) const {
149             if (required && !m_base && !m_trust)
150                 throw ConfigurationException("No TrustEngine available.");
151             return (!m_trust && m_base) ? m_base->getTrustEngine(required) : m_trust.get();
152         }
153         AttributeExtractor* getAttributeExtractor() const {
154             return (!m_attrExtractor && m_base) ? m_base->getAttributeExtractor() : m_attrExtractor.get();
155         }
156         AttributeFilter* getAttributeFilter() const {
157             return (!m_attrFilter && m_base) ? m_base->getAttributeFilter() : m_attrFilter.get();
158         }
159         AttributeResolver* getAttributeResolver() const {
160             return (!m_attrResolver && m_base) ? m_base->getAttributeResolver() : m_attrResolver.get();
161         }
162         CredentialResolver* getCredentialResolver() const {
163             return (!m_credResolver && m_base) ? m_base->getCredentialResolver() : m_credResolver.get();
164         }
165         const PropertySet* getRelyingParty(const EntityDescriptor* provider) const;
166         const PropertySet* getRelyingParty(const XMLCh* entityID) const;
167
168         const vector<const XMLCh*>* getAudiences() const {
169             return (m_audiences.empty() && m_base) ? m_base->getAudiences() : &m_audiences;
170         }
171 #endif
172         string getNotificationURL(const char* resource, bool front, unsigned int index) const;
173
174         const vector<string>& getRemoteUserAttributeIds() const {
175             return (m_remoteUsers.empty() && m_base) ? m_base->getRemoteUserAttributeIds() : m_remoteUsers;
176         }
177
178         void clearHeader(SPRequest& request, const char* rawname, const char* cginame) const;
179         void setHeader(SPRequest& request, const char* name, const char* value) const;
180         string getSecureHeader(const SPRequest& request, const char* name) const;
181
182         const SessionInitiator* getDefaultSessionInitiator() const;
183         const SessionInitiator* getSessionInitiatorById(const char* id) const;
184         const Handler* getDefaultAssertionConsumerService() const;
185         const Handler* getAssertionConsumerServiceByIndex(unsigned short index) const;
186         const Handler* getAssertionConsumerServiceByProtocol(const XMLCh* protocol, const char* binding=nullptr) const;
187         const vector<const Handler*>& getAssertionConsumerServicesByBinding(const XMLCh* binding) const;
188         const Handler* getHandler(const char* path) const;
189         void getHandlers(vector<const Handler*>& handlers) const;
190         void limitRedirect(const GenericRequest& request, const char* url) const;
191
192         void receive(DDF& in, ostream& out) {
193             // Only current function is to return the headers to clear.
194             DDF header;
195             DDF ret=DDF(nullptr).list();
196             DDFJanitor jret(ret);
197             for (vector< pair<string,string> >::const_iterator i = m_unsetHeaders.begin(); i!=m_unsetHeaders.end(); ++i) {
198                 header = DDF(i->first.c_str()).string(i->second.c_str());
199                 ret.add(header);
200             }
201             out << ret;
202         }
203
204         // Provides filter to exclude special config elements.
205 #ifdef SHIBSP_XERCESC_SHORT_ACCEPTNODE
206         short
207 #else
208         FilterAction
209 #endif
210         acceptNode(const DOMNode* node) const;
211
212     private:
213         template <class T> T* doChainedPlugins(
214             PluginManager<T,string,const DOMElement*>& pluginMgr,
215             const char* pluginType,
216             const char* chainingType,
217             const XMLCh* localName,
218             DOMElement* e,
219             Category& log,
220             const char* dummyType=nullptr
221             );
222         void doAttributeInfo();
223         void doHandlers(const ProtocolProvider*, const DOMElement*, Category&);
224         void doSSO(const ProtocolProvider&, set<string>&, DOMElement*, Category&);
225         void doLogout(const ProtocolProvider&, set<string>&, DOMElement*, Category&);
226         void doNameIDMgmt(const ProtocolProvider&, set<string>&, DOMElement*, Category&);
227         void doArtifactResolution(const ProtocolProvider&, const char*, DOMElement*, Category&);
228         const XMLApplication* m_base;
229         string m_hash;
230         std::pair<std::string,std::string> m_attributePrefix;
231 #ifndef SHIBSP_LITE
232         void doAttributePlugins(DOMElement*, Category&);
233         scoped_ptr<MetadataProvider> m_metadata;
234         scoped_ptr<TrustEngine> m_trust;
235         scoped_ptr<AttributeExtractor> m_attrExtractor;
236         scoped_ptr<AttributeFilter> m_attrFilter;
237         scoped_ptr<AttributeResolver> m_attrResolver;
238         scoped_ptr<CredentialResolver> m_credResolver;
239         vector<const XMLCh*> m_audiences;
240
241         // RelyingParty properties
242         map< xstring,boost::shared_ptr<PropertySet> > m_partyMap;   // name-based matching
243         vector< pair< boost::shared_ptr<EntityMatcher>,boost::shared_ptr<PropertySet> > > m_partyVec;  // plugin-based matching
244 #endif
245         vector<string> m_remoteUsers,m_frontLogout,m_backLogout;
246
247         // manage handler objects
248         vector< boost::shared_ptr<Handler> > m_handlers;
249
250         // maps location (path info) to applicable handlers
251         map<string,const Handler*> m_handlerMap;
252
253         // maps unique indexes to consumer services
254         map<unsigned int,const Handler*> m_acsIndexMap;
255
256         // pointer to default consumer service
257         const Handler* m_acsDefault;
258
259         // maps binding strings to supporting consumer service(s)
260         typedef map< xstring,vector<const Handler*> > ACSBindingMap;
261         ACSBindingMap m_acsBindingMap;
262
263         // maps protocol strings to supporting consumer service(s)
264         typedef map< xstring,vector<const Handler*> > ACSProtocolMap;
265         ACSProtocolMap m_acsProtocolMap;
266
267         // pointer to default session initiator
268         const SessionInitiator* m_sessionInitDefault;
269
270         // maps unique ID strings to session initiators
271         map<string,const SessionInitiator*> m_sessionInitMap;
272
273         // pointer to default artifact resolution service
274         const Handler* m_artifactResolutionDefault;
275
276         pair<bool,int> getArtifactEndpointIndex() const {
277             if (m_artifactResolutionDefault) return m_artifactResolutionDefault->getInt("index");
278             return m_base ? m_base->getArtifactEndpointIndex() : make_pair(false,0);
279         }
280
281         enum {
282             REDIRECT_LIMIT_INHERIT,
283             REDIRECT_LIMIT_NONE,
284             REDIRECT_LIMIT_EXACT,
285             REDIRECT_LIMIT_HOST,
286             REDIRECT_LIMIT_WHITELIST,
287             REDIRECT_LIMIT_EXACT_WHITELIST,
288             REDIRECT_LIMIT_HOST_WHITELIST
289         } m_redirectLimit;
290         vector<string> m_redirectWhitelist;
291     };
292
293     // Top-level configuration implementation
294     class SHIBSP_DLLLOCAL XMLConfig;
295     class SHIBSP_DLLLOCAL XMLConfigImpl : public DOMPropertySet, public DOMNodeFilter
296     {
297     public:
298         XMLConfigImpl(const DOMElement* e, bool first, XMLConfig* outer, Category& log);
299         ~XMLConfigImpl() {
300             if (m_document)
301                 m_document->release();
302         }
303
304 #ifndef SHIBSP_LITE
305         scoped_ptr<TransactionLog> m_tranLog;
306         scoped_ptr<SecurityPolicyProvider> m_policy;
307         vector< tuple<string,string,string> > m_transportOptions;
308 #endif
309         scoped_ptr<RequestMapper> m_requestMapper;
310         map< string,boost::shared_ptr<Application> > m_appmap;
311
312         // Provides filter to exclude special config elements.
313 #ifdef SHIBSP_XERCESC_SHORT_ACCEPTNODE
314         short
315 #else
316         FilterAction
317 #endif
318         acceptNode(const DOMNode* node) const;
319
320         void setDocument(DOMDocument* doc) {
321             m_document = doc;
322         }
323
324     private:
325         void doExtensions(const DOMElement*, const char*, Category&);
326         void doListener(const DOMElement*, XMLConfig*, Category&);
327         void doCaching(const DOMElement*, XMLConfig*, Category&);
328
329         DOMDocument* m_document;
330     };
331
332     class SHIBSP_DLLLOCAL XMLConfig : public ServiceProvider, public ReloadableXMLFile
333 #ifndef SHIBSP_LITE
334         ,public Remoted
335 #endif
336     {
337     public:
338         XMLConfig(const DOMElement* e) : ReloadableXMLFile(e, Category::getInstance(SHIBSP_LOGCAT".Config")) {}
339
340         void init() {
341             background_load();
342         }
343
344         ~XMLConfig() {
345             shutdown();
346 #ifndef SHIBSP_LITE
347             SAMLConfig::getConfig().setArtifactMap(nullptr);
348             XMLToolingConfig::getConfig().setReplayCache(nullptr);
349 #endif
350         }
351
352 #ifndef SHIBSP_LITE
353         // Lockable
354         Lockable* lock() {
355             ReloadableXMLFile::lock();
356             if (m_impl->m_policy)
357                 m_impl->m_policy->lock();
358             return this;
359         }
360         void unlock() {
361             if (m_impl->m_policy)
362                 m_impl->m_policy->unlock();
363             ReloadableXMLFile::unlock();
364         }
365 #endif
366
367         // PropertySet
368         const PropertySet* getParent() const { return m_impl->getParent(); }
369         void setParent(const PropertySet* parent) {return m_impl->setParent(parent);}
370         pair<bool,bool> getBool(const char* name, const char* ns=nullptr) const {return m_impl->getBool(name,ns);}
371         pair<bool,const char*> getString(const char* name, const char* ns=nullptr) const {return m_impl->getString(name,ns);}
372         pair<bool,const XMLCh*> getXMLString(const char* name, const char* ns=nullptr) const {return m_impl->getXMLString(name,ns);}
373         pair<bool,unsigned int> getUnsignedInt(const char* name, const char* ns=nullptr) const {return m_impl->getUnsignedInt(name,ns);}
374         pair<bool,int> getInt(const char* name, const char* ns=nullptr) const {return m_impl->getInt(name,ns);}
375         void getAll(map<string,const char*>& properties) const {return m_impl->getAll(properties);}
376         const PropertySet* getPropertySet(const char* name, const char* ns="urn:mace:shibboleth:2.0:native:sp:config") const {return m_impl->getPropertySet(name,ns);}
377         const DOMElement* getElement() const {return m_impl->getElement();}
378
379         // ServiceProvider
380 #ifndef SHIBSP_LITE
381         // Remoted
382         void receive(DDF& in, ostream& out);
383
384         TransactionLog* getTransactionLog() const {
385             if (m_impl->m_tranLog)
386                 return m_impl->m_tranLog.get();
387             throw ConfigurationException("No TransactionLog available.");
388         }
389
390         StorageService* getStorageService(const char* id) const {
391             if (id) {
392                 map< string,boost::shared_ptr<StorageService> >::const_iterator i = m_storage.find(id);
393                 if (i != m_storage.end())
394                     return i->second.get();
395             }
396             else if (!m_storage.empty())
397                 return m_storage.begin()->second.get();
398             return nullptr;
399         }
400 #endif
401
402         ListenerService* getListenerService(bool required=true) const {
403             if (required && !m_listener)
404                 throw ConfigurationException("No ListenerService available.");
405             return m_listener.get();
406         }
407
408         SessionCache* getSessionCache(bool required=true) const {
409             if (required && !m_sessionCache)
410                 throw ConfigurationException("No SessionCache available.");
411             return m_sessionCache.get();
412         }
413
414         RequestMapper* getRequestMapper(bool required=true) const {
415             if (required && !m_impl->m_requestMapper)
416                 throw ConfigurationException("No RequestMapper available.");
417             return m_impl->m_requestMapper.get();
418         }
419
420         const Application* getApplication(const char* applicationId) const {
421             map< string,boost::shared_ptr<Application> >::const_iterator i = m_impl->m_appmap.find(applicationId ? applicationId : "default");
422             return (i != m_impl->m_appmap.end()) ? i->second.get() : nullptr;
423         }
424
425 #ifndef SHIBSP_LITE
426         SecurityPolicyProvider* getSecurityPolicyProvider(bool required=true) const {
427             if (required && !m_impl->m_policy)
428                 throw ConfigurationException("No SecurityPolicyProvider available.");
429             return m_impl->m_policy.get();
430         }
431
432         const PropertySet* getPolicySettings(const char* id) const {
433             return getSecurityPolicyProvider()->getPolicySettings(id);
434         }
435
436         const vector<const SecurityPolicyRule*>& getPolicyRules(const char* id) const {
437             return getSecurityPolicyProvider()->getPolicyRules(id);
438         }
439
440         bool setTransportOptions(SOAPTransport& transport) const {
441             bool ret = true;
442             for (vector< tuple<string,string,string> >::const_iterator opt = m_impl->m_transportOptions.begin();
443                     opt != m_impl->m_transportOptions.end(); ++opt) {
444                 if (!transport.setProviderOption(opt->get<0>().c_str(), opt->get<1>().c_str(), opt->get<2>().c_str())) {
445                     m_log.error("failed to set SOAPTransport option (%s)", opt->get<1>().c_str());
446                     ret = false;
447                 }
448             }
449             return ret;
450         }
451 #endif
452
453     protected:
454         pair<bool,DOMElement*> background_load();
455
456     private:
457         friend class XMLConfigImpl;
458         // The order of these members actually matters. If we want to rely on auto-destruction, then
459         // anything dependent on anything else has to come later in the object so it will pop first.
460         // Storage is the lowest, then remoting, then the cache, and finally the rest.
461 #ifndef SHIBSP_LITE
462         map< string,boost::shared_ptr<StorageService> > m_storage;
463 #endif
464         scoped_ptr<ListenerService> m_listener;
465         scoped_ptr<SessionCache> m_sessionCache;
466         scoped_ptr<XMLConfigImpl> m_impl;
467     };
468
469 #if defined (_MSC_VER)
470     #pragma warning( pop )
471 #endif
472
473     static const XMLCh applicationId[] =        UNICODE_LITERAL_13(a,p,p,l,i,c,a,t,i,o,n,I,d);
474     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);
475     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);
476     static const XMLCh _ArtifactMap[] =         UNICODE_LITERAL_11(A,r,t,i,f,a,c,t,M,a,p);
477     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);
478     static const XMLCh _AttributeFilter[] =     UNICODE_LITERAL_15(A,t,t,r,i,b,u,t,e,F,i,l,t,e,r);
479     static const XMLCh _AttributeResolver[] =   UNICODE_LITERAL_17(A,t,t,r,i,b,u,t,e,R,e,s,o,l,v,e,r);
480     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);
481     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);
482     static const XMLCh _Audience[] =            UNICODE_LITERAL_8(A,u,d,i,e,n,c,e);
483     static const XMLCh Binding[] =              UNICODE_LITERAL_7(B,i,n,d,i,n,g);
484     static const XMLCh Channel[]=               UNICODE_LITERAL_7(C,h,a,n,n,e,l);
485     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);
486     static const XMLCh _default[] =             UNICODE_LITERAL_7(d,e,f,a,u,l,t);
487     static const XMLCh _Extensions[] =          UNICODE_LITERAL_10(E,x,t,e,n,s,i,o,n,s);
488     static const XMLCh _fatal[] =               UNICODE_LITERAL_5(f,a,t,a,l);
489     static const XMLCh _Handler[] =             UNICODE_LITERAL_7(H,a,n,d,l,e,r);
490     static const XMLCh _id[] =                  UNICODE_LITERAL_2(i,d);
491     static const XMLCh _index[] =               UNICODE_LITERAL_5(i,n,d,e,x);
492     static const XMLCh InProcess[] =            UNICODE_LITERAL_9(I,n,P,r,o,c,e,s,s);
493     static const XMLCh Library[] =              UNICODE_LITERAL_7(L,i,b,r,a,r,y);
494     static const XMLCh Listener[] =             UNICODE_LITERAL_8(L,i,s,t,e,n,e,r);
495     static const XMLCh Location[] =             UNICODE_LITERAL_8(L,o,c,a,t,i,o,n);
496     static const XMLCh logger[] =               UNICODE_LITERAL_6(l,o,g,g,e,r);
497     static const XMLCh Logout[] =               UNICODE_LITERAL_6(L,o,g,o,u,t);
498     static const XMLCh _LogoutInitiator[] =     UNICODE_LITERAL_15(L,o,g,o,u,t,I,n,i,t,i,a,t,o,r);
499     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);
500     static const XMLCh _MetadataProvider[] =    UNICODE_LITERAL_16(M,e,t,a,d,a,t,a,P,r,o,v,i,d,e,r);
501     static const XMLCh NameIDMgmt[] =           UNICODE_LITERAL_10(N,a,m,e,I,D,M,g,m,t);
502     static const XMLCh Notify[] =               UNICODE_LITERAL_6(N,o,t,i,f,y);
503     static const XMLCh _option[] =              UNICODE_LITERAL_6(o,p,t,i,o,n);
504     static const XMLCh OutOfProcess[] =         UNICODE_LITERAL_12(O,u,t,O,f,P,r,o,c,e,s,s);
505     static const XMLCh _path[] =                UNICODE_LITERAL_4(p,a,t,h);
506     static const XMLCh _ProtocolProvider[] =    UNICODE_LITERAL_16(P,r,o,t,o,c,o,l,P,r,o,v,i,d,e,r);
507     static const XMLCh _provider[] =            UNICODE_LITERAL_8(p,r,o,v,i,d,e,r);
508     static const XMLCh RelyingParty[] =         UNICODE_LITERAL_12(R,e,l,y,i,n,g,P,a,r,t,y);
509     static const XMLCh _ReplayCache[] =         UNICODE_LITERAL_11(R,e,p,l,a,y,C,a,c,h,e);
510     static const XMLCh _RequestMapper[] =       UNICODE_LITERAL_13(R,e,q,u,e,s,t,M,a,p,p,e,r);
511     static const XMLCh RequestMap[] =           UNICODE_LITERAL_10(R,e,q,u,e,s,t,M,a,p);
512     static const XMLCh SecurityPolicies[] =     UNICODE_LITERAL_16(S,e,c,u,r,i,t,y,P,o,l,i,c,i,e,s);
513     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);
514     static const XMLCh _SessionCache[] =        UNICODE_LITERAL_12(S,e,s,s,i,o,n,C,a,c,h,e);
515     static const XMLCh _SessionInitiator[] =    UNICODE_LITERAL_16(S,e,s,s,i,o,n,I,n,i,t,i,a,t,o,r);
516     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);
517     static const XMLCh Site[] =                 UNICODE_LITERAL_4(S,i,t,e);
518     static const XMLCh SSO[] =                  UNICODE_LITERAL_3(S,S,O);
519     static const XMLCh _StorageService[] =      UNICODE_LITERAL_14(S,t,o,r,a,g,e,S,e,r,v,i,c,e);
520     static const XMLCh TCPListener[] =          UNICODE_LITERAL_11(T,C,P,L,i,s,t,e,n,e,r);
521     static const XMLCh tranLogFiller[] =        UNICODE_LITERAL_13(t,r,a,n,L,o,g,F,i,l,l,e,r);
522     static const XMLCh tranLogFormat[] =        UNICODE_LITERAL_13(t,r,a,n,L,o,g,F,o,r,m,a,t);
523     static const XMLCh TransportOption[] =      UNICODE_LITERAL_15(T,r,a,n,s,p,o,r,t,O,p,t,i,o,n);
524     static const XMLCh _TrustEngine[] =         UNICODE_LITERAL_11(T,r,u,s,t,E,n,g,i,n,e);
525     static const XMLCh _type[] =                UNICODE_LITERAL_4(t,y,p,e);
526     static const XMLCh UnixListener[] =         UNICODE_LITERAL_12(U,n,i,x,L,i,s,t,e,n,e,r);
527 };
528
529 namespace shibsp {
530     ServiceProvider* XMLServiceProviderFactory(const DOMElement* const & e)
531     {
532         return new XMLConfig(e);
533     }
534 };
535
536 XMLApplication::XMLApplication(
537     const ServiceProvider* sp,
538     const ProtocolProvider* pp,
539     DOMElement* e,
540     const XMLApplication* base
541     ) : Application(sp), m_base(base), m_acsDefault(nullptr), m_sessionInitDefault(nullptr), m_artifactResolutionDefault(nullptr)
542 {
543 #ifdef _DEBUG
544     xmltooling::NDC ndc("XMLApplication");
545 #endif
546     Category& log = Category::getInstance(SHIBSP_LOGCAT".Application");
547
548     // First load any property sets.
549     map<string,string> remapper;
550     remapper["relayStateLimit"] = "redirectLimit";
551     remapper["relayStateWhitelist"] = "redirectWhitelist";
552     load(e, nullptr, this, &remapper);
553
554     // Process redirect limit policy. Do this before assigning the parent pointer
555     // to ensure we get only our Sessions element.
556     const PropertySet* sessionProps = getPropertySet("Sessions");
557     if (sessionProps) {
558         pair<bool,const char*> prop = sessionProps->getString("redirectLimit");
559         if (prop.first) {
560             if (!strcmp(prop.second, "none"))
561                 m_redirectLimit = REDIRECT_LIMIT_NONE;
562             else if (!strcmp(prop.second, "exact"))
563                 m_redirectLimit = REDIRECT_LIMIT_EXACT;
564             else if (!strcmp(prop.second, "host"))
565                 m_redirectLimit = REDIRECT_LIMIT_HOST;
566             else {
567                 if (!strcmp(prop.second, "exact+whitelist"))
568                     m_redirectLimit = REDIRECT_LIMIT_EXACT_WHITELIST;
569                 else if (!strcmp(prop.second, "host+whitelist"))
570                     m_redirectLimit = REDIRECT_LIMIT_HOST_WHITELIST;
571                 else if (!strcmp(prop.second, "whitelist"))
572                     m_redirectLimit = REDIRECT_LIMIT_WHITELIST;
573                 else
574                     throw ConfigurationException("Unrecognized redirectLimit setting ($1)", params(1, prop.second));
575                 prop = sessionProps->getString("redirectWhitelist");
576                 if (prop.first) {
577                     string dup(prop.second);
578                     split(m_redirectWhitelist, dup, is_space(), algorithm::token_compress_on);
579                 }
580             }
581         }
582         else {
583             m_redirectLimit = base ? REDIRECT_LIMIT_INHERIT : REDIRECT_LIMIT_NONE;
584         }
585
586         // Audit some additional settings for logging purposes.
587         prop = sessionProps->getString("cookieProps");
588         if (!prop.first) {
589             log.warn("empty/missing cookieProps setting, set to \"https\" for SSL/TLS-only usage");
590         }
591         else if (!strcmp(prop.second, "http")) {
592             log.warn("insecure cookieProps setting, set to \"https\" for SSL/TLS-only usage");
593         }
594         else if (strcmp(prop.second, "https")) {
595             if (!strstr(prop.second, ";secure") && !strstr(prop.second, "; secure"))
596                 log.warn("custom cookieProps setting should include \"; secure\" for SSL/TLS-only usage");
597             else if (!strstr(prop.second, ";HttpOnly") && !strstr(prop.second, "; HttpOnly"))
598                 log.warn("custom cookieProps setting should include \"; HttpOnly\", site is vulnerable to client-side cookie theft");
599         }
600
601         pair<bool,bool> handlerSSL = sessionProps->getBool("handlerSSL");
602         if (handlerSSL.first && !handlerSSL.second)
603             log.warn("handlerSSL should be enabled for SSL/TLS-enabled web sites");
604     }
605     else {
606         m_redirectLimit = base ? REDIRECT_LIMIT_INHERIT : REDIRECT_LIMIT_NONE;
607     }
608
609     // Assign parent.
610     if (base)
611         setParent(base);
612
613     SPConfig& conf=SPConfig::getConfig();
614 #ifndef SHIBSP_LITE
615     XMLToolingConfig& xmlConf=XMLToolingConfig::getConfig();
616 #endif
617
618     // This used to be an actual hash, but now it's just a hex-encode to avoid xmlsec dependency.
619     static char DIGITS[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
620     string tohash=getId();
621     tohash+=getString("entityID").second;
622     for (const char* ch = tohash.c_str(); *ch; ++ch) {
623         m_hash += (DIGITS[((unsigned char)(0xF0 & *ch)) >> 4 ]);
624         m_hash += (DIGITS[0x0F & *ch]);
625     }
626
627     doAttributeInfo();
628
629     if (conf.isEnabled(SPConfig::Handlers))
630         doHandlers(pp, e, log);
631
632     // Notification.
633     DOMNodeList* nlist = e->getElementsByTagNameNS(shibspconstants::SHIB2SPCONFIG_NS, Notify);
634     for (XMLSize_t i = 0; nlist && i < nlist->getLength(); ++i) {
635         if (nlist->item(i)->getParentNode()->isSameNode(e)) {
636             const XMLCh* channel = static_cast<DOMElement*>(nlist->item(i))->getAttributeNS(nullptr, Channel);
637             string loc(XMLHelper::getAttrString(static_cast<DOMElement*>(nlist->item(i)), nullptr, Location));
638             if (!loc.empty()) {
639                 if (channel && *channel == chLatin_f)
640                     m_frontLogout.push_back(loc);
641                 else
642                     m_backLogout.push_back(loc);
643             }
644         }
645     }
646
647 #ifndef SHIBSP_LITE
648     nlist = e->getElementsByTagNameNS(samlconstants::SAML20_NS, Audience::LOCAL_NAME);
649     if (nlist && nlist->getLength()) {
650         log.warn("use of <saml:Audience> elements outside of a Security Policy Rule is deprecated");
651         for (XMLSize_t i = 0; i < nlist->getLength(); ++i)
652             if (nlist->item(i)->getParentNode()->isSameNode(e) && nlist->item(i)->hasChildNodes())
653                 m_audiences.push_back(nlist->item(i)->getFirstChild()->getNodeValue());
654     }
655
656     if (conf.isEnabled(SPConfig::Metadata)) {
657         m_metadata.reset(
658             doChainedPlugins(
659                 SAMLConfig::getConfig().MetadataProviderManager, "MetadataProvider", CHAINING_METADATA_PROVIDER, _MetadataProvider, e, log
660                 )
661             );
662         try {
663             if (m_metadata)
664                 m_metadata->init();
665             else if (!m_base)
666                 log.warn("no MetadataProvider available, configure at least one for standard SSO usage");
667         }
668         catch (std::exception& ex) {
669             log.crit("error initializing MetadataProvider: %s", ex.what());
670         }
671     }
672
673     if (conf.isEnabled(SPConfig::Trust)) {
674         m_trust.reset(doChainedPlugins(xmlConf.TrustEngineManager, "TrustEngine", CHAINING_TRUSTENGINE, _TrustEngine, e, log));
675         if (!m_trust && !m_base) {
676             log.info(
677                 "no TrustEngine specified or installed, using default chain {%s, %s}",
678                 EXPLICIT_KEY_TRUSTENGINE, SHIBBOLETH_PKIX_TRUSTENGINE
679                 );
680             m_trust.reset(xmlConf.TrustEngineManager.newPlugin(CHAINING_TRUSTENGINE, nullptr));
681             ChainingTrustEngine* trustchain = dynamic_cast<ChainingTrustEngine*>(m_trust.get());
682             if (trustchain) {
683                 trustchain->addTrustEngine(xmlConf.TrustEngineManager.newPlugin(EXPLICIT_KEY_TRUSTENGINE, nullptr));
684                 trustchain->addTrustEngine(xmlConf.TrustEngineManager.newPlugin(SHIBBOLETH_PKIX_TRUSTENGINE, nullptr));
685             }
686         }
687     }
688
689     if (conf.isEnabled(SPConfig::AttributeResolution)) {
690         doAttributePlugins(e, log);
691     }
692
693     if (conf.isEnabled(SPConfig::Credentials)) {
694         m_credResolver.reset(
695             doChainedPlugins(xmlConf.CredentialResolverManager, "CredentialResolver", CHAINING_CREDENTIAL_RESOLVER, _CredentialResolver, e, log)
696             );
697     }
698
699     // Finally, load relying parties.
700     const DOMElement* child = XMLHelper::getFirstChildElement(e, RelyingParty);
701     while (child) {
702         if (child->hasAttributeNS(nullptr, saml2::Attribute::NAME_ATTRIB_NAME)) {
703             boost::shared_ptr<DOMPropertySet> rp(new DOMPropertySet());
704             rp->load(child, nullptr, this);
705             rp->setParent(this);
706             m_partyMap[child->getAttributeNS(nullptr, saml2::Attribute::NAME_ATTRIB_NAME)] = rp;
707         }
708         else if (child->hasAttributeNS(nullptr, _type)) {
709             string emtype(XMLHelper::getAttrString(child, nullptr, _type));
710             boost::shared_ptr<EntityMatcher> em(SAMLConfig::getConfig().EntityMatcherManager.newPlugin(emtype, child));
711             boost::shared_ptr<DOMPropertySet> rp(new DOMPropertySet());
712             rp->load(child, nullptr, this);
713             rp->setParent(this);
714             m_partyVec.push_back(make_pair(em, rp));
715         }
716         child = XMLHelper::getNextSiblingElement(child, RelyingParty);
717     }
718     if (base && m_partyMap.empty() && m_partyVec.empty() && (!base->m_partyMap.empty() || !base->m_partyVec.empty())) {
719         // For inheritance of RPs to work, we have to pull them in to the override by cloning the DOM.
720         child = XMLHelper::getFirstChildElement(base->getElement(), RelyingParty);
721         while (child) {
722             if (child->hasAttributeNS(nullptr, saml2::Attribute::NAME_ATTRIB_NAME)) {
723                 DOMElement* rpclone = static_cast<DOMElement*>(child->cloneNode(true));
724                 boost::shared_ptr<DOMPropertySet> rp(new DOMPropertySet());
725                 rp->load(rpclone, nullptr, this);
726                 rp->setParent(this);
727                 m_partyMap[rpclone->getAttributeNS(nullptr, saml2::Attribute::NAME_ATTRIB_NAME)] = rp;
728             }
729             else if (child->hasAttributeNS(nullptr, _type)) {
730                 DOMElement* rpclone = static_cast<DOMElement*>(child->cloneNode(true));
731                 string emtype(XMLHelper::getAttrString(rpclone, nullptr, _type));
732                 boost::shared_ptr<EntityMatcher> em(SAMLConfig::getConfig().EntityMatcherManager.newPlugin(emtype, rpclone));
733                 boost::shared_ptr<DOMPropertySet> rp(new DOMPropertySet());
734                 rp->load(rpclone, nullptr, this);
735                 rp->setParent(this);
736                 m_partyVec.push_back(make_pair(em, rp));
737             }
738             child = XMLHelper::getNextSiblingElement(child, RelyingParty);
739         }
740     }
741 #endif
742
743     // Out of process only, we register a listener endpoint.
744     if (!conf.isEnabled(SPConfig::InProcess)) {
745         ListenerService* listener = sp->getListenerService(false);
746         if (listener) {
747             string addr=string(getId()) + "::getHeaders::Application";
748             listener->regListener(addr.c_str(), this);
749         }
750         else {
751             log.info("no ListenerService available, Application remoting disabled");
752         }
753     }
754 }
755
756 XMLApplication::~XMLApplication()
757 {
758     ListenerService* listener=getServiceProvider().getListenerService(false);
759     if (listener && SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess) && !SPConfig::getConfig().isEnabled(SPConfig::InProcess)) {
760         string addr=string(getId()) + "::getHeaders::Application";
761         listener->unregListener(addr.c_str(), this);
762     }
763 }
764
765 template <class T> T* XMLApplication::doChainedPlugins(
766     PluginManager<T,string,const DOMElement*>& pluginMgr,
767     const char* pluginType,
768     const char* chainingType,
769     const XMLCh* localName,
770     DOMElement* e,
771     Category& log,
772     const char* dummyType
773     )
774 {
775     string t;
776     DOMElement* child = XMLHelper::getFirstChildElement(e, localName);
777     if (child) {
778         // Check for multiple.
779         if (XMLHelper::getNextSiblingElement(child, localName)) {
780             log.info("multiple %s plugins, wrapping in a chain", pluginType);
781             DOMElement* chain = child->getOwnerDocument()->createElementNS(nullptr, localName);
782             while (child) {
783                 chain->appendChild(child);
784                 child = XMLHelper::getFirstChildElement(e, localName);
785             }
786             t = chainingType;
787             child = chain;
788             e->appendChild(chain);
789         }
790         else {
791             // Only a single one.
792             t = XMLHelper::getAttrString(child, nullptr, _type);
793         }
794
795         try {
796             if (!t.empty()) {
797                 log.info("building %s of type %s...", pluginType, t.c_str());
798                 return pluginMgr.newPlugin(t.c_str(), child);
799             }
800             else {
801                 throw ConfigurationException("$1 element had no type attribute.", params(1, pluginType));
802             }
803         }
804         catch (std::exception& ex) {
805             log.crit("error building %s: %s", pluginType, ex.what());
806             if (dummyType) {
807                 // Install a dummy version as a safety valve.
808                 log.crit("installing safe %s in place of failed version", pluginType);
809                 return pluginMgr.newPlugin(dummyType, nullptr);
810             }
811         }
812     }
813
814     return nullptr;
815 }
816
817 void XMLApplication::doAttributeInfo()
818 {
819     // Populate prefix pair.
820     m_attributePrefix.second = "HTTP_";
821     pair<bool,const char*> prefix = getString("attributePrefix");
822     if (prefix.first) {
823         m_attributePrefix.first = prefix.second;
824         const char* pch = prefix.second;
825         while (*pch) {
826             m_attributePrefix.second += (isalnum(*pch) ? toupper(*pch) : '_');
827             pch++;
828         }
829     }
830
831     pair<bool,const char*> attributes = getString("REMOTE_USER");
832     if (attributes.first) {
833         string dup(attributes.second);
834         split(m_remoteUsers, dup, is_space(), algorithm::token_compress_on);
835     }
836
837     // Load attribute ID lists for REMOTE_USER and header clearing.
838     if (SPConfig::getConfig().isEnabled(SPConfig::InProcess)) {
839         attributes = getString("unsetHeaders");
840         if (attributes.first) {
841             string transformedprefix(m_attributePrefix.second);
842             const char* pch;
843             prefix = getString("metadataAttributePrefix");
844             if (prefix.first) {
845                 pch = prefix.second;
846                 while (*pch) {
847                     transformedprefix += (isalnum(*pch) ? toupper(*pch) : '_');
848                     pch++;
849                 }
850             }
851
852             string dup(attributes.second);
853             vector<string> headerNames;
854             split(headerNames, dup, is_space(), algorithm::token_compress_on);
855             for (vector<string>::const_iterator h = headerNames.begin(); h != headerNames.end(); ++h) {
856                 string transformed;
857                 const char* pch = h->c_str();
858                 while (*pch) {
859                     transformed += (isalnum(*pch) ? toupper(*pch) : '_');
860                     pch++;
861                 }
862                 m_unsetHeaders.push_back(pair<string,string>(m_attributePrefix.first + *h, m_attributePrefix.second + transformed));
863                 if (prefix.first)
864                     m_unsetHeaders.push_back(pair<string,string>(m_attributePrefix.first + prefix.second + *h, transformedprefix + transformed));
865             }
866             m_unsetHeaders.push_back(pair<string,string>(m_attributePrefix.first + "Shib-Application-ID", m_attributePrefix.second + "SHIB_APPLICATION_ID"));
867         }
868     }
869 }
870
871 void XMLApplication::doHandlers(const ProtocolProvider* pp, const DOMElement* e, Category& log)
872 {
873     SPConfig& conf = SPConfig::getConfig();
874
875     const PropertySet* sessions = getPropertySet("Sessions");
876
877     // Process assertion export handler.
878     pair<bool,const char*> location = sessions ? sessions->getString("exportLocation") : pair<bool,const char*>(false,nullptr);
879     if (location.first) {
880         try {
881             DOMElement* exportElement = e->getOwnerDocument()->createElementNS(shibspconstants::SHIB2SPCONFIG_NS, _Handler);
882             exportElement->setAttributeNS(nullptr,Location,sessions->getXMLString("exportLocation").second);
883             pair<bool,const XMLCh*> exportACL = sessions->getXMLString("exportACL");
884             if (exportACL.first) {
885                 static const XMLCh _acl[] = UNICODE_LITERAL_9(e,x,p,o,r,t,A,C,L);
886                 exportElement->setAttributeNS(nullptr,_acl,exportACL.second);
887             }
888             boost::shared_ptr<Handler> exportHandler(
889                 conf.HandlerManager.newPlugin(samlconstants::SAML20_BINDING_URI, pair<const DOMElement*,const char*>(exportElement, getId()))
890                 );
891             m_handlers.push_back(exportHandler);
892
893             // Insert into location map. If it contains the handlerURL, we skip past that part.
894             const char* hurl = sessions->getString("handlerURL").second;
895             if (!hurl)
896                 hurl = "/Shibboleth.sso";
897             const char* pch = strstr(location.second, hurl);
898             if (pch)
899                 location.second = pch + strlen(hurl);
900             if (*location.second == '/')
901                 m_handlerMap[location.second] = exportHandler.get();
902             else
903                 m_handlerMap[string("/") + location.second] = exportHandler.get();
904         }
905         catch (std::exception& ex) {
906             log.error("caught exception installing assertion lookup handler: %s", ex.what());
907         }
908     }
909
910     // Look for "shorthand" elements first.
911     set<string> protocols;
912     DOMElement* child = sessions ? XMLHelper::getFirstChildElement(sessions->getElement()) : nullptr;
913     while (child) {
914         if (XMLHelper::isNodeNamed(child, shibspconstants::SHIB2SPCONFIG_NS, SSO)) {
915             if (pp)
916                 doSSO(*pp, protocols, child, log);
917             else
918                 log.error("no ProtocolProvider, SSO auto-configure unsupported");
919         }
920         else if (XMLHelper::isNodeNamed(child, shibspconstants::SHIB2SPCONFIG_NS, Logout)) {
921             if (pp)
922                 doLogout(*pp, protocols, child, log);
923             else
924                 log.error("no ProtocolProvider, Logout auto-configure unsupported");
925         }
926         else if (XMLHelper::isNodeNamed(child, shibspconstants::SHIB2SPCONFIG_NS, NameIDMgmt)) {
927             if (pp)
928                 doNameIDMgmt(*pp, protocols, child, log);
929             else
930                 log.error("no ProtocolProvider, NameIDMgmt auto-configure unsupported");
931         }
932         else {
933             break;  // drop into next while loop
934         }
935         child = XMLHelper::getNextSiblingElement(child);
936     }
937
938     // Process other handlers.
939     bool hardACS=false, hardSessionInit=false, hardArt=false;
940     while (child) {
941         if (!child->hasAttributeNS(nullptr, Location)) {
942             auto_ptr_char hclass(child->getLocalName());
943             log.error("%s handler with no Location property cannot be processed", hclass.get());
944             child = XMLHelper::getNextSiblingElement(child);
945             continue;
946         }
947         try {
948             boost::shared_ptr<Handler> handler;
949             if (XMLString::equals(child->getLocalName(), _AssertionConsumerService)) {
950                 string bindprop(XMLHelper::getAttrString(child, nullptr, Binding));
951                 if (bindprop.empty()) {
952                     log.error("AssertionConsumerService element has no Binding attribute, skipping it...");
953                     child = XMLHelper::getNextSiblingElement(child);
954                     continue;
955                 }
956                 handler.reset(conf.AssertionConsumerServiceManager.newPlugin(bindprop.c_str(), pair<const DOMElement*,const char*>(child, getId())));
957                 // Map by binding and protocol (may be > 1 per protocol and binding)
958                 m_acsBindingMap[handler->getXMLString("Binding").second].push_back(handler.get());
959                 const XMLCh* protfamily = handler->getProtocolFamily();
960                 if (protfamily)
961                     m_acsProtocolMap[protfamily].push_back(handler.get());
962                 m_acsIndexMap[handler->getUnsignedInt("index").second] = handler.get();
963
964                 if (!hardACS) {
965                     pair<bool,bool> defprop = handler->getBool("isDefault");
966                     if (defprop.first) {
967                         if (defprop.second) {
968                             hardACS = true;
969                             m_acsDefault = handler.get();
970                         }
971                     }
972                     else if (!m_acsDefault)
973                         m_acsDefault = handler.get();
974                 }
975             }
976             else if (XMLString::equals(child->getLocalName(), _SessionInitiator)) {
977                 string t(XMLHelper::getAttrString(child, nullptr, _type));
978                 if (t.empty()) {
979                     log.error("SessionInitiator element has no type attribute, skipping it...");
980                     child = XMLHelper::getNextSiblingElement(child);
981                     continue;
982                 }
983                 boost::shared_ptr<SessionInitiator> sihandler(
984                     conf.SessionInitiatorManager.newPlugin(t.c_str(), pair<const DOMElement*,const char*>(child, getId()))
985                     );
986                 handler = sihandler;
987                 pair<bool,const char*> si_id = handler->getString("id");
988                 if (si_id.first && si_id.second)
989                     m_sessionInitMap[si_id.second] = sihandler.get();
990                 if (!hardSessionInit) {
991                     pair<bool,bool> defprop = handler->getBool("isDefault");
992                     if (defprop.first) {
993                         if (defprop.second) {
994                             hardSessionInit = true;
995                             m_sessionInitDefault = sihandler.get();
996                         }
997                     }
998                     else if (!m_sessionInitDefault) {
999                         m_sessionInitDefault = sihandler.get();
1000                     }
1001                 }
1002             }
1003             else if (XMLString::equals(child->getLocalName(), _LogoutInitiator)) {
1004                 string t(XMLHelper::getAttrString(child, nullptr, _type));
1005                 if (t.empty()) {
1006                     log.error("LogoutInitiator element has no type attribute, skipping it...");
1007                     child = XMLHelper::getNextSiblingElement(child);
1008                     continue;
1009                 }
1010                 handler.reset(conf.LogoutInitiatorManager.newPlugin(t.c_str(), pair<const DOMElement*,const char*>(child, getId())));
1011             }
1012             else if (XMLString::equals(child->getLocalName(), _ArtifactResolutionService)) {
1013                 string bindprop(XMLHelper::getAttrString(child, nullptr, Binding));
1014                 if (bindprop.empty()) {
1015                     log.error("ArtifactResolutionService element has no Binding attribute, skipping it...");
1016                     child = XMLHelper::getNextSiblingElement(child);
1017                     continue;
1018                 }
1019                 handler.reset(conf.ArtifactResolutionServiceManager.newPlugin(bindprop.c_str(), pair<const DOMElement*,const char*>(child, getId())));
1020
1021                 if (!hardArt) {
1022                     pair<bool,bool> defprop = handler->getBool("isDefault");
1023                     if (defprop.first) {
1024                         if (defprop.second) {
1025                             hardArt = true;
1026                             m_artifactResolutionDefault = handler.get();
1027                         }
1028                     }
1029                     else if (!m_artifactResolutionDefault)
1030                         m_artifactResolutionDefault = handler.get();
1031                 }
1032             }
1033             else if (XMLString::equals(child->getLocalName(), _SingleLogoutService)) {
1034                 string bindprop(XMLHelper::getAttrString(child, nullptr, Binding));
1035                 if (bindprop.empty()) {
1036                     log.error("SingleLogoutService element has no Binding attribute, skipping it...");
1037                     child = XMLHelper::getNextSiblingElement(child);
1038                     continue;
1039                 }
1040                 handler.reset(conf.SingleLogoutServiceManager.newPlugin(bindprop.c_str(), pair<const DOMElement*,const char*>(child, getId())));
1041             }
1042             else if (XMLString::equals(child->getLocalName(), _ManageNameIDService)) {
1043                 string bindprop(XMLHelper::getAttrString(child, nullptr, Binding));
1044                 if (bindprop.empty()) {
1045                     log.error("ManageNameIDService element has no Binding attribute, skipping it...");
1046                     child = XMLHelper::getNextSiblingElement(child);
1047                     continue;
1048                 }
1049                 handler.reset(conf.ManageNameIDServiceManager.newPlugin(bindprop.c_str(), pair<const DOMElement*,const char*>(child, getId())));
1050             }
1051             else {
1052                 string t(XMLHelper::getAttrString(child, nullptr, _type));
1053                 if (t.empty()) {
1054                     log.error("Handler element has no type attribute, skipping it...");
1055                     child = XMLHelper::getNextSiblingElement(child);
1056                     continue;
1057                 }
1058                 handler.reset(conf.HandlerManager.newPlugin(t.c_str(), pair<const DOMElement*,const char*>(child, getId())));
1059             }
1060
1061             m_handlers.push_back(handler);
1062
1063             // Insert into location map.
1064             location = handler->getString("Location");
1065             if (location.first && *location.second == '/')
1066                 m_handlerMap[location.second] = handler.get();
1067             else if (location.first)
1068                 m_handlerMap[string("/") + location.second] = handler.get();
1069         }
1070         catch (std::exception& ex) {
1071             log.error("caught exception processing handler element: %s", ex.what());
1072         }
1073
1074         child = XMLHelper::getNextSiblingElement(child);
1075     }
1076 }
1077
1078 void XMLApplication::doSSO(const ProtocolProvider& pp, set<string>& protocols, DOMElement* e, Category& log)
1079 {
1080     if (!e->hasChildNodes())
1081         return;
1082
1083     SPConfig& conf = SPConfig::getConfig();
1084
1085     int index = 0; // track ACS indexes globally across all protocols
1086
1087     // Tokenize the protocol list inside the element.
1088     XMLStringTokenizer prottokens(e->getTextContent());
1089     while (prottokens.hasMoreTokens()) {
1090         auto_ptr_char prot(prottokens.nextToken());
1091
1092         // Look for initiator.
1093         const PropertySet* initiator = pp.getInitiator(prot.get(), "SSO");
1094         if (initiator) {
1095             log.info("auto-configuring SSO initiation for protocol (%s)", prot.get());
1096             pair<bool,const XMLCh*> inittype = initiator->getXMLString("id");
1097             if (inittype.first) {
1098                 // Append a session initiator element of the designated type to the root element.
1099                 DOMElement* sidom = e->getOwnerDocument()->createElementNS(shibspconstants::SHIB2SPCONFIG_NS, _SessionInitiator);
1100                 sidom->setAttributeNS(nullptr, _type, inittype.second);
1101                 e->appendChild(sidom);
1102                 log.info("adding SessionInitiator of type (%s) to chain (/Login)", initiator->getString("id").second);
1103
1104                 doArtifactResolution(pp, prot.get(), e, log);
1105                 protocols.insert(prot.get());
1106             }
1107             else {
1108                 log.error("missing id property on Initiator element, check config for protocol (%s)", prot.get());
1109             }
1110         }
1111
1112         // Look for incoming bindings.
1113         const vector<const PropertySet*>& bindings = pp.getBindings(prot.get(), "SSO");
1114         if (!bindings.empty()) {
1115             log.info("auto-configuring SSO 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, ++index) {
1118                 idprop = (*b)->getXMLString("id");
1119                 pathprop = (*b)->getXMLString("path");
1120                 if (idprop.first && pathprop.first) {
1121                     DOMElement* acsdom = e->getOwnerDocument()->createElementNS(samlconstants::SAML20MD_NS, _AssertionConsumerService);
1122                     acsdom->setAttributeNS(nullptr, Binding, idprop.second);
1123                     acsdom->setAttributeNS(nullptr, Location, pathprop.second);
1124                     xstring indexbuf(1, chDigit_1 + (index % 10));
1125                     if (index / 10)
1126                         indexbuf = (XMLCh)(chDigit_1 + (index / 10)) + indexbuf;
1127                     acsdom->setAttributeNS(nullptr, _index, indexbuf.c_str());
1128
1129                     log.info("adding AssertionConsumerService for Binding (%s) at (%s)", (*b)->getString("id").second, (*b)->getString("path").second);
1130                     boost::shared_ptr<Handler> handler(
1131                         conf.AssertionConsumerServiceManager.newPlugin(
1132                             (*b)->getString("id").second, pair<const DOMElement*,const char*>(acsdom, getId())
1133                             )
1134                         );
1135                     m_handlers.push_back(handler);
1136
1137                     // Setup maps and defaults.
1138                     m_acsBindingMap[handler->getXMLString("Binding").second].push_back(handler.get());
1139                     const XMLCh* protfamily = handler->getProtocolFamily();
1140                     if (protfamily)
1141                         m_acsProtocolMap[protfamily].push_back(handler.get());
1142                     m_acsIndexMap[handler->getUnsignedInt("index").second] = handler.get();
1143                     if (!m_acsDefault)
1144                         m_acsDefault = handler.get();
1145
1146                     // Insert into location map.
1147                     pair<bool,const char*> location = handler->getString("Location");
1148                     if (location.first && *location.second == '/')
1149                         m_handlerMap[location.second] = handler.get();
1150                     else if (location.first)
1151                         m_handlerMap[string("/") + location.second] = handler.get();
1152                 }
1153                 else {
1154                     log.error("missing id or path property on Binding element, check config for protocol (%s)", prot.get());
1155                 }
1156             }
1157         }
1158
1159         if (!initiator && bindings.empty()) {
1160             log.error("no SSO Initiator or Binding config for protocol (%s)", prot.get());
1161         }
1162     }
1163
1164     // Handle discovery.
1165     static const XMLCh discoveryProtocol[] = UNICODE_LITERAL_17(d,i,s,c,o,v,e,r,y,P,r,o,t,o,c,o,l);
1166     static const XMLCh discoveryURL[] = UNICODE_LITERAL_12(d,i,s,c,o,v,e,r,y,U,R,L);
1167     static const XMLCh _URL[] = UNICODE_LITERAL_3(U,R,L);
1168     const XMLCh* discop = e->getAttributeNS(nullptr, discoveryProtocol);
1169     if (discop && *discop) {
1170         const XMLCh* discou = e->getAttributeNS(nullptr, discoveryURL);
1171         if (discou && *discou) {
1172             // Append a session initiator element of the designated type to the root element.
1173             DOMElement* sidom = e->getOwnerDocument()->createElementNS(shibspconstants::SHIB2SPCONFIG_NS, _SessionInitiator);
1174             sidom->setAttributeNS(nullptr, _type, discop);
1175             sidom->setAttributeNS(nullptr, _URL, discou);
1176             e->appendChild(sidom);
1177             if (log.isInfoEnabled()) {
1178                 auto_ptr_char dp(discop);
1179                 log.info("adding SessionInitiator of type (%s) to chain (/Login)", dp.get());
1180             }
1181         }
1182         else {
1183             log.error("SSO discoveryProtocol specified without discoveryURL");
1184         }
1185     }
1186
1187     // Attach default Location to SSO element.
1188     static const XMLCh _loc[] = { chForwardSlash, chLatin_L, chLatin_o, chLatin_g, chLatin_i, chLatin_n, chNull };
1189     e->setAttributeNS(nullptr, Location, _loc);
1190
1191     // Instantiate Chaining initiator around the SSO element.
1192     boost::shared_ptr<SessionInitiator> chain(
1193         conf.SessionInitiatorManager.newPlugin(CHAINING_SESSION_INITIATOR, pair<const DOMElement*,const char*>(e, getId()))
1194         );
1195     m_handlers.push_back(chain);
1196     m_sessionInitDefault = chain.get();
1197     m_handlerMap["/Login"] = chain.get();
1198 }
1199
1200 void XMLApplication::doLogout(const ProtocolProvider& pp, set<string>& protocols, DOMElement* e, Category& log)
1201 {
1202     if (!e->hasChildNodes())
1203         return;
1204
1205     SPConfig& conf = SPConfig::getConfig();
1206
1207     // Tokenize the protocol list inside the element.
1208     XMLStringTokenizer prottokens(e->getTextContent());
1209     while (prottokens.hasMoreTokens()) {
1210         auto_ptr_char prot(prottokens.nextToken());
1211
1212         // Look for initiator.
1213         const PropertySet* initiator = pp.getInitiator(prot.get(), "Logout");
1214         if (initiator) {
1215             log.info("auto-configuring Logout initiation for protocol (%s)", prot.get());
1216             pair<bool,const XMLCh*> inittype = initiator->getXMLString("id");
1217             if (inittype.first) {
1218                 // Append a logout initiator element of the designated type to the root element.
1219                 DOMElement* lidom = e->getOwnerDocument()->createElementNS(shibspconstants::SHIB2SPCONFIG_NS, _LogoutInitiator);
1220                 lidom->setAttributeNS(nullptr, _type, inittype.second);
1221                 e->appendChild(lidom);
1222                 log.info("adding LogoutInitiator of type (%s) to chain (/Logout)", initiator->getString("id").second);
1223
1224                 if (protocols.count(prot.get()) == 0) {
1225                     doArtifactResolution(pp, prot.get(), e, log);
1226                     protocols.insert(prot.get());
1227                 }
1228             }
1229             else {
1230                 log.error("missing id property on Initiator element, check config for protocol (%s)", prot.get());
1231             }
1232         }
1233
1234         // Look for incoming bindings.
1235         const vector<const PropertySet*>& bindings = pp.getBindings(prot.get(), "Logout");
1236         if (!bindings.empty()) {
1237             log.info("auto-configuring Logout endpoints for protocol (%s)", prot.get());
1238             pair<bool,const XMLCh*> idprop,pathprop;
1239             for (vector<const PropertySet*>::const_iterator b = bindings.begin(); b != bindings.end(); ++b) {
1240                 idprop = (*b)->getXMLString("id");
1241                 pathprop = (*b)->getXMLString("path");
1242                 if (idprop.first && pathprop.first) {
1243                     DOMElement* slodom = e->getOwnerDocument()->createElementNS(samlconstants::SAML20MD_NS, _SingleLogoutService);
1244                     slodom->setAttributeNS(nullptr, Binding, idprop.second);
1245                     slodom->setAttributeNS(nullptr, Location, pathprop.second);
1246
1247                     log.info("adding SingleLogoutService for Binding (%s) at (%s)", (*b)->getString("id").second, (*b)->getString("path").second);
1248                     boost::shared_ptr<Handler> handler(
1249                         conf.SingleLogoutServiceManager.newPlugin((*b)->getString("id").second, pair<const DOMElement*,const char*>(slodom, getId()))
1250                         );
1251                     m_handlers.push_back(handler);
1252
1253                     // Insert into location map.
1254                     pair<bool,const char*> location = handler->getString("Location");
1255                     if (location.first && *location.second == '/')
1256                         m_handlerMap[location.second] = handler.get();
1257                     else if (location.first)
1258                         m_handlerMap[string("/") + location.second] = handler.get();
1259                 }
1260                 else {
1261                     log.error("missing id or path property on Binding element, check config for protocol (%s)", prot.get());
1262                 }
1263             }
1264
1265             if (protocols.count(prot.get()) == 0) {
1266                 doArtifactResolution(pp, prot.get(), e, log);
1267                 protocols.insert(prot.get());
1268             }
1269         }
1270
1271         if (!initiator && bindings.empty()) {
1272             log.error("no Logout Initiator or Binding config for protocol (%s)", prot.get());
1273         }
1274     }
1275
1276     // Attach default Location to Logout element.
1277     static const XMLCh _loc[] = { chForwardSlash, chLatin_L, chLatin_o, chLatin_g, chLatin_o, chLatin_u, chLatin_t, chNull };
1278     e->setAttributeNS(nullptr, Location, _loc);
1279
1280     // Instantiate Chaining initiator around the SSO element.
1281     boost::shared_ptr<Handler> chain(
1282         conf.LogoutInitiatorManager.newPlugin(CHAINING_LOGOUT_INITIATOR, pair<const DOMElement*,const char*>(e, getId()))
1283         );
1284     m_handlers.push_back(chain);
1285     m_handlerMap["/Logout"] = chain.get();
1286 }
1287
1288 void XMLApplication::doNameIDMgmt(const ProtocolProvider& pp, set<string>& protocols, DOMElement* e, Category& log)
1289 {
1290     if (!e->hasChildNodes())
1291         return;
1292
1293     SPConfig& conf = SPConfig::getConfig();
1294
1295     // Tokenize the protocol list inside the element.
1296     XMLStringTokenizer prottokens(e->getTextContent());
1297     while (prottokens.hasMoreTokens()) {
1298         auto_ptr_char prot(prottokens.nextToken());
1299
1300         // Look for incoming bindings.
1301         const vector<const PropertySet*>& bindings = pp.getBindings(prot.get(), "NameIDMgmt");
1302         if (!bindings.empty()) {
1303             log.info("auto-configuring NameIDMgmt endpoints for protocol (%s)", prot.get());
1304             pair<bool,const XMLCh*> idprop,pathprop;
1305             for (vector<const PropertySet*>::const_iterator b = bindings.begin(); b != bindings.end(); ++b) {
1306                 idprop = (*b)->getXMLString("id");
1307                 pathprop = (*b)->getXMLString("path");
1308                 if (idprop.first && pathprop.first) {
1309                     DOMElement* nimdom = e->getOwnerDocument()->createElementNS(samlconstants::SAML20MD_NS, _ManageNameIDService);
1310                     nimdom->setAttributeNS(nullptr, Binding, idprop.second);
1311                     nimdom->setAttributeNS(nullptr, Location, pathprop.second);
1312
1313                     log.info("adding ManageNameIDService for Binding (%s) at (%s)", (*b)->getString("id").second, (*b)->getString("path").second);
1314                     boost::shared_ptr<Handler> handler(
1315                         conf.ManageNameIDServiceManager.newPlugin((*b)->getString("id").second, pair<const DOMElement*,const char*>(nimdom, getId()))
1316                         );
1317                     m_handlers.push_back(handler);
1318
1319                     // Insert into location map.
1320                     pair<bool,const char*> location = handler->getString("Location");
1321                     if (location.first && *location.second == '/')
1322                         m_handlerMap[location.second] = handler.get();
1323                     else if (location.first)
1324                         m_handlerMap[string("/") + location.second] = handler.get();
1325                 }
1326                 else {
1327                     log.error("missing id or path property on Binding element, check config for protocol (%s)", prot.get());
1328                 }
1329             }
1330
1331             if (protocols.count(prot.get()) == 0) {
1332                 doArtifactResolution(pp, prot.get(), e, log);
1333                 protocols.insert(prot.get());
1334             }
1335         }
1336         else {
1337             log.error("no NameIDMgmt Binding config for protocol (%s)", prot.get());
1338         }
1339     }
1340 }
1341
1342 void XMLApplication::doArtifactResolution(const ProtocolProvider& pp, const char* protocol, DOMElement* e, Category& log)
1343 {
1344     SPConfig& conf = SPConfig::getConfig();
1345
1346     int index = 0; // track indexes globally across all protocols
1347
1348     // Look for incoming bindings.
1349     const vector<const PropertySet*>& bindings = pp.getBindings(protocol, "ArtifactResolution");
1350     if (!bindings.empty()) {
1351         log.info("auto-configuring ArtifactResolution endpoints for protocol (%s)", protocol);
1352         pair<bool,const XMLCh*> idprop,pathprop;
1353         for (vector<const PropertySet*>::const_iterator b = bindings.begin(); b != bindings.end(); ++b, ++index) {
1354             idprop = (*b)->getXMLString("id");
1355             pathprop = (*b)->getXMLString("path");
1356             if (idprop.first && pathprop.first) {
1357                 DOMElement* artdom = e->getOwnerDocument()->createElementNS(samlconstants::SAML20MD_NS, _ArtifactResolutionService);
1358                 artdom->setAttributeNS(nullptr, Binding, idprop.second);
1359                 artdom->setAttributeNS(nullptr, Location, pathprop.second);
1360                 xstring indexbuf(1, chDigit_1 + (index % 10));
1361                 if (index / 10)
1362                     indexbuf = (XMLCh)(chDigit_1 + (index / 10)) + indexbuf;
1363                 artdom->setAttributeNS(nullptr, _index, indexbuf.c_str());
1364
1365                 log.info("adding ArtifactResolutionService for Binding (%s) at (%s)", (*b)->getString("id").second, (*b)->getString("path").second);
1366                 boost::shared_ptr<Handler> handler(
1367                     conf.ArtifactResolutionServiceManager.newPlugin((*b)->getString("id").second, pair<const DOMElement*,const char*>(artdom, getId()))
1368                     );
1369                 m_handlers.push_back(handler);
1370
1371                 if (!m_artifactResolutionDefault)
1372                     m_artifactResolutionDefault = handler.get();
1373
1374                 // Insert into location map.
1375                 pair<bool,const char*> location = handler->getString("Location");
1376                 if (location.first && *location.second == '/')
1377                     m_handlerMap[location.second] = handler.get();
1378                 else if (location.first)
1379                     m_handlerMap[string("/") + location.second] = handler.get();
1380             }
1381             else {
1382                 log.error("missing id or path property on Binding element, check config for protocol (%s)", protocol);
1383             }
1384         }
1385     }
1386 }
1387
1388 #ifndef SHIBSP_LITE
1389 void XMLApplication::doAttributePlugins(DOMElement* e, Category& log)
1390 {
1391     SPConfig& conf = SPConfig::getConfig();
1392
1393     m_attrExtractor.reset(
1394         doChainedPlugins(conf.AttributeExtractorManager, "AttributeExtractor", CHAINING_ATTRIBUTE_EXTRACTOR, _AttributeExtractor, e, log)
1395         );
1396
1397     m_attrFilter.reset(
1398         doChainedPlugins(conf.AttributeFilterManager, "AttributeFilter", CHAINING_ATTRIBUTE_FILTER, _AttributeFilter, e, log, DUMMY_ATTRIBUTE_FILTER)
1399         );
1400
1401     m_attrResolver.reset(
1402         doChainedPlugins(conf.AttributeResolverManager, "AttributeResolver", CHAINING_ATTRIBUTE_RESOLVER, _AttributeResolver, e, log)
1403         );
1404
1405     if (m_unsetHeaders.empty()) {
1406         vector<string> unsetHeaders;
1407         if (m_attrExtractor) {
1408             Locker extlock(m_attrExtractor.get());
1409             m_attrExtractor->getAttributeIds(unsetHeaders);
1410         }
1411         else if (m_base && m_base->m_attrExtractor) {
1412             Locker extlock(m_base->m_attrExtractor.get());
1413             m_base->m_attrExtractor->getAttributeIds(unsetHeaders);
1414         }
1415         if (m_attrResolver) {
1416             Locker reslock(m_attrResolver.get());
1417             m_attrResolver->getAttributeIds(unsetHeaders);
1418         }
1419         else if (m_base && m_base->m_attrResolver) {
1420             Locker extlock(m_base->m_attrResolver.get());
1421             m_base->m_attrResolver->getAttributeIds(unsetHeaders);
1422         }
1423         if (!unsetHeaders.empty()) {
1424             string transformedprefix(m_attributePrefix.second);
1425             const char* pch;
1426             pair<bool,const char*> prefix = getString("metadataAttributePrefix");
1427             if (prefix.first) {
1428                 pch = prefix.second;
1429                 while (*pch) {
1430                     transformedprefix += (isalnum(*pch) ? toupper(*pch) : '_');
1431                     pch++;
1432                 }
1433             }
1434             for (vector<string>::const_iterator hdr = unsetHeaders.begin(); hdr!=unsetHeaders.end(); ++hdr) {
1435                 string transformed;
1436                 pch = hdr->c_str();
1437                 while (*pch) {
1438                     transformed += (isalnum(*pch) ? toupper(*pch) : '_');
1439                     pch++;
1440                 }
1441                 m_unsetHeaders.push_back(make_pair(m_attributePrefix.first + *hdr, m_attributePrefix.second + transformed));
1442                 if (prefix.first)
1443                     m_unsetHeaders.push_back(make_pair(m_attributePrefix.first + prefix.second + *hdr, transformedprefix + transformed));
1444             }
1445         }
1446         m_unsetHeaders.push_back(make_pair(m_attributePrefix.first + "Shib-Application-ID", m_attributePrefix.second + "SHIB_APPLICATION_ID"));
1447     }
1448 }
1449 #endif
1450
1451 #ifdef SHIBSP_XERCESC_SHORT_ACCEPTNODE
1452 short
1453 #else
1454 DOMNodeFilter::FilterAction
1455 #endif
1456 XMLApplication::acceptNode(const DOMNode* node) const
1457 {
1458     const XMLCh* name=node->getLocalName();
1459     if (XMLString::equals(name,ApplicationOverride) ||
1460         XMLString::equals(name,_Audience) ||
1461         XMLString::equals(name,Notify) ||
1462         XMLString::equals(name,_Handler) ||
1463         XMLString::equals(name,_AssertionConsumerService) ||
1464         XMLString::equals(name,_ArtifactResolutionService) ||
1465         XMLString::equals(name,Logout) ||
1466         XMLString::equals(name,_LogoutInitiator) ||
1467         XMLString::equals(name,_ManageNameIDService) ||
1468         XMLString::equals(name,NameIDMgmt) ||
1469         XMLString::equals(name,_SessionInitiator) ||
1470         XMLString::equals(name,_SingleLogoutService) ||
1471         XMLString::equals(name,SSO) ||
1472         XMLString::equals(name,RelyingParty) ||
1473         XMLString::equals(name,_MetadataProvider) ||
1474         XMLString::equals(name,_TrustEngine) ||
1475         XMLString::equals(name,_CredentialResolver) ||
1476         XMLString::equals(name,_AttributeFilter) ||
1477         XMLString::equals(name,_AttributeExtractor) ||
1478         XMLString::equals(name,_AttributeResolver))
1479         return FILTER_REJECT;
1480
1481     return FILTER_ACCEPT;
1482 }
1483
1484 #ifndef SHIBSP_LITE
1485
1486 const PropertySet* XMLApplication::getRelyingParty(const EntityDescriptor* provider) const
1487 {
1488     if (!provider)
1489         return this;
1490
1491     // Check for exact match on name.
1492     map< xstring,boost::shared_ptr<PropertySet> >::const_iterator i = m_partyMap.find(provider->getEntityID());
1493     if (i != m_partyMap.end())
1494         return i->second.get();
1495
1496     // Check for extensible matching.
1497     vector < pair< boost::shared_ptr<EntityMatcher>,boost::shared_ptr<PropertySet> > >::const_iterator j;
1498     for (j = m_partyVec.begin(); j != m_partyVec.end(); ++j) {
1499         if (j->first->matches(*provider))
1500             return j->second.get();
1501     }
1502
1503     // Check for group match.
1504     const EntitiesDescriptor* group = dynamic_cast<const EntitiesDescriptor*>(provider->getParent());
1505     while (group) {
1506         if (group->getName()) {
1507             i = m_partyMap.find(group->getName());
1508             if (i != m_partyMap.end())
1509                 return i->second.get();
1510         }
1511         group = dynamic_cast<const EntitiesDescriptor*>(group->getParent());
1512     }
1513     return this;
1514 }
1515
1516 const PropertySet* XMLApplication::getRelyingParty(const XMLCh* entityID) const
1517 {
1518     if (!entityID)
1519         return this;
1520     map< xstring,boost::shared_ptr<PropertySet> >::const_iterator i = m_partyMap.find(entityID);
1521     return (i != m_partyMap.end()) ? i->second.get() : this;
1522 }
1523
1524 #endif
1525
1526 string XMLApplication::getNotificationURL(const char* resource, bool front, unsigned int index) const
1527 {
1528     const vector<string>& locs = front ? m_frontLogout : m_backLogout;
1529     if (locs.empty())
1530         return m_base ? m_base->getNotificationURL(resource, front, index) : string();
1531     else if (index >= locs.size())
1532         return string();
1533
1534 #ifdef HAVE_STRCASECMP
1535     if (!resource || (strncasecmp(resource,"http://",7) && strncasecmp(resource,"https://",8)))
1536 #else
1537     if (!resource || (strnicmp(resource,"http://",7) && strnicmp(resource,"https://",8)))
1538 #endif
1539         throw ConfigurationException("Request URL was not absolute.");
1540
1541     const char* handler = locs[index].c_str();
1542
1543     // Should never happen...
1544     if (!handler || (*handler!='/' && strncmp(handler,"http:",5) && strncmp(handler,"https:",6)))
1545         throw ConfigurationException(
1546             "Invalid Location property ($1) in Notify element for Application ($2)",
1547             params(2, handler ? handler : "null", getId())
1548             );
1549
1550     // The "Location" property can be in one of three formats:
1551     //
1552     // 1) a full URI:       http://host/foo/bar
1553     // 2) a hostless URI:   http:///foo/bar
1554     // 3) a relative path:  /foo/bar
1555     //
1556     // #  Protocol  Host        Path
1557     // 1  handler   handler     handler
1558     // 2  handler   resource    handler
1559     // 3  resource  resource    handler
1560
1561     const char* path = nullptr;
1562
1563     // Decide whether to use the handler or the resource for the "protocol"
1564     const char* prot;
1565     if (*handler != '/') {
1566         prot = handler;
1567     }
1568     else {
1569         prot = resource;
1570         path = handler;
1571     }
1572
1573     // break apart the "protocol" string into protocol, host, and "the rest"
1574     const char* colon=strchr(prot,':');
1575     colon += 3;
1576     const char* slash=strchr(colon,'/');
1577     if (!path)
1578         path = slash;
1579
1580     // Compute the actual protocol and store.
1581     string notifyURL(prot, colon-prot);
1582
1583     // create the "host" from either the colon/slash or from the target string
1584     // If prot == handler then we're in either #1 or #2, else #3.
1585     // If slash == colon then we're in #2.
1586     if (prot != handler || slash == colon) {
1587         colon = strchr(resource, ':');
1588         colon += 3;      // Get past the ://
1589         slash = strchr(colon, '/');
1590     }
1591     string host(colon, (slash ? slash-colon : strlen(colon)));
1592
1593     // Build the URL
1594     notifyURL += host + path;
1595     return notifyURL;
1596 }
1597
1598 void XMLApplication::clearHeader(SPRequest& request, const char* rawname, const char* cginame) const
1599 {
1600     if (!m_attributePrefix.first.empty()) {
1601         string temp = m_attributePrefix.first + rawname;
1602         string temp2 = m_attributePrefix.second + (cginame + 5);
1603         request.clearHeader(temp.c_str(), temp2.c_str());
1604     }
1605     else if (m_base) {
1606         m_base->clearHeader(request, rawname, cginame);
1607     }
1608     else {
1609         request.clearHeader(rawname, cginame);
1610     }
1611 }
1612
1613 void XMLApplication::setHeader(SPRequest& request, const char* name, const char* value) const
1614 {
1615     if (!m_attributePrefix.first.empty()) {
1616         string temp = m_attributePrefix.first + name;
1617         request.setHeader(temp.c_str(), value);
1618     }
1619     else if (m_base) {
1620         m_base->setHeader(request, name, value);
1621     }
1622     else {
1623         request.setHeader(name, value);
1624     }
1625 }
1626
1627 string XMLApplication::getSecureHeader(const SPRequest& request, const char* name) const
1628 {
1629     if (!m_attributePrefix.first.empty()) {
1630         string temp = m_attributePrefix.first + name;
1631         return request.getSecureHeader(temp.c_str());
1632     }
1633     else if (m_base) {
1634         return m_base->getSecureHeader(request,name);
1635     }
1636     else {
1637         return request.getSecureHeader(name);
1638     }
1639 }
1640
1641 const SessionInitiator* XMLApplication::getDefaultSessionInitiator() const
1642 {
1643     if (m_sessionInitDefault) return m_sessionInitDefault;
1644     return m_base ? m_base->getDefaultSessionInitiator() : nullptr;
1645 }
1646
1647 const SessionInitiator* XMLApplication::getSessionInitiatorById(const char* id) const
1648 {
1649     map<string,const SessionInitiator*>::const_iterator i = m_sessionInitMap.find(id);
1650     if (i != m_sessionInitMap.end()) return i->second;
1651     return m_base ? m_base->getSessionInitiatorById(id) : nullptr;
1652 }
1653
1654 const Handler* XMLApplication::getDefaultAssertionConsumerService() const
1655 {
1656     if (m_acsDefault) return m_acsDefault;
1657     return m_base ? m_base->getDefaultAssertionConsumerService() : nullptr;
1658 }
1659
1660 const Handler* XMLApplication::getAssertionConsumerServiceByIndex(unsigned short index) const
1661 {
1662     map<unsigned int,const Handler*>::const_iterator i = m_acsIndexMap.find(index);
1663     if (i != m_acsIndexMap.end()) return i->second;
1664     return m_base ? m_base->getAssertionConsumerServiceByIndex(index) : nullptr;
1665 }
1666
1667 const Handler* XMLApplication::getAssertionConsumerServiceByProtocol(const XMLCh* protocol, const char* binding) const
1668 {
1669     ACSProtocolMap::const_iterator i = m_acsProtocolMap.find(protocol);
1670     if (i != m_acsProtocolMap.end() && !i->second.empty()) {
1671         if (!binding || !*binding)
1672             return i->second.front();
1673         for (ACSProtocolMap::value_type::second_type::const_iterator j = i->second.begin(); j != i->second.end(); ++j) {
1674             if (!strcmp(binding, (*j)->getString("Binding").second))
1675                 return *j;
1676         }
1677     }
1678     return m_base ? m_base->getAssertionConsumerServiceByProtocol(protocol, binding) : nullptr;
1679 }
1680
1681 const vector<const Handler*>& XMLApplication::getAssertionConsumerServicesByBinding(const XMLCh* binding) const
1682 {
1683     ACSBindingMap::const_iterator i = m_acsBindingMap.find(binding);
1684     if (i != m_acsBindingMap.end())
1685         return i->second;
1686     return m_base ? m_base->getAssertionConsumerServicesByBinding(binding) : g_noHandlers;
1687 }
1688
1689 const Handler* XMLApplication::getHandler(const char* path) const
1690 {
1691     string wrap(path);
1692     wrap = wrap.substr(0, wrap.find(';'));
1693     map<string,const Handler*>::const_iterator i = m_handlerMap.find(wrap.substr(0, wrap.find('?')));
1694     if (i != m_handlerMap.end())
1695         return i->second;
1696     return m_base ? m_base->getHandler(path) : nullptr;
1697 }
1698
1699 void XMLApplication::getHandlers(vector<const Handler*>& handlers) const
1700 {
1701     static void (vector<const Handler*>::* pb)(const Handler* const&) = &vector<const Handler*>::push_back;
1702     for_each(m_handlers.begin(), m_handlers.end(), boost::bind(pb, boost::ref(handlers), boost::bind(&boost::shared_ptr<Handler>::get, _1)));
1703     if (m_base) {
1704         for (map<string,const Handler*>::const_iterator h = m_base->m_handlerMap.begin(); h != m_base->m_handlerMap.end(); ++h) {
1705             if (m_handlerMap.count(h->first) == 0)
1706                 handlers.push_back(h->second);
1707         }
1708     }
1709 }
1710
1711 void XMLApplication::limitRedirect(const GenericRequest& request, const char* url) const
1712 {
1713     if (!url || *url == '/')
1714         return;
1715     if (m_redirectLimit == REDIRECT_LIMIT_INHERIT)
1716         return m_base->limitRedirect(request, url);
1717     if (m_redirectLimit != REDIRECT_LIMIT_NONE) {
1718         vector<string> whitelist;
1719         if (m_redirectLimit == REDIRECT_LIMIT_EXACT || m_redirectLimit == REDIRECT_LIMIT_EXACT_WHITELIST) {
1720             // Scheme and hostname have to match.
1721             if (request.isDefaultPort()) {
1722                 whitelist.push_back(string(request.getScheme()) + "://" + request.getHostname() + '/');
1723             }
1724             whitelist.push_back(string(request.getScheme()) + "://" + request.getHostname() + ':' + lexical_cast<string>(request.getPort()) + '/');
1725         }
1726         else if (m_redirectLimit == REDIRECT_LIMIT_HOST || m_redirectLimit == REDIRECT_LIMIT_HOST_WHITELIST) {
1727             // Allow any scheme or port.
1728             whitelist.push_back(string("https://") + request.getHostname() + '/');
1729             whitelist.push_back(string("http://") + request.getHostname() + '/');
1730             whitelist.push_back(string("https://") + request.getHostname() + ':');
1731             whitelist.push_back(string("http://") + request.getHostname() + ':');
1732         }
1733
1734         static bool (*startsWithI)(const char*,const char*) = XMLString::startsWithI;
1735         if (!whitelist.empty() && find_if(whitelist.begin(), whitelist.end(),
1736                 boost::bind(startsWithI, url, boost::bind(&string::c_str, _1))) != whitelist.end()) {
1737             return;
1738         }
1739         else if (!m_redirectWhitelist.empty() && find_if(m_redirectWhitelist.begin(), m_redirectWhitelist.end(),
1740                 boost::bind(startsWithI, url, boost::bind(&string::c_str, _1))) != m_redirectWhitelist.end()) {
1741             return;
1742         }
1743         Category::getInstance(SHIBSP_LOGCAT".Application").warn("redirectLimit policy enforced, blocked redirect to (%s)", url);
1744         throw opensaml::SecurityPolicyException("Blocked unacceptable redirect location.");
1745     }
1746 }
1747
1748 #ifdef SHIBSP_XERCESC_SHORT_ACCEPTNODE
1749 short
1750 #else
1751 DOMNodeFilter::FilterAction
1752 #endif
1753 XMLConfigImpl::acceptNode(const DOMNode* node) const
1754 {
1755     if (!XMLString::equals(node->getNamespaceURI(),shibspconstants::SHIB2SPCONFIG_NS))
1756         return FILTER_ACCEPT;
1757     const XMLCh* name=node->getLocalName();
1758     if (XMLString::equals(name,ApplicationDefaults) ||
1759         XMLString::equals(name,_ArtifactMap) ||
1760         XMLString::equals(name,_Extensions) ||
1761         XMLString::equals(name,Listener) ||
1762         XMLString::equals(name,_ProtocolProvider) ||
1763         XMLString::equals(name,_RequestMapper) ||
1764         XMLString::equals(name,_ReplayCache) ||
1765         XMLString::equals(name,SecurityPolicies) ||
1766         XMLString::equals(name,_SecurityPolicyProvider) ||
1767         XMLString::equals(name,_SessionCache) ||
1768         XMLString::equals(name,Site) ||
1769         XMLString::equals(name,_StorageService) ||
1770         XMLString::equals(name,TCPListener) ||
1771         XMLString::equals(name,TransportOption) ||
1772         XMLString::equals(name,UnixListener))
1773         return FILTER_REJECT;
1774
1775     return FILTER_ACCEPT;
1776 }
1777
1778 void XMLConfigImpl::doExtensions(const DOMElement* e, const char* label, Category& log)
1779 {
1780     const DOMElement* exts = XMLHelper::getFirstChildElement(e, _Extensions);
1781     if (exts) {
1782         exts = XMLHelper::getFirstChildElement(exts, Library);
1783         while (exts) {
1784             string path(XMLHelper::getAttrString(exts, nullptr, _path));
1785             try {
1786                 if (!path.empty()) {
1787                     if (!XMLToolingConfig::getConfig().load_library(path.c_str(), (void*)exts))
1788                         throw ConfigurationException("XMLToolingConfig::load_library failed.");
1789                     log.debug("loaded %s extension library (%s)", label, path.c_str());
1790                 }
1791             }
1792             catch (std::exception& e) {
1793                 if (XMLHelper::getAttrBool(exts, false, _fatal)) {
1794                     log.fatal("unable to load mandatory %s extension library %s: %s", label, path.c_str(), e.what());
1795                     throw;
1796                 }
1797                 else {
1798                     log.crit("unable to load optional %s extension library %s: %s", label, path.c_str(), e.what());
1799                 }
1800             }
1801             exts = XMLHelper::getNextSiblingElement(exts, Library);
1802         }
1803     }
1804 }
1805
1806 void XMLConfigImpl::doListener(const DOMElement* e, XMLConfig* conf, Category& log)
1807 {
1808 #ifdef WIN32
1809     string plugtype(TCP_LISTENER_SERVICE);
1810 #else
1811     string plugtype(UNIX_LISTENER_SERVICE);
1812 #endif
1813     DOMElement* child = XMLHelper::getFirstChildElement(e, UnixListener);
1814     if (child)
1815         plugtype = UNIX_LISTENER_SERVICE;
1816     else {
1817         child = XMLHelper::getFirstChildElement(e, TCPListener);
1818         if (child)
1819             plugtype = TCP_LISTENER_SERVICE;
1820         else {
1821             child = XMLHelper::getFirstChildElement(e, Listener);
1822             if (child) {
1823                 auto_ptr_char type(child->getAttributeNS(nullptr, _type));
1824                 if (type.get() && *type.get())
1825                     plugtype = type.get();
1826             }
1827         }
1828     }
1829
1830     log.info("building ListenerService of type %s...", plugtype.c_str());
1831     conf->m_listener.reset(SPConfig::getConfig().ListenerServiceManager.newPlugin(plugtype.c_str(), child));
1832 }
1833
1834 void XMLConfigImpl::doCaching(const DOMElement* e, XMLConfig* conf, Category& log)
1835 {
1836     SPConfig& spConf = SPConfig::getConfig();
1837 #ifndef SHIBSP_LITE
1838     SAMLConfig& samlConf = SAMLConfig::getConfig();
1839 #endif
1840
1841     DOMElement* child;
1842 #ifndef SHIBSP_LITE
1843     if (spConf.isEnabled(SPConfig::OutOfProcess)) {
1844         XMLToolingConfig& xmlConf = XMLToolingConfig::getConfig();
1845         // First build any StorageServices.
1846         child = XMLHelper::getFirstChildElement(e, _StorageService);
1847         while (child) {
1848             string id(XMLHelper::getAttrString(child, nullptr, _id));
1849             string t(XMLHelper::getAttrString(child, nullptr, _type));
1850             if (!t.empty()) {
1851                 try {
1852                     log.info("building StorageService (%s) of type %s...", id.c_str(), t.c_str());
1853                     conf->m_storage[id] = boost::shared_ptr<StorageService>(xmlConf.StorageServiceManager.newPlugin(t.c_str(), child));
1854                 }
1855                 catch (std::exception& ex) {
1856                     log.crit("failed to instantiate StorageService (%s): %s", id.c_str(), ex.what());
1857                 }
1858             }
1859             child = XMLHelper::getNextSiblingElement(child, _StorageService);
1860         }
1861
1862         if (conf->m_storage.empty()) {
1863             log.info("no StorageService plugin(s) installed, using (mem) in-memory instance");
1864             conf->m_storage["mem"] = boost::shared_ptr<StorageService>(xmlConf.StorageServiceManager.newPlugin(MEMORY_STORAGE_SERVICE, nullptr));
1865         }
1866
1867         // Replay cache.
1868         StorageService* replaySS = nullptr;
1869         child = XMLHelper::getFirstChildElement(e, _ReplayCache);
1870         if (child) {
1871             string ssid(XMLHelper::getAttrString(child, nullptr, _StorageService));
1872             if (!ssid.empty()) {
1873                 if (conf->m_storage.count(ssid)) {
1874                     log.info("building ReplayCache on top of StorageService (%s)...", ssid.c_str());
1875                     replaySS = conf->m_storage[ssid].get();
1876                 }
1877                 else {
1878                     log.error("unable to locate StorageService (%s), using arbitrary instance for ReplayCache", ssid.c_str());
1879                     replaySS = conf->m_storage.begin()->second.get();
1880                 }
1881             }
1882             else {
1883                 log.info("no StorageService specified for ReplayCache, using arbitrary instance");
1884                 replaySS = conf->m_storage.begin()->second.get();
1885             }
1886         }
1887         else {
1888             log.info("no ReplayCache specified, using arbitrary StorageService instance");
1889             replaySS = conf->m_storage.begin()->second.get();
1890         }
1891         xmlConf.setReplayCache(new ReplayCache(replaySS));
1892
1893         // ArtifactMap
1894         child = XMLHelper::getFirstChildElement(e, _ArtifactMap);
1895         if (child) {
1896             string ssid(XMLHelper::getAttrString(child, nullptr, _StorageService));
1897             if (!ssid.empty()) {
1898                 if (conf->m_storage.count(ssid)) {
1899                     log.info("building ArtifactMap on top of StorageService (%s)...", ssid.c_str());
1900                     samlConf.setArtifactMap(new ArtifactMap(child, conf->m_storage[ssid].get()));
1901                 }
1902                 else {
1903                     log.error("unable to locate StorageService (%s), using in-memory ArtifactMap", ssid.c_str());
1904                     samlConf.setArtifactMap(new ArtifactMap(child));
1905                 }
1906             }
1907             else {
1908                 log.info("no StorageService specified, using in-memory ArtifactMap");
1909                 samlConf.setArtifactMap(new ArtifactMap(child));
1910             }
1911         }
1912         else {
1913             log.info("no ArtifactMap specified, building in-memory ArtifactMap...");
1914             samlConf.setArtifactMap(new ArtifactMap(child));
1915         }
1916     }   // end of out of process caching components
1917 #endif
1918
1919     child = XMLHelper::getFirstChildElement(e, _SessionCache);
1920     if (child) {
1921         string t(XMLHelper::getAttrString(child, nullptr, _type));
1922         if (!t.empty()) {
1923             log.info("building SessionCache of type %s...", t.c_str());
1924             conf->m_sessionCache.reset(spConf.SessionCacheManager.newPlugin(t.c_str(), child));
1925         }
1926     }
1927     if (!conf->m_sessionCache) {
1928         log.info("no SessionCache specified, using StorageService-backed instance");
1929         conf->m_sessionCache.reset(spConf.SessionCacheManager.newPlugin(STORAGESERVICE_SESSION_CACHE, nullptr));
1930     }
1931 }
1932
1933 XMLConfigImpl::XMLConfigImpl(const DOMElement* e, bool first, XMLConfig* outer, Category& log) : m_document(nullptr)
1934 {
1935 #ifdef _DEBUG
1936     xmltooling::NDC ndc("XMLConfigImpl");
1937 #endif
1938     SPConfig& conf=SPConfig::getConfig();
1939     XMLToolingConfig& xmlConf=XMLToolingConfig::getConfig();
1940     const DOMElement* SHAR=XMLHelper::getFirstChildElement(e, OutOfProcess);
1941     const DOMElement* SHIRE=XMLHelper::getFirstChildElement(e, InProcess);
1942
1943     // Initialize logging manually in order to redirect log messages as soon as possible.
1944     // If no explicit config is supplied, we now assume the caller has done this, so that
1945     // setuid processes can potentially do this as root.
1946     if (conf.isEnabled(SPConfig::Logging)) {
1947         string logconf;
1948         if (conf.isEnabled(SPConfig::OutOfProcess))
1949             logconf = XMLHelper::getAttrString(SHAR, nullptr, logger);
1950         else if (conf.isEnabled(SPConfig::InProcess))
1951             logconf = XMLHelper::getAttrString(SHIRE, nullptr, logger);
1952         if (logconf.empty())
1953             logconf = XMLHelper::getAttrString(e, nullptr, logger);
1954         if (!logconf.empty()) {
1955             log.debug("loading new logging configuration from (%s), check log destination for status of configuration", logconf.c_str());
1956             if (!XMLToolingConfig::getConfig().log_config(logconf.c_str()))
1957                 log.crit("failed to load new logging configuration from (%s)", logconf.c_str());
1958         }
1959
1960 #ifndef SHIBSP_LITE
1961         m_tranLog.reset(
1962             new TransactionLog(
1963                 XMLHelper::getAttrString(SHAR, nullptr, tranLogFormat).c_str(),
1964                 XMLHelper::getAttrString(SHAR, nullptr, tranLogFiller).c_str()
1965                 )
1966             );
1967 #endif
1968     }
1969
1970     // Re-log library versions now that logging is set up.
1971     log.info("Shibboleth SP Version %s", PACKAGE_VERSION);
1972 #ifndef SHIBSP_LITE
1973     log.info(
1974         "Library versions: %s %s, Xerces-C %s, XML-Security-C %s, XMLTooling-C %s, OpenSAML-C %s, Shibboleth %s",
1975 # if defined(LOG4SHIB_VERSION)
1976     "log4shib", LOG4SHIB_VERSION,
1977 # elif defined(LOG4CPP_VERSION)
1978     "log4cpp", LOG4CPP_VERSION,
1979 # else
1980     "", "",
1981 # endif
1982         XERCES_FULLVERSIONDOT, XSEC_FULLVERSIONDOT, gXMLToolingDotVersionStr, gOpenSAMLDotVersionStr, gShibSPDotVersionStr
1983         );
1984 #else
1985     log.info(
1986         "Library versions: %s %s, Xerces-C %s, XMLTooling-C %s, Shibboleth %s",
1987 # if defined(LOG4SHIB_VERSION)
1988     "log4shib", LOG4SHIB_VERSION,
1989 # elif defined(LOG4CPP_VERSION)
1990     "log4cpp", LOG4CPP_VERSION,
1991 # else
1992     "", "",
1993 # endif
1994         XERCES_FULLVERSIONDOT, gXMLToolingDotVersionStr, gShibSPDotVersionStr
1995         );
1996 #endif
1997
1998     // First load any property sets.
1999     load(e, nullptr, this);
2000
2001     DOMElement* child;
2002
2003     // Much of the processing can only occur on the first instantiation.
2004     if (first) {
2005         // Set clock skew.
2006         pair<bool,unsigned int> skew=getUnsignedInt("clockSkew");
2007         if (skew.first)
2008             xmlConf.clock_skew_secs=min(skew.second,(60*60*24*7*28));
2009
2010         pair<bool,const char*> unsafe = getString("unsafeChars");
2011         if (unsafe.first)
2012             TemplateEngine::unsafe_chars = unsafe.second;
2013
2014         unsafe = getString("allowedSchemes");
2015         if (unsafe.first) {
2016             HTTPResponse::getAllowedSchemes().clear();
2017             string schemes(unsafe.second);
2018             split(HTTPResponse::getAllowedSchemes(), schemes, is_space(), algorithm::token_compress_on);
2019         }
2020
2021         // Default language handling.
2022         pair<bool,bool> langFromClient = getBool("langFromClient");
2023         pair<bool,const XMLCh*> langPriority = getXMLString("langPriority");
2024         GenericRequest::setLangDefaults(!langFromClient.first || langFromClient.second, langPriority.second);
2025
2026 #ifndef SHIBSP_LITE
2027         langPriority = getXMLString("contactPriority");
2028         if (langPriority.first)
2029             SAMLConfig::getConfig().setContactPriority(langPriority.second);
2030 #endif
2031
2032         // Extensions
2033         doExtensions(e, "global", log);
2034         if (conf.isEnabled(SPConfig::OutOfProcess))
2035             doExtensions(SHAR, "out of process", log);
2036
2037         if (conf.isEnabled(SPConfig::InProcess))
2038             doExtensions(SHIRE, "in process", log);
2039
2040         // Instantiate the ListenerService and SessionCache objects.
2041         if (conf.isEnabled(SPConfig::Listener))
2042             doListener(e, outer, log);
2043
2044 #ifndef SHIBSP_LITE
2045         if (outer->m_listener && conf.isEnabled(SPConfig::OutOfProcess) && !conf.isEnabled(SPConfig::InProcess)) {
2046             outer->m_listener->regListener("set::RelayState", outer);
2047             outer->m_listener->regListener("get::RelayState", outer);
2048             outer->m_listener->regListener("set::PostData", outer);
2049             outer->m_listener->regListener("get::PostData", outer);
2050         }
2051 #endif
2052         if (conf.isEnabled(SPConfig::Caching))
2053             doCaching(e, outer, log);
2054     } // end of first-time-only stuff
2055
2056     // Back to the fully dynamic stuff...next up is the RequestMapper.
2057     if (conf.isEnabled(SPConfig::RequestMapping)) {
2058         if (child = XMLHelper::getFirstChildElement(e, _RequestMapper)) {
2059             string t(XMLHelper::getAttrString(child, nullptr, _type));
2060             if (!t.empty()) {
2061                 log.info("building RequestMapper of type %s...", t.c_str());
2062                 m_requestMapper.reset(conf.RequestMapperManager.newPlugin(t.c_str(), child));
2063             }
2064         }
2065         if (!m_requestMapper) {
2066             log.info("no RequestMapper specified, using 'Native' plugin with empty/default map");
2067             child = e->getOwnerDocument()->createElementNS(nullptr, _RequestMapper);
2068             DOMElement* mapperDummy = e->getOwnerDocument()->createElementNS(shibspconstants::SHIB2SPCONFIG_NS, RequestMap);
2069             mapperDummy->setAttributeNS(nullptr, applicationId, _default);
2070             child->appendChild(mapperDummy);
2071             m_requestMapper.reset(conf.RequestMapperManager.newPlugin(NATIVE_REQUEST_MAPPER, child));
2072         }
2073     }
2074
2075 #ifndef SHIBSP_LITE
2076     // Load security policies.
2077     if (child = XMLHelper::getLastChildElement(e, _SecurityPolicyProvider)) {
2078         string t(XMLHelper::getAttrString(child, nullptr, _type));
2079         if (!t.empty()) {
2080             log.info("building SecurityPolicyProvider of type %s...", t.c_str());
2081             m_policy.reset(conf.SecurityPolicyProviderManager.newPlugin(t.c_str(), child));
2082         }
2083         else {
2084             throw ConfigurationException("can't build SecurityPolicyProvider, no type specified");
2085         }
2086     }
2087     else if (child = XMLHelper::getLastChildElement(e, SecurityPolicies)) {
2088         // For backward compatibility, wrap in a plugin element.
2089         DOMElement* polwrapper = e->getOwnerDocument()->createElementNS(nullptr, _SecurityPolicyProvider);
2090         polwrapper->appendChild(child);
2091         log.info("building SecurityPolicyProvider of type %s...", XML_SECURITYPOLICY_PROVIDER);
2092         m_policy.reset(conf.SecurityPolicyProviderManager.newPlugin(XML_SECURITYPOLICY_PROVIDER, polwrapper));
2093     }
2094     else {
2095         log.fatal("can't build SecurityPolicyProvider, missing conf:SecurityPolicyProvider element?");
2096         throw ConfigurationException("Can't build SecurityPolicyProvider, missing conf:SecurityPolicyProvider element?");
2097     }
2098
2099     if (first) {
2100         if (!m_policy->getAlgorithmBlacklist().empty()) {
2101 #ifdef SHIBSP_XMLSEC_WHITELISTING
2102             for_each(
2103                 m_policy->getAlgorithmBlacklist().begin(), m_policy->getAlgorithmBlacklist().end(),
2104                 boost::bind(&XSECPlatformUtils::blacklistAlgorithm, boost::bind(&xstring::c_str, _1))
2105                 );
2106 #else
2107             log.crit("XML-Security-C library prior to 1.6.0 does not support algorithm white/blacklists");
2108 #endif
2109         }
2110         else if (!m_policy->getAlgorithmWhitelist().empty()) {
2111 #ifdef SHIBSP_XMLSEC_WHITELISTING
2112             for_each(
2113                 m_policy->getAlgorithmWhitelist().begin(), m_policy->getAlgorithmWhitelist().end(),
2114                 boost::bind(&XSECPlatformUtils::whitelistAlgorithm, boost::bind(&xstring::c_str, _1))
2115                 );
2116 #else
2117             log.crit("XML-Security-C library prior to 1.6.0 does not support algorithm white/blacklists");
2118 #endif
2119         }
2120     }
2121
2122     // Process TransportOption elements.
2123     child = XMLHelper::getLastChildElement(e, TransportOption);
2124     while (child) {
2125         if (child->hasChildNodes()) {
2126             string provider(XMLHelper::getAttrString(child, nullptr, _provider));
2127             string option(XMLHelper::getAttrString(child, nullptr, _option));
2128             auto_ptr_char value(child->getFirstChild()->getNodeValue());
2129             if (!provider.empty() && !option.empty() && value.get() && *value.get()) {
2130                 m_transportOptions.push_back(make_tuple(provider, option, string(value.get())));
2131             }
2132         }
2133         child = XMLHelper::getPreviousSiblingElement(child, TransportOption);
2134     }
2135 #endif
2136
2137     scoped_ptr<ProtocolProvider> pp;
2138     if (conf.isEnabled(SPConfig::Handlers)) {
2139         if (child = XMLHelper::getLastChildElement(e, _ProtocolProvider)) {
2140             string t(XMLHelper::getAttrString(child, nullptr, _type));
2141             if (!t.empty()) {
2142                 log.info("building ProtocolProvider of type %s...", t.c_str());
2143                 pp.reset(conf.ProtocolProviderManager.newPlugin(t.c_str(), child));
2144             }
2145         }
2146     }
2147     Locker pplocker(pp.get());
2148
2149     // Load the default application.
2150     child = XMLHelper::getLastChildElement(e, ApplicationDefaults);
2151     if (!child) {
2152         log.fatal("can't build default Application object, missing conf:ApplicationDefaults element?");
2153         throw ConfigurationException("can't build default Application object, missing conf:ApplicationDefaults element?");
2154     }
2155     boost::shared_ptr<XMLApplication> defapp(new XMLApplication(outer, pp.get(), child));
2156     m_appmap[defapp->getId()] = defapp;
2157
2158     // Load any overrides.
2159     child = XMLHelper::getFirstChildElement(child, ApplicationOverride);
2160     while (child) {
2161         boost::shared_ptr<XMLApplication> iapp(new XMLApplication(outer, pp.get(), child, defapp.get()));
2162         if (m_appmap.count(iapp->getId()))
2163             log.crit("found conf:ApplicationOverride element with duplicate id attribute (%s), skipping it", iapp->getId());
2164         else
2165             m_appmap[iapp->getId()] = iapp;
2166
2167         child = XMLHelper::getNextSiblingElement(child, ApplicationOverride);
2168     }
2169
2170     // Check for extra AuthTypes to recognize.
2171     if (conf.isEnabled(SPConfig::InProcess)) {
2172         const PropertySet* inprocs = getPropertySet("InProcess");
2173         if (inprocs) {
2174             pair<bool,const char*> extraAuthTypes = inprocs->getString("extraAuthTypes");
2175             if (extraAuthTypes.first) {
2176                 string types(extraAuthTypes.second);
2177                 split(outer->m_authTypes, types, is_space(), algorithm::token_compress_on);
2178                 outer->m_authTypes.insert("shibboleth");
2179             }
2180         }
2181     }
2182 }
2183
2184 #ifndef SHIBSP_LITE
2185 void XMLConfig::receive(DDF& in, ostream& out)
2186 {
2187     if (!strcmp(in.name(), "get::RelayState")) {
2188         const char* id = in["id"].string();
2189         const char* key = in["key"].string();
2190         if (!id || !key)
2191             throw ListenerException("Required parameters missing for RelayState recovery.");
2192
2193         string relayState;
2194         StorageService* storage = getStorageService(id);
2195         if (storage) {
2196             if (storage->readString("RelayState",key,&relayState)>0) {
2197                 if (in["clear"].integer())
2198                     storage->deleteString("RelayState",key);
2199             }
2200             else if (storage->readText("RelayState",key,&relayState)>0) {
2201                 if (in["clear"].integer())
2202                     storage->deleteText("RelayState",key);
2203             }
2204         }
2205         else {
2206             Category::getInstance(SHIBSP_LOGCAT".ServiceProvider").error(
2207                 "Storage-backed RelayState with invalid StorageService ID (%s)", id
2208                 );
2209         }
2210
2211         // Repack for return to caller.
2212         DDF ret=DDF(nullptr).unsafe_string(relayState.c_str());
2213         DDFJanitor jret(ret);
2214         out << ret;
2215     }
2216     else if (!strcmp(in.name(), "set::RelayState")) {
2217         const char* id = in["id"].string();
2218         const char* value = in["value"].string();
2219         if (!id || !value)
2220             throw ListenerException("Required parameters missing for RelayState creation.");
2221
2222         string rsKey;
2223         StorageService* storage = getStorageService(id);
2224         if (storage) {
2225             SAMLConfig::getConfig().generateRandomBytes(rsKey,32);
2226             rsKey = SAMLArtifact::toHex(rsKey);
2227             if (strlen(value) <= storage->getCapabilities().getStringSize())
2228                 storage->createString("RelayState", rsKey.c_str(), value, time(nullptr) + 600);
2229             else
2230                 storage->createText("RelayState", rsKey.c_str(), value, time(nullptr) + 600);
2231         }
2232         else {
2233             Category::getInstance(SHIBSP_LOGCAT".ServiceProvider").error(
2234                 "Storage-backed RelayState with invalid StorageService ID (%s)", id
2235                 );
2236         }
2237
2238         // Repack for return to caller.
2239         DDF ret=DDF(nullptr).string(rsKey.c_str());
2240         DDFJanitor jret(ret);
2241         out << ret;
2242     }
2243     else if (!strcmp(in.name(), "get::PostData")) {
2244         const char* id = in["id"].string();
2245         const char* key = in["key"].string();
2246         if (!id || !key)
2247             throw ListenerException("Required parameters missing for PostData recovery.");
2248
2249         string postData;
2250         StorageService* storage = getStorageService(id);
2251         if (storage) {
2252             if (storage->readText("PostData",key,&postData) > 0) {
2253                 storage->deleteText("PostData",key);
2254             }
2255         }
2256         else {
2257             Category::getInstance(SHIBSP_LOGCAT".ServiceProvider").error(
2258                 "Storage-backed PostData with invalid StorageService ID (%s)", id
2259                 );
2260         }
2261         // If the data's empty, we'll send nothing back.
2262         // If not, we don't need to round trip it, just send back the serialized DDF list.
2263         if (postData.empty()) {
2264             DDF ret(nullptr);
2265             DDFJanitor jret(ret);
2266             out << ret;
2267         }
2268         else {
2269             out << postData;
2270         }
2271     }
2272     else if (!strcmp(in.name(), "set::PostData")) {
2273         const char* id = in["id"].string();
2274         if (!id || !in["parameters"].islist())
2275             throw ListenerException("Required parameters missing for PostData creation.");
2276
2277         string rsKey;
2278         StorageService* storage = getStorageService(id);
2279         if (storage) {
2280             SAMLConfig::getConfig().generateRandomBytes(rsKey,32);
2281             rsKey = SAMLArtifact::toHex(rsKey);
2282             ostringstream params;
2283             params << in["parameters"];
2284             storage->createText("PostData", rsKey.c_str(), params.str().c_str(), time(nullptr) + 600);
2285         }
2286         else {
2287             Category::getInstance(SHIBSP_LOGCAT".ServiceProvider").error(
2288                 "Storage-backed PostData with invalid StorageService ID (%s)", id
2289                 );
2290         }
2291
2292         // Repack for return to caller.
2293         DDF ret=DDF(nullptr).string(rsKey.c_str());
2294         DDFJanitor jret(ret);
2295         out << ret;
2296     }
2297 }
2298 #endif
2299
2300 pair<bool,DOMElement*> XMLConfig::background_load()
2301 {
2302     // Load from source using base class.
2303     pair<bool,DOMElement*> raw = ReloadableXMLFile::load();
2304
2305     // If we own it, wrap it.
2306     XercesJanitor<DOMDocument> docjanitor(raw.first ? raw.second->getOwnerDocument() : nullptr);
2307
2308     scoped_ptr<XMLConfigImpl> impl(new XMLConfigImpl(raw.second, (m_impl==nullptr), this, m_log));
2309
2310     // If we held the document, transfer it to the impl. If we didn't, it's a no-op.
2311     impl->setDocument(docjanitor.release());
2312
2313     // Perform the swap inside a lock.
2314     if (m_lock)
2315         m_lock->wrlock();
2316     SharedLock locker(m_lock, false);
2317     m_impl.swap(impl);
2318
2319     return make_pair(false,(DOMElement*)nullptr);
2320 }