Remote additional headers based on plugin requirements.
[shibboleth/cpp-sp.git] / shibsp / impl / StorageServiceSessionCache.cpp
1 /*
2  *  Copyright 2001-2010 Internet2
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 /**
18  * StorageServiceSessionCache.cpp
19  *
20  * StorageService-based SessionCache implementation.
21  *
22  * Instead of optimizing this plugin with a buffering scheme that keeps objects around
23  * and avoids extra parsing steps, I'm assuming that systems that require such can
24  * layer their own cache plugin on top of this version either by delegating to it
25  * or using the remoting support. So this version will load sessions directly
26  * from the StorageService, instantiate enough to expose the Session API,
27  * and then delete everything when they're unlocked. All data in memory is always
28  * kept in sync with the StorageService (no lazy updates).
29  */
30
31 #include "internal.h"
32 #include "Application.h"
33 #include "exceptions.h"
34 #include "ServiceProvider.h"
35 #include "SessionCacheEx.h"
36 #include "TransactionLog.h"
37 #include "attribute/Attribute.h"
38 #include "handler/RemotedHandler.h"
39 #include "remoting/ListenerService.h"
40 #include "util/SPConstants.h"
41
42 #include <algorithm>
43 #include <xmltooling/io/HTTPRequest.h>
44 #include <xmltooling/io/HTTPResponse.h>
45 #include <xmltooling/util/DateTime.h>
46 #include <xmltooling/util/NDC.h>
47 #include <xmltooling/util/ParserPool.h>
48 #include <xmltooling/util/Threads.h>
49 #include <xmltooling/util/XMLHelper.h>
50 #include <xercesc/util/XMLUniDefs.hpp>
51
52 #ifndef SHIBSP_LITE
53 # include <saml/exceptions.h>
54 # include <saml/SAMLConfig.h>
55 # include <saml/saml2/core/Assertions.h>
56 # include <saml/saml2/metadata/Metadata.h>
57 # include <xmltooling/XMLToolingConfig.h>
58 # include <xmltooling/util/StorageService.h>
59 using namespace opensaml::saml2md;
60 #else
61 # include <ctime>
62 # include <xmltooling/util/DateTime.h>
63 #endif
64
65 using namespace shibsp;
66 using namespace opensaml;
67 using namespace xmltooling;
68 using namespace std;
69
70 namespace shibsp {
71
72     class StoredSession;
73     class SSCache : public SessionCacheEx
74 #ifndef SHIBSP_LITE
75         ,public virtual Remoted
76 #endif
77     {
78     public:
79         SSCache(const DOMElement* e);
80         ~SSCache();
81
82 #ifndef SHIBSP_LITE
83         void receive(DDF& in, ostream& out);
84
85         void insert(
86             const Application& app,
87             const HTTPRequest& httpRequest,
88             HTTPResponse& httpResponse,
89             time_t expires,
90             const saml2md::EntityDescriptor* issuer=nullptr,
91             const XMLCh* protocol=nullptr,
92             const saml2::NameID* nameid=nullptr,
93             const XMLCh* authn_instant=nullptr,
94             const XMLCh* session_index=nullptr,
95             const XMLCh* authncontext_class=nullptr,
96             const XMLCh* authncontext_decl=nullptr,
97             const vector<const Assertion*>* tokens=nullptr,
98             const vector<Attribute*>* attributes=nullptr
99             );
100         vector<string>::size_type logout(
101             const Application& app,
102             const saml2md::EntityDescriptor* issuer,
103             const saml2::NameID& nameid,
104             const set<string>* indexes,
105             time_t expires,
106             vector<string>& sessions
107             );
108         bool matches(
109             const Application& app,
110             const HTTPRequest& request,
111             const saml2md::EntityDescriptor* issuer,
112             const saml2::NameID& nameid,
113             const set<string>* indexes
114             );
115 #endif
116         Session* find(const Application& app, const char* key, const char* client_addr=nullptr, time_t* timeout=nullptr);
117         void remove(const Application& app, const char* key);
118         void test();
119
120         string active(const Application& app, const HTTPRequest& request) {
121             if (m_inboundHeader.empty()) {
122                 pair<string,const char*> shib_cookie = app.getCookieNameProps("_shibsession_");
123                 const char* session_id = request.getCookie(shib_cookie.first.c_str());
124                 return (session_id ? session_id : "");
125             }
126             else {
127                 string session_id = request.getHeader(m_inboundHeader.c_str());
128                 if (!session_id.empty())
129                     return session_id;
130                 const char* p = request.getParameter(m_inboundHeader.c_str());
131                 return (p ? p : "");
132             }
133         }
134
135         Session* find(const Application& app, const HTTPRequest& request, const char* client_addr=nullptr, time_t* timeout=nullptr) {
136             string id = active(app, request);
137             if (!id.empty())
138                 return find(app, id.c_str(), client_addr, timeout);
139             return nullptr;
140         }
141
142         Session* find(const Application& app, HTTPRequest& request, const char* client_addr=nullptr, time_t* timeout=nullptr);
143         void remove(const Application& app, const HTTPRequest& request, HTTPResponse* response=nullptr);
144
145         unsigned long getCacheTimeout(const Application& app) {
146             // Computes offset for adjusting expiration of sessions.
147             // This can either be static, or dynamic based on the per-app session timeout.
148             if (m_cacheTimeout)
149                 return m_cacheTimeout;
150             pair<bool,unsigned int> timeout;
151             const PropertySet* props = app.getPropertySet("Sessions");
152             if (props) {
153                 timeout = props->getUnsignedInt("timeout");
154                 if (!timeout.first)
155                     timeout.second = 3600;
156             }
157             return timeout.second + m_cacheAllowance;
158         }
159
160         Category& m_log;
161         bool inproc;
162 #ifndef SHIBSP_LITE
163         StorageService* m_storage;
164         StorageService* m_storage_lite;
165 #endif
166
167     private:
168 #ifndef SHIBSP_LITE
169         // maintain back-mappings of NameID/SessionIndex -> session key
170         void insert(const char* key, time_t expires, const char* name, const char* index);
171         bool stronglyMatches(const XMLCh* idp, const XMLCh* sp, const saml2::NameID& n1, const saml2::NameID& n2) const;
172
173         bool m_cacheAssertions;
174 #endif
175         const DOMElement* m_root;         // Only valid during initialization
176         unsigned long m_inprocTimeout,m_cacheTimeout,m_cacheAllowance;
177         string m_inboundHeader,m_outboundHeader;
178
179         // inproc means we buffer sessions in memory
180         RWLock* m_lock;
181         map<string,StoredSession*> m_hashtable;
182
183         // management of buffered sessions
184        void dormant(const char* key);
185        static void* cleanup_fn(void*);
186
187         bool shutdown;
188         CondWait* shutdown_wait;
189         Thread* cleanup_thread;
190     };
191
192     class StoredSession : public virtual Session
193     {
194     public:
195         StoredSession(SSCache* cache, DDF& obj) : m_obj(obj),
196 #ifndef SHIBSP_LITE
197                 m_nameid(nullptr),
198 #endif
199                 m_cache(cache), m_expires(0), m_lastAccess(time(nullptr)), m_lock(nullptr) {
200             auto_ptr_XMLCh exp(m_obj["expires"].string());
201             if (exp.get()) {
202                 DateTime iso(exp.get());
203                 iso.parseDateTime();
204                 m_expires = iso.getEpoch();
205             }
206
207 #ifndef SHIBSP_LITE
208             const char* nameid = obj["nameid"].string();
209             if (nameid) {
210                 // Parse and bind the document into an XMLObject.
211                 istringstream instr(nameid);
212                 DOMDocument* doc = XMLToolingConfig::getConfig().getParser().parse(instr);
213                 XercesJanitor<DOMDocument> janitor(doc);
214                 auto_ptr<saml2::NameID> n(saml2::NameIDBuilder::buildNameID());
215                 n->unmarshall(doc->getDocumentElement(), true);
216                 janitor.release();
217                 m_nameid = n.release();
218             }
219 #endif
220             if (cache->inproc)
221                 m_lock = Mutex::create();
222         }
223
224         ~StoredSession() {
225             delete m_lock;
226             m_obj.destroy();
227             for_each(m_attributes.begin(), m_attributes.end(), xmltooling::cleanup<Attribute>());
228 #ifndef SHIBSP_LITE
229             delete m_nameid;
230             for_each(m_tokens.begin(), m_tokens.end(), cleanup_pair<string,Assertion>());
231 #endif
232         }
233
234         Lockable* lock() {
235             if (m_lock)
236                 m_lock->lock();
237             return this;
238         }
239         void unlock() {
240             if (m_lock)
241                 m_lock->unlock();
242             else
243                 delete this;
244         }
245
246         const char* getID() const {
247             return m_obj.name();
248         }
249         const char* getApplicationID() const {
250             return m_obj["application_id"].string();
251         }
252         const char* getClientAddress() const {
253             return m_obj["client_addr"].string();
254         }
255         const char* getEntityID() const {
256             return m_obj["entity_id"].string();
257         }
258         const char* getProtocol() const {
259             return m_obj["protocol"].string();
260         }
261         const char* getAuthnInstant() const {
262             return m_obj["authn_instant"].string();
263         }
264 #ifndef SHIBSP_LITE
265         const saml2::NameID* getNameID() const {
266             return m_nameid;
267         }
268 #endif
269         const char* getSessionIndex() const {
270             return m_obj["session_index"].string();
271         }
272         const char* getAuthnContextClassRef() const {
273             return m_obj["authncontext_class"].string();
274         }
275         const char* getAuthnContextDeclRef() const {
276             return m_obj["authncontext_decl"].string();
277         }
278         const vector<Attribute*>& getAttributes() const {
279             if (m_attributes.empty())
280                 unmarshallAttributes();
281             return m_attributes;
282         }
283         const multimap<string,const Attribute*>& getIndexedAttributes() const {
284             if (m_attributeIndex.empty()) {
285                 if (m_attributes.empty())
286                     unmarshallAttributes();
287                 for (vector<Attribute*>::const_iterator a = m_attributes.begin(); a != m_attributes.end(); ++a) {
288                     const vector<string>& aliases = (*a)->getAliases();
289                     for (vector<string>::const_iterator alias = aliases.begin(); alias != aliases.end(); ++alias)
290                         m_attributeIndex.insert(multimap<string,const Attribute*>::value_type(*alias, *a));
291                 }
292             }
293             return m_attributeIndex;
294         }
295         const vector<const char*>& getAssertionIDs() const {
296             if (m_ids.empty()) {
297                 DDF ids = m_obj["assertions"];
298                 DDF id = ids.first();
299                 while (id.isstring()) {
300                     m_ids.push_back(id.string());
301                     id = ids.next();
302                 }
303             }
304             return m_ids;
305         }
306
307         void validate(const Application& application, const char* client_addr, time_t* timeout);
308
309 #ifndef SHIBSP_LITE
310         void addAttributes(const vector<Attribute*>& attributes);
311         const Assertion* getAssertion(const char* id) const;
312         void addAssertion(Assertion* assertion);
313 #endif
314
315         time_t getExpiration() const { return m_expires; }
316         time_t getLastAccess() const { return m_lastAccess; }
317
318     private:
319         void unmarshallAttributes() const;
320
321         DDF m_obj;
322 #ifndef SHIBSP_LITE
323         saml2::NameID* m_nameid;
324         mutable map<string,Assertion*> m_tokens;
325 #endif
326         mutable vector<Attribute*> m_attributes;
327         mutable multimap<string,const Attribute*> m_attributeIndex;
328         mutable vector<const char*> m_ids;
329
330         SSCache* m_cache;
331         time_t m_expires,m_lastAccess;
332         Mutex* m_lock;
333     };
334
335     SessionCache* SHIBSP_DLLLOCAL StorageServiceCacheFactory(const DOMElement* const & e)
336     {
337         return new SSCache(e);
338     }
339 }
340
341 Session* SessionCache::find(const Application& application, HTTPRequest& request, const char* client_addr, time_t* timeout)
342 {
343     return find(application, const_cast<const HTTPRequest&>(request), client_addr, timeout);
344 }
345
346 void SHIBSP_API shibsp::registerSessionCaches()
347 {
348     SPConfig::getConfig().SessionCacheManager.registerFactory(STORAGESERVICE_SESSION_CACHE, StorageServiceCacheFactory);
349 }
350
351 Session::Session()
352 {
353 }
354
355 Session::~Session()
356 {
357 }
358
359 void StoredSession::unmarshallAttributes() const
360 {
361     Attribute* attribute;
362     DDF attrs = m_obj["attributes"];
363     DDF attr = attrs.first();
364     while (!attr.isnull()) {
365         try {
366             attribute = Attribute::unmarshall(attr);
367             m_attributes.push_back(attribute);
368             if (m_cache->m_log.isDebugEnabled())
369                 m_cache->m_log.debug("unmarshalled attribute (ID: %s) with %d value%s",
370                     attribute->getId(), attr.first().integer(), attr.first().integer()!=1 ? "s" : "");
371         }
372         catch (AttributeException& ex) {
373             const char* id = attr.first().name();
374             m_cache->m_log.error("error unmarshalling attribute (ID: %s): %s", id ? id : "none", ex.what());
375         }
376         attr = attrs.next();
377     }
378 }
379
380 void StoredSession::validate(const Application& app, const char* client_addr, time_t* timeout)
381 {
382     time_t now = time(nullptr);
383
384     // Basic expiration?
385     if (m_expires > 0) {
386         if (now > m_expires) {
387             m_cache->m_log.info("session expired (ID: %s)", getID());
388             throw RetryableProfileException("Your session has expired, and you must re-authenticate.");
389         }
390     }
391
392     // Address check?
393     if (client_addr) {
394         if (m_cache->m_log.isDebugEnabled())
395             m_cache->m_log.debug("comparing client address %s against %s", client_addr, getClientAddress());
396         if (!XMLString::equals(getClientAddress(),client_addr)) {
397             m_cache->m_log.warn("client address mismatch");
398             throw RetryableProfileException(
399                 "Your IP address ($1) does not match the address recorded at the time the session was established.",
400                 params(1,client_addr)
401                 );
402         }
403     }
404
405     if (!timeout)
406         return;
407
408     if (!SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess)) {
409         DDF in("touch::"STORAGESERVICE_SESSION_CACHE"::SessionCache"), out;
410         DDFJanitor jin(in);
411         in.structure();
412         in.addmember("key").string(getID());
413         in.addmember("version").integer(m_obj["version"].integer());
414         if (*timeout) {
415             // On 64-bit Windows, time_t doesn't fit in a long, so I'm using ISO timestamps.
416 #ifndef HAVE_GMTIME_R
417             struct tm* ptime=gmtime(timeout);
418 #else
419             struct tm res;
420             struct tm* ptime=gmtime_r(timeout,&res);
421 #endif
422             char timebuf[32];
423             strftime(timebuf,32,"%Y-%m-%dT%H:%M:%SZ",ptime);
424             in.addmember("timeout").string(timebuf);
425         }
426
427         try {
428             out=app.getServiceProvider().getListenerService()->send(in);
429         }
430         catch (...) {
431             out.destroy();
432             throw;
433         }
434
435         if (out.isstruct()) {
436             // We got an updated record back.
437             m_ids.clear();
438             for_each(m_attributes.begin(), m_attributes.end(), xmltooling::cleanup<Attribute>());
439             m_attributes.clear();
440             m_attributeIndex.clear();
441             m_obj.destroy();
442             m_obj = out;
443         }
444     }
445     else {
446 #ifndef SHIBSP_LITE
447         if (!m_cache->m_storage)
448             throw ConfigurationException("Session touch requires a StorageService.");
449
450         // Do a versioned read.
451         string record;
452         time_t lastAccess;
453         int curver = m_obj["version"].integer();
454         int ver = m_cache->m_storage->readText(getID(), "session", &record, &lastAccess, curver);
455         if (ver == 0) {
456             m_cache->m_log.warn("unsuccessful versioned read of session (ID: %s), cache out of sync?", getID());
457             throw RetryableProfileException("Your session has expired, and you must re-authenticate.");
458         }
459
460         // Adjust for expiration to recover last access time and check timeout.
461         unsigned long cacheTimeout = m_cache->getCacheTimeout(app);
462         lastAccess -= cacheTimeout;
463         if (*timeout > 0 && now - lastAccess >= *timeout) {
464             m_cache->m_log.info("session timed out (ID: %s)", getID());
465             throw RetryableProfileException("Your session has expired, and you must re-authenticate.");
466         }
467
468         // Update storage expiration, if possible.
469         try {
470             m_cache->m_storage->updateContext(getID(), now + cacheTimeout);
471         }
472         catch (exception& ex) {
473             m_cache->m_log.error("failed to update session expiration: %s", ex.what());
474         }
475
476         if (ver > curver) {
477             // We got an updated record back.
478             DDF newobj;
479             istringstream in(record);
480             in >> newobj;
481             m_ids.clear();
482             for_each(m_attributes.begin(), m_attributes.end(), xmltooling::cleanup<Attribute>());
483             m_attributes.clear();
484             m_attributeIndex.clear();
485             m_obj.destroy();
486             m_obj = newobj;
487         }
488 #else
489         throw ConfigurationException("Session touch requires a StorageService.");
490 #endif
491     }
492
493     m_lastAccess = now;
494 }
495
496 #ifndef SHIBSP_LITE
497
498 void StoredSession::addAttributes(const vector<Attribute*>& attributes)
499 {
500 #ifdef _DEBUG
501     xmltooling::NDC ndc("addAttributes");
502 #endif
503
504     if (!m_cache->m_storage)
505         throw ConfigurationException("Session modification requires a StorageService.");
506
507     m_cache->m_log.debug("adding attributes to session (%s)", getID());
508
509     int ver;
510     do {
511         DDF attr;
512         DDF attrs = m_obj["attributes"];
513         if (!attrs.islist())
514             attrs = m_obj.addmember("attributes").list();
515         for (vector<Attribute*>::const_iterator a=attributes.begin(); a!=attributes.end(); ++a) {
516             attr = (*a)->marshall();
517             attrs.add(attr);
518         }
519
520         // Tentatively increment the version.
521         m_obj["version"].integer(m_obj["version"].integer()+1);
522
523         ostringstream str;
524         str << m_obj;
525         string record(str.str());
526
527         try {
528             ver = m_cache->m_storage->updateText(getID(), "session", record.c_str(), 0, m_obj["version"].integer()-1);
529         }
530         catch (exception&) {
531             // Roll back modification to record.
532             m_obj["version"].integer(m_obj["version"].integer()-1);
533             vector<Attribute*>::size_type count = attributes.size();
534             while (count--)
535                 attrs.last().destroy();
536             throw;
537         }
538
539         if (ver <= 0) {
540             // Roll back modification to record.
541             m_obj["version"].integer(m_obj["version"].integer()-1);
542             vector<Attribute*>::size_type count = attributes.size();
543             while (count--)
544                 attrs.last().destroy();
545         }
546         if (!ver) {
547             // Fatal problem with update.
548             throw IOException("Unable to update stored session.");
549         }
550         else if (ver < 0) {
551             // Out of sync.
552             m_cache->m_log.warn("storage service indicates the record is out of sync, updating with a fresh copy...");
553             ver = m_cache->m_storage->readText(getID(), "session", &record, nullptr);
554             if (!ver) {
555                 m_cache->m_log.error("readText failed on StorageService for session (%s)", getID());
556                 throw IOException("Unable to read back stored session.");
557             }
558
559             // Reset object.
560             DDF newobj;
561             istringstream in(record);
562             in >> newobj;
563
564             m_ids.clear();
565             for_each(m_attributes.begin(), m_attributes.end(), xmltooling::cleanup<Attribute>());
566             m_attributes.clear();
567             m_attributeIndex.clear();
568             newobj["version"].integer(ver);
569             m_obj.destroy();
570             m_obj = newobj;
571
572             ver = -1;
573         }
574     } while (ver < 0);  // negative indicates a sync issue so we retry
575
576     TransactionLog* xlog = SPConfig::getConfig().getServiceProvider()->getTransactionLog();
577     Locker locker(xlog);
578     xlog->log.infoStream() <<
579         "Added the following attributes to session (ID: " <<
580             getID() <<
581         ") for (applicationId: " <<
582             m_obj["application_id"].string() <<
583         ") {";
584     for (vector<Attribute*>::const_iterator a=attributes.begin(); a!=attributes.end(); ++a)
585         xlog->log.infoStream() << "\t" << (*a)->getId() << " (" << (*a)->valueCount() << " values)";
586     xlog->log.info("}");
587
588     // We own them now, so clean them up.
589     for_each(attributes.begin(), attributes.end(), xmltooling::cleanup<Attribute>());
590 }
591
592 const Assertion* StoredSession::getAssertion(const char* id) const
593 {
594     if (!m_cache->m_storage)
595         throw ConfigurationException("Assertion retrieval requires a StorageService.");
596
597     map<string,Assertion*>::const_iterator i = m_tokens.find(id);
598     if (i!=m_tokens.end())
599         return i->second;
600
601     string tokenstr;
602     if (!m_cache->m_storage->readText(getID(), id, &tokenstr, nullptr))
603         throw FatalProfileException("Assertion not found in cache.");
604
605     // Parse and bind the document into an XMLObject.
606     istringstream instr(tokenstr);
607     DOMDocument* doc = XMLToolingConfig::getConfig().getParser().parse(instr);
608     XercesJanitor<DOMDocument> janitor(doc);
609     auto_ptr<XMLObject> xmlObject(XMLObjectBuilder::buildOneFromElement(doc->getDocumentElement(), true));
610     janitor.release();
611
612     Assertion* token = dynamic_cast<Assertion*>(xmlObject.get());
613     if (!token)
614         throw FatalProfileException("Request for cached assertion returned an unknown object type.");
615
616     // Transfer ownership to us.
617     xmlObject.release();
618     m_tokens[id]=token;
619     return token;
620 }
621
622 void StoredSession::addAssertion(Assertion* assertion)
623 {
624 #ifdef _DEBUG
625     xmltooling::NDC ndc("addAssertion");
626 #endif
627
628     if (!m_cache->m_storage)
629         throw ConfigurationException("Session modification requires a StorageService.");
630
631     if (!assertion)
632         throw FatalProfileException("Unknown object type passed to session for storage.");
633
634     auto_ptr_char id(assertion->getID());
635
636     m_cache->m_log.debug("adding assertion (%s) to session (%s)", id.get(), getID());
637
638     time_t exp;
639     if (!m_cache->m_storage->readText(getID(), "session", nullptr, &exp))
640         throw IOException("Unable to load expiration time for stored session.");
641
642     ostringstream tokenstr;
643     tokenstr << *assertion;
644     if (!m_cache->m_storage->createText(getID(), id.get(), tokenstr.str().c_str(), exp))
645         throw IOException("Attempted to insert duplicate assertion ID into session.");
646
647     int ver;
648     do {
649         DDF token = DDF(nullptr).string(id.get());
650         m_obj["assertions"].add(token);
651
652         // Tentatively increment the version.
653         m_obj["version"].integer(m_obj["version"].integer()+1);
654
655         ostringstream str;
656         str << m_obj;
657         string record(str.str());
658
659         try {
660             ver = m_cache->m_storage->updateText(getID(), "session", record.c_str(), 0, m_obj["version"].integer()-1);
661         }
662         catch (exception&) {
663             token.destroy();
664             m_obj["version"].integer(m_obj["version"].integer()-1);
665             m_cache->m_storage->deleteText(getID(), id.get());
666             throw;
667         }
668
669         if (ver <= 0) {
670             token.destroy();
671             m_obj["version"].integer(m_obj["version"].integer()-1);
672         }
673         if (!ver) {
674             // Fatal problem with update.
675             m_cache->m_log.error("updateText failed on StorageService for session (%s)", getID());
676             m_cache->m_storage->deleteText(getID(), id.get());
677             throw IOException("Unable to update stored session.");
678         }
679         else if (ver < 0) {
680             // Out of sync.
681             m_cache->m_log.warn("storage service indicates the record is out of sync, updating with a fresh copy...");
682             ver = m_cache->m_storage->readText(getID(), "session", &record, nullptr);
683             if (!ver) {
684                 m_cache->m_log.error("readText failed on StorageService for session (%s)", getID());
685                 m_cache->m_storage->deleteText(getID(), id.get());
686                 throw IOException("Unable to read back stored session.");
687             }
688
689             // Reset object.
690             DDF newobj;
691             istringstream in(record);
692             in >> newobj;
693
694             m_ids.clear();
695             for_each(m_attributes.begin(), m_attributes.end(), xmltooling::cleanup<Attribute>());
696             m_attributes.clear();
697             m_attributeIndex.clear();
698             newobj["version"].integer(ver);
699             m_obj.destroy();
700             m_obj = newobj;
701
702             ver = -1;
703         }
704     } while (ver < 0); // negative indicates a sync issue so we retry
705
706     m_ids.clear();
707     delete assertion;
708
709     TransactionLog* xlog = SPConfig::getConfig().getServiceProvider()->getTransactionLog();
710     Locker locker(xlog);
711     xlog->log.info(
712         "Added assertion (ID: %s) to session for (applicationId: %s) with (ID: %s)",
713         id.get(), m_obj["application_id"].string(), getID()
714         );
715 }
716
717 #endif
718
719 SessionCache::SessionCache()
720 {
721 }
722
723 SessionCache::~SessionCache()
724 {
725 }
726
727 SessionCacheEx::SessionCacheEx()
728 {
729 }
730
731 SessionCacheEx::~SessionCacheEx()
732 {
733 }
734
735 SSCache::SSCache(const DOMElement* e)
736     : m_log(Category::getInstance(SHIBSP_LOGCAT".SessionCache")), inproc(true),
737 #ifndef SHIBSP_LITE
738       m_storage(nullptr), m_storage_lite(nullptr), m_cacheAssertions(true),
739 #endif
740       m_root(e), m_inprocTimeout(900), m_cacheTimeout(0), m_cacheAllowance(0),
741       m_lock(nullptr), shutdown(false), shutdown_wait(nullptr), cleanup_thread(nullptr)
742 {
743     SPConfig& conf = SPConfig::getConfig();
744     inproc = conf.isEnabled(SPConfig::InProcess);
745
746     static const XMLCh cacheAllowance[] =   UNICODE_LITERAL_14(c,a,c,h,e,A,l,l,o,w,a,n,c,e);
747     static const XMLCh cacheAssertions[] =  UNICODE_LITERAL_15(c,a,c,h,e,A,s,s,e,r,t,i,o,n,s);
748     static const XMLCh cacheTimeout[] =     UNICODE_LITERAL_12(c,a,c,h,e,T,i,m,e,o,u,t);
749     static const XMLCh inprocTimeout[] =    UNICODE_LITERAL_13(i,n,p,r,o,c,T,i,m,e,o,u,t);
750     static const XMLCh inboundHeader[] =    UNICODE_LITERAL_13(i,n,b,o,u,n,d,H,e,a,d,e,r);
751     static const XMLCh outboundHeader[] =   UNICODE_LITERAL_14(o,u,t,b,o,u,n,d,H,e,a,d,e,r);
752     static const XMLCh _StorageService[] =  UNICODE_LITERAL_14(S,t,o,r,a,g,e,S,e,r,v,i,c,e);
753     static const XMLCh _StorageServiceLite[] = UNICODE_LITERAL_18(S,t,o,r,a,g,e,S,e,r,v,i,c,e,L,i,t,e);
754
755     m_cacheTimeout = XMLHelper::getAttrInt(e, 0, cacheTimeout);
756     m_cacheAllowance = XMLHelper::getAttrInt(e, 0, cacheAllowance);
757     if (inproc)
758         m_inprocTimeout = XMLHelper::getAttrInt(e, 900, inprocTimeout);
759     m_inboundHeader = XMLHelper::getAttrString(e, nullptr, inboundHeader);
760     if (!m_inboundHeader.empty())
761         RemotedHandler::addRemotedHeader(m_inboundHeader.c_str());
762     m_outboundHeader = XMLHelper::getAttrString(e, nullptr, outboundHeader);
763
764 #ifndef SHIBSP_LITE
765     if (conf.isEnabled(SPConfig::OutOfProcess)) {
766         string ssid(XMLHelper::getAttrString(e, nullptr, _StorageService));
767         if (!ssid.empty()) {
768             m_storage = conf.getServiceProvider()->getStorageService(ssid.c_str());
769             if (m_storage)
770                 m_log.info("bound to StorageService (%s)", ssid.c_str());
771             else
772                 m_log.warn("specified StorageService (%s) not found", ssid.c_str());
773         }
774         if (!m_storage) {
775             m_storage = conf.getServiceProvider()->getStorageService(nullptr);
776             if (m_storage)
777                 m_log.info("bound to arbitrary StorageService");
778             else
779                 throw ConfigurationException("SessionCache unable to locate StorageService, check configuration.");
780         }
781
782         ssid = XMLHelper::getAttrString(e, nullptr, _StorageServiceLite);
783         if (!ssid.empty()) {
784             m_storage_lite = conf.getServiceProvider()->getStorageService(ssid.c_str());
785             if (m_storage_lite)
786                 m_log.info("bound to 'lite' StorageService (%s)", ssid.c_str());
787             else
788                 m_log.warn("specified 'lite' StorageService (%s) not found", ssid.c_str());
789         }
790         if (!m_storage_lite) {
791             m_log.info("StorageService for 'lite' use not set, using standard StorageService");
792             m_storage_lite = m_storage;
793         }
794
795         m_cacheAssertions = XMLHelper::getAttrBool(e, true, cacheAssertions);
796     }
797 #endif
798
799     ListenerService* listener=conf.getServiceProvider()->getListenerService(false);
800     if (inproc) {
801         if (!conf.isEnabled(SPConfig::OutOfProcess) && !listener)
802             throw ConfigurationException("SessionCache requires a ListenerService, but none available.");
803         m_lock = RWLock::create();
804         shutdown_wait = CondWait::create();
805         cleanup_thread = Thread::create(&cleanup_fn, this);
806     }
807 #ifndef SHIBSP_LITE
808     else {
809         if (listener && conf.isEnabled(SPConfig::OutOfProcess)) {
810             listener->regListener("find::"STORAGESERVICE_SESSION_CACHE"::SessionCache",this);
811             listener->regListener("remove::"STORAGESERVICE_SESSION_CACHE"::SessionCache",this);
812             listener->regListener("touch::"STORAGESERVICE_SESSION_CACHE"::SessionCache",this);
813         }
814         else {
815             m_log.info("no ListenerService available, cache remoting disabled");
816         }
817     }
818 #endif
819 }
820
821 SSCache::~SSCache()
822 {
823     if (inproc) {
824         // Shut down the cleanup thread and let it know...
825         shutdown = true;
826         shutdown_wait->signal();
827         cleanup_thread->join(nullptr);
828
829         for_each(m_hashtable.begin(),m_hashtable.end(),cleanup_pair<string,StoredSession>());
830         delete m_lock;
831
832         delete cleanup_thread;
833         delete shutdown_wait;
834     }
835 #ifndef SHIBSP_LITE
836     else {
837         SPConfig& conf = SPConfig::getConfig();
838         ListenerService* listener=conf.getServiceProvider()->getListenerService(false);
839         if (listener && conf.isEnabled(SPConfig::OutOfProcess)) {
840             listener->unregListener("find::"STORAGESERVICE_SESSION_CACHE"::SessionCache",this);
841             listener->unregListener("remove::"STORAGESERVICE_SESSION_CACHE"::SessionCache",this);
842             listener->unregListener("touch::"STORAGESERVICE_SESSION_CACHE"::SessionCache",this);
843         }
844     }
845 #endif
846 }
847
848 #ifndef SHIBSP_LITE
849
850 void SSCache::test()
851 {
852     auto_ptr_char temp(SAMLConfig::getConfig().generateIdentifier());
853     m_storage->createString("SessionCacheTest", temp.get(), "Test", time(nullptr) + 60);
854     m_storage->deleteString("SessionCacheTest", temp.get());
855 }
856
857 void SSCache::insert(const char* key, time_t expires, const char* name, const char* index)
858 {
859     string dup;
860     if (strlen(name) > 255) {
861         dup = string(name).substr(0,255);
862         name = dup.c_str();
863     }
864
865     DDF obj;
866     DDFJanitor jobj(obj);
867
868     // Since we can't guarantee uniqueness, check for an existing record.
869     string record;
870     time_t recordexp;
871     int ver = m_storage_lite->readText("NameID", name, &record, &recordexp);
872     if (ver > 0) {
873         // Existing record, so we need to unmarshall it.
874         istringstream in(record);
875         in >> obj;
876     }
877     else {
878         // New record.
879         obj = DDF(nullptr).structure();
880     }
881
882     if (!index || !*index)
883         index = "_shibnull";
884     DDF sessions = obj.addmember(index);
885     if (!sessions.islist())
886         sessions.list();
887     DDF session = DDF(nullptr).string(key);
888     sessions.add(session);
889
890     // Remarshall the record.
891     ostringstream out;
892     out << obj;
893
894     // Try and store it back...
895     if (ver > 0) {
896         ver = m_storage_lite->updateText("NameID", name, out.str().c_str(), max(expires, recordexp), ver);
897         if (ver <= 0) {
898             // Out of sync, or went missing, so retry.
899             return insert(key, expires, name, index);
900         }
901     }
902     else if (!m_storage_lite->createText("NameID", name, out.str().c_str(), expires)) {
903         // Hit a dup, so just retry, hopefully hitting the other branch.
904         return insert(key, expires, name, index);
905     }
906 }
907
908 void SSCache::insert(
909     const Application& app,
910     const HTTPRequest& httpRequest,
911     HTTPResponse& httpResponse,
912     time_t expires,
913     const saml2md::EntityDescriptor* issuer,
914     const XMLCh* protocol,
915     const saml2::NameID* nameid,
916     const XMLCh* authn_instant,
917     const XMLCh* session_index,
918     const XMLCh* authncontext_class,
919     const XMLCh* authncontext_decl,
920     const vector<const Assertion*>* tokens,
921     const vector<Attribute*>* attributes
922     )
923 {
924 #ifdef _DEBUG
925     xmltooling::NDC ndc("insert");
926 #endif
927     if (!m_storage)
928         throw ConfigurationException("SessionCache insertion requires a StorageService.");
929
930     m_log.debug("creating new session");
931
932     time_t now = time(nullptr);
933     auto_ptr_char index(session_index);
934     auto_ptr_char entity_id(issuer ? issuer->getEntityID() : nullptr);
935     auto_ptr_char name(nameid ? nameid->getName() : nullptr);
936
937     if (nameid) {
938         // Check for a pending logout.
939         char namebuf[256];
940         strncpy(namebuf, name.get(), 255);
941         namebuf[255] = 0;
942         string pending;
943         int ver = m_storage_lite->readText("Logout", namebuf, &pending);
944         if (ver > 0) {
945             DDF pendobj;
946             DDFJanitor jpend(pendobj);
947             istringstream pstr(pending);
948             pstr >> pendobj;
949             // IdP.SP.index contains logout expiration, if any.
950             DDF deadmenwalking = pendobj[issuer ? entity_id.get() : "_shibnull"][app.getRelyingParty(issuer)->getString("entityID").second];
951             const char* logexpstr = deadmenwalking[session_index ? index.get() : "_shibnull"].string();
952             if (!logexpstr && session_index)    // we tried an exact session match, now try for nullptr
953                 logexpstr = deadmenwalking["_shibnull"].string();
954             if (logexpstr) {
955                 auto_ptr_XMLCh dt(logexpstr);
956                 DateTime dtobj(dt.get());
957                 dtobj.parseDateTime();
958                 time_t logexp = dtobj.getEpoch();
959                 if (now - XMLToolingConfig::getConfig().clock_skew_secs < logexp)
960                     throw FatalProfileException("A logout message from your identity provider has blocked your login attempt.");
961             }
962         }
963     }
964
965     auto_ptr_char key(SAMLConfig::getConfig().generateIdentifier());
966
967     // Store session properties in DDF.
968     DDF obj = DDF(key.get()).structure();
969     DDFJanitor entryobj(obj);
970     obj.addmember("version").integer(1);
971     obj.addmember("application_id").string(app.getId());
972
973     // On 64-bit Windows, time_t doesn't fit in a long, so I'm using ISO timestamps.
974 #ifndef HAVE_GMTIME_R
975     struct tm* ptime=gmtime(&expires);
976 #else
977     struct tm res;
978     struct tm* ptime=gmtime_r(&expires,&res);
979 #endif
980     char timebuf[32];
981     strftime(timebuf,32,"%Y-%m-%dT%H:%M:%SZ",ptime);
982     obj.addmember("expires").string(timebuf);
983
984     obj.addmember("client_addr").string(httpRequest.getRemoteAddr().c_str());
985     if (issuer)
986         obj.addmember("entity_id").string(entity_id.get());
987     if (protocol) {
988         auto_ptr_char prot(protocol);
989         obj.addmember("protocol").string(prot.get());
990     }
991     if (authn_instant) {
992         auto_ptr_char instant(authn_instant);
993         obj.addmember("authn_instant").string(instant.get());
994     }
995     if (session_index)
996         obj.addmember("session_index").string(index.get());
997     if (authncontext_class) {
998         auto_ptr_char ac(authncontext_class);
999         obj.addmember("authncontext_class").string(ac.get());
1000     }
1001     if (authncontext_decl) {
1002         auto_ptr_char ad(authncontext_decl);
1003         obj.addmember("authncontext_decl").string(ad.get());
1004     }
1005
1006     if (nameid) {
1007         ostringstream namestr;
1008         namestr << *nameid;
1009         obj.addmember("nameid").string(namestr.str().c_str());
1010     }
1011
1012     if (tokens && m_cacheAssertions) {
1013         obj.addmember("assertions").list();
1014         for (vector<const Assertion*>::const_iterator t = tokens->begin(); t!=tokens->end(); ++t) {
1015             auto_ptr_char tokenid((*t)->getID());
1016             DDF tokid = DDF(nullptr).string(tokenid.get());
1017             obj["assertions"].add(tokid);
1018         }
1019     }
1020
1021     if (attributes) {
1022         DDF attr;
1023         DDF attrlist = obj.addmember("attributes").list();
1024         for (vector<Attribute*>::const_iterator a=attributes->begin(); a!=attributes->end(); ++a) {
1025             attr = (*a)->marshall();
1026             attrlist.add(attr);
1027         }
1028     }
1029
1030     ostringstream record;
1031     record << obj;
1032
1033     m_log.debug("storing new session...");
1034     unsigned long cacheTimeout = getCacheTimeout(app);
1035     if (!m_storage->createText(key.get(), "session", record.str().c_str(), now + cacheTimeout))
1036         throw FatalProfileException("Attempted to create a session with a duplicate key.");
1037
1038     // Store the reverse mapping for logout.
1039     try {
1040         if (nameid)
1041             insert(key.get(), expires, name.get(), index.get());
1042     }
1043     catch (exception& ex) {
1044         m_log.error("error storing back mapping of NameID for logout: %s", ex.what());
1045     }
1046
1047     if (tokens && m_cacheAssertions) {
1048         try {
1049             for (vector<const Assertion*>::const_iterator t = tokens->begin(); t!=tokens->end(); ++t) {
1050                 ostringstream tokenstr;
1051                 tokenstr << *(*t);
1052                 auto_ptr_char tokenid((*t)->getID());
1053                 if (!m_storage->createText(key.get(), tokenid.get(), tokenstr.str().c_str(), now + cacheTimeout))
1054                     throw IOException("duplicate assertion ID ($1)", params(1, tokenid.get()));
1055             }
1056         }
1057         catch (exception& ex) {
1058             m_log.error("error storing assertion along with session: %s", ex.what());
1059         }
1060     }
1061
1062     const char* pid = obj["entity_id"].string();
1063     const char* prot = obj["protocol"].string();
1064     m_log.info("new session created: ID (%s) IdP (%s) Protocol(%s) Address (%s)",
1065         key.get(), pid ? pid : "none", prot ? prot : "none", httpRequest.getRemoteAddr().c_str());
1066
1067     // Transaction Logging
1068     string primaryAssertionID("none");
1069     if (m_cacheAssertions) {
1070         if (tokens)
1071             primaryAssertionID = obj["assertions"].first().string();
1072     }
1073     else if (tokens) {
1074         auto_ptr_char tokenid(tokens->front()->getID());
1075         primaryAssertionID = tokenid.get();
1076     }
1077     TransactionLog* xlog = app.getServiceProvider().getTransactionLog();
1078     Locker locker(xlog);
1079     xlog->log.infoStream() <<
1080         "New session (ID: " <<
1081             key.get() <<
1082         ") with (applicationId: " <<
1083             app.getId() <<
1084         ") for principal from (IdP: " <<
1085             (pid ? pid : "none") <<
1086         ") at (ClientAddress: " <<
1087             httpRequest.getRemoteAddr() <<
1088         ") with (NameIdentifier: " <<
1089             (nameid ? name.get() : "none") <<
1090         ") using (Protocol: " <<
1091             (prot ? prot : "none") <<
1092         ") from (AssertionID: " <<
1093             primaryAssertionID <<
1094         ")";
1095
1096     if (attributes) {
1097         xlog->log.infoStream() <<
1098             "Cached the following attributes with session (ID: " <<
1099                 key.get() <<
1100             ") for (applicationId: " <<
1101                 app.getId() <<
1102             ") {";
1103         for (vector<Attribute*>::const_iterator a=attributes->begin(); a!=attributes->end(); ++a)
1104             xlog->log.infoStream() << "\t" << (*a)->getId() << " (" << (*a)->valueCount() << " values)";
1105         xlog->log.info("}");
1106     }
1107
1108     if (m_outboundHeader.empty()) {
1109         time_t cookieLifetime = 0;
1110         pair<string,const char*> shib_cookie = app.getCookieNameProps("_shibsession_", &cookieLifetime);
1111         string k(key.get());
1112         k += shib_cookie.second;
1113
1114         if (cookieLifetime > 0) {
1115             cookieLifetime += now;
1116 #ifndef HAVE_GMTIME_R
1117             ptime=gmtime(&cookieLifetime);
1118 #else
1119             ptime=gmtime_r(&cookieLifetime,&res);
1120 #endif
1121             char cookietimebuf[64];
1122             strftime(cookietimebuf,64,"; expires=%a, %d %b %Y %H:%M:%S GMT",ptime);
1123             k += cookietimebuf;
1124         }
1125
1126         httpResponse.setCookie(shib_cookie.first.c_str(), k.c_str());
1127     }
1128     else {
1129         // Use an arbitrary header to pass back the session ID instead of a cookie.
1130         httpResponse.setResponseHeader(m_outboundHeader.c_str(), key.get());
1131     }
1132 }
1133
1134 bool SSCache::matches(
1135     const Application& app,
1136     const xmltooling::HTTPRequest& request,
1137     const saml2md::EntityDescriptor* issuer,
1138     const saml2::NameID& nameid,
1139     const set<string>* indexes
1140     )
1141 {
1142     auto_ptr_char entityID(issuer ? issuer->getEntityID() : nullptr);
1143     try {
1144         Session* session = find(app, request);
1145         if (session) {
1146             Locker locker(session, false);
1147             if (XMLString::equals(session->getEntityID(), entityID.get()) && session->getNameID() &&
1148                     stronglyMatches(issuer->getEntityID(), app.getRelyingParty(issuer)->getXMLString("entityID").second, nameid, *session->getNameID())) {
1149                 return (!indexes || indexes->empty() || (session->getSessionIndex() ? (indexes->count(session->getSessionIndex())>0) : false));
1150             }
1151         }
1152     }
1153     catch (exception& ex) {
1154         m_log.error("error while matching session: %s", ex.what());
1155     }
1156     return false;
1157 }
1158
1159 vector<string>::size_type SSCache::logout(
1160     const Application& app,
1161     const saml2md::EntityDescriptor* issuer,
1162     const saml2::NameID& nameid,
1163     const set<string>* indexes,
1164     time_t expires,
1165     vector<string>& sessionsKilled
1166     )
1167 {
1168 #ifdef _DEBUG
1169     xmltooling::NDC ndc("logout");
1170 #endif
1171
1172     if (!m_storage)
1173         throw ConfigurationException("SessionCache insertion requires a StorageService.");
1174
1175     auto_ptr_char entityID(issuer ? issuer->getEntityID() : nullptr);
1176     auto_ptr_char name(nameid.getName());
1177
1178     m_log.info("request to logout sessions from (%s) for (%s)", entityID.get() ? entityID.get() : "unknown", name.get());
1179
1180     if (strlen(name.get()) > 255)
1181         const_cast<char*>(name.get())[255] = 0;
1182
1183     DDF obj;
1184     DDFJanitor jobj(obj);
1185     string record;
1186     int ver;
1187
1188     if (expires) {
1189         // Record the logout to prevent post-delivered assertions.
1190         // On 64-bit Windows, time_t doesn't fit in a long, so I'm using ISO timestamps.
1191 #ifndef HAVE_GMTIME_R
1192         struct tm* ptime=gmtime(&expires);
1193 #else
1194         struct tm res;
1195         struct tm* ptime=gmtime_r(&expires,&res);
1196 #endif
1197         char timebuf[32];
1198         strftime(timebuf,32,"%Y-%m-%dT%H:%M:%SZ",ptime);
1199
1200         time_t oldexp = 0;
1201         ver = m_storage_lite->readText("Logout", name.get(), &record, &oldexp);
1202         if (ver > 0) {
1203             istringstream lin(record);
1204             lin >> obj;
1205         }
1206         else {
1207             obj = DDF(nullptr).structure();
1208         }
1209
1210         // Structure is keyed by the IdP and SP, with a member per session index containing the expiration.
1211         DDF root = obj.addmember(issuer ? entityID.get() : "_shibnull").addmember(app.getRelyingParty(issuer)->getString("entityID").second);
1212         if (indexes) {
1213             for (set<string>::const_iterator x = indexes->begin(); x!=indexes->end(); ++x)
1214                 root.addmember(x->c_str()).string(timebuf);
1215         }
1216         else {
1217             root.addmember("_shibnull").string(timebuf);
1218         }
1219
1220         // Write it back.
1221         ostringstream lout;
1222         lout << obj;
1223
1224         if (ver > 0) {
1225             ver = m_storage_lite->updateText("Logout", name.get(), lout.str().c_str(), max(expires, oldexp), ver);
1226             if (ver <= 0) {
1227                 // Out of sync, or went missing, so retry.
1228                 return logout(app, issuer, nameid, indexes, expires, sessionsKilled);
1229             }
1230         }
1231         else if (!m_storage_lite->createText("Logout", name.get(), lout.str().c_str(), expires)) {
1232             // Hit a dup, so just retry, hopefully hitting the other branch.
1233             return logout(app, issuer, nameid, indexes, expires, sessionsKilled);
1234         }
1235
1236         obj.destroy();
1237         record.erase();
1238     }
1239
1240     // Read in potentially matching sessions.
1241     ver = m_storage_lite->readText("NameID", name.get(), &record);
1242     if (ver == 0) {
1243         m_log.debug("no active sessions to logout for supplied issuer and subject");
1244         return 0;
1245     }
1246
1247     istringstream in(record);
1248     in >> obj;
1249
1250     // The record contains child lists for each known session index.
1251     DDF key;
1252     DDF sessions = obj.first();
1253     while (sessions.islist()) {
1254         if (!indexes || indexes->empty() || indexes->count(sessions.name())) {
1255             key = sessions.first();
1256             while (key.isstring()) {
1257                 // Fetch the session for comparison.
1258                 Session* session = nullptr;
1259                 try {
1260                     session = find(app, key.string());
1261                 }
1262                 catch (exception& ex) {
1263                     m_log.error("error locating session (%s): %s", key.string(), ex.what());
1264                 }
1265
1266                 if (session) {
1267                     Locker locker(session, false);
1268                     // Same issuer?
1269                     if (XMLString::equals(session->getEntityID(), entityID.get())) {
1270                         // Same NameID?
1271                         if (stronglyMatches(issuer->getEntityID(), app.getRelyingParty(issuer)->getXMLString("entityID").second, nameid, *session->getNameID())) {
1272                             sessionsKilled.push_back(key.string());
1273                             key.destroy();
1274                         }
1275                         else {
1276                             m_log.debug("session (%s) contained a non-matching NameID, leaving it alone", key.string());
1277                         }
1278                     }
1279                     else {
1280                         m_log.debug("session (%s) established by different IdP, leaving it alone", key.string());
1281                     }
1282                 }
1283                 else {
1284                     // Session's gone, so...
1285                     sessionsKilled.push_back(key.string());
1286                     key.destroy();
1287                 }
1288                 key = sessions.next();
1289             }
1290
1291             // No sessions left for this index?
1292             if (sessions.first().isnull())
1293                 sessions.destroy();
1294         }
1295         sessions = obj.next();
1296     }
1297
1298     if (obj.first().isnull())
1299         obj.destroy();
1300
1301     // If possible, write back the mapping record (this isn't crucial).
1302     try {
1303         if (obj.isnull()) {
1304             m_storage_lite->deleteText("NameID", name.get());
1305         }
1306         else if (!sessionsKilled.empty()) {
1307             ostringstream out;
1308             out << obj;
1309             if (m_storage_lite->updateText("NameID", name.get(), out.str().c_str(), 0, ver) <= 0)
1310                 m_log.warn("logout mapping record changed behind us, leaving it alone");
1311         }
1312     }
1313     catch (exception& ex) {
1314         m_log.error("error updating logout mapping record: %s", ex.what());
1315     }
1316
1317     return sessionsKilled.size();
1318 }
1319
1320 bool SSCache::stronglyMatches(const XMLCh* idp, const XMLCh* sp, const saml2::NameID& n1, const saml2::NameID& n2) const
1321 {
1322     if (!XMLString::equals(n1.getName(), n2.getName()))
1323         return false;
1324
1325     const XMLCh* s1 = n1.getFormat();
1326     const XMLCh* s2 = n2.getFormat();
1327     if (!s1 || !*s1)
1328         s1 = saml2::NameID::UNSPECIFIED;
1329     if (!s2 || !*s2)
1330         s2 = saml2::NameID::UNSPECIFIED;
1331     if (!XMLString::equals(s1,s2))
1332         return false;
1333
1334     s1 = n1.getNameQualifier();
1335     s2 = n2.getNameQualifier();
1336     if (!s1 || !*s1)
1337         s1 = idp;
1338     if (!s2 || !*s2)
1339         s2 = idp;
1340     if (!XMLString::equals(s1,s2))
1341         return false;
1342
1343     s1 = n1.getSPNameQualifier();
1344     s2 = n2.getSPNameQualifier();
1345     if (!s1 || !*s1)
1346         s1 = sp;
1347     if (!s2 || !*s2)
1348         s2 = sp;
1349     if (!XMLString::equals(s1,s2))
1350         return false;
1351
1352     return true;
1353 }
1354
1355 #endif
1356
1357 Session* SSCache::find(const Application& app, const char* key, const char* client_addr, time_t* timeout)
1358 {
1359 #ifdef _DEBUG
1360     xmltooling::NDC ndc("find");
1361 #endif
1362     StoredSession* session=nullptr;
1363
1364     if (inproc) {
1365         m_log.debug("searching local cache for session (%s)", key);
1366         m_lock->rdlock();
1367         map<string,StoredSession*>::const_iterator i=m_hashtable.find(key);
1368         if (i!=m_hashtable.end()) {
1369             // Save off and lock the session.
1370             session = i->second;
1371             session->lock();
1372             m_lock->unlock();
1373             m_log.debug("session found locally, validating it for use");
1374         }
1375         else {
1376             m_lock->unlock();
1377         }
1378     }
1379
1380     if (!session) {
1381         if (!SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess)) {
1382             m_log.debug("session not found locally, remoting the search");
1383             // Remote the request.
1384             DDF in("find::"STORAGESERVICE_SESSION_CACHE"::SessionCache"), out;
1385             DDFJanitor jin(in);
1386             in.structure();
1387             in.addmember("key").string(key);
1388             in.addmember("application_id").string(app.getId());
1389             if (timeout && *timeout) {
1390                 // On 64-bit Windows, time_t doesn't fit in a long, so I'm using ISO timestamps.
1391 #ifndef HAVE_GMTIME_R
1392                 struct tm* ptime=gmtime(timeout);
1393 #else
1394                 struct tm res;
1395                 struct tm* ptime=gmtime_r(timeout,&res);
1396 #endif
1397                 char timebuf[32];
1398                 strftime(timebuf,32,"%Y-%m-%dT%H:%M:%SZ",ptime);
1399                 in.addmember("timeout").string(timebuf);
1400             }
1401
1402             try {
1403                 out=app.getServiceProvider().getListenerService()->send(in);
1404                 if (!out.isstruct()) {
1405                     out.destroy();
1406                     m_log.debug("session not found in remote cache");
1407                     return nullptr;
1408                 }
1409
1410                 // Wrap the results in a local entry and save it.
1411                 session = new StoredSession(this, out);
1412                 // The remote end has handled timeout issues, we handle address and expiration checks.
1413                 timeout = nullptr;
1414             }
1415             catch (...) {
1416                 out.destroy();
1417                 throw;
1418             }
1419         }
1420         else {
1421             // We're out of process, so we can search the storage service directly.
1422 #ifndef SHIBSP_LITE
1423             if (!m_storage)
1424                 throw ConfigurationException("SessionCache lookup requires a StorageService.");
1425
1426             m_log.debug("searching for session (%s)", key);
1427
1428             DDF obj;
1429             time_t lastAccess;
1430             string record;
1431             int ver = m_storage->readText(key, "session", &record, &lastAccess);
1432             if (!ver)
1433                 return nullptr;
1434
1435             m_log.debug("reconstituting session and checking validity");
1436
1437             istringstream in(record);
1438             in >> obj;
1439
1440             unsigned long cacheTimeout = getCacheTimeout(app);
1441             lastAccess -= cacheTimeout;   // adjusts it back to the last time the record's timestamp was touched
1442             time_t now=time(nullptr);
1443
1444             if (timeout && *timeout > 0 && now - lastAccess >= *timeout) {
1445                 m_log.info("session timed out (ID: %s)", key);
1446                 remove(app, key);
1447                 const char* eid = obj["entity_id"].string();
1448                 if (!eid) {
1449                     obj.destroy();
1450                     throw RetryableProfileException("Your session has expired, and you must re-authenticate.");
1451                 }
1452                 string eid2(eid);
1453                 obj.destroy();
1454                 throw RetryableProfileException("Your session has expired, and you must re-authenticate.", namedparams(1, "entityID", eid2.c_str()));
1455             }
1456
1457             if (timeout) {
1458                 // Update storage expiration, if possible.
1459                 try {
1460                     m_storage->updateContext(key, now + cacheTimeout);
1461                 }
1462                 catch (exception& ex) {
1463                     m_log.error("failed to update session expiration: %s", ex.what());
1464                 }
1465             }
1466
1467             // Wrap the results in a local entry and save it.
1468             session = new StoredSession(this, obj);
1469             // We handled timeout issues, still need to handle address and expiration checks.
1470             timeout = nullptr;
1471 #else
1472             throw ConfigurationException("SessionCache search requires a StorageService.");
1473 #endif
1474         }
1475
1476         if (inproc) {
1477             // Lock for writing and repeat the search to avoid duplication.
1478             m_lock->wrlock();
1479             SharedLock shared(m_lock, false);
1480             if (m_hashtable.count(key)) {
1481                 // We're using an existing session entry.
1482                 delete session;
1483                 session = m_hashtable[key];
1484                 session->lock();
1485             }
1486             else {
1487                 m_hashtable[key]=session;
1488                 session->lock();
1489             }
1490         }
1491     }
1492
1493     if (!XMLString::equals(session->getApplicationID(), app.getId())) {
1494         m_log.error("an application (%s) tried to access another application's session", app.getId());
1495         session->unlock();
1496         return nullptr;
1497     }
1498
1499     // Verify currency and update the timestamp if indicated by caller.
1500     try {
1501         session->validate(app, client_addr, timeout);
1502     }
1503     catch (...) {
1504         session->unlock();
1505         remove(app, key);
1506         throw;
1507     }
1508
1509     return session;
1510 }
1511
1512 Session* SSCache::find(const Application& app, HTTPRequest& request, const char* client_addr, time_t* timeout)
1513 {
1514     string id = active(app, request);
1515     if (id.empty())
1516         return nullptr;
1517     try {
1518         Session* session = find(app, id.c_str(), client_addr, timeout);
1519         if (session)
1520             return session;
1521         HTTPResponse* response = dynamic_cast<HTTPResponse*>(&request);
1522         if (response) {
1523             if (m_outboundHeader.empty()) {
1524                 pair<string,const char*> shib_cookie = app.getCookieNameProps("_shibsession_");
1525                 string exp(shib_cookie.second);
1526                 exp += "; expires=Mon, 01 Jan 2001 00:00:00 GMT";
1527                 response->setCookie(shib_cookie.first.c_str(), exp.c_str());
1528             }
1529             else {
1530                 response->setResponseHeader(m_outboundHeader.c_str(), nullptr);
1531             }
1532         }
1533     }
1534     catch (exception&) {
1535         if (m_outboundHeader.empty()) {
1536             HTTPResponse* response = dynamic_cast<HTTPResponse*>(&request);
1537             if (response) {
1538                 if (m_outboundHeader.empty()) {
1539                     pair<string,const char*> shib_cookie = app.getCookieNameProps("_shibsession_");
1540                     string exp(shib_cookie.second);
1541                     exp += "; expires=Mon, 01 Jan 2001 00:00:00 GMT";
1542                     response->setCookie(shib_cookie.first.c_str(), exp.c_str());
1543                 }
1544                 else {
1545                     response->setResponseHeader(m_outboundHeader.c_str(), nullptr);
1546                 }
1547             }
1548         }
1549         throw;
1550     }
1551     return nullptr;
1552 }
1553
1554 void SSCache::remove(const Application& app, const HTTPRequest& request, HTTPResponse* response)
1555 {
1556     if (m_inboundHeader.empty()) {
1557         pair<string,const char*> shib_cookie = app.getCookieNameProps("_shibsession_");
1558         const char* session_id = request.getCookie(shib_cookie.first.c_str());
1559         if (session_id && *session_id) {
1560             if (response) {
1561                 if (m_outboundHeader.empty()) {
1562                     string exp(shib_cookie.second);
1563                     exp += "; expires=Mon, 01 Jan 2001 00:00:00 GMT";
1564                     response->setCookie(shib_cookie.first.c_str(), exp.c_str());
1565                 }
1566                 else {
1567                     response->setResponseHeader(m_outboundHeader.c_str(), nullptr);
1568                 }
1569             }
1570             remove(app, session_id);
1571         }
1572     }
1573     else {
1574         string session_id = request.getHeader(m_inboundHeader.c_str());
1575         if (session_id.empty()) {
1576             const char* p = request.getParameter(m_inboundHeader.c_str());
1577             if (p)
1578                 session_id = p;
1579         }
1580         if (!session_id.empty()) {
1581             if (response && !m_outboundHeader.empty())
1582                 response->setResponseHeader(m_outboundHeader.c_str(), nullptr);
1583             remove(app, session_id.c_str());
1584         }
1585     }
1586 }
1587
1588 void SSCache::remove(const Application& app, const char* key)
1589 {
1590 #ifdef _DEBUG
1591     xmltooling::NDC ndc("remove");
1592 #endif
1593     // Take care of local copy.
1594     if (inproc)
1595         dormant(key);
1596
1597     if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess)) {
1598         // Remove the session from storage directly.
1599 #ifndef SHIBSP_LITE
1600         m_storage->deleteContext(key);
1601         m_log.info("removed session (%s)", key);
1602
1603         TransactionLog* xlog = app.getServiceProvider().getTransactionLog();
1604         Locker locker(xlog);
1605         xlog->log.info("Destroyed session (applicationId: %s) (ID: %s)", app.getId(), key);
1606 #else
1607         throw ConfigurationException("SessionCache removal requires a StorageService.");
1608 #endif
1609     }
1610     else {
1611         // Remote the request.
1612         DDF in("remove::"STORAGESERVICE_SESSION_CACHE"::SessionCache");
1613         DDFJanitor jin(in);
1614         in.structure();
1615         in.addmember("key").string(key);
1616         in.addmember("application_id").string(app.getId());
1617
1618         DDF out = app.getServiceProvider().getListenerService()->send(in);
1619         out.destroy();
1620     }
1621 }
1622
1623 void SSCache::dormant(const char* key)
1624 {
1625 #ifdef _DEBUG
1626     xmltooling::NDC ndc("dormant");
1627 #endif
1628
1629     m_log.debug("deleting local copy of session (%s)", key);
1630
1631     // lock the cache for writing, which means we know nobody is sitting in find()
1632     m_lock->wrlock();
1633
1634     // grab the entry from the table
1635     map<string,StoredSession*>::const_iterator i=m_hashtable.find(key);
1636     if (i==m_hashtable.end()) {
1637         m_lock->unlock();
1638         return;
1639     }
1640
1641     // ok, remove the entry and lock it
1642     StoredSession* entry=i->second;
1643     m_hashtable.erase(key);
1644     entry->lock();
1645
1646     // unlock the cache
1647     m_lock->unlock();
1648
1649     // we can release the cache entry lock because we know we're not in the cache anymore
1650     entry->unlock();
1651
1652     delete entry;
1653 }
1654
1655 void* SSCache::cleanup_fn(void* p)
1656 {
1657 #ifdef _DEBUG
1658     xmltooling::NDC ndc("cleanup");
1659 #endif
1660
1661     SSCache* pcache = reinterpret_cast<SSCache*>(p);
1662
1663 #ifndef WIN32
1664     // First, let's block all signals
1665     Thread::mask_all_signals();
1666 #endif
1667
1668     auto_ptr<Mutex> mutex(Mutex::create());
1669
1670     // Load our configuration details...
1671     static const XMLCh cleanupInterval[] = UNICODE_LITERAL_15(c,l,e,a,n,u,p,I,n,t,e,r,v,a,l);
1672     const XMLCh* tag=pcache->m_root ? pcache->m_root->getAttributeNS(nullptr, cleanupInterval) : nullptr;
1673     int rerun_timer = 900;
1674     if (tag && *tag) {
1675         rerun_timer = XMLString::parseInt(tag);
1676         if (rerun_timer <= 0)
1677             rerun_timer = 900;
1678     }
1679
1680     mutex->lock();
1681
1682     pcache->m_log.info("cleanup thread started...run every %d secs; timeout after %d secs", rerun_timer, pcache->m_inprocTimeout);
1683
1684     while (!pcache->shutdown) {
1685         pcache->shutdown_wait->timedwait(mutex.get(), rerun_timer);
1686         if (pcache->shutdown)
1687             break;
1688
1689         // Ok, let's run through the cleanup process and clean out
1690         // really old sessions.  This is a two-pass process.  The
1691         // first pass is done holding a read-lock while we iterate over
1692         // the cache.  The second pass doesn't need a lock because
1693         // the 'deletes' will lock the cache.
1694
1695         // Pass 1: iterate over the map and find all entries that have not been
1696         // used in the allotted timeout.
1697         vector<string> stale_keys;
1698         time_t stale = time(nullptr) - pcache->m_inprocTimeout;
1699
1700         pcache->m_log.debug("cleanup thread running");
1701
1702         pcache->m_lock->rdlock();
1703         for (map<string,StoredSession*>::const_iterator i=pcache->m_hashtable.begin(); i!=pcache->m_hashtable.end(); ++i) {
1704             // If the last access was BEFORE the stale timeout...
1705             i->second->lock();
1706             time_t last=i->second->getLastAccess();
1707             i->second->unlock();
1708             if (last < stale)
1709                 stale_keys.push_back(i->first);
1710         }
1711         pcache->m_lock->unlock();
1712
1713         if (!stale_keys.empty()) {
1714             pcache->m_log.info("purging %d old sessions", stale_keys.size());
1715
1716             // Pass 2: walk through the list of stale entries and remove them from the cache
1717             for (vector<string>::const_iterator j = stale_keys.begin(); j != stale_keys.end(); ++j)
1718                 pcache->dormant(j->c_str());
1719         }
1720
1721         pcache->m_log.debug("cleanup thread completed");
1722     }
1723
1724     pcache->m_log.info("cleanup thread exiting");
1725
1726     mutex->unlock();
1727     return nullptr;
1728 }
1729
1730 #ifndef SHIBSP_LITE
1731
1732 void SSCache::receive(DDF& in, ostream& out)
1733 {
1734 #ifdef _DEBUG
1735     xmltooling::NDC ndc("receive");
1736 #endif
1737     const Application* app = SPConfig::getConfig().getServiceProvider()->getApplication(in["application_id"].string());
1738     if (!app)
1739         throw ListenerException("Application not found, check configuration?");
1740
1741     if (!strcmp(in.name(),"find::"STORAGESERVICE_SESSION_CACHE"::SessionCache")) {
1742         const char* key=in["key"].string();
1743         if (!key)
1744             throw ListenerException("Required parameters missing for session lookup.");
1745
1746         // Do an unversioned read.
1747         string record;
1748         time_t lastAccess;
1749         if (!m_storage->readText(key, "session", &record, &lastAccess)) {
1750             DDF ret(nullptr);
1751             DDFJanitor jan(ret);
1752             out << ret;
1753             return;
1754         }
1755
1756         // Adjust for expiration to recover last access time and check timeout.
1757         unsigned long cacheTimeout = getCacheTimeout(*app);
1758         lastAccess -= cacheTimeout;
1759         time_t now=time(nullptr);
1760
1761         // See if we need to check for a timeout.
1762         if (in["timeout"].string()) {
1763             time_t timeout = 0;
1764             auto_ptr_XMLCh dt(in["timeout"].string());
1765             DateTime dtobj(dt.get());
1766             dtobj.parseDateTime();
1767             timeout = dtobj.getEpoch();
1768
1769             if (timeout > 0 && now - lastAccess >= timeout) {
1770                 m_log.info("session timed out (ID: %s)", key);
1771                 remove(*app, key);
1772                 throw RetryableProfileException("Your session has expired, and you must re-authenticate.");
1773             }
1774
1775             // Update storage expiration, if possible.
1776             try {
1777                 m_storage->updateContext(key, now + cacheTimeout);
1778             }
1779             catch (exception& ex) {
1780                 m_log.error("failed to update session expiration: %s", ex.what());
1781             }
1782         }
1783
1784         // Send the record back.
1785         out << record;
1786     }
1787     else if (!strcmp(in.name(),"touch::"STORAGESERVICE_SESSION_CACHE"::SessionCache")) {
1788         const char* key=in["key"].string();
1789         if (!key)
1790             throw ListenerException("Required parameters missing for session check.");
1791
1792         // Do a versioned read.
1793         string record;
1794         time_t lastAccess;
1795         int curver = in["version"].integer();
1796         int ver = m_storage->readText(key, "session", &record, &lastAccess, curver);
1797         if (ver == 0) {
1798             m_log.warn("unsuccessful versioned read of session (ID: %s), caches out of sync?", key);
1799             throw RetryableProfileException("Your session has expired, and you must re-authenticate.");
1800         }
1801
1802         // Adjust for expiration to recover last access time and check timeout.
1803         unsigned long cacheTimeout = getCacheTimeout(*app);
1804         lastAccess -= cacheTimeout;
1805         time_t now=time(nullptr);
1806
1807         // See if we need to check for a timeout.
1808         time_t timeout = 0;
1809         auto_ptr_XMLCh dt(in["timeout"].string());
1810         if (dt.get()) {
1811             DateTime dtobj(dt.get());
1812             dtobj.parseDateTime();
1813             timeout = dtobj.getEpoch();
1814         }
1815
1816         if (timeout > 0 && now - lastAccess >= timeout) {
1817             m_log.info("session timed out (ID: %s)", key);
1818             throw RetryableProfileException("Your session has expired, and you must re-authenticate.");
1819         }
1820
1821         // Update storage expiration, if possible.
1822         try {
1823             m_storage->updateContext(key, now + cacheTimeout);
1824         }
1825         catch (exception& ex) {
1826             m_log.error("failed to update session expiration: %s", ex.what());
1827         }
1828
1829         if (ver > curver) {
1830             // Send the record back.
1831             out << record;
1832         }
1833         else {
1834             DDF ret(nullptr);
1835             DDFJanitor jan(ret);
1836             out << ret;
1837         }
1838     }
1839     else if (!strcmp(in.name(),"remove::"STORAGESERVICE_SESSION_CACHE"::SessionCache")) {
1840         const char* key=in["key"].string();
1841         if (!key)
1842             throw ListenerException("Required parameter missing for session removal.");
1843
1844         remove(*app, key);
1845         DDF ret(nullptr);
1846         DDFJanitor jan(ret);
1847         out << ret;
1848     }
1849 }
1850
1851 #endif