SSPCPP-613 - add warning if no semi-colon found
[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< boost::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< boost::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 _policyId[] =            UNICODE_LITERAL_8(p,o,l,i,c,y,I,d);
507     static const XMLCh _ProtocolProvider[] =    UNICODE_LITERAL_16(P,r,o,t,o,c,o,l,P,r,o,v,i,d,e,r);
508     static const XMLCh _provider[] =            UNICODE_LITERAL_8(p,r,o,v,i,d,e,r);
509     static const XMLCh RelyingParty[] =         UNICODE_LITERAL_12(R,e,l,y,i,n,g,P,a,r,t,y);
510     static const XMLCh _ReplayCache[] =         UNICODE_LITERAL_11(R,e,p,l,a,y,C,a,c,h,e);
511     static const XMLCh _RequestMapper[] =       UNICODE_LITERAL_13(R,e,q,u,e,s,t,M,a,p,p,e,r);
512     static const XMLCh RequestMap[] =           UNICODE_LITERAL_10(R,e,q,u,e,s,t,M,a,p);
513     static const XMLCh SecurityPolicies[] =     UNICODE_LITERAL_16(S,e,c,u,r,i,t,y,P,o,l,i,c,i,e,s);
514     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);
515     static const XMLCh _SessionCache[] =        UNICODE_LITERAL_12(S,e,s,s,i,o,n,C,a,c,h,e);
516     static const XMLCh _SessionInitiator[] =    UNICODE_LITERAL_16(S,e,s,s,i,o,n,I,n,i,t,i,a,t,o,r);
517     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);
518     static const XMLCh Site[] =                 UNICODE_LITERAL_4(S,i,t,e);
519     static const XMLCh SSO[] =                  UNICODE_LITERAL_3(S,S,O);
520     static const XMLCh _StorageService[] =      UNICODE_LITERAL_14(S,t,o,r,a,g,e,S,e,r,v,i,c,e);
521     static const XMLCh TCPListener[] =          UNICODE_LITERAL_11(T,C,P,L,i,s,t,e,n,e,r);
522     static const XMLCh tranLogFiller[] =        UNICODE_LITERAL_13(t,r,a,n,L,o,g,F,i,l,l,e,r);
523     static const XMLCh tranLogFormat[] =        UNICODE_LITERAL_13(t,r,a,n,L,o,g,F,o,r,m,a,t);
524     static const XMLCh TransportOption[] =      UNICODE_LITERAL_15(T,r,a,n,s,p,o,r,t,O,p,t,i,o,n);
525     static const XMLCh _TrustEngine[] =         UNICODE_LITERAL_11(T,r,u,s,t,E,n,g,i,n,e);
526     static const XMLCh _type[] =                UNICODE_LITERAL_4(t,y,p,e);
527     static const XMLCh UnixListener[] =         UNICODE_LITERAL_12(U,n,i,x,L,i,s,t,e,n,e,r);
528 };
529
530 namespace shibsp {
531     ServiceProvider* XMLServiceProviderFactory(const DOMElement* const & e)
532     {
533         return new XMLConfig(e);
534     }
535 };
536
537 XMLApplication::XMLApplication(
538     const ServiceProvider* sp,
539     const ProtocolProvider* pp,
540     DOMElement* e,
541     const XMLApplication* base
542     ) : Application(sp), m_base(base), m_acsDefault(nullptr), m_sessionInitDefault(nullptr), m_artifactResolutionDefault(nullptr)
543 {
544 #ifdef _DEBUG
545     xmltooling::NDC ndc("XMLApplication");
546 #endif
547     Category& log = Category::getInstance(SHIBSP_LOGCAT ".Application");
548
549     // First load any property sets.
550     map<string,string> remapper;
551     remapper["relayStateLimit"] = "redirectLimit";
552     remapper["relayStateWhitelist"] = "redirectWhitelist";
553     load(e, nullptr, this, &remapper);
554
555     // Process redirect limit policy. Do this before assigning the parent pointer
556     // to ensure we get only our Sessions element.
557     const PropertySet* sessionProps = getPropertySet("Sessions");
558     if (sessionProps) {
559         pair<bool,const char*> prop = sessionProps->getString("redirectLimit");
560         if (prop.first) {
561             if (!strcmp(prop.second, "none"))
562                 m_redirectLimit = REDIRECT_LIMIT_NONE;
563             else if (!strcmp(prop.second, "exact"))
564                 m_redirectLimit = REDIRECT_LIMIT_EXACT;
565             else if (!strcmp(prop.second, "host"))
566                 m_redirectLimit = REDIRECT_LIMIT_HOST;
567             else {
568                 if (!strcmp(prop.second, "exact+whitelist"))
569                     m_redirectLimit = REDIRECT_LIMIT_EXACT_WHITELIST;
570                 else if (!strcmp(prop.second, "host+whitelist"))
571                     m_redirectLimit = REDIRECT_LIMIT_HOST_WHITELIST;
572                 else if (!strcmp(prop.second, "whitelist"))
573                     m_redirectLimit = REDIRECT_LIMIT_WHITELIST;
574                 else
575                     throw ConfigurationException("Unrecognized redirectLimit setting ($1)", params(1, prop.second));
576                 prop = sessionProps->getString("redirectWhitelist");
577                 if (prop.first) {
578                     string dup(prop.second);
579                     trim(dup);
580                     split(m_redirectWhitelist, dup, is_space(), algorithm::token_compress_on);
581                 }
582             }
583         }
584         else {
585             m_redirectLimit = base ? REDIRECT_LIMIT_INHERIT : REDIRECT_LIMIT_NONE;
586         }
587
588         // Audit some additional settings for logging purposes.
589         prop = sessionProps->getString("cookieProps");
590         if (!prop.first) {
591             log.warn("empty/missing cookieProps setting, set to \"https\" for SSL/TLS-only usage");
592         }
593         else if (!strcmp(prop.second, "http")) {
594             log.warn("insecure cookieProps setting, set to \"https\" for SSL/TLS-only usage");
595         }
596         else if (strcmp(prop.second, "https")) {
597             if (!strstr(prop.second, "secure"))
598                 log.warn("custom cookieProps setting should include \"; secure\" for SSL/TLS-only usage");
599             else if (!strstr(prop.second, "HttpOnly"))
600                 log.warn("custom cookieProps setting should include \"; HttpOnly\", site is vulnerable to client-side cookie theft");
601
602             while (*prop.second && isspace(*prop.second))
603                 ++prop.second;
604             if (*prop.second != ';')
605                 log.warn("custom cookieProps setting must begin with a semicolon (;) as a delimiter");
606         }
607
608         pair<bool,bool> handlerSSL = sessionProps->getBool("handlerSSL");
609         if (handlerSSL.first && !handlerSSL.second)
610             log.warn("handlerSSL should be enabled for SSL/TLS-enabled web sites");
611     }
612     else {
613         m_redirectLimit = base ? REDIRECT_LIMIT_INHERIT : REDIRECT_LIMIT_NONE;
614     }
615
616     // Assign parent.
617     if (base)
618         setParent(base);
619
620     SPConfig& conf=SPConfig::getConfig();
621 #ifndef SHIBSP_LITE
622     XMLToolingConfig& xmlConf=XMLToolingConfig::getConfig();
623 #endif
624
625     // This used to be an actual hash, but now it's just a hex-encode to avoid xmlsec dependency.
626     static char DIGITS[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
627     string tohash=getId();
628     tohash+=getString("entityID").second;
629     for (const char* ch = tohash.c_str(); *ch; ++ch) {
630         m_hash += (DIGITS[((unsigned char)(0xF0 & *ch)) >> 4 ]);
631         m_hash += (DIGITS[0x0F & *ch]);
632     }
633
634     doAttributeInfo();
635
636     if (conf.isEnabled(SPConfig::Handlers))
637         doHandlers(pp, e, log);
638
639     // Notification.
640     DOMNodeList* nlist = e->getElementsByTagNameNS(shibspconstants::SHIB2SPCONFIG_NS, Notify);
641     for (XMLSize_t i = 0; nlist && i < nlist->getLength(); ++i) {
642         if (nlist->item(i)->getParentNode()->isSameNode(e)) {
643             const XMLCh* channel = static_cast<DOMElement*>(nlist->item(i))->getAttributeNS(nullptr, Channel);
644             string loc(XMLHelper::getAttrString(static_cast<DOMElement*>(nlist->item(i)), nullptr, Location));
645             if (!loc.empty()) {
646                 if (channel && *channel == chLatin_f)
647                     m_frontLogout.push_back(loc);
648                 else
649                     m_backLogout.push_back(loc);
650             }
651         }
652     }
653
654 #ifndef SHIBSP_LITE
655     nlist = e->getElementsByTagNameNS(samlconstants::SAML20_NS, Audience::LOCAL_NAME);
656     if (nlist && nlist->getLength()) {
657         log.warn("use of <saml:Audience> elements outside of a Security Policy Rule is deprecated");
658         for (XMLSize_t i = 0; i < nlist->getLength(); ++i)
659             if (nlist->item(i)->getParentNode()->isSameNode(e) && nlist->item(i)->hasChildNodes())
660                 m_audiences.push_back(nlist->item(i)->getFirstChild()->getNodeValue());
661     }
662
663     if (conf.isEnabled(SPConfig::Metadata)) {
664         m_metadata.reset(
665             doChainedPlugins(
666                 SAMLConfig::getConfig().MetadataProviderManager, "MetadataProvider", CHAINING_METADATA_PROVIDER, _MetadataProvider, e, log
667                 )
668             );
669         try {
670             if (m_metadata)
671                 m_metadata->init();
672             else if (!m_base)
673                 log.warn("no MetadataProvider available, configure at least one for standard SSO usage");
674         }
675         catch (std::exception& ex) {
676             log.crit("error initializing MetadataProvider: %s", ex.what());
677         }
678     }
679
680     if (conf.isEnabled(SPConfig::Trust)) {
681         m_trust.reset(doChainedPlugins(xmlConf.TrustEngineManager, "TrustEngine", CHAINING_TRUSTENGINE, _TrustEngine, e, log));
682         if (!m_trust && !m_base) {
683             log.info(
684                 "no TrustEngine specified or installed, using default chain {%s, %s}",
685                 EXPLICIT_KEY_TRUSTENGINE, SHIBBOLETH_PKIX_TRUSTENGINE
686                 );
687             m_trust.reset(xmlConf.TrustEngineManager.newPlugin(CHAINING_TRUSTENGINE, nullptr));
688             ChainingTrustEngine* trustchain = dynamic_cast<ChainingTrustEngine*>(m_trust.get());
689             if (trustchain) {
690                 trustchain->addTrustEngine(xmlConf.TrustEngineManager.newPlugin(EXPLICIT_KEY_TRUSTENGINE, nullptr));
691                 trustchain->addTrustEngine(xmlConf.TrustEngineManager.newPlugin(SHIBBOLETH_PKIX_TRUSTENGINE, nullptr));
692             }
693         }
694     }
695
696     if (conf.isEnabled(SPConfig::AttributeResolution)) {
697         doAttributePlugins(e, log);
698     }
699
700     if (conf.isEnabled(SPConfig::Credentials)) {
701         m_credResolver.reset(
702             doChainedPlugins(xmlConf.CredentialResolverManager, "CredentialResolver", CHAINING_CREDENTIAL_RESOLVER, _CredentialResolver, e, log)
703             );
704     }
705
706     // Finally, load relying parties.
707     const DOMElement* child = XMLHelper::getFirstChildElement(e, RelyingParty);
708     while (child) {
709         if (child->hasAttributeNS(nullptr, saml2::Attribute::NAME_ATTRIB_NAME)) {
710             boost::shared_ptr<DOMPropertySet> rp(new DOMPropertySet());
711             rp->load(child, nullptr, this);
712             rp->setParent(this);
713             m_partyMap[child->getAttributeNS(nullptr, saml2::Attribute::NAME_ATTRIB_NAME)] = rp;
714         }
715         else if (child->hasAttributeNS(nullptr, _type)) {
716             string emtype(XMLHelper::getAttrString(child, nullptr, _type));
717             boost::shared_ptr<EntityMatcher> em(SAMLConfig::getConfig().EntityMatcherManager.newPlugin(emtype, child));
718             boost::shared_ptr<DOMPropertySet> rp(new DOMPropertySet());
719             rp->load(child, nullptr, this);
720             rp->setParent(this);
721             m_partyVec.push_back(make_pair(em, rp));
722         }
723         child = XMLHelper::getNextSiblingElement(child, RelyingParty);
724     }
725     if (base && m_partyMap.empty() && m_partyVec.empty() && (!base->m_partyMap.empty() || !base->m_partyVec.empty())) {
726         // For inheritance of RPs to work, we have to pull them in to the override by cloning the DOM.
727         child = XMLHelper::getFirstChildElement(base->getElement(), RelyingParty);
728         while (child) {
729             if (child->hasAttributeNS(nullptr, saml2::Attribute::NAME_ATTRIB_NAME)) {
730                 DOMElement* rpclone = static_cast<DOMElement*>(child->cloneNode(true));
731                 boost::shared_ptr<DOMPropertySet> rp(new DOMPropertySet());
732                 rp->load(rpclone, nullptr, this);
733                 rp->setParent(this);
734                 m_partyMap[rpclone->getAttributeNS(nullptr, saml2::Attribute::NAME_ATTRIB_NAME)] = rp;
735             }
736             else if (child->hasAttributeNS(nullptr, _type)) {
737                 DOMElement* rpclone = static_cast<DOMElement*>(child->cloneNode(true));
738                 string emtype(XMLHelper::getAttrString(rpclone, nullptr, _type));
739                 boost::shared_ptr<EntityMatcher> em(SAMLConfig::getConfig().EntityMatcherManager.newPlugin(emtype, rpclone));
740                 boost::shared_ptr<DOMPropertySet> rp(new DOMPropertySet());
741                 rp->load(rpclone, nullptr, this);
742                 rp->setParent(this);
743                 m_partyVec.push_back(make_pair(em, rp));
744             }
745             child = XMLHelper::getNextSiblingElement(child, RelyingParty);
746         }
747     }
748 #endif
749
750     // Out of process only, we register a listener endpoint.
751     if (!conf.isEnabled(SPConfig::InProcess)) {
752         ListenerService* listener = sp->getListenerService(false);
753         if (listener) {
754             string addr=string(getId()) + "::getHeaders::Application";
755             listener->regListener(addr.c_str(), this);
756         }
757         else {
758             log.info("no ListenerService available, Application remoting disabled");
759         }
760     }
761 }
762
763 XMLApplication::~XMLApplication()
764 {
765     ListenerService* listener=getServiceProvider().getListenerService(false);
766     if (listener && SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess) && !SPConfig::getConfig().isEnabled(SPConfig::InProcess)) {
767         string addr=string(getId()) + "::getHeaders::Application";
768         listener->unregListener(addr.c_str(), this);
769     }
770 }
771
772 template <class T> T* XMLApplication::doChainedPlugins(
773     PluginManager<T,string,const DOMElement*>& pluginMgr,
774     const char* pluginType,
775     const char* chainingType,
776     const XMLCh* localName,
777     DOMElement* e,
778     Category& log,
779     const char* dummyType
780     )
781 {
782     string t;
783     DOMElement* child = XMLHelper::getFirstChildElement(e, localName);
784     if (child) {
785         // Check for multiple.
786         if (XMLHelper::getNextSiblingElement(child, localName)) {
787             log.info("multiple %s plugins, wrapping in a chain", pluginType);
788             DOMElement* chain = child->getOwnerDocument()->createElementNS(nullptr, localName);
789             while (child) {
790                 chain->appendChild(child);
791                 child = XMLHelper::getFirstChildElement(e, localName);
792             }
793             t = chainingType;
794             child = chain;
795             e->appendChild(chain);
796         }
797         else {
798             // Only a single one.
799             t = XMLHelper::getAttrString(child, nullptr, _type);
800         }
801
802         try {
803             if (!t.empty()) {
804                 log.info("building %s of type %s...", pluginType, t.c_str());
805                 return pluginMgr.newPlugin(t.c_str(), child);
806             }
807             else {
808                 throw ConfigurationException("$1 element had no type attribute.", params(1, pluginType));
809             }
810         }
811         catch (std::exception& ex) {
812             log.crit("error building %s: %s", pluginType, ex.what());
813             if (dummyType) {
814                 // Install a dummy version as a safety valve.
815                 log.crit("installing safe %s in place of failed version", pluginType);
816                 return pluginMgr.newPlugin(dummyType, nullptr);
817             }
818         }
819     }
820
821     return nullptr;
822 }
823
824 void XMLApplication::doAttributeInfo()
825 {
826     // Populate prefix pair.
827     m_attributePrefix.second = "HTTP_";
828     pair<bool,const char*> prefix = getString("attributePrefix");
829     if (prefix.first) {
830         m_attributePrefix.first = prefix.second;
831         const char* pch = prefix.second;
832         while (*pch) {
833             m_attributePrefix.second += (isalnum(*pch) ? toupper(*pch) : '_');
834             pch++;
835         }
836     }
837
838     pair<bool,const char*> attributes = getString("REMOTE_USER");
839     if (attributes.first) {
840         string dup(attributes.second);
841         trim(dup);
842         split(m_remoteUsers, dup, is_space(), algorithm::token_compress_on);
843     }
844
845     // Load attribute ID lists for REMOTE_USER and header clearing.
846     if (SPConfig::getConfig().isEnabled(SPConfig::InProcess)) {
847         attributes = getString("unsetHeaders");
848         if (attributes.first) {
849             string transformedprefix(m_attributePrefix.second);
850             const char* pch;
851             prefix = getString("metadataAttributePrefix");
852             if (prefix.first) {
853                 pch = prefix.second;
854                 while (*pch) {
855                     transformedprefix += (isalnum(*pch) ? toupper(*pch) : '_');
856                     pch++;
857                 }
858             }
859
860             string dup(attributes.second);
861             trim(dup);
862             vector<string> headerNames;
863             split(headerNames, dup, is_space(), algorithm::token_compress_on);
864             for (vector<string>::const_iterator h = headerNames.begin(); h != headerNames.end(); ++h) {
865                 string transformed;
866                 const char* pch = h->c_str();
867                 while (*pch) {
868                     transformed += (isalnum(*pch) ? toupper(*pch) : '_');
869                     pch++;
870                 }
871                 m_unsetHeaders.push_back(pair<string,string>(m_attributePrefix.first + *h, m_attributePrefix.second + transformed));
872                 if (prefix.first)
873                     m_unsetHeaders.push_back(pair<string,string>(m_attributePrefix.first + prefix.second + *h, transformedprefix + transformed));
874             }
875             m_unsetHeaders.push_back(pair<string,string>(m_attributePrefix.first + "Shib-Application-ID", m_attributePrefix.second + "SHIB_APPLICATION_ID"));
876         }
877     }
878 }
879
880 void XMLApplication::doHandlers(const ProtocolProvider* pp, const DOMElement* e, Category& log)
881 {
882     SPConfig& conf = SPConfig::getConfig();
883
884     const PropertySet* sessions = getPropertySet("Sessions");
885
886     // Process assertion export handler.
887     pair<bool,const char*> location = sessions ? sessions->getString("exportLocation") : pair<bool,const char*>(false,nullptr);
888     if (location.first) {
889         try {
890             DOMElement* exportElement = e->getOwnerDocument()->createElementNS(shibspconstants::SHIB2SPCONFIG_NS, _Handler);
891             exportElement->setAttributeNS(nullptr,Location,sessions->getXMLString("exportLocation").second);
892             pair<bool,const XMLCh*> exportACL = sessions->getXMLString("exportACL");
893             if (exportACL.first) {
894                 static const XMLCh _acl[] = UNICODE_LITERAL_9(e,x,p,o,r,t,A,C,L);
895                 exportElement->setAttributeNS(nullptr,_acl,exportACL.second);
896             }
897             boost::shared_ptr<Handler> exportHandler(
898                 conf.HandlerManager.newPlugin(samlconstants::SAML20_BINDING_URI, pair<const DOMElement*,const char*>(exportElement, getId()))
899                 );
900             m_handlers.push_back(exportHandler);
901
902             // Insert into location map. If it contains the handlerURL, we skip past that part.
903             const char* hurl = sessions->getString("handlerURL").second;
904             if (!hurl)
905                 hurl = "/Shibboleth.sso";
906             const char* pch = strstr(location.second, hurl);
907             if (pch)
908                 location.second = pch + strlen(hurl);
909             if (*location.second == '/')
910                 m_handlerMap[location.second] = exportHandler.get();
911             else
912                 m_handlerMap[string("/") + location.second] = exportHandler.get();
913         }
914         catch (std::exception& ex) {
915             log.error("caught exception installing assertion lookup handler: %s", ex.what());
916         }
917     }
918
919     // Look for "shorthand" elements first.
920     set<string> protocols;
921     DOMElement* child = sessions ? XMLHelper::getFirstChildElement(sessions->getElement()) : nullptr;
922     while (child) {
923         if (XMLHelper::isNodeNamed(child, shibspconstants::SHIB2SPCONFIG_NS, SSO)) {
924             if (pp)
925                 doSSO(*pp, protocols, child, log);
926             else
927                 log.error("no ProtocolProvider, SSO auto-configure unsupported");
928         }
929         else if (XMLHelper::isNodeNamed(child, shibspconstants::SHIB2SPCONFIG_NS, Logout)) {
930             if (pp)
931                 doLogout(*pp, protocols, child, log);
932             else
933                 log.error("no ProtocolProvider, Logout auto-configure unsupported");
934         }
935         else if (XMLHelper::isNodeNamed(child, shibspconstants::SHIB2SPCONFIG_NS, NameIDMgmt)) {
936             if (pp)
937                 doNameIDMgmt(*pp, protocols, child, log);
938             else
939                 log.error("no ProtocolProvider, NameIDMgmt auto-configure unsupported");
940         }
941         else {
942             break;  // drop into next while loop
943         }
944         child = XMLHelper::getNextSiblingElement(child);
945     }
946
947     // Process other handlers.
948     bool hardACS=false, hardSessionInit=false, hardArt=false;
949     while (child) {
950         if (!child->hasAttributeNS(nullptr, Location)) {
951             auto_ptr_char hclass(child->getLocalName());
952             log.error("%s handler with no Location property cannot be processed", hclass.get());
953             child = XMLHelper::getNextSiblingElement(child);
954             continue;
955         }
956         try {
957             boost::shared_ptr<Handler> handler;
958             if (XMLString::equals(child->getLocalName(), _AssertionConsumerService)) {
959                 string bindprop(XMLHelper::getAttrString(child, nullptr, Binding));
960                 if (bindprop.empty()) {
961                     log.error("AssertionConsumerService element has no Binding attribute, skipping it...");
962                     child = XMLHelper::getNextSiblingElement(child);
963                     continue;
964                 }
965                 handler.reset(conf.AssertionConsumerServiceManager.newPlugin(bindprop.c_str(), pair<const DOMElement*,const char*>(child, getId())));
966                 // Map by binding and protocol (may be > 1 per protocol and binding)
967                 m_acsBindingMap[handler->getXMLString("Binding").second].push_back(handler.get());
968                 const XMLCh* protfamily = handler->getProtocolFamily();
969                 if (protfamily)
970                     m_acsProtocolMap[protfamily].push_back(handler.get());
971                 m_acsIndexMap[handler->getUnsignedInt("index").second] = handler.get();
972
973                 if (!hardACS) {
974                     pair<bool,bool> defprop = handler->getBool("isDefault");
975                     if (defprop.first) {
976                         if (defprop.second) {
977                             hardACS = true;
978                             m_acsDefault = handler.get();
979                         }
980                     }
981                     else if (!m_acsDefault)
982                         m_acsDefault = handler.get();
983                 }
984             }
985             else if (XMLString::equals(child->getLocalName(), _SessionInitiator)) {
986                 string t(XMLHelper::getAttrString(child, nullptr, _type));
987                 if (t.empty()) {
988                     log.error("SessionInitiator element has no type attribute, skipping it...");
989                     child = XMLHelper::getNextSiblingElement(child);
990                     continue;
991                 }
992                 boost::shared_ptr<SessionInitiator> sihandler(
993                     conf.SessionInitiatorManager.newPlugin(t.c_str(), pair<const DOMElement*,const char*>(child, getId()))
994                     );
995                 handler = sihandler;
996                 pair<bool,const char*> si_id = handler->getString("id");
997                 if (si_id.first && si_id.second)
998                     m_sessionInitMap[si_id.second] = sihandler.get();
999                 if (!hardSessionInit) {
1000                     pair<bool,bool> defprop = handler->getBool("isDefault");
1001                     if (defprop.first) {
1002                         if (defprop.second) {
1003                             hardSessionInit = true;
1004                             m_sessionInitDefault = sihandler.get();
1005                         }
1006                     }
1007                     else if (!m_sessionInitDefault) {
1008                         m_sessionInitDefault = sihandler.get();
1009                     }
1010                 }
1011             }
1012             else if (XMLString::equals(child->getLocalName(), _LogoutInitiator)) {
1013                 string t(XMLHelper::getAttrString(child, nullptr, _type));
1014                 if (t.empty()) {
1015                     log.error("LogoutInitiator element has no type attribute, skipping it...");
1016                     child = XMLHelper::getNextSiblingElement(child);
1017                     continue;
1018                 }
1019                 handler.reset(conf.LogoutInitiatorManager.newPlugin(t.c_str(), pair<const DOMElement*,const char*>(child, getId())));
1020             }
1021             else if (XMLString::equals(child->getLocalName(), _ArtifactResolutionService)) {
1022                 string bindprop(XMLHelper::getAttrString(child, nullptr, Binding));
1023                 if (bindprop.empty()) {
1024                     log.error("ArtifactResolutionService element has no Binding attribute, skipping it...");
1025                     child = XMLHelper::getNextSiblingElement(child);
1026                     continue;
1027                 }
1028                 handler.reset(conf.ArtifactResolutionServiceManager.newPlugin(bindprop.c_str(), pair<const DOMElement*,const char*>(child, getId())));
1029
1030                 if (!hardArt) {
1031                     pair<bool,bool> defprop = handler->getBool("isDefault");
1032                     if (defprop.first) {
1033                         if (defprop.second) {
1034                             hardArt = true;
1035                             m_artifactResolutionDefault = handler.get();
1036                         }
1037                     }
1038                     else if (!m_artifactResolutionDefault)
1039                         m_artifactResolutionDefault = handler.get();
1040                 }
1041             }
1042             else if (XMLString::equals(child->getLocalName(), _SingleLogoutService)) {
1043                 string bindprop(XMLHelper::getAttrString(child, nullptr, Binding));
1044                 if (bindprop.empty()) {
1045                     log.error("SingleLogoutService element has no Binding attribute, skipping it...");
1046                     child = XMLHelper::getNextSiblingElement(child);
1047                     continue;
1048                 }
1049                 handler.reset(conf.SingleLogoutServiceManager.newPlugin(bindprop.c_str(), pair<const DOMElement*,const char*>(child, getId())));
1050             }
1051             else if (XMLString::equals(child->getLocalName(), _ManageNameIDService)) {
1052                 string bindprop(XMLHelper::getAttrString(child, nullptr, Binding));
1053                 if (bindprop.empty()) {
1054                     log.error("ManageNameIDService element has no Binding attribute, skipping it...");
1055                     child = XMLHelper::getNextSiblingElement(child);
1056                     continue;
1057                 }
1058                 handler.reset(conf.ManageNameIDServiceManager.newPlugin(bindprop.c_str(), pair<const DOMElement*,const char*>(child, getId())));
1059             }
1060             else {
1061                 string t(XMLHelper::getAttrString(child, nullptr, _type));
1062                 if (t.empty()) {
1063                     log.error("Handler element has no type attribute, skipping it...");
1064                     child = XMLHelper::getNextSiblingElement(child);
1065                     continue;
1066                 }
1067                 handler.reset(conf.HandlerManager.newPlugin(t.c_str(), pair<const DOMElement*,const char*>(child, getId())));
1068             }
1069
1070             m_handlers.push_back(handler);
1071
1072             // Insert into location map.
1073             location = handler->getString("Location");
1074             if (location.first && *location.second == '/')
1075                 m_handlerMap[location.second] = handler.get();
1076             else if (location.first)
1077                 m_handlerMap[string("/") + location.second] = handler.get();
1078         }
1079         catch (std::exception& ex) {
1080             log.error("caught exception processing handler element: %s", ex.what());
1081         }
1082
1083         child = XMLHelper::getNextSiblingElement(child);
1084     }
1085 }
1086
1087 void XMLApplication::doSSO(const ProtocolProvider& pp, set<string>& protocols, DOMElement* e, Category& log)
1088 {
1089     if (!e->hasChildNodes())
1090         return;
1091     DOMNamedNodeMap* ssoprops = e->getAttributes();
1092     XMLSize_t ssopropslen = ssoprops ? ssoprops->getLength() : 0;
1093
1094     SPConfig& conf = SPConfig::getConfig();
1095
1096     int index = 0; // track ACS indexes globally across all protocols
1097
1098     // Tokenize the protocol list inside the element.
1099     XMLStringTokenizer prottokens(e->getTextContent());
1100     while (prottokens.hasMoreTokens()) {
1101         auto_ptr_char prot(prottokens.nextToken());
1102
1103         // Look for initiator.
1104         const PropertySet* initiator = pp.getInitiator(prot.get(), "SSO");
1105         if (initiator) {
1106             log.info("auto-configuring SSO initiation for protocol (%s)", prot.get());
1107             pair<bool,const XMLCh*> inittype = initiator->getXMLString("id");
1108             if (inittype.first) {
1109                 // Append a session initiator element of the designated type to the root element.
1110                 DOMElement* sidom = e->getOwnerDocument()->createElementNS(shibspconstants::SHIB2SPCONFIG_NS, _SessionInitiator);
1111                 sidom->setAttributeNS(nullptr, _type, inittype.second);
1112                 e->appendChild(sidom);
1113                 log.info("adding SessionInitiator of type (%s) to chain (/Login)", initiator->getString("id").second);
1114
1115                 doArtifactResolution(pp, prot.get(), e, log);
1116                 protocols.insert(prot.get());
1117             }
1118             else {
1119                 log.error("missing id property on Initiator element, check config for protocol (%s)", prot.get());
1120             }
1121         }
1122
1123         // Look for incoming bindings.
1124         const vector<const PropertySet*>& bindings = pp.getBindings(prot.get(), "SSO");
1125         if (!bindings.empty()) {
1126             log.info("auto-configuring SSO endpoints for protocol (%s)", prot.get());
1127             pair<bool,const XMLCh*> idprop,pathprop;
1128             for (vector<const PropertySet*>::const_iterator b = bindings.begin(); b != bindings.end(); ++b, ++index) {
1129                 idprop = (*b)->getXMLString("id");
1130                 pathprop = (*b)->getXMLString("path");
1131                 if (idprop.first && pathprop.first) {
1132                     DOMElement* acsdom = e->getOwnerDocument()->createElementNS(samlconstants::SAML20MD_NS, _AssertionConsumerService);
1133
1134                     // Copy in any attributes from the <SSO> element so they can be accessed as properties in the ACS handler.
1135                     for (XMLSize_t p = 0; p < ssopropslen; ++p) {
1136                         DOMNode* ssoprop = ssoprops->item(p);
1137                         if (ssoprop->getNodeType() == DOMNode::ATTRIBUTE_NODE) {
1138                             acsdom->setAttributeNS(
1139                                 ((DOMAttr*)ssoprop)->getNamespaceURI(),
1140                                 ((DOMAttr*)ssoprop)->getLocalName(),
1141                                 ((DOMAttr*)ssoprop)->getValue()
1142                                 );
1143                         }
1144                     }
1145
1146                     // Set necessary properties based on context.
1147                     acsdom->setAttributeNS(nullptr, Binding, idprop.second);
1148                     acsdom->setAttributeNS(nullptr, Location, pathprop.second);
1149                     xstring indexbuf(1, chDigit_1 + (index % 10));
1150                     if (index / 10)
1151                         indexbuf = (XMLCh)(chDigit_1 + (index / 10)) + indexbuf;
1152                     acsdom->setAttributeNS(nullptr, _index, indexbuf.c_str());
1153
1154                     log.info("adding AssertionConsumerService for Binding (%s) at (%s)", (*b)->getString("id").second, (*b)->getString("path").second);
1155                     boost::shared_ptr<Handler> handler(
1156                         conf.AssertionConsumerServiceManager.newPlugin(
1157                             (*b)->getString("id").second, pair<const DOMElement*,const char*>(acsdom, getId())
1158                             )
1159                         );
1160                     m_handlers.push_back(handler);
1161
1162                     // Setup maps and defaults.
1163                     m_acsBindingMap[handler->getXMLString("Binding").second].push_back(handler.get());
1164                     const XMLCh* protfamily = handler->getProtocolFamily();
1165                     if (protfamily)
1166                         m_acsProtocolMap[protfamily].push_back(handler.get());
1167                     m_acsIndexMap[handler->getUnsignedInt("index").second] = handler.get();
1168                     if (!m_acsDefault)
1169                         m_acsDefault = handler.get();
1170
1171                     // Insert into location map.
1172                     pair<bool,const char*> location = handler->getString("Location");
1173                     if (location.first && *location.second == '/')
1174                         m_handlerMap[location.second] = handler.get();
1175                     else if (location.first)
1176                         m_handlerMap[string("/") + location.second] = handler.get();
1177                 }
1178                 else {
1179                     log.error("missing id or path property on Binding element, check config for protocol (%s)", prot.get());
1180                 }
1181             }
1182         }
1183
1184         if (!initiator && bindings.empty()) {
1185             log.error("no SSO Initiator or Binding config for protocol (%s)", prot.get());
1186         }
1187     }
1188
1189     // Handle discovery.
1190     static const XMLCh discoveryProtocol[] = UNICODE_LITERAL_17(d,i,s,c,o,v,e,r,y,P,r,o,t,o,c,o,l);
1191     static const XMLCh discoveryURL[] = UNICODE_LITERAL_12(d,i,s,c,o,v,e,r,y,U,R,L);
1192     static const XMLCh _URL[] = UNICODE_LITERAL_3(U,R,L);
1193     const XMLCh* discop = e->getAttributeNS(nullptr, discoveryProtocol);
1194     if (discop && *discop) {
1195         const XMLCh* discou = e->getAttributeNS(nullptr, discoveryURL);
1196         if (discou && *discou) {
1197             // Append a session initiator element of the designated type to the root element.
1198             DOMElement* sidom = e->getOwnerDocument()->createElementNS(shibspconstants::SHIB2SPCONFIG_NS, _SessionInitiator);
1199             sidom->setAttributeNS(nullptr, _type, discop);
1200             sidom->setAttributeNS(nullptr, _URL, discou);
1201             e->appendChild(sidom);
1202             if (log.isInfoEnabled()) {
1203                 auto_ptr_char dp(discop);
1204                 log.info("adding SessionInitiator of type (%s) to chain (/Login)", dp.get());
1205             }
1206         }
1207         else {
1208             log.error("SSO discoveryProtocol specified without discoveryURL");
1209         }
1210     }
1211
1212     // Attach default Location to SSO element.
1213     static const XMLCh _loc[] = { chForwardSlash, chLatin_L, chLatin_o, chLatin_g, chLatin_i, chLatin_n, chNull };
1214     e->setAttributeNS(nullptr, Location, _loc);
1215
1216     // Instantiate Chaining initiator around the SSO element.
1217     boost::shared_ptr<SessionInitiator> chain(
1218         conf.SessionInitiatorManager.newPlugin(CHAINING_SESSION_INITIATOR, pair<const DOMElement*,const char*>(e, getId()))
1219         );
1220     m_handlers.push_back(chain);
1221     m_sessionInitDefault = chain.get();
1222     m_handlerMap["/Login"] = chain.get();
1223 }
1224
1225 void XMLApplication::doLogout(const ProtocolProvider& pp, set<string>& protocols, DOMElement* e, Category& log)
1226 {
1227     if (!e->hasChildNodes())
1228         return;
1229     DOMNamedNodeMap* sloprops = e->getAttributes();
1230     XMLSize_t slopropslen = sloprops ? sloprops->getLength() : 0;
1231
1232     SPConfig& conf = SPConfig::getConfig();
1233
1234     // Tokenize the protocol list inside the element.
1235     XMLStringTokenizer prottokens(e->getTextContent());
1236     while (prottokens.hasMoreTokens()) {
1237         auto_ptr_char prot(prottokens.nextToken());
1238
1239         // Look for initiator.
1240         const PropertySet* initiator = pp.getInitiator(prot.get(), "Logout");
1241         if (initiator) {
1242             log.info("auto-configuring Logout initiation for protocol (%s)", prot.get());
1243             pair<bool,const XMLCh*> inittype = initiator->getXMLString("id");
1244             if (inittype.first) {
1245                 // Append a logout initiator element of the designated type to the root element.
1246                 DOMElement* lidom = e->getOwnerDocument()->createElementNS(shibspconstants::SHIB2SPCONFIG_NS, _LogoutInitiator);
1247                 lidom->setAttributeNS(nullptr, _type, inittype.second);
1248                 e->appendChild(lidom);
1249                 log.info("adding LogoutInitiator of type (%s) to chain (/Logout)", initiator->getString("id").second);
1250
1251                 if (protocols.count(prot.get()) == 0) {
1252                     doArtifactResolution(pp, prot.get(), e, log);
1253                     protocols.insert(prot.get());
1254                 }
1255             }
1256             else {
1257                 log.error("missing id property on Initiator element, check config for protocol (%s)", prot.get());
1258             }
1259         }
1260
1261         // Look for incoming bindings.
1262         const vector<const PropertySet*>& bindings = pp.getBindings(prot.get(), "Logout");
1263         if (!bindings.empty()) {
1264             log.info("auto-configuring Logout endpoints for protocol (%s)", prot.get());
1265             pair<bool,const XMLCh*> idprop,pathprop;
1266             for (vector<const PropertySet*>::const_iterator b = bindings.begin(); b != bindings.end(); ++b) {
1267                 idprop = (*b)->getXMLString("id");
1268                 pathprop = (*b)->getXMLString("path");
1269                 if (idprop.first && pathprop.first) {
1270                     DOMElement* slodom = e->getOwnerDocument()->createElementNS(samlconstants::SAML20MD_NS, _SingleLogoutService);
1271
1272                     // Copy in any attributes from the <Logout> element so they can be accessed as properties in the SLO handler.
1273                     for (XMLSize_t p = 0; p < slopropslen; ++p) {
1274                         DOMNode* sloprop = sloprops->item(p);
1275                         if (sloprop->getNodeType() == DOMNode::ATTRIBUTE_NODE) {
1276                             slodom->setAttributeNS(
1277                                 ((DOMAttr*)sloprop)->getNamespaceURI(),
1278                                 ((DOMAttr*)sloprop)->getLocalName(),
1279                                 ((DOMAttr*)sloprop)->getValue()
1280                                 );
1281                         }
1282                     }
1283
1284                     // Set necessary properties based on context.
1285                     slodom->setAttributeNS(nullptr, Binding, idprop.second);
1286                     slodom->setAttributeNS(nullptr, Location, pathprop.second);
1287                     if (e->hasAttributeNS(nullptr, _policyId))
1288                         slodom->setAttributeNS(shibspconstants::SHIB2SPCONFIG_NS, _policyId, e->getAttributeNS(nullptr, _policyId));
1289
1290                     log.info("adding SingleLogoutService for Binding (%s) at (%s)", (*b)->getString("id").second, (*b)->getString("path").second);
1291                     boost::shared_ptr<Handler> handler(
1292                         conf.SingleLogoutServiceManager.newPlugin((*b)->getString("id").second, pair<const DOMElement*,const char*>(slodom, getId()))
1293                         );
1294                     m_handlers.push_back(handler);
1295
1296                     // Insert into location map.
1297                     pair<bool,const char*> location = handler->getString("Location");
1298                     if (location.first && *location.second == '/')
1299                         m_handlerMap[location.second] = handler.get();
1300                     else if (location.first)
1301                         m_handlerMap[string("/") + location.second] = handler.get();
1302                 }
1303                 else {
1304                     log.error("missing id or path property on Binding element, check config for protocol (%s)", prot.get());
1305                 }
1306             }
1307
1308             if (protocols.count(prot.get()) == 0) {
1309                 doArtifactResolution(pp, prot.get(), e, log);
1310                 protocols.insert(prot.get());
1311             }
1312         }
1313
1314         if (!initiator && bindings.empty()) {
1315             log.error("no Logout Initiator or Binding config for protocol (%s)", prot.get());
1316         }
1317     }
1318
1319     // Attach default Location to Logout element.
1320     static const XMLCh _loc[] = { chForwardSlash, chLatin_L, chLatin_o, chLatin_g, chLatin_o, chLatin_u, chLatin_t, chNull };
1321     e->setAttributeNS(nullptr, Location, _loc);
1322
1323     // Instantiate Chaining initiator around the SSO element.
1324     boost::shared_ptr<Handler> chain(
1325         conf.LogoutInitiatorManager.newPlugin(CHAINING_LOGOUT_INITIATOR, pair<const DOMElement*,const char*>(e, getId()))
1326         );
1327     m_handlers.push_back(chain);
1328     m_handlerMap["/Logout"] = chain.get();
1329 }
1330
1331 void XMLApplication::doNameIDMgmt(const ProtocolProvider& pp, set<string>& protocols, DOMElement* e, Category& log)
1332 {
1333     if (!e->hasChildNodes())
1334         return;
1335     DOMNamedNodeMap* nimprops = e->getAttributes();
1336     XMLSize_t nimpropslen = nimprops ? nimprops->getLength() : 0;
1337
1338     SPConfig& conf = SPConfig::getConfig();
1339
1340     // Tokenize the protocol list inside the element.
1341     XMLStringTokenizer prottokens(e->getTextContent());
1342     while (prottokens.hasMoreTokens()) {
1343         auto_ptr_char prot(prottokens.nextToken());
1344
1345         // Look for incoming bindings.
1346         const vector<const PropertySet*>& bindings = pp.getBindings(prot.get(), "NameIDMgmt");
1347         if (!bindings.empty()) {
1348             log.info("auto-configuring NameIDMgmt endpoints for protocol (%s)", prot.get());
1349             pair<bool,const XMLCh*> idprop,pathprop;
1350             for (vector<const PropertySet*>::const_iterator b = bindings.begin(); b != bindings.end(); ++b) {
1351                 idprop = (*b)->getXMLString("id");
1352                 pathprop = (*b)->getXMLString("path");
1353                 if (idprop.first && pathprop.first) {
1354                     DOMElement* nimdom = e->getOwnerDocument()->createElementNS(samlconstants::SAML20MD_NS, _ManageNameIDService);
1355
1356                     // Copy in any attributes from the <NameIDMgmt> element so they can be accessed as properties in the NIM handler.
1357                     for (XMLSize_t p = 0; p < nimpropslen; ++p) {
1358                         DOMNode* nimprop = nimprops->item(p);
1359                         if (nimprop->getNodeType() == DOMNode::ATTRIBUTE_NODE) {
1360                             nimdom->setAttributeNS(
1361                                 ((DOMAttr*)nimprop)->getNamespaceURI(),
1362                                 ((DOMAttr*)nimprop)->getLocalName(),
1363                                 ((DOMAttr*)nimprop)->getValue()
1364                                 );
1365                         }
1366                     }
1367
1368                     // Set necessary properties based on context.
1369                     nimdom->setAttributeNS(nullptr, Binding, idprop.second);
1370                     nimdom->setAttributeNS(nullptr, Location, pathprop.second);
1371                     if (e->hasAttributeNS(nullptr, _policyId))
1372                         nimdom->setAttributeNS(shibspconstants::SHIB2SPCONFIG_NS, _policyId, e->getAttributeNS(nullptr, _policyId));
1373
1374                     log.info("adding ManageNameIDService for Binding (%s) at (%s)", (*b)->getString("id").second, (*b)->getString("path").second);
1375                     boost::shared_ptr<Handler> handler(
1376                         conf.ManageNameIDServiceManager.newPlugin((*b)->getString("id").second, pair<const DOMElement*,const char*>(nimdom, getId()))
1377                         );
1378                     m_handlers.push_back(handler);
1379
1380                     // Insert into location map.
1381                     pair<bool,const char*> location = handler->getString("Location");
1382                     if (location.first && *location.second == '/')
1383                         m_handlerMap[location.second] = handler.get();
1384                     else if (location.first)
1385                         m_handlerMap[string("/") + location.second] = handler.get();
1386                 }
1387                 else {
1388                     log.error("missing id or path property on Binding element, check config for protocol (%s)", prot.get());
1389                 }
1390             }
1391
1392             if (protocols.count(prot.get()) == 0) {
1393                 doArtifactResolution(pp, prot.get(), e, log);
1394                 protocols.insert(prot.get());
1395             }
1396         }
1397         else {
1398             log.error("no NameIDMgmt Binding config for protocol (%s)", prot.get());
1399         }
1400     }
1401 }
1402
1403 void XMLApplication::doArtifactResolution(const ProtocolProvider& pp, const char* protocol, DOMElement* e, Category& log)
1404 {
1405     SPConfig& conf = SPConfig::getConfig();
1406
1407     int index = 0; // track indexes globally across all protocols
1408
1409     // Look for incoming bindings.
1410     const vector<const PropertySet*>& bindings = pp.getBindings(protocol, "ArtifactResolution");
1411     if (!bindings.empty()) {
1412         log.info("auto-configuring ArtifactResolution endpoints for protocol (%s)", protocol);
1413         pair<bool,const XMLCh*> idprop,pathprop;
1414         for (vector<const PropertySet*>::const_iterator b = bindings.begin(); b != bindings.end(); ++b, ++index) {
1415             idprop = (*b)->getXMLString("id");
1416             pathprop = (*b)->getXMLString("path");
1417             if (idprop.first && pathprop.first) {
1418                 DOMElement* artdom = e->getOwnerDocument()->createElementNS(samlconstants::SAML20MD_NS, _ArtifactResolutionService);
1419                 artdom->setAttributeNS(nullptr, Binding, idprop.second);
1420                 artdom->setAttributeNS(nullptr, Location, pathprop.second);
1421                 xstring indexbuf(1, chDigit_1 + (index % 10));
1422                 if (index / 10)
1423                     indexbuf = (XMLCh)(chDigit_1 + (index / 10)) + indexbuf;
1424                 artdom->setAttributeNS(nullptr, _index, indexbuf.c_str());
1425
1426                 log.info("adding ArtifactResolutionService for Binding (%s) at (%s)", (*b)->getString("id").second, (*b)->getString("path").second);
1427                 boost::shared_ptr<Handler> handler(
1428                     conf.ArtifactResolutionServiceManager.newPlugin((*b)->getString("id").second, pair<const DOMElement*,const char*>(artdom, getId()))
1429                     );
1430                 m_handlers.push_back(handler);
1431
1432                 if (!m_artifactResolutionDefault)
1433                     m_artifactResolutionDefault = handler.get();
1434
1435                 // Insert into location map.
1436                 pair<bool,const char*> location = handler->getString("Location");
1437                 if (location.first && *location.second == '/')
1438                     m_handlerMap[location.second] = handler.get();
1439                 else if (location.first)
1440                     m_handlerMap[string("/") + location.second] = handler.get();
1441             }
1442             else {
1443                 log.error("missing id or path property on Binding element, check config for protocol (%s)", protocol);
1444             }
1445         }
1446     }
1447 }
1448
1449 #ifndef SHIBSP_LITE
1450 void XMLApplication::doAttributePlugins(DOMElement* e, Category& log)
1451 {
1452     SPConfig& conf = SPConfig::getConfig();
1453
1454     m_attrExtractor.reset(
1455         doChainedPlugins(conf.AttributeExtractorManager, "AttributeExtractor", CHAINING_ATTRIBUTE_EXTRACTOR, _AttributeExtractor, e, log)
1456         );
1457
1458     m_attrFilter.reset(
1459         doChainedPlugins(conf.AttributeFilterManager, "AttributeFilter", CHAINING_ATTRIBUTE_FILTER, _AttributeFilter, e, log, DUMMY_ATTRIBUTE_FILTER)
1460         );
1461
1462     m_attrResolver.reset(
1463         doChainedPlugins(conf.AttributeResolverManager, "AttributeResolver", CHAINING_ATTRIBUTE_RESOLVER, _AttributeResolver, e, log)
1464         );
1465
1466     if (m_unsetHeaders.empty()) {
1467         vector<string> unsetHeaders;
1468         if (m_attrExtractor) {
1469             Locker extlock(m_attrExtractor.get());
1470             m_attrExtractor->getAttributeIds(unsetHeaders);
1471         }
1472         else if (m_base && m_base->m_attrExtractor) {
1473             Locker extlock(m_base->m_attrExtractor.get());
1474             m_base->m_attrExtractor->getAttributeIds(unsetHeaders);
1475         }
1476         if (m_attrResolver) {
1477             Locker reslock(m_attrResolver.get());
1478             m_attrResolver->getAttributeIds(unsetHeaders);
1479         }
1480         else if (m_base && m_base->m_attrResolver) {
1481             Locker extlock(m_base->m_attrResolver.get());
1482             m_base->m_attrResolver->getAttributeIds(unsetHeaders);
1483         }
1484         if (!unsetHeaders.empty()) {
1485             string transformedprefix(m_attributePrefix.second);
1486             const char* pch;
1487             pair<bool,const char*> prefix = getString("metadataAttributePrefix");
1488             if (prefix.first) {
1489                 pch = prefix.second;
1490                 while (*pch) {
1491                     transformedprefix += (isalnum(*pch) ? toupper(*pch) : '_');
1492                     pch++;
1493                 }
1494             }
1495             for (vector<string>::const_iterator hdr = unsetHeaders.begin(); hdr!=unsetHeaders.end(); ++hdr) {
1496                 string transformed;
1497                 pch = hdr->c_str();
1498                 while (*pch) {
1499                     transformed += (isalnum(*pch) ? toupper(*pch) : '_');
1500                     pch++;
1501                 }
1502                 m_unsetHeaders.push_back(make_pair(m_attributePrefix.first + *hdr, m_attributePrefix.second + transformed));
1503                 if (prefix.first)
1504                     m_unsetHeaders.push_back(make_pair(m_attributePrefix.first + prefix.second + *hdr, transformedprefix + transformed));
1505             }
1506         }
1507         m_unsetHeaders.push_back(make_pair(m_attributePrefix.first + "Shib-Application-ID", m_attributePrefix.second + "SHIB_APPLICATION_ID"));
1508     }
1509 }
1510 #endif
1511
1512 #ifdef SHIBSP_XERCESC_SHORT_ACCEPTNODE
1513 short
1514 #else
1515 DOMNodeFilter::FilterAction
1516 #endif
1517 XMLApplication::acceptNode(const DOMNode* node) const
1518 {
1519     const XMLCh* name=node->getLocalName();
1520     if (XMLString::equals(name,ApplicationOverride) ||
1521         XMLString::equals(name,_Audience) ||
1522         XMLString::equals(name,Notify) ||
1523         XMLString::equals(name,_Handler) ||
1524         XMLString::equals(name,_AssertionConsumerService) ||
1525         XMLString::equals(name,_ArtifactResolutionService) ||
1526         XMLString::equals(name,Logout) ||
1527         XMLString::equals(name,_LogoutInitiator) ||
1528         XMLString::equals(name,_ManageNameIDService) ||
1529         XMLString::equals(name,NameIDMgmt) ||
1530         XMLString::equals(name,_SessionInitiator) ||
1531         XMLString::equals(name,_SingleLogoutService) ||
1532         XMLString::equals(name,SSO) ||
1533         XMLString::equals(name,RelyingParty) ||
1534         XMLString::equals(name,_MetadataProvider) ||
1535         XMLString::equals(name,_TrustEngine) ||
1536         XMLString::equals(name,_CredentialResolver) ||
1537         XMLString::equals(name,_AttributeFilter) ||
1538         XMLString::equals(name,_AttributeExtractor) ||
1539         XMLString::equals(name,_AttributeResolver))
1540         return FILTER_REJECT;
1541
1542     return FILTER_ACCEPT;
1543 }
1544
1545 #ifndef SHIBSP_LITE
1546
1547 const PropertySet* XMLApplication::getRelyingParty(const EntityDescriptor* provider) const
1548 {
1549     if (!provider)
1550         return this;
1551
1552     // Check for exact match on name.
1553     map< xstring,boost::shared_ptr<PropertySet> >::const_iterator i = m_partyMap.find(provider->getEntityID());
1554     if (i != m_partyMap.end())
1555         return i->second.get();
1556
1557     // Check for extensible matching.
1558     vector < pair< boost::shared_ptr<EntityMatcher>,boost::shared_ptr<PropertySet> > >::const_iterator j;
1559     for (j = m_partyVec.begin(); j != m_partyVec.end(); ++j) {
1560         if (j->first->matches(*provider))
1561             return j->second.get();
1562     }
1563
1564     // Check for group match.
1565     const EntitiesDescriptor* group = dynamic_cast<const EntitiesDescriptor*>(provider->getParent());
1566     while (group) {
1567         if (group->getName()) {
1568             i = m_partyMap.find(group->getName());
1569             if (i != m_partyMap.end())
1570                 return i->second.get();
1571         }
1572         group = dynamic_cast<const EntitiesDescriptor*>(group->getParent());
1573     }
1574     return this;
1575 }
1576
1577 const PropertySet* XMLApplication::getRelyingParty(const XMLCh* entityID) const
1578 {
1579     if (!entityID)
1580         return this;
1581     map< xstring,boost::shared_ptr<PropertySet> >::const_iterator i = m_partyMap.find(entityID);
1582     return (i != m_partyMap.end()) ? i->second.get() : this;
1583 }
1584
1585 #endif
1586
1587 string XMLApplication::getNotificationURL(const char* resource, bool front, unsigned int index) const
1588 {
1589     const vector<string>& locs = front ? m_frontLogout : m_backLogout;
1590     if (locs.empty())
1591         return m_base ? m_base->getNotificationURL(resource, front, index) : string();
1592     else if (index >= locs.size())
1593         return string();
1594
1595 #ifdef HAVE_STRCASECMP
1596     if (!resource || (strncasecmp(resource,"http://",7) && strncasecmp(resource,"https://",8)))
1597 #else
1598     if (!resource || (strnicmp(resource,"http://",7) && strnicmp(resource,"https://",8)))
1599 #endif
1600         throw ConfigurationException("Request URL was not absolute.");
1601
1602     const char* handler = locs[index].c_str();
1603
1604     // Should never happen...
1605     if (!handler || (*handler!='/' && strncmp(handler,"http:",5) && strncmp(handler,"https:",6)))
1606         throw ConfigurationException(
1607             "Invalid Location property ($1) in Notify element for Application ($2)",
1608             params(2, handler ? handler : "null", getId())
1609             );
1610
1611     // The "Location" property can be in one of three formats:
1612     //
1613     // 1) a full URI:       http://host/foo/bar
1614     // 2) a hostless URI:   http:///foo/bar
1615     // 3) a relative path:  /foo/bar
1616     //
1617     // #  Protocol  Host        Path
1618     // 1  handler   handler     handler
1619     // 2  handler   resource    handler
1620     // 3  resource  resource    handler
1621
1622     const char* path = nullptr;
1623
1624     // Decide whether to use the handler or the resource for the "protocol"
1625     const char* prot;
1626     if (*handler != '/') {
1627         prot = handler;
1628     }
1629     else {
1630         prot = resource;
1631         path = handler;
1632     }
1633
1634     // break apart the "protocol" string into protocol, host, and "the rest"
1635     const char* colon=strchr(prot,':');
1636     colon += 3;
1637     const char* slash=strchr(colon,'/');
1638     if (!path)
1639         path = slash;
1640
1641     // Compute the actual protocol and store.
1642     string notifyURL(prot, colon-prot);
1643
1644     // create the "host" from either the colon/slash or from the target string
1645     // If prot == handler then we're in either #1 or #2, else #3.
1646     // If slash == colon then we're in #2.
1647     if (prot != handler || slash == colon) {
1648         colon = strchr(resource, ':');
1649         colon += 3;      // Get past the ://
1650         slash = strchr(colon, '/');
1651     }
1652     string host(colon, (slash ? slash-colon : strlen(colon)));
1653
1654     // Build the URL
1655     notifyURL += host + path;
1656     return notifyURL;
1657 }
1658
1659 void XMLApplication::clearHeader(SPRequest& request, const char* rawname, const char* cginame) const
1660 {
1661     if (!m_attributePrefix.first.empty()) {
1662         string temp = m_attributePrefix.first + rawname;
1663         string temp2 = m_attributePrefix.second + (cginame + 5);
1664         request.clearHeader(temp.c_str(), temp2.c_str());
1665     }
1666     else if (m_base) {
1667         m_base->clearHeader(request, rawname, cginame);
1668     }
1669     else {
1670         request.clearHeader(rawname, cginame);
1671     }
1672 }
1673
1674 void XMLApplication::setHeader(SPRequest& request, const char* name, const char* value) const
1675 {
1676     if (!m_attributePrefix.first.empty()) {
1677         string temp = m_attributePrefix.first + name;
1678         request.setHeader(temp.c_str(), value);
1679     }
1680     else if (m_base) {
1681         m_base->setHeader(request, name, value);
1682     }
1683     else {
1684         request.setHeader(name, value);
1685     }
1686 }
1687
1688 string XMLApplication::getSecureHeader(const SPRequest& request, const char* name) const
1689 {
1690     if (!m_attributePrefix.first.empty()) {
1691         string temp = m_attributePrefix.first + name;
1692         return request.getSecureHeader(temp.c_str());
1693     }
1694     else if (m_base) {
1695         return m_base->getSecureHeader(request,name);
1696     }
1697     else {
1698         return request.getSecureHeader(name);
1699     }
1700 }
1701
1702 const SessionInitiator* XMLApplication::getDefaultSessionInitiator() const
1703 {
1704     if (m_sessionInitDefault) return m_sessionInitDefault;
1705     return m_base ? m_base->getDefaultSessionInitiator() : nullptr;
1706 }
1707
1708 const SessionInitiator* XMLApplication::getSessionInitiatorById(const char* id) const
1709 {
1710     map<string,const SessionInitiator*>::const_iterator i = m_sessionInitMap.find(id);
1711     if (i != m_sessionInitMap.end()) return i->second;
1712     return m_base ? m_base->getSessionInitiatorById(id) : nullptr;
1713 }
1714
1715 const Handler* XMLApplication::getDefaultAssertionConsumerService() const
1716 {
1717     if (m_acsDefault) return m_acsDefault;
1718     return m_base ? m_base->getDefaultAssertionConsumerService() : nullptr;
1719 }
1720
1721 const Handler* XMLApplication::getAssertionConsumerServiceByIndex(unsigned short index) const
1722 {
1723     map<unsigned int,const Handler*>::const_iterator i = m_acsIndexMap.find(index);
1724     if (i != m_acsIndexMap.end()) return i->second;
1725     return m_base ? m_base->getAssertionConsumerServiceByIndex(index) : nullptr;
1726 }
1727
1728 const Handler* XMLApplication::getAssertionConsumerServiceByProtocol(const XMLCh* protocol, const char* binding) const
1729 {
1730     ACSProtocolMap::const_iterator i = m_acsProtocolMap.find(protocol);
1731     if (i != m_acsProtocolMap.end() && !i->second.empty()) {
1732         if (!binding || !*binding)
1733             return i->second.front();
1734         for (ACSProtocolMap::value_type::second_type::const_iterator j = i->second.begin(); j != i->second.end(); ++j) {
1735             if (!strcmp(binding, (*j)->getString("Binding").second))
1736                 return *j;
1737         }
1738     }
1739     return m_base ? m_base->getAssertionConsumerServiceByProtocol(protocol, binding) : nullptr;
1740 }
1741
1742 const vector<const Handler*>& XMLApplication::getAssertionConsumerServicesByBinding(const XMLCh* binding) const
1743 {
1744     ACSBindingMap::const_iterator i = m_acsBindingMap.find(binding);
1745     if (i != m_acsBindingMap.end())
1746         return i->second;
1747     return m_base ? m_base->getAssertionConsumerServicesByBinding(binding) : g_noHandlers;
1748 }
1749
1750 const Handler* XMLApplication::getHandler(const char* path) const
1751 {
1752     string wrap(path);
1753     wrap = wrap.substr(0, wrap.find(';'));
1754     map<string,const Handler*>::const_iterator i = m_handlerMap.find(wrap.substr(0, wrap.find('?')));
1755     if (i != m_handlerMap.end())
1756         return i->second;
1757     return m_base ? m_base->getHandler(path) : nullptr;
1758 }
1759
1760 void XMLApplication::getHandlers(vector<const Handler*>& handlers) const
1761 {
1762     static void (vector<const Handler*>::* pb)(const Handler* const&) = &vector<const Handler*>::push_back;
1763     for_each(m_handlers.begin(), m_handlers.end(), boost::bind(pb, boost::ref(handlers), boost::bind(&boost::shared_ptr<Handler>::get, _1)));
1764     if (m_base) {
1765         for (map<string,const Handler*>::const_iterator h = m_base->m_handlerMap.begin(); h != m_base->m_handlerMap.end(); ++h) {
1766             if (m_handlerMap.count(h->first) == 0)
1767                 handlers.push_back(h->second);
1768         }
1769     }
1770 }
1771
1772 void XMLApplication::limitRedirect(const GenericRequest& request, const char* url) const
1773 {
1774     if (!url || *url == '/')
1775         return;
1776     if (m_redirectLimit == REDIRECT_LIMIT_INHERIT)
1777         return m_base->limitRedirect(request, url);
1778     if (m_redirectLimit != REDIRECT_LIMIT_NONE) {
1779         vector<string> whitelist;
1780         if (m_redirectLimit == REDIRECT_LIMIT_EXACT || m_redirectLimit == REDIRECT_LIMIT_EXACT_WHITELIST) {
1781             // Scheme and hostname have to match.
1782             if (request.isDefaultPort()) {
1783                 whitelist.push_back(string(request.getScheme()) + "://" + request.getHostname() + '/');
1784             }
1785             whitelist.push_back(string(request.getScheme()) + "://" + request.getHostname() + ':' + lexical_cast<string>(request.getPort()) + '/');
1786         }
1787         else if (m_redirectLimit == REDIRECT_LIMIT_HOST || m_redirectLimit == REDIRECT_LIMIT_HOST_WHITELIST) {
1788             // Allow any scheme or port.
1789             whitelist.push_back(string("https://") + request.getHostname() + '/');
1790             whitelist.push_back(string("http://") + request.getHostname() + '/');
1791             whitelist.push_back(string("https://") + request.getHostname() + ':');
1792             whitelist.push_back(string("http://") + request.getHostname() + ':');
1793         }
1794
1795         static bool (*startsWithI)(const char*,const char*) = XMLString::startsWithI;
1796         if (!whitelist.empty() && find_if(whitelist.begin(), whitelist.end(),
1797                 boost::bind(startsWithI, url, boost::bind(&string::c_str, _1))) != whitelist.end()) {
1798             return;
1799         }
1800         else if (!m_redirectWhitelist.empty() && find_if(m_redirectWhitelist.begin(), m_redirectWhitelist.end(),
1801                 boost::bind(startsWithI, url, boost::bind(&string::c_str, _1))) != m_redirectWhitelist.end()) {
1802             return;
1803         }
1804         Category::getInstance(SHIBSP_LOGCAT ".Application").warn("redirectLimit policy enforced, blocked redirect to (%s)", url);
1805         throw opensaml::SecurityPolicyException("Blocked unacceptable redirect location.");
1806     }
1807 }
1808
1809 #ifdef SHIBSP_XERCESC_SHORT_ACCEPTNODE
1810 short
1811 #else
1812 DOMNodeFilter::FilterAction
1813 #endif
1814 XMLConfigImpl::acceptNode(const DOMNode* node) const
1815 {
1816     if (!XMLString::equals(node->getNamespaceURI(),shibspconstants::SHIB2SPCONFIG_NS))
1817         return FILTER_ACCEPT;
1818     const XMLCh* name=node->getLocalName();
1819     if (XMLString::equals(name,ApplicationDefaults) ||
1820         XMLString::equals(name,_ArtifactMap) ||
1821         XMLString::equals(name,_Extensions) ||
1822         XMLString::equals(name,Listener) ||
1823         XMLString::equals(name,_ProtocolProvider) ||
1824         XMLString::equals(name,_RequestMapper) ||
1825         XMLString::equals(name,_ReplayCache) ||
1826         XMLString::equals(name,SecurityPolicies) ||
1827         XMLString::equals(name,_SecurityPolicyProvider) ||
1828         XMLString::equals(name,_SessionCache) ||
1829         XMLString::equals(name,Site) ||
1830         XMLString::equals(name,_StorageService) ||
1831         XMLString::equals(name,TCPListener) ||
1832         XMLString::equals(name,TransportOption) ||
1833         XMLString::equals(name,UnixListener))
1834         return FILTER_REJECT;
1835
1836     return FILTER_ACCEPT;
1837 }
1838
1839 void XMLConfigImpl::doExtensions(const DOMElement* e, const char* label, Category& log)
1840 {
1841     const DOMElement* exts = XMLHelper::getFirstChildElement(e, _Extensions);
1842     if (exts) {
1843         exts = XMLHelper::getFirstChildElement(exts, Library);
1844         while (exts) {
1845             string path(XMLHelper::getAttrString(exts, nullptr, _path));
1846             try {
1847                 if (!path.empty()) {
1848                     if (!XMLToolingConfig::getConfig().load_library(path.c_str(), (void*)exts))
1849                         throw ConfigurationException("XMLToolingConfig::load_library failed.");
1850                     log.debug("loaded %s extension library (%s)", label, path.c_str());
1851                 }
1852             }
1853             catch (std::exception& e) {
1854                 if (XMLHelper::getAttrBool(exts, false, _fatal)) {
1855                     log.fatal("unable to load mandatory %s extension library %s: %s", label, path.c_str(), e.what());
1856                     throw;
1857                 }
1858                 else {
1859                     log.crit("unable to load optional %s extension library %s: %s", label, path.c_str(), e.what());
1860                 }
1861             }
1862             exts = XMLHelper::getNextSiblingElement(exts, Library);
1863         }
1864     }
1865 }
1866
1867 void XMLConfigImpl::doListener(const DOMElement* e, XMLConfig* conf, Category& log)
1868 {
1869 #ifdef WIN32
1870     string plugtype(TCP_LISTENER_SERVICE);
1871 #else
1872     string plugtype(UNIX_LISTENER_SERVICE);
1873 #endif
1874     DOMElement* child = XMLHelper::getFirstChildElement(e, UnixListener);
1875     if (child)
1876         plugtype = UNIX_LISTENER_SERVICE;
1877     else {
1878         child = XMLHelper::getFirstChildElement(e, TCPListener);
1879         if (child)
1880             plugtype = TCP_LISTENER_SERVICE;
1881         else {
1882             child = XMLHelper::getFirstChildElement(e, Listener);
1883             if (child) {
1884                 auto_ptr_char type(child->getAttributeNS(nullptr, _type));
1885                 if (type.get() && *type.get())
1886                     plugtype = type.get();
1887             }
1888         }
1889     }
1890
1891     log.info("building ListenerService of type %s...", plugtype.c_str());
1892     conf->m_listener.reset(SPConfig::getConfig().ListenerServiceManager.newPlugin(plugtype.c_str(), child));
1893 }
1894
1895 void XMLConfigImpl::doCaching(const DOMElement* e, XMLConfig* conf, Category& log)
1896 {
1897     SPConfig& spConf = SPConfig::getConfig();
1898 #ifndef SHIBSP_LITE
1899     SAMLConfig& samlConf = SAMLConfig::getConfig();
1900 #endif
1901
1902     DOMElement* child;
1903 #ifndef SHIBSP_LITE
1904     if (spConf.isEnabled(SPConfig::OutOfProcess)) {
1905         XMLToolingConfig& xmlConf = XMLToolingConfig::getConfig();
1906         // First build any StorageServices.
1907         child = XMLHelper::getFirstChildElement(e, _StorageService);
1908         while (child) {
1909             string id(XMLHelper::getAttrString(child, nullptr, _id));
1910             string t(XMLHelper::getAttrString(child, nullptr, _type));
1911             if (!t.empty()) {
1912                 try {
1913                     log.info("building StorageService (%s) of type %s...", id.c_str(), t.c_str());
1914                     conf->m_storage[id] = boost::shared_ptr<StorageService>(xmlConf.StorageServiceManager.newPlugin(t.c_str(), child));
1915                 }
1916                 catch (std::exception& ex) {
1917                     log.crit("failed to instantiate StorageService (%s): %s", id.c_str(), ex.what());
1918                 }
1919             }
1920             child = XMLHelper::getNextSiblingElement(child, _StorageService);
1921         }
1922
1923         if (conf->m_storage.empty()) {
1924             log.info("no StorageService plugin(s) installed, using (mem) in-memory instance");
1925             conf->m_storage["mem"] = boost::shared_ptr<StorageService>(xmlConf.StorageServiceManager.newPlugin(MEMORY_STORAGE_SERVICE, nullptr));
1926         }
1927
1928         // Replay cache.
1929         StorageService* replaySS = nullptr;
1930         child = XMLHelper::getFirstChildElement(e, _ReplayCache);
1931         if (child) {
1932             string ssid(XMLHelper::getAttrString(child, nullptr, _StorageService));
1933             if (!ssid.empty()) {
1934                 if (conf->m_storage.count(ssid)) {
1935                     log.info("building ReplayCache on top of StorageService (%s)...", ssid.c_str());
1936                     replaySS = conf->m_storage[ssid].get();
1937                 }
1938                 else {
1939                     log.error("unable to locate StorageService (%s), using arbitrary instance for ReplayCache", ssid.c_str());
1940                     replaySS = conf->m_storage.begin()->second.get();
1941                 }
1942             }
1943             else {
1944                 log.info("no StorageService specified for ReplayCache, using arbitrary instance");
1945                 replaySS = conf->m_storage.begin()->second.get();
1946             }
1947         }
1948         else {
1949             log.info("no ReplayCache specified, using arbitrary StorageService instance");
1950             replaySS = conf->m_storage.begin()->second.get();
1951         }
1952         xmlConf.setReplayCache(new ReplayCache(replaySS));
1953
1954         // ArtifactMap
1955         child = XMLHelper::getFirstChildElement(e, _ArtifactMap);
1956         if (child) {
1957             string ssid(XMLHelper::getAttrString(child, nullptr, _StorageService));
1958             if (!ssid.empty()) {
1959                 if (conf->m_storage.count(ssid)) {
1960                     log.info("building ArtifactMap on top of StorageService (%s)...", ssid.c_str());
1961                     samlConf.setArtifactMap(new ArtifactMap(child, conf->m_storage[ssid].get()));
1962                 }
1963                 else {
1964                     log.error("unable to locate StorageService (%s), using in-memory ArtifactMap", ssid.c_str());
1965                     samlConf.setArtifactMap(new ArtifactMap(child));
1966                 }
1967             }
1968             else {
1969                 log.info("no StorageService specified, using in-memory ArtifactMap");
1970                 samlConf.setArtifactMap(new ArtifactMap(child));
1971             }
1972         }
1973         else {
1974             log.info("no ArtifactMap specified, building in-memory ArtifactMap...");
1975             samlConf.setArtifactMap(new ArtifactMap(child));
1976         }
1977     }   // end of out of process caching components
1978 #endif
1979
1980     child = XMLHelper::getFirstChildElement(e, _SessionCache);
1981     if (child) {
1982         string t(XMLHelper::getAttrString(child, nullptr, _type));
1983         if (!t.empty()) {
1984             log.info("building SessionCache of type %s...", t.c_str());
1985             conf->m_sessionCache.reset(spConf.SessionCacheManager.newPlugin(t.c_str(), child));
1986         }
1987     }
1988     if (!conf->m_sessionCache) {
1989         log.info("no SessionCache specified, using StorageService-backed instance");
1990         conf->m_sessionCache.reset(spConf.SessionCacheManager.newPlugin(STORAGESERVICE_SESSION_CACHE, nullptr));
1991     }
1992 }
1993
1994 XMLConfigImpl::XMLConfigImpl(const DOMElement* e, bool first, XMLConfig* outer, Category& log) : m_document(nullptr)
1995 {
1996 #ifdef _DEBUG
1997     xmltooling::NDC ndc("XMLConfigImpl");
1998 #endif
1999     SPConfig& conf=SPConfig::getConfig();
2000     XMLToolingConfig& xmlConf=XMLToolingConfig::getConfig();
2001     const DOMElement* SHAR=XMLHelper::getFirstChildElement(e, OutOfProcess);
2002     const DOMElement* SHIRE=XMLHelper::getFirstChildElement(e, InProcess);
2003
2004     // Initialize logging manually in order to redirect log messages as soon as possible.
2005     // If no explicit config is supplied, we now assume the caller has done this, so that
2006     // setuid processes can potentially do this as root.
2007     if (conf.isEnabled(SPConfig::Logging)) {
2008         string logconf;
2009         if (conf.isEnabled(SPConfig::OutOfProcess))
2010             logconf = XMLHelper::getAttrString(SHAR, nullptr, logger);
2011         else if (conf.isEnabled(SPConfig::InProcess))
2012             logconf = XMLHelper::getAttrString(SHIRE, nullptr, logger);
2013         if (logconf.empty())
2014             logconf = XMLHelper::getAttrString(e, nullptr, logger);
2015         if (!logconf.empty()) {
2016             log.debug("loading new logging configuration from (%s), check log destination for status of configuration", logconf.c_str());
2017             if (!XMLToolingConfig::getConfig().log_config(logconf.c_str()))
2018                 log.crit("failed to load new logging configuration from (%s)", logconf.c_str());
2019         }
2020
2021 #ifndef SHIBSP_LITE
2022         m_tranLog.reset(
2023             new TransactionLog(
2024                 XMLHelper::getAttrString(SHAR, nullptr, tranLogFormat).c_str(),
2025                 XMLHelper::getAttrString(SHAR, nullptr, tranLogFiller).c_str()
2026                 )
2027             );
2028 #endif
2029     }
2030
2031     // Re-log library versions now that logging is set up.
2032     log.info("Shibboleth SP Version %s", PACKAGE_VERSION);
2033 #ifndef SHIBSP_LITE
2034     log.info(
2035         "Library versions: %s %s, Xerces-C %s, XML-Security-C %s, XMLTooling-C %s, OpenSAML-C %s, Shibboleth %s",
2036 # if defined(LOG4SHIB_VERSION)
2037     "log4shib", LOG4SHIB_VERSION,
2038 # elif defined(LOG4CPP_VERSION)
2039     "log4cpp", LOG4CPP_VERSION,
2040 # else
2041     "", "",
2042 # endif
2043         XERCES_FULLVERSIONDOT, XSEC_FULLVERSIONDOT, gXMLToolingDotVersionStr, gOpenSAMLDotVersionStr, gShibSPDotVersionStr
2044         );
2045 #else
2046     log.info(
2047         "Library versions: %s %s, Xerces-C %s, XMLTooling-C %s, Shibboleth %s",
2048 # if defined(LOG4SHIB_VERSION)
2049     "log4shib", LOG4SHIB_VERSION,
2050 # elif defined(LOG4CPP_VERSION)
2051     "log4cpp", LOG4CPP_VERSION,
2052 # else
2053     "", "",
2054 # endif
2055         XERCES_FULLVERSIONDOT, gXMLToolingDotVersionStr, gShibSPDotVersionStr
2056         );
2057 #endif
2058
2059     // First load any property sets.
2060     load(e, nullptr, this);
2061
2062     DOMElement* child;
2063
2064     // Much of the processing can only occur on the first instantiation.
2065     if (first) {
2066         // Set clock skew.
2067         pair<bool,unsigned int> skew=getUnsignedInt("clockSkew");
2068         if (skew.first)
2069             xmlConf.clock_skew_secs=min(skew.second,(60*60*24*7*28));
2070
2071         pair<bool,const char*> unsafe = getString("unsafeChars");
2072         if (unsafe.first)
2073             TemplateEngine::unsafe_chars = unsafe.second;
2074
2075         unsafe = getString("allowedSchemes");
2076         if (unsafe.first) {
2077             HTTPResponse::getAllowedSchemes().clear();
2078             string schemes(unsafe.second);
2079             trim(schemes);
2080             split(HTTPResponse::getAllowedSchemes(), schemes, is_space(), algorithm::token_compress_on);
2081         }
2082
2083         // Default language handling.
2084         pair<bool,bool> langFromClient = getBool("langFromClient");
2085         pair<bool,const XMLCh*> langPriority = getXMLString("langPriority");
2086         GenericRequest::setLangDefaults(!langFromClient.first || langFromClient.second, langPriority.second);
2087
2088 #ifndef SHIBSP_LITE
2089         langPriority = getXMLString("contactPriority");
2090         if (langPriority.first)
2091             SAMLConfig::getConfig().setContactPriority(langPriority.second);
2092 #endif
2093
2094         // Extensions
2095         doExtensions(e, "global", log);
2096         if (conf.isEnabled(SPConfig::OutOfProcess))
2097             doExtensions(SHAR, "out of process", log);
2098
2099         if (conf.isEnabled(SPConfig::InProcess))
2100             doExtensions(SHIRE, "in process", log);
2101
2102         // Instantiate the ListenerService and SessionCache objects.
2103         if (conf.isEnabled(SPConfig::Listener))
2104             doListener(e, outer, log);
2105
2106 #ifndef SHIBSP_LITE
2107         if (outer->m_listener && conf.isEnabled(SPConfig::OutOfProcess) && !conf.isEnabled(SPConfig::InProcess)) {
2108             outer->m_listener->regListener("set::RelayState", outer);
2109             outer->m_listener->regListener("get::RelayState", outer);
2110             outer->m_listener->regListener("set::PostData", outer);
2111             outer->m_listener->regListener("get::PostData", outer);
2112         }
2113 #endif
2114         if (conf.isEnabled(SPConfig::Caching))
2115             doCaching(e, outer, log);
2116     } // end of first-time-only stuff
2117
2118     // Back to the fully dynamic stuff...next up is the RequestMapper.
2119     if (conf.isEnabled(SPConfig::RequestMapping)) {
2120         if (child = XMLHelper::getFirstChildElement(e, _RequestMapper)) {
2121             string t(XMLHelper::getAttrString(child, nullptr, _type));
2122             if (!t.empty()) {
2123                 log.info("building RequestMapper of type %s...", t.c_str());
2124                 m_requestMapper.reset(conf.RequestMapperManager.newPlugin(t.c_str(), child));
2125             }
2126         }
2127         if (!m_requestMapper) {
2128             log.info("no RequestMapper specified, using 'Native' plugin with empty/default map");
2129             child = e->getOwnerDocument()->createElementNS(nullptr, _RequestMapper);
2130             DOMElement* mapperDummy = e->getOwnerDocument()->createElementNS(shibspconstants::SHIB2SPCONFIG_NS, RequestMap);
2131             mapperDummy->setAttributeNS(nullptr, applicationId, _default);
2132             child->appendChild(mapperDummy);
2133             m_requestMapper.reset(conf.RequestMapperManager.newPlugin(NATIVE_REQUEST_MAPPER, child));
2134         }
2135     }
2136
2137 #ifndef SHIBSP_LITE
2138     // Load security policies.
2139     if (child = XMLHelper::getLastChildElement(e, _SecurityPolicyProvider)) {
2140         string t(XMLHelper::getAttrString(child, nullptr, _type));
2141         if (!t.empty()) {
2142             log.info("building SecurityPolicyProvider of type %s...", t.c_str());
2143             m_policy.reset(conf.SecurityPolicyProviderManager.newPlugin(t.c_str(), child));
2144         }
2145         else {
2146             throw ConfigurationException("can't build SecurityPolicyProvider, no type specified");
2147         }
2148     }
2149     else if (child = XMLHelper::getLastChildElement(e, SecurityPolicies)) {
2150         // For backward compatibility, wrap in a plugin element.
2151         DOMElement* polwrapper = e->getOwnerDocument()->createElementNS(nullptr, _SecurityPolicyProvider);
2152         polwrapper->appendChild(child);
2153         log.warn("deprecated/legacy SecurityPolicy configuration, consider externalizing with <SecurityPolicyProvider>");
2154         m_policy.reset(conf.SecurityPolicyProviderManager.newPlugin(XML_SECURITYPOLICY_PROVIDER, polwrapper));
2155     }
2156     else {
2157         log.fatal("can't build SecurityPolicyProvider, missing conf:SecurityPolicyProvider element?");
2158         throw ConfigurationException("Can't build SecurityPolicyProvider, missing conf:SecurityPolicyProvider element?");
2159     }
2160
2161     if (first) {
2162         if (!m_policy->getAlgorithmWhitelist().empty()) {
2163 #ifdef SHIBSP_XMLSEC_WHITELISTING
2164             for (vector<xstring>::const_iterator white = m_policy->getAlgorithmWhitelist().begin();
2165                     white != m_policy->getAlgorithmWhitelist().end(); ++white) {
2166                 XSECPlatformUtils::whitelistAlgorithm(white->c_str());
2167                 auto_ptr_char whitelog(white->c_str());
2168                 log.info("explicitly whitelisting security algorithm (%s)", whitelog.get());
2169             }
2170 #else
2171             log.crit("XML-Security-C library prior to 1.6.0 does not support algorithm white/blacklists");
2172 #endif
2173         }
2174         else if (!m_policy->getDefaultAlgorithmBlacklist().empty() || !m_policy->getAlgorithmBlacklist().empty()) {
2175 #ifdef SHIBSP_XMLSEC_WHITELISTING
2176             for (vector<xstring>::const_iterator black = m_policy->getDefaultAlgorithmBlacklist().begin();
2177                     black != m_policy->getDefaultAlgorithmBlacklist().end(); ++black) {
2178                 XSECPlatformUtils::blacklistAlgorithm(black->c_str());
2179                 auto_ptr_char blacklog(black->c_str());
2180                 log.info("automatically blacklisting security algorithm (%s)", blacklog.get());
2181             }
2182             for (vector<xstring>::const_iterator black = m_policy->getAlgorithmBlacklist().begin();
2183                     black != m_policy->getAlgorithmBlacklist().end(); ++black) {
2184                 XSECPlatformUtils::blacklistAlgorithm(black->c_str());
2185                 auto_ptr_char blacklog(black->c_str());
2186                 log.info("explicitly blacklisting security algorithm (%s)", blacklog.get());
2187             }
2188 #else
2189             log.crit("XML-Security-C library prior to 1.6.0 does not support algorithm white/blacklists");
2190 #endif
2191         }
2192     }
2193
2194     // Process TransportOption elements.
2195     child = XMLHelper::getLastChildElement(e, TransportOption);
2196     while (child) {
2197         if (child->hasChildNodes()) {
2198             string provider(XMLHelper::getAttrString(child, nullptr, _provider));
2199             string option(XMLHelper::getAttrString(child, nullptr, _option));
2200             auto_ptr_char value(child->getFirstChild()->getNodeValue());
2201             if (!provider.empty() && !option.empty() && value.get() && *value.get()) {
2202                 m_transportOptions.push_back(boost::make_tuple(provider, option, string(value.get())));
2203             }
2204         }
2205         child = XMLHelper::getPreviousSiblingElement(child, TransportOption);
2206     }
2207 #endif
2208
2209     scoped_ptr<ProtocolProvider> pp;
2210     if (conf.isEnabled(SPConfig::Handlers)) {
2211         if (child = XMLHelper::getLastChildElement(e, _ProtocolProvider)) {
2212             string t(XMLHelper::getAttrString(child, nullptr, _type));
2213             if (!t.empty()) {
2214                 log.info("building ProtocolProvider of type %s...", t.c_str());
2215                 pp.reset(conf.ProtocolProviderManager.newPlugin(t.c_str(), child));
2216             }
2217         }
2218     }
2219     Locker pplocker(pp.get());
2220
2221     // Load the default application.
2222     child = XMLHelper::getLastChildElement(e, ApplicationDefaults);
2223     if (!child) {
2224         log.fatal("can't build default Application object, missing conf:ApplicationDefaults element?");
2225         throw ConfigurationException("can't build default Application object, missing conf:ApplicationDefaults element?");
2226     }
2227     boost::shared_ptr<XMLApplication> defapp(new XMLApplication(outer, pp.get(), child));
2228     m_appmap[defapp->getId()] = defapp;
2229
2230     // Load any overrides.
2231     child = XMLHelper::getFirstChildElement(child, ApplicationOverride);
2232     while (child) {
2233         boost::shared_ptr<XMLApplication> iapp(new XMLApplication(outer, pp.get(), child, defapp.get()));
2234         if (m_appmap.count(iapp->getId()))
2235             log.crit("found conf:ApplicationOverride element with duplicate id attribute (%s), skipping it", iapp->getId());
2236         else
2237             m_appmap[iapp->getId()] = iapp;
2238
2239         child = XMLHelper::getNextSiblingElement(child, ApplicationOverride);
2240     }
2241
2242     // Check for extra AuthTypes to recognize.
2243     if (conf.isEnabled(SPConfig::InProcess)) {
2244         const PropertySet* inprocs = getPropertySet("InProcess");
2245         if (inprocs) {
2246             pair<bool,const char*> extraAuthTypes = inprocs->getString("extraAuthTypes");
2247             if (extraAuthTypes.first) {
2248                 string types(extraAuthTypes.second);
2249                 trim(types);
2250                 split(outer->m_authTypes, types, is_space(), algorithm::token_compress_on);
2251                 outer->m_authTypes.insert("shibboleth");
2252             }
2253         }
2254     }
2255 }
2256
2257 #ifndef SHIBSP_LITE
2258 void XMLConfig::receive(DDF& in, ostream& out)
2259 {
2260     if (!strcmp(in.name(), "get::RelayState")) {
2261         const char* id = in["id"].string();
2262         const char* key = in["key"].string();
2263         if (!id || !key)
2264             throw ListenerException("Required parameters missing for RelayState recovery.");
2265
2266         string relayState;
2267         StorageService* storage = getStorageService(id);
2268         if (storage) {
2269             if (storage->readString("RelayState",key,&relayState)>0) {
2270                 if (in["clear"].integer())
2271                     storage->deleteString("RelayState",key);
2272             }
2273             else if (storage->readText("RelayState",key,&relayState)>0) {
2274                 if (in["clear"].integer())
2275                     storage->deleteText("RelayState",key);
2276             }
2277         }
2278         else {
2279             Category::getInstance(SHIBSP_LOGCAT ".ServiceProvider").error(
2280                 "Storage-backed RelayState with invalid StorageService ID (%s)", id
2281                 );
2282         }
2283
2284         // Repack for return to caller.
2285         DDF ret=DDF(nullptr).unsafe_string(relayState.c_str());
2286         DDFJanitor jret(ret);
2287         out << ret;
2288     }
2289     else if (!strcmp(in.name(), "set::RelayState")) {
2290         const char* id = in["id"].string();
2291         const char* value = in["value"].string();
2292         if (!id || !value)
2293             throw ListenerException("Required parameters missing for RelayState creation.");
2294
2295         string rsKey;
2296         StorageService* storage = getStorageService(id);
2297         if (storage) {
2298             SAMLConfig::getConfig().generateRandomBytes(rsKey,32);
2299             rsKey = SAMLArtifact::toHex(rsKey);
2300             if (strlen(value) <= storage->getCapabilities().getStringSize())
2301                 storage->createString("RelayState", rsKey.c_str(), value, time(nullptr) + 600);
2302             else
2303                 storage->createText("RelayState", rsKey.c_str(), value, time(nullptr) + 600);
2304         }
2305         else {
2306             Category::getInstance(SHIBSP_LOGCAT ".ServiceProvider").error(
2307                 "Storage-backed RelayState with invalid StorageService ID (%s)", id
2308                 );
2309         }
2310
2311         // Repack for return to caller.
2312         DDF ret=DDF(nullptr).string(rsKey.c_str());
2313         DDFJanitor jret(ret);
2314         out << ret;
2315     }
2316     else if (!strcmp(in.name(), "get::PostData")) {
2317         const char* id = in["id"].string();
2318         const char* key = in["key"].string();
2319         if (!id || !key)
2320             throw ListenerException("Required parameters missing for PostData recovery.");
2321
2322         string postData;
2323         StorageService* storage = getStorageService(id);
2324         if (storage) {
2325             if (storage->readText("PostData",key,&postData) > 0) {
2326                 storage->deleteText("PostData",key);
2327             }
2328         }
2329         else {
2330             Category::getInstance(SHIBSP_LOGCAT ".ServiceProvider").error(
2331                 "Storage-backed PostData with invalid StorageService ID (%s)", id
2332                 );
2333         }
2334         // If the data's empty, we'll send nothing back.
2335         // If not, we don't need to round trip it, just send back the serialized DDF list.
2336         if (postData.empty()) {
2337             DDF ret(nullptr);
2338             DDFJanitor jret(ret);
2339             out << ret;
2340         }
2341         else {
2342             out << postData;
2343         }
2344     }
2345     else if (!strcmp(in.name(), "set::PostData")) {
2346         const char* id = in["id"].string();
2347         if (!id || !in["parameters"].islist())
2348             throw ListenerException("Required parameters missing for PostData creation.");
2349
2350         string rsKey;
2351         StorageService* storage = getStorageService(id);
2352         if (storage) {
2353             SAMLConfig::getConfig().generateRandomBytes(rsKey,32);
2354             rsKey = SAMLArtifact::toHex(rsKey);
2355             ostringstream params;
2356             params << in["parameters"];
2357             storage->createText("PostData", rsKey.c_str(), params.str().c_str(), time(nullptr) + 600);
2358         }
2359         else {
2360             Category::getInstance(SHIBSP_LOGCAT ".ServiceProvider").error(
2361                 "Storage-backed PostData with invalid StorageService ID (%s)", id
2362                 );
2363         }
2364
2365         // Repack for return to caller.
2366         DDF ret=DDF(nullptr).string(rsKey.c_str());
2367         DDFJanitor jret(ret);
2368         out << ret;
2369     }
2370 }
2371 #endif
2372
2373 pair<bool,DOMElement*> XMLConfig::background_load()
2374 {
2375     // Load from source using base class.
2376     pair<bool,DOMElement*> raw = ReloadableXMLFile::load();
2377
2378     // If we own it, wrap it.
2379     XercesJanitor<DOMDocument> docjanitor(raw.first ? raw.second->getOwnerDocument() : nullptr);
2380
2381     scoped_ptr<XMLConfigImpl> impl(new XMLConfigImpl(raw.second, (m_impl==nullptr), this, m_log));
2382
2383     // If we held the document, transfer it to the impl. If we didn't, it's a no-op.
2384     impl->setDocument(docjanitor.release());
2385
2386     // Perform the swap inside a lock.
2387     if (m_lock)
2388         m_lock->wrlock();
2389     SharedLock locker(m_lock, false);
2390     m_impl.swap(impl);
2391
2392     return make_pair(false,(DOMElement*)nullptr);
2393 }