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