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