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