2 * Licensed to the University Corporation for Advanced Internet
3 * Development, Inc. (UCAID) under one or more contributor license
4 * agreements. See the NOTICE file distributed with this work for
5 * additional information regarding copyright ownership.
7 * UCAID licenses this file to you under the Apache License,
8 * Version 2.0 (the "License"); you may not use this file except
9 * in compliance with the License. You may obtain a copy of the
12 * http://www.apache.org/licenses/LICENSE-2.0
14 * Unless required by applicable law or agreed to in writing,
15 * software distributed under the License is distributed on an
16 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
17 * either express or implied. See the License for the specific
18 * language governing permissions and limitations under the License.
22 * StorageServiceSessionCache.cpp
24 * StorageService-based SessionCache implementation.
26 * Instead of optimizing this plugin with a buffering scheme that keeps objects around
27 * and avoids extra parsing steps, I'm assuming that systems that require such can
28 * layer their own cache plugin on top of this version either by delegating to it
29 * or using the remoting support. So this version will load sessions directly
30 * from the StorageService, instantiate enough to expose the Session API,
31 * and then delete everything when they're unlocked. All data in memory is always
32 * kept in sync with the StorageService (no lazy updates).
36 #include "Application.h"
37 #include "exceptions.h"
38 #include "ServiceProvider.h"
39 #include "SessionCacheEx.h"
40 #include "TransactionLog.h"
41 #include "attribute/Attribute.h"
42 #include "handler/RemotedHandler.h"
43 #include "remoting/ListenerService.h"
44 #include "util/SPConstants.h"
47 #include <boost/bind.hpp>
48 #include <boost/shared_ptr.hpp>
49 #include <xmltooling/io/HTTPRequest.h>
50 #include <xmltooling/io/HTTPResponse.h>
51 #include <xmltooling/util/DateTime.h>
52 #include <xmltooling/util/NDC.h>
53 #include <xmltooling/util/ParserPool.h>
54 #include <xmltooling/util/Threads.h>
55 #include <xmltooling/util/XMLHelper.h>
56 #include <xercesc/util/XMLUniDefs.hpp>
59 # include <saml/exceptions.h>
60 # include <saml/SAMLConfig.h>
61 # include <saml/saml2/core/Assertions.h>
62 # include <saml/saml2/metadata/Metadata.h>
63 # include <xmltooling/XMLToolingConfig.h>
64 # include <xmltooling/util/StorageService.h>
65 # include <xercesc/util/XMLStringTokenizer.hpp>
66 using namespace opensaml::saml2md;
69 # include <xmltooling/util/DateTime.h>
72 using namespace shibsp;
73 using namespace opensaml;
74 using namespace xmltooling;
75 using namespace boost;
81 class SSCache : public SessionCacheEx
83 ,public virtual Remoted
87 SSCache(const DOMElement* e);
91 void receive(DDF& in, ostream& out);
94 const Application& app,
95 const HTTPRequest& httpRequest,
96 HTTPResponse& httpResponse,
98 const EntityDescriptor* issuer=nullptr,
99 const XMLCh* protocol=nullptr,
100 const saml2::NameID* nameid=nullptr,
101 const XMLCh* authn_instant=nullptr,
102 const XMLCh* session_index=nullptr,
103 const XMLCh* authncontext_class=nullptr,
104 const XMLCh* authncontext_decl=nullptr,
105 const vector<const Assertion*>* tokens=nullptr,
106 const vector<Attribute*>* attributes=nullptr
109 insert(dummy, app, httpRequest, httpResponse, expires, issuer, protocol, nameid,
110 authn_instant, session_index, authncontext_class, authncontext_decl, tokens, attributes);
115 const Application& app,
116 const HTTPRequest& httpRequest,
117 HTTPResponse& httpResponse,
119 const EntityDescriptor* issuer=nullptr,
120 const XMLCh* protocol=nullptr,
121 const saml2::NameID* nameid=nullptr,
122 const XMLCh* authn_instant=nullptr,
123 const XMLCh* session_index=nullptr,
124 const XMLCh* authncontext_class=nullptr,
125 const XMLCh* authncontext_decl=nullptr,
126 const vector<const Assertion*>* tokens=nullptr,
127 const vector<Attribute*>* attributes=nullptr
129 vector<string>::size_type logout(
130 const Application& app,
131 const EntityDescriptor* issuer,
132 const saml2::NameID& nameid,
133 const set<string>* indexes,
135 vector<string>& sessions
138 const Application& app,
139 const HTTPRequest& request,
140 const EntityDescriptor* issuer,
141 const saml2::NameID& nameid,
142 const set<string>* indexes
145 Session* find(const Application& app, const char* key, const char* client_addr=nullptr, time_t* timeout=nullptr);
146 void remove(const Application& app, const char* key);
149 string active(const Application& app, const HTTPRequest& request) {
150 if (!m_inboundHeader.empty()) {
151 string session_id = request.getHeader(m_inboundHeader.c_str());
152 if (!session_id.empty())
155 pair<string,const char*> shib_cookie = app.getCookieNameProps("_shibsession_");
156 const char* session_id = request.getCookie(shib_cookie.first.c_str());
157 return (session_id ? session_id : "");
160 Session* find(const Application& app, const HTTPRequest& request, const char* client_addr=nullptr, time_t* timeout=nullptr) {
161 string id = active(app, request);
163 return find(app, id.c_str(), client_addr, timeout);
167 Session* find(const Application& app, HTTPRequest& request, const char* client_addr=nullptr, time_t* timeout=nullptr);
168 void remove(const Application& app, const HTTPRequest& request, HTTPResponse* response=nullptr);
170 unsigned long getCacheTimeout(const Application& app) {
171 // Computes offset for adjusting expiration of sessions.
172 // This can either be static, or dynamic based on the per-app session timeout or lifetime.
174 return m_cacheTimeout;
175 pair<bool,unsigned int> timeout = pair<bool,unsigned int>(false, 3600);
176 const PropertySet* props = app.getPropertySet("Sessions");
178 timeout = props->getUnsignedInt("timeout");
180 timeout.second = 3600;
182 // As long as one of the two factors is set, add them together.
183 if (timeout.second > 0 || m_cacheAllowance > 0)
184 return timeout.second + m_cacheAllowance;
186 // If timeouts are off, and there's no cache slop set, then use the lifetime.
187 timeout = pair<bool,unsigned int>(false, 28800);
189 timeout = props->getUnsignedInt("lifetime");
190 if (!timeout.first || timeout.second == 0)
191 timeout.second = 28800;
193 return timeout.second;
199 StorageService* m_storage;
200 StorageService* m_storage_lite;
205 // maintain back-mappings of NameID/SessionIndex -> session key
206 void insert(const char* key, time_t expires, const char* name, const char* index);
207 bool stronglyMatches(const XMLCh* idp, const XMLCh* sp, const saml2::NameID& n1, const saml2::NameID& n2) const;
208 LogoutEvent* newLogoutEvent(const Application& app) const;
210 bool m_cacheAssertions,m_reverseIndex;
211 set<xstring> m_excludedNames;
213 const DOMElement* m_root; // Only valid during initialization
214 unsigned long m_inprocTimeout,m_cacheTimeout,m_cacheAllowance;
215 string m_inboundHeader,m_outboundHeader;
217 // inproc means we buffer sessions in memory
218 scoped_ptr<RWLock> m_lock;
219 map<string,StoredSession*> m_hashtable;
221 // management of buffered sessions
222 void dormant(const char* key);
223 static void* cleanup_fn(void*);
226 scoped_ptr<CondWait> shutdown_wait;
227 scoped_ptr<Thread> cleanup_thread;
230 class StoredSession : public virtual Session
233 StoredSession(SSCache* cache, DDF& obj) : m_obj(obj), m_cache(cache), m_expires(0), m_lastAccess(time(nullptr)) {
234 auto_ptr_XMLCh exp(m_obj["expires"].string());
236 DateTime iso(exp.get());
238 m_expires = iso.getEpoch();
242 const char* nameid = obj["nameid"].string();
244 // Parse and bind the document into an XMLObject.
245 istringstream instr(nameid);
246 DOMDocument* doc = XMLToolingConfig::getConfig().getParser().parse(instr);
247 XercesJanitor<DOMDocument> janitor(doc);
248 m_nameid.reset(saml2::NameIDBuilder::buildNameID());
249 m_nameid->unmarshall(doc->getDocumentElement(), true);
254 m_lock.reset(Mutex::create());
259 for_each(m_attributes.begin(), m_attributes.end(), xmltooling::cleanup<Attribute>());
274 const char* getID() const {
277 const char* getApplicationID() const {
278 return m_obj["application_id"].string();
280 const char* getClientAddress() const {
281 return m_obj["client_addr"].string();
283 const char* getEntityID() const {
284 return m_obj["entity_id"].string();
286 const char* getProtocol() const {
287 return m_obj["protocol"].string();
289 const char* getAuthnInstant() const {
290 return m_obj["authn_instant"].string();
293 const saml2::NameID* getNameID() const {
294 return m_nameid.get();
297 const char* getSessionIndex() const {
298 return m_obj["session_index"].string();
300 const char* getAuthnContextClassRef() const {
301 return m_obj["authncontext_class"].string();
303 const char* getAuthnContextDeclRef() const {
304 return m_obj["authncontext_decl"].string();
306 const vector<Attribute*>& getAttributes() const {
307 if (m_attributes.empty())
308 unmarshallAttributes();
311 const multimap<string,const Attribute*>& getIndexedAttributes() const {
312 if (m_attributeIndex.empty()) {
313 if (m_attributes.empty())
314 unmarshallAttributes();
315 for (vector<Attribute*>::const_iterator a = m_attributes.begin(); a != m_attributes.end(); ++a) {
316 const vector<string>& aliases = (*a)->getAliases();
317 for (vector<string>::const_iterator alias = aliases.begin(); alias != aliases.end(); ++alias)
318 m_attributeIndex.insert(multimap<string,const Attribute*>::value_type(*alias, *a));
321 return m_attributeIndex;
323 const vector<const char*>& getAssertionIDs() const {
325 DDF ids = m_obj["assertions"];
326 DDF id = ids.first();
327 while (id.isstring()) {
328 m_ids.push_back(id.string());
335 void validate(const Application& application, const char* client_addr, time_t* timeout);
338 void addAttributes(const vector<Attribute*>& attributes);
339 const Assertion* getAssertion(const char* id) const;
340 void addAssertion(Assertion* assertion);
343 time_t getExpiration() const { return m_expires; }
344 time_t getLastAccess() const { return m_lastAccess; }
347 void unmarshallAttributes() const;
351 scoped_ptr<saml2::NameID> m_nameid;
352 mutable map< string,boost::shared_ptr<Assertion> > m_tokens;
354 mutable vector<Attribute*> m_attributes;
355 mutable multimap<string,const Attribute*> m_attributeIndex;
356 mutable vector<const char*> m_ids;
359 time_t m_expires,m_lastAccess;
360 scoped_ptr<Mutex> m_lock;
363 SessionCache* SHIBSP_DLLLOCAL StorageServiceCacheFactory(const DOMElement* const & e)
365 return new SSCache(e);
369 Session* SessionCache::find(const Application& application, HTTPRequest& request, const char* client_addr, time_t* timeout)
371 return find(application, const_cast<const HTTPRequest&>(request), client_addr, timeout);
374 void SHIBSP_API shibsp::registerSessionCaches()
376 SPConfig::getConfig().SessionCacheManager.registerFactory(STORAGESERVICE_SESSION_CACHE, StorageServiceCacheFactory);
387 void StoredSession::unmarshallAttributes() const
389 Attribute* attribute;
390 DDF attrs = m_obj["attributes"];
391 DDF attr = attrs.first();
392 while (!attr.isnull()) {
394 attribute = Attribute::unmarshall(attr);
395 m_attributes.push_back(attribute);
396 if (m_cache->m_log.isDebugEnabled())
397 m_cache->m_log.debug("unmarshalled attribute (ID: %s) with %d value%s",
398 attribute->getId(), attr.first().integer(), attr.first().integer()!=1 ? "s" : "");
400 catch (AttributeException& ex) {
401 const char* id = attr.first().name();
402 m_cache->m_log.error("error unmarshalling attribute (ID: %s): %s", id ? id : "none", ex.what());
408 void StoredSession::validate(const Application& app, const char* client_addr, time_t* timeout)
410 time_t now = time(nullptr);
414 if (now > m_expires) {
415 m_cache->m_log.info("session expired (ID: %s)", getID());
416 throw RetryableProfileException("Your session has expired, and you must re-authenticate.");
422 if (!XMLString::equals(getClientAddress(),client_addr)) {
423 m_cache->m_log.warn("client address mismatch, client (%s), session (%s)", client_addr, getClientAddress());
424 throw RetryableProfileException(
425 "Your IP address ($1) does not match the address recorded at the time the session was established.",
426 params(1,client_addr)
434 if (!SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess)) {
435 DDF in("touch::"STORAGESERVICE_SESSION_CACHE"::SessionCache"), out;
438 in.addmember("key").string(getID());
439 in.addmember("version").integer(m_obj["version"].integer());
440 in.addmember("application_id").string(app.getId());
442 // On 64-bit Windows, time_t doesn't fit in a long, so I'm using ISO timestamps.
443 #ifndef HAVE_GMTIME_R
444 struct tm* ptime=gmtime(timeout);
447 struct tm* ptime=gmtime_r(timeout,&res);
450 strftime(timebuf,32,"%Y-%m-%dT%H:%M:%SZ",ptime);
451 in.addmember("timeout").string(timebuf);
455 out=app.getServiceProvider().getListenerService()->send(in);
462 if (out.isstruct()) {
463 // We got an updated record back.
465 for_each(m_attributes.begin(), m_attributes.end(), xmltooling::cleanup<Attribute>());
466 m_attributes.clear();
467 m_attributeIndex.clear();
474 if (!m_cache->m_storage)
475 throw ConfigurationException("Session touch requires a StorageService.");
477 // Do a versioned read.
480 int curver = m_obj["version"].integer();
481 int ver = m_cache->m_storage->readText(getID(), "session", &record, &lastAccess, curver);
483 m_cache->m_log.warn("unsuccessful versioned read of session (ID: %s), cache out of sync?", getID());
484 throw RetryableProfileException("Your session has expired, and you must re-authenticate.");
487 // Adjust for expiration to recover last access time and check timeout.
488 unsigned long cacheTimeout = m_cache->getCacheTimeout(app);
489 lastAccess -= cacheTimeout;
490 if (*timeout > 0 && now - lastAccess >= *timeout) {
491 m_cache->m_log.info("session timed out (ID: %s)", getID());
492 throw RetryableProfileException("Your session has expired, and you must re-authenticate.");
495 // Update storage expiration, if possible.
497 m_cache->m_storage->updateContext(getID(), now + cacheTimeout);
499 catch (std::exception& ex) {
500 m_cache->m_log.error("failed to update session expiration: %s", ex.what());
504 // We got an updated record back.
506 istringstream in(record);
509 for_each(m_attributes.begin(), m_attributes.end(), xmltooling::cleanup<Attribute>());
510 m_attributes.clear();
511 m_attributeIndex.clear();
516 throw ConfigurationException("Session touch requires a StorageService.");
525 void StoredSession::addAttributes(const vector<Attribute*>& attributes)
528 xmltooling::NDC ndc("addAttributes");
531 if (!m_cache->m_storage)
532 throw ConfigurationException("Session modification requires a StorageService.");
534 m_cache->m_log.debug("adding attributes to session (%s)", getID());
539 DDF attrs = m_obj["attributes"];
541 attrs = m_obj.addmember("attributes").list();
542 for (vector<Attribute*>::const_iterator a=attributes.begin(); a!=attributes.end(); ++a) {
543 attr = (*a)->marshall();
547 // Tentatively increment the version.
548 m_obj["version"].integer(m_obj["version"].integer()+1);
552 string record(str.str());
555 ver = m_cache->m_storage->updateText(getID(), "session", record.c_str(), 0, m_obj["version"].integer()-1);
557 catch (std::exception&) {
558 // Roll back modification to record.
559 m_obj["version"].integer(m_obj["version"].integer()-1);
560 vector<Attribute*>::size_type count = attributes.size();
562 attrs.last().destroy();
567 // Roll back modification to record.
568 m_obj["version"].integer(m_obj["version"].integer()-1);
569 vector<Attribute*>::size_type count = attributes.size();
571 attrs.last().destroy();
574 // Fatal problem with update.
575 throw IOException("Unable to update stored session.");
579 m_cache->m_log.warn("storage service indicates the record is out of sync, updating with a fresh copy...");
580 ver = m_cache->m_storage->readText(getID(), "session", &record, nullptr);
582 m_cache->m_log.error("readText failed on StorageService for session (%s)", getID());
583 throw IOException("Unable to read back stored session.");
588 istringstream in(record);
592 for_each(m_attributes.begin(), m_attributes.end(), xmltooling::cleanup<Attribute>());
593 m_attributes.clear();
594 m_attributeIndex.clear();
595 newobj["version"].integer(ver);
601 } while (ver < 0); // negative indicates a sync issue so we retry
603 // We own them now, so clean them up.
604 for_each(attributes.begin(), attributes.end(), xmltooling::cleanup<Attribute>());
607 const Assertion* StoredSession::getAssertion(const char* id) const
609 if (!m_cache->m_storage)
610 throw ConfigurationException("Assertion retrieval requires a StorageService.");
612 map< string,boost::shared_ptr<Assertion> >::const_iterator i = m_tokens.find(id);
613 if (i != m_tokens.end())
614 return i->second.get();
617 if (!m_cache->m_storage->readText(getID(), id, &tokenstr, nullptr))
618 throw FatalProfileException("Assertion not found in cache.");
620 // Parse and bind the document into an XMLObject.
621 istringstream instr(tokenstr);
622 DOMDocument* doc = XMLToolingConfig::getConfig().getParser().parse(instr);
623 XercesJanitor<DOMDocument> janitor(doc);
624 boost::shared_ptr<XMLObject> xmlObject(XMLObjectBuilder::buildOneFromElement(doc->getDocumentElement(), true));
627 boost::shared_ptr<Assertion> token = dynamic_pointer_cast<Assertion,XMLObject>(xmlObject);
629 throw FatalProfileException("Request for cached assertion returned an unknown object type.");
631 m_tokens[id] = token;
635 void StoredSession::addAssertion(Assertion* assertion)
638 xmltooling::NDC ndc("addAssertion");
641 if (!m_cache->m_storage)
642 throw ConfigurationException("Session modification requires a StorageService.");
644 throw FatalProfileException("Unknown object type passed to session for storage.");
646 auto_ptr_char id(assertion->getID());
647 if (!id.get() || !*id.get())
648 throw IOException("Assertion did not carry an ID.");
649 else if (strlen(id.get()) > m_cache->m_storage->getCapabilities().getKeySize())
650 throw IOException("Assertion ID ($1) exceeds allowable storage key size.", params(1, id.get()));
652 m_cache->m_log.debug("adding assertion (%s) to session (%s)", id.get(), getID());
655 if (!m_cache->m_storage->readText(getID(), "session", nullptr, &exp))
656 throw IOException("Unable to load expiration time for stored session.");
658 ostringstream tokenstr;
659 tokenstr << *assertion;
660 if (!m_cache->m_storage->createText(getID(), id.get(), tokenstr.str().c_str(), exp))
661 throw IOException("Attempted to insert duplicate assertion ID into session.");
665 DDF token = DDF(nullptr).string(id.get());
666 m_obj["assertions"].add(token);
668 // Tentatively increment the version.
669 m_obj["version"].integer(m_obj["version"].integer()+1);
673 string record(str.str());
676 ver = m_cache->m_storage->updateText(getID(), "session", record.c_str(), 0, m_obj["version"].integer()-1);
678 catch (std::exception&) {
680 m_obj["version"].integer(m_obj["version"].integer()-1);
681 m_cache->m_storage->deleteText(getID(), id.get());
687 m_obj["version"].integer(m_obj["version"].integer()-1);
690 // Fatal problem with update.
691 m_cache->m_log.error("updateText failed on StorageService for session (%s)", getID());
692 m_cache->m_storage->deleteText(getID(), id.get());
693 throw IOException("Unable to update stored session.");
697 m_cache->m_log.warn("storage service indicates the record is out of sync, updating with a fresh copy...");
698 ver = m_cache->m_storage->readText(getID(), "session", &record, nullptr);
700 m_cache->m_log.error("readText failed on StorageService for session (%s)", getID());
701 m_cache->m_storage->deleteText(getID(), id.get());
702 throw IOException("Unable to read back stored session.");
707 istringstream in(record);
711 for_each(m_attributes.begin(), m_attributes.end(), xmltooling::cleanup<Attribute>());
712 m_attributes.clear();
713 m_attributeIndex.clear();
714 newobj["version"].integer(ver);
720 } while (ver < 0); // negative indicates a sync issue so we retry
728 SessionCache::SessionCache()
732 SessionCache::~SessionCache()
738 void SessionCache::insert(
740 const Application& app,
741 const HTTPRequest& httpRequest,
742 HTTPResponse& httpResponse,
744 const EntityDescriptor* issuer,
745 const XMLCh* protocol,
746 const saml2::NameID* nameid,
747 const XMLCh* authn_instant,
748 const XMLCh* session_index,
749 const XMLCh* authncontext_class,
750 const XMLCh* authncontext_decl,
751 const vector<const Assertion*>* tokens,
752 const vector<Attribute*>* attributes
754 return insert(app, httpRequest, httpResponse, expires, issuer, protocol, nameid,
755 authn_instant, session_index, authncontext_class, authncontext_decl, tokens, attributes);
760 SessionCacheEx::SessionCacheEx()
764 SessionCacheEx::~SessionCacheEx()
768 SSCache::SSCache(const DOMElement* e)
769 : m_log(Category::getInstance(SHIBSP_LOGCAT".SessionCache")), inproc(true),
771 m_storage(nullptr), m_storage_lite(nullptr), m_cacheAssertions(true), m_reverseIndex(true),
773 m_root(e), m_inprocTimeout(900), m_cacheTimeout(0), m_cacheAllowance(0), shutdown(false)
775 SPConfig& conf = SPConfig::getConfig();
776 inproc = conf.isEnabled(SPConfig::InProcess);
778 static const XMLCh cacheAllowance[] = UNICODE_LITERAL_14(c,a,c,h,e,A,l,l,o,w,a,n,c,e);
779 static const XMLCh cacheAssertions[] = UNICODE_LITERAL_15(c,a,c,h,e,A,s,s,e,r,t,i,o,n,s);
780 static const XMLCh cacheTimeout[] = UNICODE_LITERAL_12(c,a,c,h,e,T,i,m,e,o,u,t);
781 static const XMLCh excludeReverseIndex[] = UNICODE_LITERAL_19(e,x,c,l,u,d,e,R,e,v,e,r,s,e,I,n,d,e,x);
782 static const XMLCh inprocTimeout[] = UNICODE_LITERAL_13(i,n,p,r,o,c,T,i,m,e,o,u,t);
783 static const XMLCh inboundHeader[] = UNICODE_LITERAL_13(i,n,b,o,u,n,d,H,e,a,d,e,r);
784 static const XMLCh maintainReverseIndex[] = UNICODE_LITERAL_20(m,a,i,n,t,a,i,n,R,e,v,e,r,s,e,I,n,d,e,x);
785 static const XMLCh outboundHeader[] = UNICODE_LITERAL_14(o,u,t,b,o,u,n,d,H,e,a,d,e,r);
786 static const XMLCh _StorageService[] = UNICODE_LITERAL_14(S,t,o,r,a,g,e,S,e,r,v,i,c,e);
787 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);
789 if (e && e->hasAttributeNS(nullptr, cacheTimeout)) {
790 m_log.warn("cacheTimeout property is deprecated in favor of cacheAllowance (see documentation)");
791 m_cacheTimeout = XMLHelper::getAttrInt(e, 0, cacheTimeout);
793 m_cacheAllowance = XMLHelper::getAttrInt(e, 0, cacheAllowance);
795 m_inprocTimeout = XMLHelper::getAttrInt(e, 900, inprocTimeout);
796 m_inboundHeader = XMLHelper::getAttrString(e, nullptr, inboundHeader);
797 if (!m_inboundHeader.empty())
798 RemotedHandler::addRemotedHeader(m_inboundHeader.c_str());
799 m_outboundHeader = XMLHelper::getAttrString(e, nullptr, outboundHeader);
802 if (conf.isEnabled(SPConfig::OutOfProcess)) {
803 string ssid(XMLHelper::getAttrString(e, nullptr, _StorageService));
805 m_storage = conf.getServiceProvider()->getStorageService(ssid.c_str());
807 m_log.info("bound to StorageService (%s)", ssid.c_str());
809 m_log.warn("specified StorageService (%s) not found", ssid.c_str());
812 m_storage = conf.getServiceProvider()->getStorageService(nullptr);
814 m_log.info("bound to arbitrary StorageService");
816 throw ConfigurationException("SessionCache unable to locate StorageService, check configuration.");
819 ssid = XMLHelper::getAttrString(e, nullptr, _StorageServiceLite);
821 m_storage_lite = conf.getServiceProvider()->getStorageService(ssid.c_str());
823 m_log.info("bound to 'lite' StorageService (%s)", ssid.c_str());
825 m_log.warn("specified 'lite' StorageService (%s) not found", ssid.c_str());
827 if (!m_storage_lite) {
828 m_log.info("StorageService for 'lite' use not set, using standard StorageService");
829 m_storage_lite = m_storage;
832 m_cacheAssertions = XMLHelper::getAttrBool(e, true, cacheAssertions);
833 m_reverseIndex = XMLHelper::getAttrBool(e, true, maintainReverseIndex);
834 const XMLCh* excludedNames = e ? e->getAttributeNS(nullptr, excludeReverseIndex) : nullptr;
835 if (excludedNames && *excludedNames) {
836 XMLStringTokenizer toks(excludedNames);
837 while (toks.hasMoreTokens())
838 m_excludedNames.insert(toks.nextToken());
843 ListenerService* listener=conf.getServiceProvider()->getListenerService(false);
845 if (!conf.isEnabled(SPConfig::OutOfProcess) && !listener)
846 throw ConfigurationException("SessionCache requires a ListenerService, but none available.");
847 m_lock.reset(RWLock::create());
848 shutdown_wait.reset(CondWait::create());
849 cleanup_thread.reset(Thread::create(&cleanup_fn, this));
853 if (listener && conf.isEnabled(SPConfig::OutOfProcess)) {
854 listener->regListener("find::"STORAGESERVICE_SESSION_CACHE"::SessionCache",this);
855 listener->regListener("remove::"STORAGESERVICE_SESSION_CACHE"::SessionCache",this);
856 listener->regListener("touch::"STORAGESERVICE_SESSION_CACHE"::SessionCache",this);
859 m_log.info("no ListenerService available, cache remoting disabled");
868 // Shut down the cleanup thread and let it know...
870 if (shutdown_wait.get())
871 shutdown_wait->signal();
872 if (cleanup_thread.get())
873 cleanup_thread->join(nullptr);
875 for_each(m_hashtable.begin(),m_hashtable.end(),cleanup_pair<string,StoredSession>());
879 SPConfig& conf = SPConfig::getConfig();
880 ListenerService* listener=conf.getServiceProvider()->getListenerService(false);
881 if (listener && conf.isEnabled(SPConfig::OutOfProcess)) {
882 listener->unregListener("find::"STORAGESERVICE_SESSION_CACHE"::SessionCache",this);
883 listener->unregListener("remove::"STORAGESERVICE_SESSION_CACHE"::SessionCache",this);
884 listener->unregListener("touch::"STORAGESERVICE_SESSION_CACHE"::SessionCache",this);
894 XMLCh* wide = SAMLConfig::getConfig().generateIdentifier();
895 auto_ptr_char temp(wide);
896 XMLString::release(&wide);
897 m_storage->createString("SessionCacheTest", temp.get(), "Test", time(nullptr) + 60);
898 m_storage->deleteString("SessionCacheTest", temp.get());
901 void SSCache::insert(const char* key, time_t expires, const char* name, const char* index)
904 unsigned int storageLimit = m_storage_lite->getCapabilities().getKeySize();
905 if (strlen(name) > storageLimit) {
906 dup = string(name).substr(0, storageLimit);
911 DDFJanitor jobj(obj);
913 // Since we can't guarantee uniqueness, check for an existing record.
916 int ver = m_storage_lite->readText("NameID", name, &record, &recordexp);
918 // Existing record, so we need to unmarshall it.
919 istringstream in(record);
924 obj = DDF(nullptr).structure();
927 if (!index || !*index)
929 DDF sessions = obj.addmember(index);
930 if (!sessions.islist())
932 DDF session = DDF(nullptr).string(key);
933 sessions.add(session);
935 // Remarshall the record.
939 // Try and store it back...
941 ver = m_storage_lite->updateText("NameID", name, out.str().c_str(), max(expires, recordexp), ver);
943 // Out of sync, or went missing, so retry.
944 return insert(key, expires, name, index);
947 else if (!m_storage_lite->createText("NameID", name, out.str().c_str(), expires)) {
948 // Hit a dup, so just retry, hopefully hitting the other branch.
949 return insert(key, expires, name, index);
953 void SSCache::insert(
955 const Application& app,
956 const HTTPRequest& httpRequest,
957 HTTPResponse& httpResponse,
959 const saml2md::EntityDescriptor* issuer,
960 const XMLCh* protocol,
961 const saml2::NameID* nameid,
962 const XMLCh* authn_instant,
963 const XMLCh* session_index,
964 const XMLCh* authncontext_class,
965 const XMLCh* authncontext_decl,
966 const vector<const Assertion*>* tokens,
967 const vector<Attribute*>* attributes
971 xmltooling::NDC ndc("insert");
974 throw ConfigurationException("SessionCache insertion requires a StorageService.");
976 m_log.debug("creating new session");
978 time_t now = time(nullptr);
979 auto_ptr_char index(session_index);
980 auto_ptr_char entity_id(issuer ? issuer->getEntityID() : nullptr);
981 auto_ptr_char name(nameid ? nameid->getName() : nullptr);
983 if (name.get() && *name.get()) {
984 // Check for a pending logout.
985 unsigned int storageLimit = m_storage_lite->getCapabilities().getKeySize();
986 string namebuf = name.get();
987 if (namebuf.length() > storageLimit)
988 namebuf = namebuf.substr(0, storageLimit);
990 int ver = m_storage_lite->readText("Logout", namebuf.c_str(), &pending);
993 DDFJanitor jpend(pendobj);
994 istringstream pstr(pending);
996 // IdP.SP.index contains logout expiration, if any.
997 DDF deadmenwalking = pendobj[issuer ? entity_id.get() : "_shibnull"][app.getRelyingParty(issuer)->getString("entityID").second];
998 const char* logexpstr = deadmenwalking[session_index ? index.get() : "_shibnull"].string();
999 if (!logexpstr && session_index) // we tried an exact session match, now try for nullptr
1000 logexpstr = deadmenwalking["_shibnull"].string();
1002 auto_ptr_XMLCh dt(logexpstr);
1003 DateTime dtobj(dt.get());
1004 dtobj.parseDateTime();
1005 time_t logexp = dtobj.getEpoch();
1006 if (now - XMLToolingConfig::getConfig().clock_skew_secs < logexp)
1007 throw FatalProfileException("A logout message from your identity provider has blocked your login attempt.");
1012 XMLCh* widekey = SAMLConfig::getConfig().generateIdentifier();
1013 auto_ptr_char key(widekey);
1014 XMLString::release(&widekey);
1016 // Store session properties in DDF.
1017 DDF obj = DDF(key.get()).structure();
1018 DDFJanitor entryobj(obj);
1019 obj.addmember("version").integer(1);
1020 obj.addmember("application_id").string(app.getId());
1022 // On 64-bit Windows, time_t doesn't fit in a long, so I'm using ISO timestamps.
1023 #ifndef HAVE_GMTIME_R
1024 struct tm* ptime=gmtime(&expires);
1027 struct tm* ptime=gmtime_r(&expires,&res);
1030 strftime(timebuf,32,"%Y-%m-%dT%H:%M:%SZ",ptime);
1031 obj.addmember("expires").string(timebuf);
1033 obj.addmember("client_addr").string(httpRequest.getRemoteAddr().c_str());
1035 obj.addmember("entity_id").string(entity_id.get());
1037 auto_ptr_char prot(protocol);
1038 obj.addmember("protocol").string(prot.get());
1040 if (authn_instant) {
1041 auto_ptr_char instant(authn_instant);
1042 obj.addmember("authn_instant").string(instant.get());
1045 obj.addmember("session_index").string(index.get());
1046 if (authncontext_class) {
1047 auto_ptr_char ac(authncontext_class);
1048 obj.addmember("authncontext_class").string(ac.get());
1050 if (authncontext_decl) {
1051 auto_ptr_char ad(authncontext_decl);
1052 obj.addmember("authncontext_decl").string(ad.get());
1056 ostringstream namestr;
1058 obj.addmember("nameid").string(namestr.str().c_str());
1061 if (tokens && m_cacheAssertions) {
1062 obj.addmember("assertions").list();
1063 for (vector<const Assertion*>::const_iterator t = tokens->begin(); t!=tokens->end(); ++t) {
1064 auto_ptr_char tokenid((*t)->getID());
1065 DDF tokid = DDF(nullptr).string(tokenid.get());
1066 obj["assertions"].add(tokid);
1072 DDF attrlist = obj.addmember("attributes").list();
1073 for (vector<Attribute*>::const_iterator a=attributes->begin(); a!=attributes->end(); ++a) {
1074 attr = (*a)->marshall();
1079 ostringstream record;
1082 m_log.debug("storing new session...");
1083 unsigned long cacheTimeout = getCacheTimeout(app);
1084 if (!m_storage->createText(key.get(), "session", record.str().c_str(), now + cacheTimeout))
1085 throw FatalProfileException("Attempted to create a session with a duplicate key.");
1087 // Store the reverse mapping for logout.
1088 if (nameid && m_reverseIndex && (m_excludedNames.size() == 0 || m_excludedNames.count(nameid->getName()) == 0)) {
1090 insert(key.get(), expires, name.get(), index.get());
1092 catch (std::exception& ex) {
1093 m_log.error("error storing back mapping of NameID for logout: %s", ex.what());
1097 if (tokens && m_cacheAssertions) {
1099 for (vector<const Assertion*>::const_iterator t = tokens->begin(); t!=tokens->end(); ++t) {
1100 ostringstream tokenstr;
1102 auto_ptr_char tokenid((*t)->getID());
1103 if (!tokenid.get() || !*tokenid.get() || strlen(tokenid.get()) > m_storage->getCapabilities().getKeySize())
1104 throw IOException("Assertion ID is missing or exceeds key size of storage service.");
1105 else if (!m_storage->createText(key.get(), tokenid.get(), tokenstr.str().c_str(), now + cacheTimeout))
1106 throw IOException("Duplicate assertion ID ($1)", params(1, tokenid.get()));
1109 catch (std::exception& ex) {
1110 m_log.error("error storing assertion along with session: %s", ex.what());
1114 const char* pid = obj["entity_id"].string();
1115 const char* prot = obj["protocol"].string();
1116 m_log.info("new session created: ID (%s) IdP (%s) Protocol(%s) Address (%s)",
1117 key.get(), pid ? pid : "none", prot ? prot : "none", httpRequest.getRemoteAddr().c_str());
1119 if (!m_outboundHeader.empty())
1120 httpResponse.setResponseHeader(m_outboundHeader.c_str(), key.get());
1122 time_t cookieLifetime = 0;
1123 pair<string,const char*> shib_cookie = app.getCookieNameProps("_shibsession_", &cookieLifetime);
1124 string k(key.get());
1125 k += shib_cookie.second;
1127 if (cookieLifetime > 0) {
1128 cookieLifetime += now;
1129 #ifndef HAVE_GMTIME_R
1130 ptime=gmtime(&cookieLifetime);
1132 ptime=gmtime_r(&cookieLifetime,&res);
1134 char cookietimebuf[64];
1135 strftime(cookietimebuf,64,"; expires=%a, %d %b %Y %H:%M:%S GMT",ptime);
1139 httpResponse.setCookie(shib_cookie.first.c_str(), k.c_str());
1140 sessionID = key.get();
1143 bool SSCache::matches(
1144 const Application& app,
1145 const xmltooling::HTTPRequest& request,
1146 const saml2md::EntityDescriptor* issuer,
1147 const saml2::NameID& nameid,
1148 const set<string>* indexes
1151 auto_ptr_char entityID(issuer ? issuer->getEntityID() : nullptr);
1153 Session* session = find(app, request);
1155 Locker locker(session, false);
1156 if (XMLString::equals(session->getEntityID(), entityID.get()) && session->getNameID() &&
1157 stronglyMatches(issuer->getEntityID(), app.getRelyingParty(issuer)->getXMLString("entityID").second, nameid, *session->getNameID())) {
1158 return (!indexes || indexes->empty() || (session->getSessionIndex() ? (indexes->count(session->getSessionIndex())>0) : false));
1162 catch (std::exception& ex) {
1163 m_log.error("error while matching session: %s", ex.what());
1168 vector<string>::size_type SSCache::logout(
1169 const Application& app,
1170 const saml2md::EntityDescriptor* issuer,
1171 const saml2::NameID& nameid,
1172 const set<string>* indexes,
1174 vector<string>& sessionsKilled
1178 xmltooling::NDC ndc("logout");
1182 throw ConfigurationException("SessionCache logout requires a StorageService.");
1184 auto_ptr_char entityID(issuer ? issuer->getEntityID() : nullptr);
1185 auto_ptr_char name(nameid.getName());
1187 m_log.info("request to logout sessions from (%s) for (%s)", entityID.get() ? entityID.get() : "unknown", name.get());
1189 unsigned int storageLimit = m_storage_lite->getCapabilities().getKeySize();
1190 if (strlen(name.get()) > storageLimit)
1191 const_cast<char*>(name.get())[storageLimit] = 0;
1194 DDFJanitor jobj(obj);
1199 // Record the logout to prevent post-delivered assertions.
1200 // On 64-bit Windows, time_t doesn't fit in a long, so I'm using ISO timestamps.
1201 #ifndef HAVE_GMTIME_R
1202 struct tm* ptime=gmtime(&expires);
1205 struct tm* ptime=gmtime_r(&expires,&res);
1208 strftime(timebuf,32,"%Y-%m-%dT%H:%M:%SZ",ptime);
1211 ver = m_storage_lite->readText("Logout", name.get(), &record, &oldexp);
1213 istringstream lin(record);
1217 obj = DDF(nullptr).structure();
1220 // Structure is keyed by the IdP and SP, with a member per session index containing the expiration.
1221 DDF root = obj.addmember(issuer ? entityID.get() : "_shibnull").addmember(app.getRelyingParty(issuer)->getString("entityID").second);
1223 for (set<string>::const_iterator x = indexes->begin(); x!=indexes->end(); ++x)
1224 root.addmember(x->c_str()).string(timebuf);
1227 root.addmember("_shibnull").string(timebuf);
1235 ver = m_storage_lite->updateText("Logout", name.get(), lout.str().c_str(), max(expires, oldexp), ver);
1237 // Out of sync, or went missing, so retry.
1238 return logout(app, issuer, nameid, indexes, expires, sessionsKilled);
1241 else if (!m_storage_lite->createText("Logout", name.get(), lout.str().c_str(), expires)) {
1242 // Hit a dup, so just retry, hopefully hitting the other branch.
1243 return logout(app, issuer, nameid, indexes, expires, sessionsKilled);
1250 if (!m_reverseIndex) {
1251 m_log.error("cannot support logout because maintainReverseIndex property is turned off");
1252 throw ConfigurationException("Logout is unsupported by the session cache configuration.");
1255 // Read in potentially matching sessions.
1256 ver = m_storage_lite->readText("NameID", name.get(), &record);
1258 m_log.debug("no active sessions to logout for supplied issuer and subject");
1262 istringstream in(record);
1265 // The record contains child lists for each known session index.
1267 DDF sessions = obj.first();
1268 while (sessions.islist()) {
1269 if (!indexes || indexes->empty() || indexes->count(sessions.name())) {
1270 key = sessions.first();
1271 while (key.isstring()) {
1272 // Fetch the session for comparison.
1273 Session* session = nullptr;
1275 session = find(app, key.string());
1277 catch (std::exception& ex) {
1278 m_log.error("error locating session (%s): %s", key.string(), ex.what());
1282 Locker locker(session, false);
1284 if (XMLString::equals(session->getEntityID(), entityID.get())) {
1286 if (stronglyMatches(issuer->getEntityID(), app.getRelyingParty(issuer)->getXMLString("entityID").second, nameid, *session->getNameID())) {
1287 sessionsKilled.push_back(key.string());
1291 m_log.debug("session (%s) contained a non-matching NameID, leaving it alone", key.string());
1295 m_log.debug("session (%s) established by different IdP, leaving it alone", key.string());
1299 // Session may already be gone, or it may be associated with a different application.
1300 // To be conservative, we'll leave it alone. This isn't really increasing our security
1301 // risk, because if we can't lookup the session, it's unlikely the calling logout code
1302 // can either, so there's no chance of removing the session anyway.
1303 m_log.warn("session (%s) not accessible for logout, may be gone, or associated with a different application", key.string());
1305 key = sessions.next();
1308 // No sessions left for this index?
1309 if (sessions.first().isnull())
1312 sessions = obj.next();
1315 if (obj.first().isnull())
1318 // If possible, write back the mapping record (this isn't crucial).
1321 m_storage_lite->deleteText("NameID", name.get());
1323 else if (!sessionsKilled.empty()) {
1326 if (m_storage_lite->updateText("NameID", name.get(), out.str().c_str(), 0, ver) <= 0)
1327 m_log.warn("logout mapping record changed behind us, leaving it alone");
1330 catch (std::exception& ex) {
1331 m_log.error("error updating logout mapping record: %s", ex.what());
1334 return sessionsKilled.size();
1337 bool SSCache::stronglyMatches(const XMLCh* idp, const XMLCh* sp, const saml2::NameID& n1, const saml2::NameID& n2) const
1339 if (!XMLString::equals(n1.getName(), n2.getName()))
1342 const XMLCh* s1 = n1.getFormat();
1343 const XMLCh* s2 = n2.getFormat();
1345 s1 = saml2::NameID::UNSPECIFIED;
1347 s2 = saml2::NameID::UNSPECIFIED;
1348 if (!XMLString::equals(s1,s2))
1351 s1 = n1.getNameQualifier();
1352 s2 = n2.getNameQualifier();
1357 if (!XMLString::equals(s1,s2))
1360 s1 = n1.getSPNameQualifier();
1361 s2 = n2.getSPNameQualifier();
1366 if (!XMLString::equals(s1,s2))
1372 LogoutEvent* SSCache::newLogoutEvent(const Application& app) const
1374 if (!SPConfig::getConfig().isEnabled(SPConfig::Logging))
1377 auto_ptr<TransactionLog::Event> event(SPConfig::getConfig().EventManager.newPlugin(LOGOUT_EVENT, nullptr));
1378 LogoutEvent* logout_event = dynamic_cast<LogoutEvent*>(event.get());
1380 logout_event->m_app = &app;
1382 return logout_event;
1385 m_log.warn("unable to audit event, log event object was of an incorrect type");
1388 catch (std::exception& ex) {
1389 m_log.warn("exception auditing event: %s", ex.what());
1396 Session* SSCache::find(const Application& app, const char* key, const char* client_addr, time_t* timeout)
1399 xmltooling::NDC ndc("find");
1401 StoredSession* session=nullptr;
1404 m_log.debug("searching local cache for session (%s)", key);
1406 map<string,StoredSession*>::const_iterator i=m_hashtable.find(key);
1407 if (i!=m_hashtable.end()) {
1408 // Save off and lock the session.
1409 session = i->second;
1412 m_log.debug("session found locally, validating it for use");
1420 if (!SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess)) {
1421 m_log.debug("session not found locally, remoting the search");
1422 // Remote the request.
1423 DDF in("find::"STORAGESERVICE_SESSION_CACHE"::SessionCache"), out;
1426 in.addmember("key").string(key);
1427 in.addmember("application_id").string(app.getId());
1428 if (timeout && *timeout) {
1429 // On 64-bit Windows, time_t doesn't fit in a long, so I'm using ISO timestamps.
1430 #ifndef HAVE_GMTIME_R
1431 struct tm* ptime=gmtime(timeout);
1434 struct tm* ptime=gmtime_r(timeout,&res);
1437 strftime(timebuf,32,"%Y-%m-%dT%H:%M:%SZ",ptime);
1438 in.addmember("timeout").string(timebuf);
1442 out=app.getServiceProvider().getListenerService()->send(in);
1443 if (!out.isstruct()) {
1445 m_log.debug("session not found in remote cache");
1449 // Wrap the results in a local entry and save it.
1450 session = new StoredSession(this, out);
1451 // The remote end has handled timeout issues, we handle address and expiration checks.
1460 // We're out of process, so we can search the storage service directly.
1463 throw ConfigurationException("SessionCache lookup requires a StorageService.");
1465 m_log.debug("searching for session (%s)", key);
1470 int ver = m_storage->readText(key, "session", &record, &lastAccess);
1474 m_log.debug("reconstituting session and checking validity");
1476 istringstream in(record);
1479 unsigned long cacheTimeout = getCacheTimeout(app);
1480 lastAccess -= cacheTimeout; // adjusts it back to the last time the record's timestamp was touched
1481 time_t now=time(nullptr);
1483 if (timeout && *timeout > 0 && now - lastAccess >= *timeout) {
1484 m_log.info("session timed out (ID: %s)", key);
1485 scoped_ptr<LogoutEvent> logout_event(newLogoutEvent(app));
1486 if (logout_event.get()) {
1487 logout_event->m_logoutType = LogoutEvent::LOGOUT_EVENT_INVALID;
1488 logout_event->m_sessions.push_back(key);
1489 app.getServiceProvider().getTransactionLog()->write(*logout_event);
1492 const char* eid = obj["entity_id"].string();
1495 throw RetryableProfileException("Your session has expired, and you must re-authenticate.");
1499 throw RetryableProfileException("Your session has expired, and you must re-authenticate.", namedparams(1, "entityID", eid2.c_str()));
1503 // Update storage expiration, if possible.
1505 m_storage->updateContext(key, now + cacheTimeout);
1507 catch (std::exception& ex) {
1508 m_log.error("failed to update session expiration: %s", ex.what());
1512 // Wrap the results in a local entry and save it.
1513 session = new StoredSession(this, obj);
1514 // We handled timeout issues, still need to handle address and expiration checks.
1517 throw ConfigurationException("SessionCache search requires a StorageService.");
1522 // Lock for writing and repeat the search to avoid duplication.
1524 SharedLock shared(m_lock, false);
1525 if (m_hashtable.count(key)) {
1526 // We're using an existing session entry.
1528 session = m_hashtable[key];
1532 m_hashtable[key]=session;
1538 if (!XMLString::equals(session->getApplicationID(), app.getId())) {
1539 m_log.warn("an application (%s) tried to access another application's session", app.getId());
1544 // Verify currency and update the timestamp if indicated by caller.
1546 session->validate(app, client_addr, timeout);
1550 scoped_ptr<LogoutEvent> logout_event(newLogoutEvent(app));
1551 if (logout_event.get()) {
1552 logout_event->m_logoutType = LogoutEvent::LOGOUT_EVENT_INVALID;
1553 logout_event->m_session = session;
1554 logout_event->m_sessions.push_back(session->getID());
1555 app.getServiceProvider().getTransactionLog()->write(*logout_event);
1566 Session* SSCache::find(const Application& app, HTTPRequest& request, const char* client_addr, time_t* timeout)
1568 string id = active(app, request);
1572 Session* session = find(app, id.c_str(), client_addr, timeout);
1575 HTTPResponse* response = dynamic_cast<HTTPResponse*>(&request);
1577 if (!m_outboundHeader.empty())
1578 response->setResponseHeader(m_outboundHeader.c_str(), nullptr);
1579 pair<string,const char*> shib_cookie = app.getCookieNameProps("_shibsession_");
1580 string exp(shib_cookie.second);
1581 exp += "; expires=Mon, 01 Jan 2001 00:00:00 GMT";
1582 response->setCookie(shib_cookie.first.c_str(), exp.c_str());
1585 catch (std::exception&) {
1586 HTTPResponse* response = dynamic_cast<HTTPResponse*>(&request);
1588 if (!m_outboundHeader.empty())
1589 response->setResponseHeader(m_outboundHeader.c_str(), nullptr);
1590 pair<string,const char*> shib_cookie = app.getCookieNameProps("_shibsession_");
1591 string exp(shib_cookie.second);
1592 exp += "; expires=Mon, 01 Jan 2001 00:00:00 GMT";
1593 response->setCookie(shib_cookie.first.c_str(), exp.c_str());
1600 void SSCache::remove(const Application& app, const HTTPRequest& request, HTTPResponse* response)
1603 pair<string,const char*> shib_cookie = app.getCookieNameProps("_shibsession_");
1605 if (!m_inboundHeader.empty())
1606 session_id = request.getHeader(m_inboundHeader.c_str());
1607 if (session_id.empty()) {
1608 const char* c = request.getCookie(shib_cookie.first.c_str());
1613 if (!session_id.empty()) {
1615 if (!m_outboundHeader.empty())
1616 response->setResponseHeader(m_outboundHeader.c_str(), nullptr);
1617 string exp(shib_cookie.second);
1618 exp += "; expires=Mon, 01 Jan 2001 00:00:00 GMT";
1619 response->setCookie(shib_cookie.first.c_str(), exp.c_str());
1621 remove(app, session_id.c_str());
1625 void SSCache::remove(const Application& app, const char* key)
1628 xmltooling::NDC ndc("remove");
1630 // Take care of local copy.
1634 if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess)) {
1635 // Remove the session from storage directly.
1637 m_storage->deleteContext(key);
1638 m_log.info("removed session (%s)", key);
1640 throw ConfigurationException("SessionCache removal requires a StorageService.");
1644 // Remote the request.
1645 DDF in("remove::"STORAGESERVICE_SESSION_CACHE"::SessionCache");
1648 in.addmember("key").string(key);
1649 in.addmember("application_id").string(app.getId());
1651 DDF out = app.getServiceProvider().getListenerService()->send(in);
1656 void SSCache::dormant(const char* key)
1659 xmltooling::NDC ndc("dormant");
1662 m_log.debug("deleting local copy of session (%s)", key);
1664 // lock the cache for writing, which means we know nobody is sitting in find()
1667 // grab the entry from the table
1668 map<string,StoredSession*>::const_iterator i=m_hashtable.find(key);
1669 if (i==m_hashtable.end()) {
1674 // ok, remove the entry and lock it
1675 StoredSession* entry=i->second;
1676 m_hashtable.erase(key);
1682 // we can release the cache entry lock because we know we're not in the cache anymore
1688 void* SSCache::cleanup_fn(void* p)
1691 xmltooling::NDC ndc("cleanup");
1694 SSCache* pcache = reinterpret_cast<SSCache*>(p);
1697 // First, let's block all signals
1698 Thread::mask_all_signals();
1701 scoped_ptr<Mutex> mutex(Mutex::create());
1703 // Load our configuration details...
1704 static const XMLCh cleanupInterval[] = UNICODE_LITERAL_15(c,l,e,a,n,u,p,I,n,t,e,r,v,a,l);
1705 const XMLCh* tag=pcache->m_root ? pcache->m_root->getAttributeNS(nullptr, cleanupInterval) : nullptr;
1706 int rerun_timer = 900;
1708 rerun_timer = XMLString::parseInt(tag);
1709 if (rerun_timer <= 0)
1715 pcache->m_log.info("cleanup thread started...run every %d secs; timeout after %d secs", rerun_timer, pcache->m_inprocTimeout);
1717 while (!pcache->shutdown) {
1718 pcache->shutdown_wait->timedwait(mutex.get(), rerun_timer);
1719 if (pcache->shutdown)
1722 // Ok, let's run through the cleanup process and clean out
1723 // really old sessions. This is a two-pass process. The
1724 // first pass is done holding a read-lock while we iterate over
1725 // the cache. The second pass doesn't need a lock because
1726 // the 'deletes' will lock the cache.
1728 // Pass 1: iterate over the map and find all entries that have not been
1729 // used in the allotted timeout.
1730 vector<string> stale_keys;
1731 time_t stale = time(nullptr) - pcache->m_inprocTimeout;
1733 pcache->m_log.debug("cleanup thread running");
1735 pcache->m_lock->rdlock();
1736 for (map<string,StoredSession*>::const_iterator i = pcache->m_hashtable.begin(); i != pcache->m_hashtable.end(); ++i) {
1737 // If the last access was BEFORE the stale timeout...
1739 time_t last=i->second->getLastAccess();
1740 i->second->unlock();
1742 stale_keys.push_back(i->first);
1744 pcache->m_lock->unlock();
1746 if (!stale_keys.empty()) {
1747 pcache->m_log.info("purging %d old sessions", stale_keys.size());
1749 // Pass 2: walk through the list of stale entries and remove them from the cache
1750 for_each(stale_keys.begin(), stale_keys.end(), boost::bind(&SSCache::dormant, pcache, boost::bind(&string::c_str, _1)));
1753 pcache->m_log.debug("cleanup thread completed");
1756 pcache->m_log.info("cleanup thread exiting");
1764 void SSCache::receive(DDF& in, ostream& out)
1767 xmltooling::NDC ndc("receive");
1769 const Application* app = SPConfig::getConfig().getServiceProvider()->getApplication(in["application_id"].string());
1771 throw ListenerException("Application not found, check configuration?");
1773 if (!strcmp(in.name(),"find::"STORAGESERVICE_SESSION_CACHE"::SessionCache")) {
1774 const char* key=in["key"].string();
1776 throw ListenerException("Required parameters missing for session lookup.");
1778 // Do an unversioned read.
1781 if (!m_storage->readText(key, "session", &record, &lastAccess)) {
1782 m_log.debug("session not found in cache (%s)", key);
1784 DDFJanitor jan(ret);
1789 // Adjust for expiration to recover last access time and check timeout.
1790 unsigned long cacheTimeout = getCacheTimeout(*app);
1791 lastAccess -= cacheTimeout;
1792 time_t now=time(nullptr);
1794 // See if we need to check for a timeout.
1795 if (in["timeout"].string()) {
1797 auto_ptr_XMLCh dt(in["timeout"].string());
1798 DateTime dtobj(dt.get());
1799 dtobj.parseDateTime();
1800 timeout = dtobj.getEpoch();
1802 if (timeout > 0 && now - lastAccess >= timeout) {
1803 m_log.info("session timed out (ID: %s)", key);
1804 scoped_ptr<LogoutEvent> logout_event(newLogoutEvent(*app));
1805 if (logout_event.get()) {
1806 logout_event->m_logoutType = LogoutEvent::LOGOUT_EVENT_INVALID;
1807 logout_event->m_sessions.push_back(key);
1808 app->getServiceProvider().getTransactionLog()->write(*logout_event);
1811 throw RetryableProfileException("Your session has expired, and you must re-authenticate.");
1814 // Update storage expiration, if possible.
1816 m_storage->updateContext(key, now + cacheTimeout);
1818 catch (std::exception& ex) {
1819 m_log.error("failed to update session expiration: %s", ex.what());
1823 // Send the record back.
1826 else if (!strcmp(in.name(),"touch::"STORAGESERVICE_SESSION_CACHE"::SessionCache")) {
1827 const char* key=in["key"].string();
1829 throw ListenerException("Required parameters missing for session check.");
1831 // Do a versioned read.
1834 int curver = in["version"].integer();
1835 int ver = m_storage->readText(key, "session", &record, &lastAccess, curver);
1837 m_log.warn("unsuccessful versioned read of session (ID: %s), caches out of sync?", key);
1838 throw RetryableProfileException("Your session has expired, and you must re-authenticate.");
1841 // Adjust for expiration to recover last access time and check timeout.
1842 unsigned long cacheTimeout = getCacheTimeout(*app);
1843 lastAccess -= cacheTimeout;
1844 time_t now=time(nullptr);
1846 // See if we need to check for a timeout.
1848 auto_ptr_XMLCh dt(in["timeout"].string());
1850 DateTime dtobj(dt.get());
1851 dtobj.parseDateTime();
1852 timeout = dtobj.getEpoch();
1855 if (timeout > 0 && now - lastAccess >= timeout) {
1856 m_log.info("session timed out (ID: %s)", key);
1857 throw RetryableProfileException("Your session has expired, and you must re-authenticate.");
1860 // Update storage expiration, if possible.
1862 m_storage->updateContext(key, now + cacheTimeout);
1864 catch (std::exception& ex) {
1865 m_log.error("failed to update session expiration: %s", ex.what());
1869 // Send the record back.
1874 DDFJanitor jan(ret);
1878 else if (!strcmp(in.name(),"remove::"STORAGESERVICE_SESSION_CACHE"::SessionCache")) {
1879 const char* key=in["key"].string();
1881 throw ListenerException("Required parameter missing for session removal.");
1885 DDFJanitor jan(ret);