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;
80 // Allows the cache to bind sessions to multiple client address
81 // families based on whatever this function returns.
82 static const char* getAddressFamily(const char* addr) {
83 if (strchr(addr, ':'))
90 class SSCache : public SessionCacheEx
92 ,public virtual Remoted
96 SSCache(const DOMElement* e);
100 void receive(DDF& in, ostream& out);
103 const Application& app,
104 const HTTPRequest& httpRequest,
105 HTTPResponse& httpResponse,
107 const EntityDescriptor* issuer=nullptr,
108 const XMLCh* protocol=nullptr,
109 const saml2::NameID* nameid=nullptr,
110 const XMLCh* authn_instant=nullptr,
111 const XMLCh* session_index=nullptr,
112 const XMLCh* authncontext_class=nullptr,
113 const XMLCh* authncontext_decl=nullptr,
114 const vector<const Assertion*>* tokens=nullptr,
115 const vector<Attribute*>* attributes=nullptr
118 insert(dummy, app, httpRequest, httpResponse, expires, issuer, protocol, nameid,
119 authn_instant, session_index, authncontext_class, authncontext_decl, tokens, attributes);
124 const Application& app,
125 const HTTPRequest& httpRequest,
126 HTTPResponse& httpResponse,
128 const EntityDescriptor* issuer=nullptr,
129 const XMLCh* protocol=nullptr,
130 const saml2::NameID* nameid=nullptr,
131 const XMLCh* authn_instant=nullptr,
132 const XMLCh* session_index=nullptr,
133 const XMLCh* authncontext_class=nullptr,
134 const XMLCh* authncontext_decl=nullptr,
135 const vector<const Assertion*>* tokens=nullptr,
136 const vector<Attribute*>* attributes=nullptr
138 vector<string>::size_type logout(
139 const Application& app,
140 const EntityDescriptor* issuer,
141 const saml2::NameID& nameid,
142 const set<string>* indexes,
144 vector<string>& sessions
146 return _logout(app, issuer, nameid, indexes, expires, sessions, 0);
149 const Application& app,
150 const HTTPRequest& request,
151 const EntityDescriptor* issuer,
152 const saml2::NameID& nameid,
153 const set<string>* indexes
156 Session* find(const Application& app, const char* key, const char* client_addr=nullptr, time_t* timeout=nullptr);
157 void remove(const Application& app, const char* key);
160 string active(const Application& app, const HTTPRequest& request) {
161 if (!m_inboundHeader.empty()) {
162 string session_id = request.getHeader(m_inboundHeader.c_str());
163 if (!session_id.empty())
166 pair<string,const char*> shib_cookie = app.getCookieNameProps("_shibsession_");
167 const char* session_id = request.getCookie(shib_cookie.first.c_str());
168 return (session_id ? session_id : "");
171 Session* find(const Application& app, const HTTPRequest& request, const char* client_addr=nullptr, time_t* timeout=nullptr) {
172 string id = active(app, request);
174 return find(app, id.c_str(), client_addr, timeout);
178 Session* find(const Application& app, HTTPRequest& request, const char* client_addr=nullptr, time_t* timeout=nullptr);
179 void remove(const Application& app, const HTTPRequest& request, HTTPResponse* response=nullptr);
181 unsigned long getCacheTimeout(const Application& app) {
182 // Computes offset for adjusting expiration of sessions.
183 // This can either be static, or dynamic based on the per-app session timeout or lifetime.
185 return m_cacheTimeout;
186 pair<bool,unsigned int> timeout = pair<bool,unsigned int>(false, 3600);
187 const PropertySet* props = app.getPropertySet("Sessions");
189 timeout = props->getUnsignedInt("timeout");
191 timeout.second = 3600;
193 // As long as one of the two factors is set, add them together.
194 if (timeout.second > 0 || m_cacheAllowance > 0)
195 return timeout.second + m_cacheAllowance;
197 // If timeouts are off, and there's no cache slop set, then use the lifetime.
198 timeout = pair<bool,unsigned int>(false, 28800);
200 timeout = props->getUnsignedInt("lifetime");
201 if (!timeout.first || timeout.second == 0)
202 timeout.second = 28800;
204 return timeout.second;
210 StorageService* m_storage;
211 StorageService* m_storage_lite;
216 // maintain back-mappings of NameID/SessionIndex -> session key
217 void insert(const char* key, time_t expires, const char* name, const char* index, short attempts=0);
218 vector<string>::size_type _logout(
219 const Application& app,
220 const EntityDescriptor* issuer,
221 const saml2::NameID& nameid,
222 const set<string>* indexes,
224 vector<string>& sessions,
227 bool stronglyMatches(const XMLCh* idp, const XMLCh* sp, const saml2::NameID& n1, const saml2::NameID& n2) const;
228 LogoutEvent* newLogoutEvent(const Application& app) const;
230 bool m_cacheAssertions,m_reverseIndex;
231 set<xstring> m_excludedNames;
233 const DOMElement* m_root; // Only valid during initialization
234 unsigned long m_inprocTimeout,m_cacheTimeout,m_cacheAllowance;
235 string m_inboundHeader,m_outboundHeader;
237 // inproc means we buffer sessions in memory
238 scoped_ptr<RWLock> m_lock;
239 map<string,StoredSession*> m_hashtable;
241 // management of buffered sessions
242 void dormant(const char* key);
243 static void* cleanup_fn(void*);
246 scoped_ptr<CondWait> shutdown_wait;
247 scoped_ptr<Thread> cleanup_thread;
250 class StoredSession : public virtual Session
253 StoredSession(SSCache* cache, DDF& obj) : m_obj(obj), m_cache(cache), m_expires(0), m_lastAccess(time(nullptr)) {
254 // Check for old address format.
255 if (m_obj["client_addr"].isstring()) {
256 const char* saddr = m_obj["client_addr"].string();
257 DDF addrobj = m_obj["client_addr"].structure();
258 if (saddr && *saddr) {
259 addrobj.addmember(getAddressFamily(saddr)).string(saddr);
263 auto_ptr_XMLCh exp(m_obj["expires"].string());
265 DateTime iso(exp.get());
267 m_expires = iso.getEpoch();
271 const char* nameid = obj["nameid"].string();
273 // Parse and bind the document into an XMLObject.
274 istringstream instr(nameid);
275 DOMDocument* doc = XMLToolingConfig::getConfig().getParser().parse(instr);
276 XercesJanitor<DOMDocument> janitor(doc);
277 m_nameid.reset(saml2::NameIDBuilder::buildNameID());
278 m_nameid->unmarshall(doc->getDocumentElement(), true);
283 m_lock.reset(Mutex::create());
288 for_each(m_attributes.begin(), m_attributes.end(), xmltooling::cleanup<Attribute>());
303 const char* getID() const {
306 const char* getApplicationID() const {
307 return m_obj["application_id"].string();
309 const char* getClientAddress() const {
310 return m_obj["client_addr"].first().string();
313 const char* getClientAddress(const char* family) const {
315 return m_obj["client_addr"][family].string();
318 void setClientAddress(const char* client_addr) {
319 DDF obj = m_obj["client_addr"];
321 obj = m_obj.addmember("client_addr").structure();
322 obj.addmember(getAddressFamily(client_addr)).string(client_addr);
325 const char* getEntityID() const {
326 return m_obj["entity_id"].string();
328 const char* getProtocol() const {
329 return m_obj["protocol"].string();
331 const char* getAuthnInstant() const {
332 return m_obj["authn_instant"].string();
335 const saml2::NameID* getNameID() const {
336 return m_nameid.get();
339 const char* getSessionIndex() const {
340 return m_obj["session_index"].string();
342 const char* getAuthnContextClassRef() const {
343 return m_obj["authncontext_class"].string();
345 const char* getAuthnContextDeclRef() const {
346 return m_obj["authncontext_decl"].string();
348 const vector<Attribute*>& getAttributes() const {
349 if (m_attributes.empty())
350 unmarshallAttributes();
353 const multimap<string,const Attribute*>& getIndexedAttributes() const {
354 if (m_attributeIndex.empty()) {
355 if (m_attributes.empty())
356 unmarshallAttributes();
357 for (vector<Attribute*>::const_iterator a = m_attributes.begin(); a != m_attributes.end(); ++a) {
358 const vector<string>& aliases = (*a)->getAliases();
359 for (vector<string>::const_iterator alias = aliases.begin(); alias != aliases.end(); ++alias)
360 m_attributeIndex.insert(multimap<string,const Attribute*>::value_type(*alias, *a));
363 return m_attributeIndex;
365 const vector<const char*>& getAssertionIDs() const {
367 DDF ids = m_obj["assertions"];
368 DDF id = ids.first();
369 while (id.isstring()) {
370 m_ids.push_back(id.string());
377 void validate(const Application& application, const char* client_addr, time_t* timeout);
380 void addAttributes(const vector<Attribute*>& attributes);
381 const Assertion* getAssertion(const char* id) const;
382 void addAssertion(Assertion* assertion);
385 time_t getExpiration() const { return m_expires; }
386 time_t getLastAccess() const { return m_lastAccess; }
389 void unmarshallAttributes() const;
393 scoped_ptr<saml2::NameID> m_nameid;
394 mutable map< string,boost::shared_ptr<Assertion> > m_tokens;
396 mutable vector<Attribute*> m_attributes;
397 mutable multimap<string,const Attribute*> m_attributeIndex;
398 mutable vector<const char*> m_ids;
401 time_t m_expires,m_lastAccess;
402 scoped_ptr<Mutex> m_lock;
405 SessionCache* SHIBSP_DLLLOCAL StorageServiceCacheFactory(const DOMElement* const & e)
407 return new SSCache(e);
411 Session* SessionCache::find(const Application& application, HTTPRequest& request, const char* client_addr, time_t* timeout)
413 return find(application, const_cast<const HTTPRequest&>(request), client_addr, timeout);
416 void SHIBSP_API shibsp::registerSessionCaches()
418 SPConfig::getConfig().SessionCacheManager.registerFactory(STORAGESERVICE_SESSION_CACHE, StorageServiceCacheFactory);
429 void StoredSession::unmarshallAttributes() const
431 Attribute* attribute;
432 DDF attrs = m_obj["attributes"];
433 DDF attr = attrs.first();
434 while (!attr.isnull()) {
436 attribute = Attribute::unmarshall(attr);
437 m_attributes.push_back(attribute);
438 if (m_cache->m_log.isDebugEnabled())
439 m_cache->m_log.debug("unmarshalled attribute (ID: %s) with %d value%s",
440 attribute->getId(), attr.first().integer(), attr.first().integer()!=1 ? "s" : "");
442 catch (AttributeException& ex) {
443 const char* id = attr.first().name();
444 m_cache->m_log.error("error unmarshalling attribute (ID: %s): %s", id ? id : "none", ex.what());
450 void StoredSession::validate(const Application& app, const char* client_addr, time_t* timeout)
452 time_t now = time(nullptr);
456 if (now > m_expires) {
457 m_cache->m_log.info("session expired (ID: %s)", getID());
458 throw RetryableProfileException("Your session has expired, and you must re-authenticate.");
464 const char* saddr = getClientAddress(getAddressFamily(client_addr));
465 if (saddr && *saddr) {
466 if (!XMLString::equals(saddr, client_addr)) {
467 m_cache->m_log.warn("client address mismatch, client (%s), session (%s)", client_addr, saddr);
468 throw RetryableProfileException(
469 "Your IP address ($1) does not match the address recorded at the time the session was established.",
470 params(1, client_addr)
473 client_addr = nullptr; // clear out parameter as signal that session need not be updated below
476 m_cache->m_log.info("session (%s) not yet bound to client address type, binding it to (%s)", getID(), client_addr);
480 if (!timeout && !client_addr)
483 if (!SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess)) {
484 DDF in("touch::" STORAGESERVICE_SESSION_CACHE "::SessionCache"), out;
487 in.addmember("key").string(getID());
488 in.addmember("version").integer(m_obj["version"].integer());
489 in.addmember("application_id").string(app.getId());
490 if (client_addr) // signals we need to bind an additional address to the session
491 in.addmember("client_addr").string(client_addr);
492 if (timeout && *timeout) {
493 // On 64-bit Windows, time_t doesn't fit in a long, so I'm using ISO timestamps.
494 #ifndef HAVE_GMTIME_R
495 struct tm* ptime = gmtime(timeout);
498 struct tm* ptime = gmtime_r(timeout,&res);
501 strftime(timebuf,32,"%Y-%m-%dT%H:%M:%SZ",ptime);
502 in.addmember("timeout").string(timebuf);
506 out=app.getServiceProvider().getListenerService()->send(in);
513 if (out.isstruct()) {
514 // We got an updated record back.
515 m_cache->m_log.debug("session updated, reconstituting it");
517 for_each(m_attributes.begin(), m_attributes.end(), xmltooling::cleanup<Attribute>());
518 m_attributes.clear();
519 m_attributeIndex.clear();
526 if (!m_cache->m_storage)
527 throw ConfigurationException("Session touch requires a StorageService.");
529 // Versioned read, since we already have the data in hand if it's current.
532 int curver = m_obj["version"].integer();
533 int ver = m_cache->m_storage->readText(getID(), "session", &record, &lastAccess, curver);
535 m_cache->m_log.warn("unsuccessful versioned read of session (ID: %s), cache out of sync?", getID());
536 throw RetryableProfileException("Your session has expired, and you must re-authenticate.");
540 // Adjust for expiration to recover last access time and check timeout.
541 unsigned long cacheTimeout = m_cache->getCacheTimeout(app);
542 lastAccess -= cacheTimeout;
543 if (*timeout > 0 && now - lastAccess >= *timeout) {
544 m_cache->m_log.info("session timed out (ID: %s)", getID());
545 throw RetryableProfileException("Your session has expired, and you must re-authenticate.");
548 // Update storage expiration, if possible.
550 m_cache->m_storage->updateContext(getID(), now + cacheTimeout);
552 catch (std::exception& ex) {
553 m_cache->m_log.error("failed to update session expiration: %s", ex.what());
558 // We got an updated record back.
560 istringstream in(record);
563 for_each(m_attributes.begin(), m_attributes.end(), xmltooling::cleanup<Attribute>());
564 m_attributes.clear();
565 m_attributeIndex.clear();
570 // We may need to write back a new address into the session using a versioned update loop.
574 const char* saddr = getClientAddress(getAddressFamily(client_addr));
576 // Something snuck in and bound the session to this address type, so it better match what we have.
577 if (!XMLString::equals(saddr, client_addr)) {
578 m_cache->m_log.warn("client address mismatch, client (%s), session (%s)", client_addr, saddr);
579 throw RetryableProfileException(
580 "Your IP address ($1) does not match the address recorded at the time the session was established.",
581 params(1, client_addr)
584 break; // No need to update.
587 // Bind it into the session.
588 setClientAddress(client_addr);
591 // Tentatively increment the version.
592 m_obj["version"].integer(m_obj["version"].integer() + 1);
599 ver = m_cache->m_storage->updateText(getID(), "session", record.c_str(), 0, m_obj["version"].integer() - 1);
601 catch (std::exception&) {
602 m_obj["version"].integer(m_obj["version"].integer() - 1);
607 m_obj["version"].integer(m_obj["version"].integer() - 1);
611 // Fatal problem with update.
612 m_cache->m_log.error("updateText failed on StorageService for session (%s)", getID());
613 throw IOException("Unable to update stored session.");
617 if (++attempts > 10) {
618 m_cache->m_log.error("failed to bind client address, update attempts exceeded limit");
619 throw IOException("Unable to update stored session, exceeded retry limit.");
621 m_cache->m_log.warn("storage service indicates the record is out of sync, updating with a fresh copy...");
622 ver = m_cache->m_storage->readText(getID(), "session", &record, nullptr);
624 m_cache->m_log.error("readText failed on StorageService for session (%s)", getID());
625 throw IOException("Unable to read back stored session.");
630 istringstream in(record);
634 for_each(m_attributes.begin(), m_attributes.end(), xmltooling::cleanup<Attribute>());
635 m_attributes.clear();
636 m_attributeIndex.clear();
637 newobj["version"].integer(ver);
643 } while (ver < 0); // negative indicates a sync issue so we retry
646 throw ConfigurationException("Session touch requires a StorageService.");
655 void StoredSession::addAttributes(const vector<Attribute*>& attributes)
658 xmltooling::NDC ndc("addAttributes");
661 if (!m_cache->m_storage)
662 throw ConfigurationException("Session modification requires a StorageService.");
664 m_cache->m_log.debug("adding attributes to session (%s)", getID());
670 DDF attrs = m_obj["attributes"];
672 attrs = m_obj.addmember("attributes").list();
673 for (vector<Attribute*>::const_iterator a=attributes.begin(); a!=attributes.end(); ++a) {
674 attr = (*a)->marshall();
678 // Tentatively increment the version.
679 m_obj["version"].integer(m_obj["version"].integer()+1);
683 string record(str.str());
686 ver = m_cache->m_storage->updateText(getID(), "session", record.c_str(), 0, m_obj["version"].integer()-1);
688 catch (std::exception&) {
689 // Roll back modification to record.
690 m_obj["version"].integer(m_obj["version"].integer()-1);
691 vector<Attribute*>::size_type count = attributes.size();
693 attrs.last().destroy();
698 // Roll back modification to record.
699 m_obj["version"].integer(m_obj["version"].integer()-1);
700 vector<Attribute*>::size_type count = attributes.size();
702 attrs.last().destroy();
705 // Fatal problem with update.
706 throw IOException("Unable to update stored session.");
710 if (++attempts > 10) {
711 m_cache->m_log.error("failed to update stored session, update attempts exceeded limit");
712 throw IOException("Unable to update stored session, exceeded retry limit.");
714 m_cache->m_log.warn("storage service indicates the record is out of sync, updating with a fresh copy...");
715 ver = m_cache->m_storage->readText(getID(), "session", &record, nullptr);
717 m_cache->m_log.error("readText failed on StorageService for session (%s)", getID());
718 throw IOException("Unable to read back stored session.");
723 istringstream in(record);
727 for_each(m_attributes.begin(), m_attributes.end(), xmltooling::cleanup<Attribute>());
728 m_attributes.clear();
729 m_attributeIndex.clear();
730 newobj["version"].integer(ver);
736 } while (ver < 0); // negative indicates a sync issue so we retry
738 // We own them now, so clean them up.
739 for_each(attributes.begin(), attributes.end(), xmltooling::cleanup<Attribute>());
742 const Assertion* StoredSession::getAssertion(const char* id) const
744 if (!m_cache->m_storage)
745 throw ConfigurationException("Assertion retrieval requires a StorageService.");
747 map< string,boost::shared_ptr<Assertion> >::const_iterator i = m_tokens.find(id);
748 if (i != m_tokens.end())
749 return i->second.get();
752 if (!m_cache->m_storage->readText(getID(), id, &tokenstr, nullptr))
753 throw FatalProfileException("Assertion not found in cache.");
755 // Parse and bind the document into an XMLObject.
756 istringstream instr(tokenstr);
757 DOMDocument* doc = XMLToolingConfig::getConfig().getParser().parse(instr);
758 XercesJanitor<DOMDocument> janitor(doc);
759 boost::shared_ptr<XMLObject> xmlObject(XMLObjectBuilder::buildOneFromElement(doc->getDocumentElement(), true));
762 boost::shared_ptr<Assertion> token = dynamic_pointer_cast<Assertion,XMLObject>(xmlObject);
764 throw FatalProfileException("Request for cached assertion returned an unknown object type.");
766 m_tokens[id] = token;
770 void StoredSession::addAssertion(Assertion* assertion)
773 xmltooling::NDC ndc("addAssertion");
776 if (!m_cache->m_storage)
777 throw ConfigurationException("Session modification requires a StorageService.");
779 throw FatalProfileException("Unknown object type passed to session for storage.");
781 auto_ptr_char id(assertion->getID());
782 if (!id.get() || !*id.get())
783 throw IOException("Assertion did not carry an ID.");
784 else if (strlen(id.get()) > m_cache->m_storage->getCapabilities().getKeySize())
785 throw IOException("Assertion ID ($1) exceeds allowable storage key size.", params(1, id.get()));
787 m_cache->m_log.debug("adding assertion (%s) to session (%s)", id.get(), getID());
790 if (!m_cache->m_storage->readText(getID(), "session", nullptr, &exp))
791 throw IOException("Unable to load expiration time for stored session.");
793 ostringstream tokenstr;
794 tokenstr << *assertion;
795 if (!m_cache->m_storage->createText(getID(), id.get(), tokenstr.str().c_str(), exp))
796 throw IOException("Attempted to insert duplicate assertion ID into session.");
801 DDF token = DDF(nullptr).string(id.get());
802 m_obj["assertions"].add(token);
804 // Tentatively increment the version.
805 m_obj["version"].integer(m_obj["version"].integer() + 1);
809 string record(str.str());
812 ver = m_cache->m_storage->updateText(getID(), "session", record.c_str(), 0, m_obj["version"].integer()-1);
814 catch (std::exception&) {
816 m_obj["version"].integer(m_obj["version"].integer() - 1);
817 m_cache->m_storage->deleteText(getID(), id.get());
823 m_obj["version"].integer(m_obj["version"].integer()-1);
826 // Fatal problem with update.
827 m_cache->m_log.error("updateText failed on StorageService for session (%s)", getID());
828 m_cache->m_storage->deleteText(getID(), id.get());
829 throw IOException("Unable to update stored session.");
833 if (++attempts > 10) {
834 m_cache->m_log.error("failed to update stored session, update attempts exceeded limit");
835 throw IOException("Unable to update stored session, exceeded retry limit.");
837 m_cache->m_log.warn("storage service indicates the record is out of sync, updating with a fresh copy...");
838 ver = m_cache->m_storage->readText(getID(), "session", &record, nullptr);
840 m_cache->m_log.error("readText failed on StorageService for session (%s)", getID());
841 m_cache->m_storage->deleteText(getID(), id.get());
842 throw IOException("Unable to read back stored session.");
847 istringstream in(record);
851 for_each(m_attributes.begin(), m_attributes.end(), xmltooling::cleanup<Attribute>());
852 m_attributes.clear();
853 m_attributeIndex.clear();
854 newobj["version"].integer(ver);
860 } while (ver < 0); // negative indicates a sync issue so we retry
868 SessionCache::SessionCache()
872 SessionCache::~SessionCache()
878 void SessionCache::insert(
880 const Application& app,
881 const HTTPRequest& httpRequest,
882 HTTPResponse& httpResponse,
884 const EntityDescriptor* issuer,
885 const XMLCh* protocol,
886 const saml2::NameID* nameid,
887 const XMLCh* authn_instant,
888 const XMLCh* session_index,
889 const XMLCh* authncontext_class,
890 const XMLCh* authncontext_decl,
891 const vector<const Assertion*>* tokens,
892 const vector<Attribute*>* attributes
894 return insert(app, httpRequest, httpResponse, expires, issuer, protocol, nameid,
895 authn_instant, session_index, authncontext_class, authncontext_decl, tokens, attributes);
900 SessionCacheEx::SessionCacheEx()
904 SessionCacheEx::~SessionCacheEx()
908 SSCache::SSCache(const DOMElement* e)
909 : m_log(Category::getInstance(SHIBSP_LOGCAT ".SessionCache")), inproc(true),
911 m_storage(nullptr), m_storage_lite(nullptr), m_cacheAssertions(true), m_reverseIndex(true),
913 m_root(e), m_inprocTimeout(900), m_cacheTimeout(0), m_cacheAllowance(0), shutdown(false)
915 SPConfig& conf = SPConfig::getConfig();
916 inproc = conf.isEnabled(SPConfig::InProcess);
918 static const XMLCh cacheAllowance[] = UNICODE_LITERAL_14(c,a,c,h,e,A,l,l,o,w,a,n,c,e);
919 static const XMLCh cacheAssertions[] = UNICODE_LITERAL_15(c,a,c,h,e,A,s,s,e,r,t,i,o,n,s);
920 static const XMLCh cacheTimeout[] = UNICODE_LITERAL_12(c,a,c,h,e,T,i,m,e,o,u,t);
921 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);
922 static const XMLCh inprocTimeout[] = UNICODE_LITERAL_13(i,n,p,r,o,c,T,i,m,e,o,u,t);
923 static const XMLCh inboundHeader[] = UNICODE_LITERAL_13(i,n,b,o,u,n,d,H,e,a,d,e,r);
924 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);
925 static const XMLCh outboundHeader[] = UNICODE_LITERAL_14(o,u,t,b,o,u,n,d,H,e,a,d,e,r);
926 static const XMLCh _StorageService[] = UNICODE_LITERAL_14(S,t,o,r,a,g,e,S,e,r,v,i,c,e);
927 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);
929 if (e && e->hasAttributeNS(nullptr, cacheTimeout)) {
930 m_log.warn("cacheTimeout property is deprecated in favor of cacheAllowance (see documentation)");
931 m_cacheTimeout = XMLHelper::getAttrInt(e, 0, cacheTimeout);
933 m_cacheAllowance = XMLHelper::getAttrInt(e, 0, cacheAllowance);
935 m_inprocTimeout = XMLHelper::getAttrInt(e, 900, inprocTimeout);
936 m_inboundHeader = XMLHelper::getAttrString(e, nullptr, inboundHeader);
937 if (!m_inboundHeader.empty())
938 RemotedHandler::addRemotedHeader(m_inboundHeader.c_str());
939 m_outboundHeader = XMLHelper::getAttrString(e, nullptr, outboundHeader);
942 if (conf.isEnabled(SPConfig::OutOfProcess)) {
943 string ssid(XMLHelper::getAttrString(e, nullptr, _StorageService));
945 m_storage = conf.getServiceProvider()->getStorageService(ssid.c_str());
947 m_log.info("bound to StorageService (%s)", ssid.c_str());
949 throw ConfigurationException("SessionCache unable to locate StorageService ($1), check configuration.", params(1, ssid.c_str()));
952 m_storage = conf.getServiceProvider()->getStorageService(nullptr);
954 m_log.info("bound to arbitrary StorageService");
956 throw ConfigurationException("SessionCache unable to locate StorageService, check configuration.");
959 ssid = XMLHelper::getAttrString(e, nullptr, _StorageServiceLite);
961 m_storage_lite = conf.getServiceProvider()->getStorageService(ssid.c_str());
963 m_log.info("bound to 'lite' StorageService (%s)", ssid.c_str());
965 throw ConfigurationException("SessionCache unable to locate 'lite' StorageService ($1), check configuration.", params(1, ssid.c_str()));
967 if (!m_storage_lite) {
968 m_log.info("StorageService for 'lite' use not set, using standard StorageService");
969 m_storage_lite = m_storage;
972 m_cacheAssertions = XMLHelper::getAttrBool(e, true, cacheAssertions);
973 m_reverseIndex = XMLHelper::getAttrBool(e, true, maintainReverseIndex);
974 const XMLCh* excludedNames = e ? e->getAttributeNS(nullptr, excludeReverseIndex) : nullptr;
975 if (excludedNames && *excludedNames) {
976 XMLStringTokenizer toks(excludedNames);
977 while (toks.hasMoreTokens())
978 m_excludedNames.insert(toks.nextToken());
983 ListenerService* listener=conf.getServiceProvider()->getListenerService(false);
985 if (!conf.isEnabled(SPConfig::OutOfProcess) && !listener)
986 throw ConfigurationException("SessionCache requires a ListenerService, but none available.");
987 m_lock.reset(RWLock::create());
988 shutdown_wait.reset(CondWait::create());
989 cleanup_thread.reset(Thread::create(&cleanup_fn, this));
993 if (listener && conf.isEnabled(SPConfig::OutOfProcess)) {
994 listener->regListener("find::" STORAGESERVICE_SESSION_CACHE "::SessionCache",this);
995 listener->regListener("remove::" STORAGESERVICE_SESSION_CACHE "::SessionCache",this);
996 listener->regListener("touch::" STORAGESERVICE_SESSION_CACHE "::SessionCache",this);
999 m_log.info("no ListenerService available, cache remoting disabled");
1008 // Shut down the cleanup thread and let it know...
1010 if (shutdown_wait.get())
1011 shutdown_wait->signal();
1012 if (cleanup_thread.get())
1013 cleanup_thread->join(nullptr);
1015 for_each(m_hashtable.begin(),m_hashtable.end(),cleanup_pair<string,StoredSession>());
1019 SPConfig& conf = SPConfig::getConfig();
1020 ListenerService* listener=conf.getServiceProvider()->getListenerService(false);
1021 if (listener && conf.isEnabled(SPConfig::OutOfProcess)) {
1022 listener->unregListener("find::" STORAGESERVICE_SESSION_CACHE "::SessionCache",this);
1023 listener->unregListener("remove::" STORAGESERVICE_SESSION_CACHE "::SessionCache",this);
1024 listener->unregListener("touch::" STORAGESERVICE_SESSION_CACHE "::SessionCache",this);
1032 void SSCache::test()
1034 XMLCh* wide = SAMLConfig::getConfig().generateIdentifier();
1035 auto_ptr_char temp(wide);
1036 XMLString::release(&wide);
1037 m_storage->createString("SessionCacheTest", temp.get(), "Test", time(nullptr) + 60);
1038 m_storage->deleteString("SessionCacheTest", temp.get());
1041 void SSCache::insert(const char* key, time_t expires, const char* name, const char* index, short attempts)
1043 if (attempts > 10) {
1044 throw IOException("Exceeded retry limit.");
1047 if (!name || !*name) {
1048 m_log.warn("NameID value was empty or null, ignoring request to store for logout");
1053 unsigned int storageLimit = m_storage_lite->getCapabilities().getKeySize();
1054 if (strlen(name) > storageLimit) {
1055 dup = string(name).substr(0, storageLimit);
1060 DDFJanitor jobj(obj);
1062 // Since we can't guarantee uniqueness, check for an existing record.
1065 int ver = m_storage_lite->readText("NameID", name, &record, &recordexp);
1067 // Existing record, so we need to unmarshall it.
1068 istringstream in(record);
1073 obj = DDF(nullptr).structure();
1076 if (!index || !*index)
1077 index = "_shibnull";
1078 DDF sessions = obj.addmember(index);
1079 if (!sessions.islist())
1081 DDF session = DDF(nullptr).string(key);
1082 sessions.add(session);
1084 // Remarshall the record.
1088 // Try and store it back...
1090 ver = m_storage_lite->updateText("NameID", name, out.str().c_str(), max(expires, recordexp), ver);
1092 // Out of sync, or went missing, so retry.
1093 return insert(key, expires, name, index, attempts + 1);
1096 else if (!m_storage_lite->createText("NameID", name, out.str().c_str(), expires)) {
1097 // Hit a dup, so just retry, hopefully hitting the other branch.
1098 return insert(key, expires, name, index, attempts + 1);
1102 void SSCache::insert(
1104 const Application& app,
1105 const HTTPRequest& httpRequest,
1106 HTTPResponse& httpResponse,
1108 const saml2md::EntityDescriptor* issuer,
1109 const XMLCh* protocol,
1110 const saml2::NameID* nameid,
1111 const XMLCh* authn_instant,
1112 const XMLCh* session_index,
1113 const XMLCh* authncontext_class,
1114 const XMLCh* authncontext_decl,
1115 const vector<const Assertion*>* tokens,
1116 const vector<Attribute*>* attributes
1120 xmltooling::NDC ndc("insert");
1123 throw ConfigurationException("SessionCache insertion requires a StorageService.");
1125 m_log.debug("creating new session");
1127 time_t now = time(nullptr);
1128 auto_ptr_char index(session_index);
1129 auto_ptr_char entity_id(issuer ? issuer->getEntityID() : nullptr);
1130 auto_ptr_char name(nameid ? nameid->getName() : nullptr);
1132 if (name.get() && *name.get()) {
1133 // Check for a pending logout.
1134 unsigned int storageLimit = m_storage_lite->getCapabilities().getKeySize();
1135 string namebuf = name.get();
1136 if (namebuf.length() > storageLimit)
1137 namebuf = namebuf.substr(0, storageLimit);
1139 int ver = m_storage_lite->readText("Logout", namebuf.c_str(), &pending);
1142 DDFJanitor jpend(pendobj);
1143 istringstream pstr(pending);
1145 // IdP.SP.index contains logout expiration, if any.
1146 DDF deadmenwalking = pendobj[issuer ? entity_id.get() : "_shibnull"][app.getRelyingParty(issuer)->getString("entityID").second];
1147 const char* logexpstr = deadmenwalking[session_index ? index.get() : "_shibnull"].string();
1148 if (!logexpstr && session_index) // we tried an exact session match, now try for nullptr
1149 logexpstr = deadmenwalking["_shibnull"].string();
1151 auto_ptr_XMLCh dt(logexpstr);
1152 DateTime dtobj(dt.get());
1153 dtobj.parseDateTime();
1154 time_t logexp = dtobj.getEpoch();
1155 if (now - XMLToolingConfig::getConfig().clock_skew_secs < logexp)
1156 throw FatalProfileException("A logout message from your identity provider has blocked your login attempt.");
1161 XMLCh* widekey = SAMLConfig::getConfig().generateIdentifier();
1162 auto_ptr_char key(widekey);
1163 XMLString::release(&widekey);
1165 // Store session properties in DDF.
1166 DDF obj = DDF(key.get()).structure();
1167 DDFJanitor entryobj(obj);
1168 obj.addmember("version").integer(1);
1169 obj.addmember("application_id").string(app.getId());
1171 // On 64-bit Windows, time_t doesn't fit in a long, so I'm using ISO timestamps.
1172 #ifndef HAVE_GMTIME_R
1173 struct tm* ptime=gmtime(&expires);
1176 struct tm* ptime=gmtime_r(&expires,&res);
1179 strftime(timebuf,32,"%Y-%m-%dT%H:%M:%SZ",ptime);
1180 obj.addmember("expires").string(timebuf);
1182 string caddr(httpRequest.getRemoteAddr());
1183 if (!caddr.empty()) {
1184 DDF addrobj = obj.addmember("client_addr").structure();
1185 addrobj.addmember(getAddressFamily(caddr.c_str())).string(caddr.c_str());
1189 obj.addmember("entity_id").string(entity_id.get());
1191 auto_ptr_char prot(protocol);
1192 obj.addmember("protocol").string(prot.get());
1194 if (authn_instant) {
1195 auto_ptr_char instant(authn_instant);
1196 obj.addmember("authn_instant").string(instant.get());
1199 obj.addmember("session_index").string(index.get());
1200 if (authncontext_class) {
1201 auto_ptr_char ac(authncontext_class);
1202 obj.addmember("authncontext_class").string(ac.get());
1204 if (authncontext_decl) {
1205 auto_ptr_char ad(authncontext_decl);
1206 obj.addmember("authncontext_decl").string(ad.get());
1210 ostringstream namestr;
1212 obj.addmember("nameid").string(namestr.str().c_str());
1215 if (tokens && m_cacheAssertions) {
1216 obj.addmember("assertions").list();
1217 for (vector<const Assertion*>::const_iterator t = tokens->begin(); t!=tokens->end(); ++t) {
1218 auto_ptr_char tokenid((*t)->getID());
1219 DDF tokid = DDF(nullptr).string(tokenid.get());
1220 obj["assertions"].add(tokid);
1226 DDF attrlist = obj.addmember("attributes").list();
1227 for (vector<Attribute*>::const_iterator a=attributes->begin(); a!=attributes->end(); ++a) {
1228 attr = (*a)->marshall();
1233 ostringstream record;
1236 m_log.debug("storing new session...");
1237 unsigned long cacheTimeout = getCacheTimeout(app);
1238 if (!m_storage->createText(key.get(), "session", record.str().c_str(), now + cacheTimeout))
1239 throw FatalProfileException("Attempted to create a session with a duplicate key.");
1241 // Store the reverse mapping for logout.
1242 if (name.get() && *name.get() && m_reverseIndex
1243 && (m_excludedNames.size() == 0 || m_excludedNames.count(nameid->getName()) == 0)) {
1245 insert(key.get(), expires, name.get(), index.get());
1247 catch (std::exception& ex) {
1248 m_log.error("error storing back mapping of NameID for logout: %s", ex.what());
1252 if (tokens && m_cacheAssertions) {
1254 for (vector<const Assertion*>::const_iterator t = tokens->begin(); t!=tokens->end(); ++t) {
1255 ostringstream tokenstr;
1257 auto_ptr_char tokenid((*t)->getID());
1258 if (!tokenid.get() || !*tokenid.get() || strlen(tokenid.get()) > m_storage->getCapabilities().getKeySize())
1259 throw IOException("Assertion ID is missing or exceeds key size of storage service.");
1260 else if (!m_storage->createText(key.get(), tokenid.get(), tokenstr.str().c_str(), now + cacheTimeout))
1261 throw IOException("Duplicate assertion ID ($1)", params(1, tokenid.get()));
1264 catch (std::exception& ex) {
1265 m_log.error("error storing assertion along with session: %s", ex.what());
1269 const char* pid = obj["entity_id"].string();
1270 const char* prot = obj["protocol"].string();
1271 m_log.info("new session created: ID (%s) IdP (%s) Protocol(%s) Address (%s)",
1272 key.get(), pid ? pid : "none", prot ? prot : "none", httpRequest.getRemoteAddr().c_str());
1274 if (!m_outboundHeader.empty())
1275 httpResponse.setResponseHeader(m_outboundHeader.c_str(), key.get());
1277 time_t cookieLifetime = 0;
1278 pair<string,const char*> shib_cookie = app.getCookieNameProps("_shibsession_", &cookieLifetime);
1279 string k(key.get());
1280 k += shib_cookie.second;
1282 if (cookieLifetime > 0) {
1283 cookieLifetime += now;
1284 #ifndef HAVE_GMTIME_R
1285 ptime=gmtime(&cookieLifetime);
1287 ptime=gmtime_r(&cookieLifetime,&res);
1289 char cookietimebuf[64];
1290 strftime(cookietimebuf,64,"; expires=%a, %d %b %Y %H:%M:%S GMT",ptime);
1294 httpResponse.setCookie(shib_cookie.first.c_str(), k.c_str());
1295 sessionID = key.get();
1298 bool SSCache::matches(
1299 const Application& app,
1300 const xmltooling::HTTPRequest& request,
1301 const saml2md::EntityDescriptor* issuer,
1302 const saml2::NameID& nameid,
1303 const set<string>* indexes
1306 auto_ptr_char entityID(issuer ? issuer->getEntityID() : nullptr);
1308 Session* session = find(app, request);
1310 Locker locker(session, false);
1311 if (XMLString::equals(session->getEntityID(), entityID.get()) && session->getNameID() &&
1312 stronglyMatches(issuer->getEntityID(), app.getRelyingParty(issuer)->getXMLString("entityID").second, nameid, *session->getNameID())) {
1313 return (!indexes || indexes->empty() || (session->getSessionIndex() ? (indexes->count(session->getSessionIndex())>0) : false));
1317 catch (std::exception& ex) {
1318 m_log.error("error while matching session: %s", ex.what());
1323 vector<string>::size_type SSCache::_logout(
1324 const Application& app,
1325 const saml2md::EntityDescriptor* issuer,
1326 const saml2::NameID& nameid,
1327 const set<string>* indexes,
1329 vector<string>& sessionsKilled,
1334 xmltooling::NDC ndc("logout");
1338 throw ConfigurationException("SessionCache logout requires a StorageService.");
1339 else if (attempts > 10)
1340 throw IOException("Exceeded retry limit.");
1342 auto_ptr_char entityID(issuer ? issuer->getEntityID() : nullptr);
1343 auto_ptr_char name(nameid.getName());
1345 m_log.info("request to logout sessions from (%s) for (%s)", entityID.get() ? entityID.get() : "unknown", name.get());
1347 unsigned int storageLimit = m_storage_lite->getCapabilities().getKeySize();
1348 if (strlen(name.get()) > storageLimit)
1349 const_cast<char*>(name.get())[storageLimit] = 0;
1352 DDFJanitor jobj(obj);
1357 // Record the logout to prevent post-delivered assertions.
1358 // On 64-bit Windows, time_t doesn't fit in a long, so I'm using ISO timestamps.
1359 #ifndef HAVE_GMTIME_R
1360 struct tm* ptime=gmtime(&expires);
1363 struct tm* ptime=gmtime_r(&expires,&res);
1366 strftime(timebuf,32,"%Y-%m-%dT%H:%M:%SZ",ptime);
1369 ver = m_storage_lite->readText("Logout", name.get(), &record, &oldexp);
1371 istringstream lin(record);
1375 obj = DDF(nullptr).structure();
1378 // Structure is keyed by the IdP and SP, with a member per session index containing the expiration.
1379 DDF root = obj.addmember(issuer ? entityID.get() : "_shibnull").addmember(app.getRelyingParty(issuer)->getString("entityID").second);
1381 for (set<string>::const_iterator x = indexes->begin(); x!=indexes->end(); ++x)
1382 root.addmember(x->c_str()).string(timebuf);
1385 root.addmember("_shibnull").string(timebuf);
1393 ver = m_storage_lite->updateText("Logout", name.get(), lout.str().c_str(), max(expires, oldexp), ver);
1395 // Out of sync, or went missing, so retry.
1396 return _logout(app, issuer, nameid, indexes, expires, sessionsKilled, attempts + 1);
1399 else if (!m_storage_lite->createText("Logout", name.get(), lout.str().c_str(), expires)) {
1400 // Hit a dup, so just retry, hopefully hitting the other branch.
1401 return _logout(app, issuer, nameid, indexes, expires, sessionsKilled, attempts + 1);
1408 if (!m_reverseIndex) {
1409 m_log.error("cannot support logout because maintainReverseIndex property is turned off");
1410 throw ConfigurationException("Logout is unsupported by the session cache configuration.");
1413 // Read in potentially matching sessions.
1414 ver = m_storage_lite->readText("NameID", name.get(), &record);
1416 m_log.debug("no active sessions to logout for supplied issuer and subject");
1420 istringstream in(record);
1423 // The record contains child lists for each known session index.
1425 DDF sessions = obj.first();
1426 while (sessions.islist()) {
1427 if (!indexes || indexes->empty() || indexes->count(sessions.name())) {
1428 key = sessions.first();
1429 while (key.isstring()) {
1430 // Fetch the session for comparison.
1431 Session* session = nullptr;
1433 session = find(app, key.string());
1435 catch (std::exception& ex) {
1436 m_log.error("error locating session (%s): %s", key.string(), ex.what());
1440 Locker locker(session, false);
1442 if (XMLString::equals(session->getEntityID(), entityID.get())) {
1444 if (stronglyMatches(issuer->getEntityID(), app.getRelyingParty(issuer)->getXMLString("entityID").second, nameid, *session->getNameID())) {
1445 sessionsKilled.push_back(key.string());
1449 m_log.debug("session (%s) contained a non-matching NameID, leaving it alone", key.string());
1453 m_log.debug("session (%s) established by different IdP, leaving it alone", key.string());
1457 // Session may already be gone, or it may be associated with a different application.
1458 // To be conservative, we'll leave it alone. This isn't really increasing our security
1459 // risk, because if we can't lookup the session, it's unlikely the calling logout code
1460 // can either, so there's no chance of removing the session anyway.
1461 m_log.warn("session (%s) not accessible for logout, may be gone, or associated with a different application", key.string());
1463 key = sessions.next();
1466 // No sessions left for this index?
1467 if (sessions.first().isnull())
1470 sessions = obj.next();
1473 if (obj.first().isnull())
1476 // If possible, write back the mapping record (this isn't crucial).
1479 m_storage_lite->deleteText("NameID", name.get());
1481 else if (!sessionsKilled.empty()) {
1484 if (m_storage_lite->updateText("NameID", name.get(), out.str().c_str(), 0, ver) <= 0)
1485 m_log.warn("logout mapping record changed behind us, leaving it alone");
1488 catch (std::exception& ex) {
1489 m_log.error("error updating logout mapping record: %s", ex.what());
1492 return sessionsKilled.size();
1495 bool SSCache::stronglyMatches(const XMLCh* idp, const XMLCh* sp, const saml2::NameID& n1, const saml2::NameID& n2) const
1497 if (!XMLString::equals(n1.getName(), n2.getName()))
1500 const XMLCh* s1 = n1.getFormat();
1501 const XMLCh* s2 = n2.getFormat();
1503 s1 = saml2::NameID::UNSPECIFIED;
1505 s2 = saml2::NameID::UNSPECIFIED;
1506 if (!XMLString::equals(s1,s2))
1509 s1 = n1.getNameQualifier();
1510 s2 = n2.getNameQualifier();
1515 if (!XMLString::equals(s1,s2))
1518 s1 = n1.getSPNameQualifier();
1519 s2 = n2.getSPNameQualifier();
1524 if (!XMLString::equals(s1,s2))
1530 LogoutEvent* SSCache::newLogoutEvent(const Application& app) const
1532 if (!SPConfig::getConfig().isEnabled(SPConfig::Logging))
1535 auto_ptr<TransactionLog::Event> event(SPConfig::getConfig().EventManager.newPlugin(LOGOUT_EVENT, nullptr));
1536 LogoutEvent* logout_event = dynamic_cast<LogoutEvent*>(event.get());
1538 logout_event->m_app = &app;
1540 return logout_event;
1543 m_log.warn("unable to audit event, log event object was of an incorrect type");
1546 catch (std::exception& ex) {
1547 m_log.warn("exception auditing event: %s", ex.what());
1554 Session* SSCache::find(const Application& app, const char* key, const char* client_addr, time_t* timeout)
1557 xmltooling::NDC ndc("find");
1559 StoredSession* session=nullptr;
1562 m_log.debug("searching local cache for session (%s)", key);
1564 map<string,StoredSession*>::const_iterator i=m_hashtable.find(key);
1565 if (i!=m_hashtable.end()) {
1566 // Save off and lock the session.
1567 session = i->second;
1570 m_log.debug("session found locally, validating it for use");
1578 if (!SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess)) {
1579 m_log.debug("session not found locally, remoting the search");
1580 // Remote the request.
1581 DDF in("find::" STORAGESERVICE_SESSION_CACHE "::SessionCache"), out;
1584 in.addmember("key").string(key);
1585 in.addmember("application_id").string(app.getId());
1586 if (timeout && *timeout) {
1587 // On 64-bit Windows, time_t doesn't fit in a long, so I'm using ISO timestamps.
1588 #ifndef HAVE_GMTIME_R
1589 struct tm* ptime=gmtime(timeout);
1592 struct tm* ptime=gmtime_r(timeout,&res);
1595 strftime(timebuf,32,"%Y-%m-%dT%H:%M:%SZ",ptime);
1596 in.addmember("timeout").string(timebuf);
1600 out=app.getServiceProvider().getListenerService()->send(in);
1601 if (!out.isstruct()) {
1603 m_log.debug("session not found in remote cache");
1607 // Wrap the results in a local entry and save it.
1608 session = new StoredSession(this, out);
1609 // The remote end has handled timeout issues, we handle address and expiration checks.
1618 // We're out of process, so we can search the storage service directly.
1621 throw ConfigurationException("SessionCache lookup requires a StorageService.");
1623 m_log.debug("searching for session (%s)", key);
1628 int ver = m_storage->readText(key, "session", &record, &lastAccess);
1632 m_log.debug("reconstituting session and checking validity");
1634 istringstream in(record);
1637 unsigned long cacheTimeout = getCacheTimeout(app);
1638 lastAccess -= cacheTimeout; // adjusts it back to the last time the record's timestamp was touched
1639 time_t now=time(nullptr);
1641 if (timeout && *timeout > 0 && now - lastAccess >= *timeout) {
1642 m_log.info("session timed out (ID: %s)", key);
1643 scoped_ptr<LogoutEvent> logout_event(newLogoutEvent(app));
1644 if (logout_event.get()) {
1645 logout_event->m_logoutType = LogoutEvent::LOGOUT_EVENT_INVALID;
1646 logout_event->m_sessions.push_back(key);
1647 app.getServiceProvider().getTransactionLog()->write(*logout_event);
1650 const char* eid = obj["entity_id"].string();
1653 throw RetryableProfileException("Your session has expired, and you must re-authenticate.");
1657 throw RetryableProfileException("Your session has expired, and you must re-authenticate.", namedparams(1, "entityID", eid2.c_str()));
1661 // Update storage expiration, if possible.
1663 m_storage->updateContext(key, now + cacheTimeout);
1665 catch (std::exception& ex) {
1666 m_log.error("failed to update session expiration: %s", ex.what());
1670 // Wrap the results in a local entry and save it.
1671 session = new StoredSession(this, obj);
1672 // We handled timeout issues, still need to handle address and expiration checks.
1675 throw ConfigurationException("SessionCache search requires a StorageService.");
1680 // Lock for writing and repeat the search to avoid duplication.
1682 SharedLock shared(m_lock, false);
1683 if (m_hashtable.count(key)) {
1684 // We're using an existing session entry.
1686 session = m_hashtable[key];
1690 m_hashtable[key]=session;
1696 if (!XMLString::equals(session->getApplicationID(), app.getId())) {
1697 m_log.warn("an application (%s) tried to access another application's session", app.getId());
1702 // Verify currency and update the timestamp if indicated by caller.
1704 session->validate(app, client_addr, timeout);
1708 scoped_ptr<LogoutEvent> logout_event(newLogoutEvent(app));
1709 if (logout_event.get()) {
1710 logout_event->m_logoutType = LogoutEvent::LOGOUT_EVENT_INVALID;
1711 logout_event->m_session = session;
1712 logout_event->m_sessions.push_back(session->getID());
1713 app.getServiceProvider().getTransactionLog()->write(*logout_event);
1724 Session* SSCache::find(const Application& app, HTTPRequest& request, const char* client_addr, time_t* timeout)
1726 string id = active(app, request);
1730 Session* session = find(app, id.c_str(), client_addr, timeout);
1733 HTTPResponse* response = dynamic_cast<HTTPResponse*>(&request);
1735 if (!m_outboundHeader.empty())
1736 response->setResponseHeader(m_outboundHeader.c_str(), nullptr);
1737 pair<string,const char*> shib_cookie = app.getCookieNameProps("_shibsession_");
1738 string exp(shib_cookie.second);
1739 exp += "; expires=Mon, 01 Jan 2001 00:00:00 GMT";
1740 response->setCookie(shib_cookie.first.c_str(), exp.c_str());
1743 catch (std::exception&) {
1744 HTTPResponse* response = dynamic_cast<HTTPResponse*>(&request);
1746 if (!m_outboundHeader.empty())
1747 response->setResponseHeader(m_outboundHeader.c_str(), nullptr);
1748 pair<string,const char*> shib_cookie = app.getCookieNameProps("_shibsession_");
1749 string exp(shib_cookie.second);
1750 exp += "; expires=Mon, 01 Jan 2001 00:00:00 GMT";
1751 response->setCookie(shib_cookie.first.c_str(), exp.c_str());
1758 void SSCache::remove(const Application& app, const HTTPRequest& request, HTTPResponse* response)
1761 pair<string,const char*> shib_cookie = app.getCookieNameProps("_shibsession_");
1763 if (!m_inboundHeader.empty())
1764 session_id = request.getHeader(m_inboundHeader.c_str());
1765 if (session_id.empty()) {
1766 const char* c = request.getCookie(shib_cookie.first.c_str());
1771 if (!session_id.empty()) {
1773 if (!m_outboundHeader.empty())
1774 response->setResponseHeader(m_outboundHeader.c_str(), nullptr);
1775 string exp(shib_cookie.second);
1776 exp += "; expires=Mon, 01 Jan 2001 00:00:00 GMT";
1777 response->setCookie(shib_cookie.first.c_str(), exp.c_str());
1779 remove(app, session_id.c_str());
1783 void SSCache::remove(const Application& app, const char* key)
1786 xmltooling::NDC ndc("remove");
1788 // Take care of local copy.
1792 if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess)) {
1793 // Remove the session from storage directly.
1795 m_storage->deleteContext(key);
1796 m_log.info("removed session (%s)", key);
1798 throw ConfigurationException("SessionCache removal requires a StorageService.");
1802 // Remote the request.
1803 DDF in("remove::" STORAGESERVICE_SESSION_CACHE "::SessionCache");
1806 in.addmember("key").string(key);
1807 in.addmember("application_id").string(app.getId());
1809 DDF out = app.getServiceProvider().getListenerService()->send(in);
1814 void SSCache::dormant(const char* key)
1817 xmltooling::NDC ndc("dormant");
1820 m_log.debug("deleting local copy of session (%s)", key);
1822 // lock the cache for writing, which means we know nobody is sitting in find()
1825 // grab the entry from the table
1826 map<string,StoredSession*>::const_iterator i=m_hashtable.find(key);
1827 if (i==m_hashtable.end()) {
1832 // ok, remove the entry and lock it
1833 StoredSession* entry=i->second;
1834 m_hashtable.erase(key);
1840 // we can release the cache entry lock because we know we're not in the cache anymore
1846 void* SSCache::cleanup_fn(void* p)
1849 xmltooling::NDC ndc("cleanup");
1852 SSCache* pcache = reinterpret_cast<SSCache*>(p);
1855 // First, let's block all signals
1856 Thread::mask_all_signals();
1859 scoped_ptr<Mutex> mutex(Mutex::create());
1861 // Load our configuration details...
1862 static const XMLCh cleanupInterval[] = UNICODE_LITERAL_15(c,l,e,a,n,u,p,I,n,t,e,r,v,a,l);
1863 const XMLCh* tag = pcache->m_root ? pcache->m_root->getAttributeNS(nullptr, cleanupInterval) : nullptr;
1864 int rerun_timer = 900;
1867 rerun_timer = XMLString::parseInt(tag);
1869 catch (XMLException&) {
1870 pcache->m_log.error("cleanupInterval setting was not a numeric value");
1873 if (rerun_timer <= 0)
1879 pcache->m_log.info("cleanup thread started...run every %d secs; timeout after %d secs", rerun_timer, pcache->m_inprocTimeout);
1881 while (!pcache->shutdown) {
1882 pcache->shutdown_wait->timedwait(mutex.get(), rerun_timer);
1883 if (pcache->shutdown)
1886 // Ok, let's run through the cleanup process and clean out
1887 // really old sessions. This is a two-pass process. The
1888 // first pass is done holding a read-lock while we iterate over
1889 // the cache. The second pass doesn't need a lock because
1890 // the 'deletes' will lock the cache.
1892 // Pass 1: iterate over the map and find all entries that have not been
1893 // used in the allotted timeout.
1894 vector<string> stale_keys;
1895 time_t stale = time(nullptr) - pcache->m_inprocTimeout;
1897 pcache->m_log.debug("cleanup thread running");
1899 pcache->m_lock->rdlock();
1900 for (map<string,StoredSession*>::const_iterator i = pcache->m_hashtable.begin(); i != pcache->m_hashtable.end(); ++i) {
1901 // If the last access was BEFORE the stale timeout...
1903 time_t last=i->second->getLastAccess();
1904 i->second->unlock();
1906 stale_keys.push_back(i->first);
1908 pcache->m_lock->unlock();
1910 if (!stale_keys.empty()) {
1911 pcache->m_log.info("purging %d old sessions", stale_keys.size());
1913 // Pass 2: walk through the list of stale entries and remove them from the cache
1914 for_each(stale_keys.begin(), stale_keys.end(), boost::bind(&SSCache::dormant, pcache, boost::bind(&string::c_str, _1)));
1917 pcache->m_log.debug("cleanup thread completed");
1920 pcache->m_log.info("cleanup thread exiting");
1928 void SSCache::receive(DDF& in, ostream& out)
1931 xmltooling::NDC ndc("receive");
1933 const Application* app = SPConfig::getConfig().getServiceProvider()->getApplication(in["application_id"].string());
1935 throw ListenerException("Application not found, check configuration?");
1937 if (!strcmp(in.name(),"find::" STORAGESERVICE_SESSION_CACHE "::SessionCache")) {
1938 const char* key=in["key"].string();
1940 throw ListenerException("Required parameters missing for session lookup.");
1942 // Do an unversioned read.
1945 if (!m_storage->readText(key, "session", &record, &lastAccess)) {
1946 m_log.debug("session not found in cache (%s)", key);
1948 DDFJanitor jan(ret);
1953 // Adjust for expiration to recover last access time and check timeout.
1954 unsigned long cacheTimeout = getCacheTimeout(*app);
1955 lastAccess -= cacheTimeout;
1956 time_t now=time(nullptr);
1958 // See if we need to check for a timeout.
1959 if (in["timeout"].string()) {
1961 auto_ptr_XMLCh dt(in["timeout"].string());
1962 DateTime dtobj(dt.get());
1963 dtobj.parseDateTime();
1964 timeout = dtobj.getEpoch();
1966 if (timeout > 0 && now - lastAccess >= timeout) {
1967 m_log.info("session timed out (ID: %s)", key);
1968 scoped_ptr<LogoutEvent> logout_event(newLogoutEvent(*app));
1969 if (logout_event.get()) {
1970 logout_event->m_logoutType = LogoutEvent::LOGOUT_EVENT_INVALID;
1971 logout_event->m_sessions.push_back(key);
1972 app->getServiceProvider().getTransactionLog()->write(*logout_event);
1975 throw RetryableProfileException("Your session has expired, and you must re-authenticate.");
1978 // Update storage expiration, if possible.
1980 m_storage->updateContext(key, now + cacheTimeout);
1982 catch (std::exception& ex) {
1983 m_log.error("failed to update session expiration: %s", ex.what());
1987 // Send the record back.
1990 else if (!strcmp(in.name(),"touch::" STORAGESERVICE_SESSION_CACHE "::SessionCache")) {
1991 const char* key=in["key"].string();
1993 throw ListenerException("Required parameters missing for session check.");
1994 const char* client_addr = in["client_addr"].string();
1996 // Do a read. May be unversioned if we need to bind a new client address.
1999 int curver = in["version"].integer();
2000 int ver = m_storage->readText(key, "session", &record, &lastAccess, client_addr ? 0 : curver);
2002 m_log.warn("unsuccessful read of session (ID: %s), caches out of sync?", key);
2003 throw RetryableProfileException("Your session has expired, and you must re-authenticate.");
2006 // Adjust for expiration to recover last access time and check timeout.
2007 unsigned long cacheTimeout = getCacheTimeout(*app);
2008 lastAccess -= cacheTimeout;
2009 time_t now=time(nullptr);
2011 // See if we need to check for a timeout.
2013 auto_ptr_XMLCh dt(in["timeout"].string());
2015 DateTime dtobj(dt.get());
2016 dtobj.parseDateTime();
2017 timeout = dtobj.getEpoch();
2020 if (timeout > 0 && now - lastAccess >= timeout) {
2021 m_log.info("session timed out (ID: %s)", key);
2022 throw RetryableProfileException("Your session has expired, and you must re-authenticate.");
2025 // Update storage expiration, if possible.
2027 m_storage->updateContext(key, now + cacheTimeout);
2029 catch (std::exception& ex) {
2030 m_log.error("failed to update session expiration: %s", ex.what());
2033 // We may need to write back a new address into the session using a versioned update loop.
2036 m_log.info("binding session (%s) to new client address (%s)", key, client_addr);
2038 // We have to reconstitute the session object ourselves.
2040 DDFJanitor sessionjan(sessionobj);
2041 istringstream src(record);
2043 ver = sessionobj["version"].integer();
2044 const char* saddr = sessionobj["client_addr"][getAddressFamily(client_addr)].string();
2046 // Something snuck in and bound the session to this address type, so it better match what we have.
2047 if (!XMLString::equals(saddr, client_addr)) {
2048 m_log.warn("client address mismatch, client (%s), session (%s)", client_addr, saddr);
2049 throw RetryableProfileException(
2050 "Your IP address ($1) does not match the address recorded at the time the session was established.",
2051 params(1, client_addr)
2054 break; // No need to update.
2057 // Bind it into the session.
2058 sessionobj["client_addr"].addmember(getAddressFamily(client_addr)).string(client_addr);
2061 // Tentatively increment the version.
2062 sessionobj["version"].integer(sessionobj["version"].integer() + 1);
2068 ver = m_storage->updateText(key, "session", record.c_str(), 0, ver);
2070 // Fatal problem with update.
2071 m_log.error("updateText failed on StorageService for session (%s)", key);
2072 throw IOException("Unable to update stored session.");
2076 if (++attempts > 10) {
2077 m_log.error("failed to bind client address, update attempts exceeded limit");
2078 throw IOException("Unable to update stored session, exceeded retry limit.");
2080 m_log.warn("storage service indicates the record is out of sync, updating with a fresh copy...");
2081 sessionobj["version"].integer(sessionobj["version"].integer() - 1);
2082 ver = m_storage->readText(key, "session", &record);
2084 m_log.error("readText failed on StorageService for session (%s)", key);
2085 throw IOException("Unable to read back stored session.");
2089 } while (ver < 0); // negative indicates a sync issue so we retry
2093 // Send the record back.
2098 DDFJanitor jan(ret);
2102 else if (!strcmp(in.name(),"remove::" STORAGESERVICE_SESSION_CACHE "::SessionCache")) {
2103 const char* key=in["key"].string();
2105 throw ListenerException("Required parameter missing for session removal.");
2109 DDFJanitor jan(ret);