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