2 * Copyright 2001-2009 Internet2
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
18 * StorageServiceSessionCache.cpp
20 * StorageService-based SessionCache implementation.
22 * Instead of optimizing this plugin with a buffering scheme that keeps objects around
23 * and avoids extra parsing steps, I'm assuming that systems that require such can
24 * layer their own cache plugin on top of this version either by delegating to it
25 * or using the remoting support. So this version will load sessions directly
26 * from the StorageService, instantiate enough to expose the Session API,
27 * and then delete everything when they're unlocked. All data in memory is always
28 * kept in sync with the StorageService (no lazy updates).
32 #include "Application.h"
33 #include "exceptions.h"
34 #include "ServiceProvider.h"
35 #include "SessionCacheEx.h"
36 #include "TransactionLog.h"
37 #include "attribute/Attribute.h"
38 #include "remoting/ListenerService.h"
39 #include "util/SPConstants.h"
42 #include <xmltooling/io/HTTPRequest.h>
43 #include <xmltooling/io/HTTPResponse.h>
44 #include <xmltooling/util/DateTime.h>
45 #include <xmltooling/util/NDC.h>
46 #include <xmltooling/util/XMLHelper.h>
47 #include <xercesc/util/XMLUniDefs.hpp>
50 # include <saml/exceptions.h>
51 # include <saml/SAMLConfig.h>
52 # include <saml/saml2/core/Assertions.h>
53 # include <saml/saml2/metadata/Metadata.h>
54 # include <xmltooling/XMLToolingConfig.h>
55 # include <xmltooling/util/StorageService.h>
56 using namespace opensaml::saml2md;
59 # include <xmltooling/util/DateTime.h>
62 using namespace shibsp;
63 using namespace opensaml;
64 using namespace xmltooling;
70 class SSCache : public SessionCacheEx
72 ,public virtual Remoted
76 SSCache(const DOMElement* e);
80 void receive(DDF& in, ostream& out);
83 const Application& application,
84 const HTTPRequest& httpRequest,
85 HTTPResponse& httpResponse,
87 const saml2md::EntityDescriptor* issuer=NULL,
88 const XMLCh* protocol=NULL,
89 const saml2::NameID* nameid=NULL,
90 const XMLCh* authn_instant=NULL,
91 const XMLCh* session_index=NULL,
92 const XMLCh* authncontext_class=NULL,
93 const XMLCh* authncontext_decl=NULL,
94 const vector<const Assertion*>* tokens=NULL,
95 const vector<Attribute*>* attributes=NULL
97 vector<string>::size_type logout(
98 const Application& application,
99 const saml2md::EntityDescriptor* issuer,
100 const saml2::NameID& nameid,
101 const set<string>* indexes,
103 vector<string>& sessions
106 const Application& application,
107 const xmltooling::HTTPRequest& request,
108 const saml2md::EntityDescriptor* issuer,
109 const saml2::NameID& nameid,
110 const set<string>* indexes
113 Session* find(const Application& application, const char* key, const char* client_addr=NULL, time_t* timeout=NULL);
114 void remove(const Application& application, const char* key);
117 string active(const Application& application, const xmltooling::HTTPRequest& request) {
118 pair<string,const char*> shib_cookie = application.getCookieNameProps("_shibsession_");
119 const char* session_id = request.getCookie(shib_cookie.first.c_str());
120 return (session_id ? session_id : "");
123 Session* find(const Application& application, const HTTPRequest& request, const char* client_addr=NULL, time_t* timeout=NULL) {
124 string id = active(application, request);
126 return find(application, id.c_str(), client_addr, timeout);
130 Session* find(const Application& application, HTTPRequest& request, const char* client_addr=NULL, time_t* timeout=NULL) {
131 string id = active(application, request);
135 Session* session = find(application, id.c_str(), client_addr, timeout);
138 HTTPResponse* response = dynamic_cast<HTTPResponse*>(&request);
140 pair<string,const char*> shib_cookie = application.getCookieNameProps("_shibsession_");
141 string exp(shib_cookie.second);
142 exp += "; expires=Mon, 01 Jan 2001 00:00:00 GMT";
143 response->setCookie(shib_cookie.first.c_str(), exp.c_str());
147 HTTPResponse* response = dynamic_cast<HTTPResponse*>(&request);
149 pair<string,const char*> shib_cookie = application.getCookieNameProps("_shibsession_");
150 string exp(shib_cookie.second);
151 exp += "; expires=Mon, 01 Jan 2001 00:00:00 GMT";
152 response->setCookie(shib_cookie.first.c_str(), exp.c_str());
159 void remove(const Application& application, const HTTPRequest& request, HTTPResponse* response=NULL) {
160 pair<string,const char*> shib_cookie = application.getCookieNameProps("_shibsession_");
161 const char* session_id = request.getCookie(shib_cookie.first.c_str());
162 if (session_id && *session_id) {
164 string exp(shib_cookie.second);
165 exp += "; expires=Mon, 01 Jan 2001 00:00:00 GMT";
166 response->setCookie(shib_cookie.first.c_str(), exp.c_str());
168 remove(application, session_id);
176 unsigned long m_cacheTimeout;
178 StorageService* m_storage;
179 StorageService* m_storage_lite;
184 // maintain back-mappings of NameID/SessionIndex -> session key
185 void insert(const char* key, time_t expires, const char* name, const char* index);
186 bool stronglyMatches(const XMLCh* idp, const XMLCh* sp, const saml2::NameID& n1, const saml2::NameID& n2) const;
189 const DOMElement* m_root; // Only valid during initialization
190 unsigned long m_inprocTimeout;
192 // inproc means we buffer sessions in memory
194 map<string,StoredSession*> m_hashtable;
196 // management of buffered sessions
197 void dormant(const char* key);
198 static void* cleanup_fn(void*);
200 CondWait* shutdown_wait;
201 Thread* cleanup_thread;
204 class StoredSession : public virtual Session
207 StoredSession(SSCache* cache, DDF& obj) : m_obj(obj),
211 m_cache(cache), m_expires(0), m_lastAccess(time(NULL)), m_lock(NULL) {
212 auto_ptr_XMLCh exp(m_obj["expires"].string());
214 DateTime iso(exp.get());
216 m_expires = iso.getEpoch();
220 const char* nameid = obj["nameid"].string();
222 // Parse and bind the document into an XMLObject.
223 istringstream instr(nameid);
224 DOMDocument* doc = XMLToolingConfig::getConfig().getParser().parse(instr);
225 XercesJanitor<DOMDocument> janitor(doc);
226 auto_ptr<saml2::NameID> n(saml2::NameIDBuilder::buildNameID());
227 n->unmarshall(doc->getDocumentElement(), true);
229 m_nameid = n.release();
233 m_lock = Mutex::create();
239 for_each(m_attributes.begin(), m_attributes.end(), xmltooling::cleanup<Attribute>());
242 for_each(m_tokens.begin(), m_tokens.end(), cleanup_pair<string,Assertion>());
258 const char* getID() const {
261 const char* getApplicationID() const {
262 return m_obj["application_id"].string();
264 const char* getClientAddress() const {
265 return m_obj["client_addr"].string();
267 const char* getEntityID() const {
268 return m_obj["entity_id"].string();
270 const char* getProtocol() const {
271 return m_obj["protocol"].string();
273 const char* getAuthnInstant() const {
274 return m_obj["authn_instant"].string();
277 const saml2::NameID* getNameID() const {
281 const char* getSessionIndex() const {
282 return m_obj["session_index"].string();
284 const char* getAuthnContextClassRef() const {
285 return m_obj["authncontext_class"].string();
287 const char* getAuthnContextDeclRef() const {
288 return m_obj["authncontext_decl"].string();
290 const vector<Attribute*>& getAttributes() const {
291 if (m_attributes.empty())
292 unmarshallAttributes();
295 const multimap<string,const Attribute*>& getIndexedAttributes() const {
296 if (m_attributeIndex.empty()) {
297 if (m_attributes.empty())
298 unmarshallAttributes();
299 for (vector<Attribute*>::const_iterator a = m_attributes.begin(); a != m_attributes.end(); ++a) {
300 const vector<string>& aliases = (*a)->getAliases();
301 for (vector<string>::const_iterator alias = aliases.begin(); alias != aliases.end(); ++alias)
302 m_attributeIndex.insert(multimap<string,const Attribute*>::value_type(*alias, *a));
305 return m_attributeIndex;
307 const vector<const char*>& getAssertionIDs() const {
309 DDF ids = m_obj["assertions"];
310 DDF id = ids.first();
311 while (id.isstring()) {
312 m_ids.push_back(id.string());
319 void validate(const Application& application, const char* client_addr, time_t* timeout);
322 void addAttributes(const vector<Attribute*>& attributes);
323 const Assertion* getAssertion(const char* id) const;
324 void addAssertion(Assertion* assertion);
327 time_t getExpiration() const { return m_expires; }
328 time_t getLastAccess() const { return m_lastAccess; }
331 void unmarshallAttributes() const;
335 saml2::NameID* m_nameid;
336 mutable map<string,Assertion*> m_tokens;
338 mutable vector<Attribute*> m_attributes;
339 mutable multimap<string,const Attribute*> m_attributeIndex;
340 mutable vector<const char*> m_ids;
343 time_t m_expires,m_lastAccess;
347 SessionCache* SHIBSP_DLLLOCAL StorageServiceCacheFactory(const DOMElement* const & e)
349 return new SSCache(e);
353 Session* SessionCache::find(const Application& application, HTTPRequest& request, const char* client_addr, time_t* timeout)
355 return find(application, const_cast<const HTTPRequest&>(request), client_addr, timeout);
358 void SHIBSP_API shibsp::registerSessionCaches()
360 SPConfig::getConfig().SessionCacheManager.registerFactory(STORAGESERVICE_SESSION_CACHE, StorageServiceCacheFactory);
371 void StoredSession::unmarshallAttributes() const
373 Attribute* attribute;
374 DDF attrs = m_obj["attributes"];
375 DDF attr = attrs.first();
376 while (!attr.isnull()) {
378 attribute = Attribute::unmarshall(attr);
379 m_attributes.push_back(attribute);
380 if (m_cache->m_log.isDebugEnabled())
381 m_cache->m_log.debug("unmarshalled attribute (ID: %s) with %d value%s",
382 attribute->getId(), attr.first().integer(), attr.first().integer()!=1 ? "s" : "");
384 catch (AttributeException& ex) {
385 const char* id = attr.first().name();
386 m_cache->m_log.error("error unmarshalling attribute (ID: %s): %s", id ? id : "none", ex.what());
392 void StoredSession::validate(const Application& application, const char* client_addr, time_t* timeout)
394 time_t now = time(NULL);
398 if (now > m_expires) {
399 m_cache->m_log.info("session expired (ID: %s)", getID());
400 throw RetryableProfileException("Your session has expired, and you must re-authenticate.");
406 if (m_cache->m_log.isDebugEnabled())
407 m_cache->m_log.debug("comparing client address %s against %s", client_addr, getClientAddress());
408 if (!XMLString::equals(getClientAddress(),client_addr)) {
409 m_cache->m_log.warn("client address mismatch");
410 throw RetryableProfileException(
411 "Your IP address ($1) does not match the address recorded at the time the session was established.",
412 params(1,client_addr)
420 if (!SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess)) {
421 DDF in("touch::"STORAGESERVICE_SESSION_CACHE"::SessionCache"), out;
424 in.addmember("key").string(getID());
425 in.addmember("version").integer(m_obj["version"].integer());
427 // On 64-bit Windows, time_t doesn't fit in a long, so I'm using ISO timestamps.
428 #ifndef HAVE_GMTIME_R
429 struct tm* ptime=gmtime(timeout);
432 struct tm* ptime=gmtime_r(timeout,&res);
435 strftime(timebuf,32,"%Y-%m-%dT%H:%M:%SZ",ptime);
436 in.addmember("timeout").string(timebuf);
440 out=application.getServiceProvider().getListenerService()->send(in);
447 if (out.isstruct()) {
448 // We got an updated record back.
450 for_each(m_attributes.begin(), m_attributes.end(), xmltooling::cleanup<Attribute>());
451 m_attributes.clear();
452 m_attributeIndex.clear();
459 if (!m_cache->m_storage)
460 throw ConfigurationException("Session touch requires a StorageService.");
462 // Do a versioned read.
465 int curver = m_obj["version"].integer();
466 int ver = m_cache->m_storage->readText(getID(), "session", &record, &lastAccess, curver);
468 m_cache->m_log.warn("unsuccessful versioned read of session (ID: %s), cache out of sync?", getID());
469 throw RetryableProfileException("Your session has expired, and you must re-authenticate.");
472 // Adjust for expiration to recover last access time and check timeout.
473 lastAccess -= m_cache->m_cacheTimeout;
474 if (*timeout > 0 && now - lastAccess >= *timeout) {
475 m_cache->m_log.info("session timed out (ID: %s)", getID());
476 throw RetryableProfileException("Your session has expired, and you must re-authenticate.");
479 // Update storage expiration, if possible.
481 m_cache->m_storage->updateContext(getID(), now + m_cache->m_cacheTimeout);
483 catch (exception& ex) {
484 m_cache->m_log.error("failed to update session expiration: %s", ex.what());
488 // We got an updated record back.
490 istringstream in(record);
493 for_each(m_attributes.begin(), m_attributes.end(), xmltooling::cleanup<Attribute>());
494 m_attributes.clear();
495 m_attributeIndex.clear();
500 throw ConfigurationException("Session touch requires a StorageService.");
509 void StoredSession::addAttributes(const vector<Attribute*>& attributes)
512 xmltooling::NDC ndc("addAttributes");
515 if (!m_cache->m_storage)
516 throw ConfigurationException("Session modification requires a StorageService.");
518 m_cache->m_log.debug("adding attributes to session (%s)", getID());
523 DDF attrs = m_obj["attributes"];
525 attrs = m_obj.addmember("attributes").list();
526 for (vector<Attribute*>::const_iterator a=attributes.begin(); a!=attributes.end(); ++a) {
527 attr = (*a)->marshall();
531 // Tentatively increment the version.
532 m_obj["version"].integer(m_obj["version"].integer()+1);
536 string record(str.str());
539 ver = m_cache->m_storage->updateText(getID(), "session", record.c_str(), 0, m_obj["version"].integer()-1);
542 // Roll back modification to record.
543 m_obj["version"].integer(m_obj["version"].integer()-1);
544 vector<Attribute*>::size_type count = attributes.size();
546 attrs.last().destroy();
551 // Roll back modification to record.
552 m_obj["version"].integer(m_obj["version"].integer()-1);
553 vector<Attribute*>::size_type count = attributes.size();
555 attrs.last().destroy();
558 // Fatal problem with update.
559 throw IOException("Unable to update stored session.");
563 m_cache->m_log.warn("storage service indicates the record is out of sync, updating with a fresh copy...");
564 ver = m_cache->m_storage->readText(getID(), "session", &record, NULL);
566 m_cache->m_log.error("readText failed on StorageService for session (%s)", getID());
567 throw IOException("Unable to read back stored session.");
572 istringstream in(record);
576 for_each(m_attributes.begin(), m_attributes.end(), xmltooling::cleanup<Attribute>());
577 m_attributes.clear();
578 m_attributeIndex.clear();
579 newobj["version"].integer(ver);
585 } while (ver < 0); // negative indicates a sync issue so we retry
587 TransactionLog* xlog = SPConfig::getConfig().getServiceProvider()->getTransactionLog();
589 xlog->log.infoStream() <<
590 "Added the following attributes to session (ID: " <<
592 ") for (applicationId: " <<
593 m_obj["application_id"].string() <<
595 for (vector<Attribute*>::const_iterator a=attributes.begin(); a!=attributes.end(); ++a)
596 xlog->log.infoStream() << "\t" << (*a)->getId() << " (" << (*a)->valueCount() << " values)";
599 // We own them now, so clean them up.
600 for_each(attributes.begin(), attributes.end(), xmltooling::cleanup<Attribute>());
603 const Assertion* StoredSession::getAssertion(const char* id) const
605 if (!m_cache->m_storage)
606 throw ConfigurationException("Assertion retrieval requires a StorageService.");
608 map<string,Assertion*>::const_iterator i = m_tokens.find(id);
609 if (i!=m_tokens.end())
613 if (!m_cache->m_storage->readText(getID(), id, &tokenstr, NULL))
614 throw FatalProfileException("Assertion not found in cache.");
616 // Parse and bind the document into an XMLObject.
617 istringstream instr(tokenstr);
618 DOMDocument* doc = XMLToolingConfig::getConfig().getParser().parse(instr);
619 XercesJanitor<DOMDocument> janitor(doc);
620 auto_ptr<XMLObject> xmlObject(XMLObjectBuilder::buildOneFromElement(doc->getDocumentElement(), true));
623 Assertion* token = dynamic_cast<Assertion*>(xmlObject.get());
625 throw FatalProfileException("Request for cached assertion returned an unknown object type.");
627 // Transfer ownership to us.
633 void StoredSession::addAssertion(Assertion* assertion)
636 xmltooling::NDC ndc("addAssertion");
639 if (!m_cache->m_storage)
640 throw ConfigurationException("Session modification requires a StorageService.");
643 throw FatalProfileException("Unknown object type passed to session for storage.");
645 auto_ptr_char id(assertion->getID());
647 m_cache->m_log.debug("adding assertion (%s) to session (%s)", id.get(), getID());
650 if (!m_cache->m_storage->readText(getID(), "session", NULL, &exp))
651 throw IOException("Unable to load expiration time for stored session.");
653 ostringstream tokenstr;
654 tokenstr << *assertion;
655 if (!m_cache->m_storage->createText(getID(), id.get(), tokenstr.str().c_str(), exp))
656 throw IOException("Attempted to insert duplicate assertion ID into session.");
660 DDF token = DDF(NULL).string(id.get());
661 m_obj["assertions"].add(token);
663 // Tentatively increment the version.
664 m_obj["version"].integer(m_obj["version"].integer()+1);
668 string record(str.str());
671 ver = m_cache->m_storage->updateText(getID(), "session", record.c_str(), 0, m_obj["version"].integer()-1);
675 m_obj["version"].integer(m_obj["version"].integer()-1);
676 m_cache->m_storage->deleteText(getID(), id.get());
682 m_obj["version"].integer(m_obj["version"].integer()-1);
685 // Fatal problem with update.
686 m_cache->m_log.error("updateText failed on StorageService for session (%s)", getID());
687 m_cache->m_storage->deleteText(getID(), id.get());
688 throw IOException("Unable to update stored session.");
692 m_cache->m_log.warn("storage service indicates the record is out of sync, updating with a fresh copy...");
693 ver = m_cache->m_storage->readText(getID(), "session", &record, NULL);
695 m_cache->m_log.error("readText failed on StorageService for session (%s)", getID());
696 m_cache->m_storage->deleteText(getID(), id.get());
697 throw IOException("Unable to read back stored session.");
702 istringstream in(record);
706 for_each(m_attributes.begin(), m_attributes.end(), xmltooling::cleanup<Attribute>());
707 m_attributes.clear();
708 m_attributeIndex.clear();
709 newobj["version"].integer(ver);
715 } while (ver < 0); // negative indicates a sync issue so we retry
720 TransactionLog* xlog = SPConfig::getConfig().getServiceProvider()->getTransactionLog();
723 "Added assertion (ID: %s) to session for (applicationId: %s) with (ID: %s)",
724 id.get(), m_obj["application_id"].string(), getID()
730 SessionCache::SessionCache()
734 SessionCache::~SessionCache()
738 SessionCacheEx::SessionCacheEx()
742 SessionCacheEx::~SessionCacheEx()
746 SSCache::SSCache(const DOMElement* e)
747 : m_log(Category::getInstance(SHIBSP_LOGCAT".SessionCache")), inproc(true), m_cacheTimeout(28800),
749 m_storage(NULL), m_storage_lite(NULL),
751 m_root(e), m_inprocTimeout(900), m_lock(NULL), shutdown(false), shutdown_wait(NULL), cleanup_thread(NULL)
753 static const XMLCh cacheTimeout[] = UNICODE_LITERAL_12(c,a,c,h,e,T,i,m,e,o,u,t);
754 static const XMLCh inprocTimeout[] = UNICODE_LITERAL_13(i,n,p,r,o,c,T,i,m,e,o,u,t);
755 static const XMLCh _StorageService[] = UNICODE_LITERAL_14(S,t,o,r,a,g,e,S,e,r,v,i,c,e);
756 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);
758 SPConfig& conf = SPConfig::getConfig();
759 inproc = conf.isEnabled(SPConfig::InProcess);
762 const XMLCh* tag=e->getAttributeNS(NULL,cacheTimeout);
764 m_cacheTimeout = XMLString::parseInt(tag);
766 m_cacheTimeout=28800;
769 const XMLCh* tag=e->getAttributeNS(NULL,inprocTimeout);
771 m_inprocTimeout = XMLString::parseInt(tag);
772 if (!m_inprocTimeout)
779 if (conf.isEnabled(SPConfig::OutOfProcess)) {
780 const XMLCh* tag = e ? e->getAttributeNS(NULL,_StorageService) : NULL;
782 auto_ptr_char ssid(tag);
783 m_storage = conf.getServiceProvider()->getStorageService(ssid.get());
785 m_log.info("bound to StorageService (%s)", ssid.get());
788 throw ConfigurationException("SessionCache unable to locate StorageService, check configuration.");
790 tag = e ? e->getAttributeNS(NULL,_StorageServiceLite) : NULL;
792 auto_ptr_char ssid(tag);
793 m_storage_lite = conf.getServiceProvider()->getStorageService(ssid.get());
795 m_log.info("bound to StorageServiceLite (%s)", ssid.get());
797 if (!m_storage_lite) {
798 m_log.info("No StorageServiceLite specified. Using standard StorageService.");
799 m_storage_lite = m_storage;
804 ListenerService* listener=conf.getServiceProvider()->getListenerService(false);
806 if (!conf.isEnabled(SPConfig::OutOfProcess) && !listener)
807 throw ConfigurationException("SessionCache requires a ListenerService, but none available.");
808 m_lock = RWLock::create();
809 shutdown_wait = CondWait::create();
810 cleanup_thread = Thread::create(&cleanup_fn, (void*)this);
814 if (listener && conf.isEnabled(SPConfig::OutOfProcess)) {
815 listener->regListener("find::"STORAGESERVICE_SESSION_CACHE"::SessionCache",this);
816 listener->regListener("remove::"STORAGESERVICE_SESSION_CACHE"::SessionCache",this);
817 listener->regListener("touch::"STORAGESERVICE_SESSION_CACHE"::SessionCache",this);
820 m_log.info("no ListenerService available, cache remoting disabled");
829 // Shut down the cleanup thread and let it know...
831 shutdown_wait->signal();
832 cleanup_thread->join(NULL);
834 for_each(m_hashtable.begin(),m_hashtable.end(),cleanup_pair<string,StoredSession>());
836 delete shutdown_wait;
840 SPConfig& conf = SPConfig::getConfig();
841 ListenerService* listener=conf.getServiceProvider()->getListenerService(false);
842 if (listener && conf.isEnabled(SPConfig::OutOfProcess)) {
843 listener->unregListener("find::"STORAGESERVICE_SESSION_CACHE"::SessionCache",this);
844 listener->unregListener("remove::"STORAGESERVICE_SESSION_CACHE"::SessionCache",this);
845 listener->unregListener("touch::"STORAGESERVICE_SESSION_CACHE"::SessionCache",this);
855 auto_ptr_char temp(SAMLConfig::getConfig().generateIdentifier());
856 m_storage->createString("SessionCacheTest", temp.get(), "Test", time(NULL) + 60);
857 m_storage->deleteString("SessionCacheTest", temp.get());
860 void SSCache::insert(const char* key, time_t expires, const char* name, const char* index)
863 if (strlen(name) > 255) {
864 dup = string(name).substr(0,255);
869 DDFJanitor jobj(obj);
871 // Since we can't guarantee uniqueness, check for an existing record.
874 int ver = m_storage_lite->readText("NameID", name, &record, &recordexp);
876 // Existing record, so we need to unmarshall it.
877 istringstream in(record);
882 obj = DDF(NULL).structure();
885 if (!index || !*index)
887 DDF sessions = obj.addmember(index);
888 if (!sessions.islist())
890 DDF session = DDF(NULL).string(key);
891 sessions.add(session);
893 // Remarshall the record.
897 // Try and store it back...
899 ver = m_storage_lite->updateText("NameID", name, out.str().c_str(), max(expires, recordexp), ver);
901 // Out of sync, or went missing, so retry.
902 return insert(key, expires, name, index);
905 else if (!m_storage_lite->createText("NameID", name, out.str().c_str(), expires)) {
906 // Hit a dup, so just retry, hopefully hitting the other branch.
907 return insert(key, expires, name, index);
911 void SSCache::insert(
912 const Application& application,
913 const HTTPRequest& httpRequest,
914 HTTPResponse& httpResponse,
916 const saml2md::EntityDescriptor* issuer,
917 const XMLCh* protocol,
918 const saml2::NameID* nameid,
919 const XMLCh* authn_instant,
920 const XMLCh* session_index,
921 const XMLCh* authncontext_class,
922 const XMLCh* authncontext_decl,
923 const vector<const Assertion*>* tokens,
924 const vector<Attribute*>* attributes
928 xmltooling::NDC ndc("insert");
931 throw ConfigurationException("SessionCache insertion requires a StorageService.");
933 m_log.debug("creating new session");
935 time_t now = time(NULL);
936 auto_ptr_char index(session_index);
937 auto_ptr_char entity_id(issuer ? issuer->getEntityID() : NULL);
938 auto_ptr_char name(nameid ? nameid->getName() : NULL);
941 // Check for a pending logout.
942 if (strlen(name.get()) > 255)
943 const_cast<char*>(name.get())[255] = 0;
945 int ver = m_storage_lite->readText("Logout", name.get(), &pending);
948 DDFJanitor jpend(pendobj);
949 istringstream pstr(pending);
951 // IdP.SP.index contains logout expiration, if any.
952 DDF deadmenwalking = pendobj[issuer ? entity_id.get() : "_shibnull"][application.getRelyingParty(issuer)->getString("entityID").second];
953 const char* logexpstr = deadmenwalking[session_index ? index.get() : "_shibnull"].string();
954 if (!logexpstr && session_index) // we tried an exact session match, now try for NULL
955 logexpstr = deadmenwalking["_shibnull"].string();
957 auto_ptr_XMLCh dt(logexpstr);
958 DateTime dtobj(dt.get());
959 dtobj.parseDateTime();
960 time_t logexp = dtobj.getEpoch();
961 if (now - XMLToolingConfig::getConfig().clock_skew_secs < logexp)
962 throw FatalProfileException("A logout message from your identity provider has blocked your login attempt.");
967 auto_ptr_char key(SAMLConfig::getConfig().generateIdentifier());
969 // Store session properties in DDF.
970 DDF obj = DDF(key.get()).structure();
971 DDFJanitor entryobj(obj);
972 obj.addmember("version").integer(1);
973 obj.addmember("application_id").string(application.getId());
975 // On 64-bit Windows, time_t doesn't fit in a long, so I'm using ISO timestamps.
976 #ifndef HAVE_GMTIME_R
977 struct tm* ptime=gmtime(&expires);
980 struct tm* ptime=gmtime_r(&expires,&res);
983 strftime(timebuf,32,"%Y-%m-%dT%H:%M:%SZ",ptime);
984 obj.addmember("expires").string(timebuf);
986 obj.addmember("client_addr").string(httpRequest.getRemoteAddr().c_str());
988 obj.addmember("entity_id").string(entity_id.get());
990 auto_ptr_char prot(protocol);
991 obj.addmember("protocol").string(prot.get());
994 auto_ptr_char instant(authn_instant);
995 obj.addmember("authn_instant").string(instant.get());
998 obj.addmember("session_index").string(index.get());
999 if (authncontext_class) {
1000 auto_ptr_char ac(authncontext_class);
1001 obj.addmember("authncontext_class").string(ac.get());
1003 if (authncontext_decl) {
1004 auto_ptr_char ad(authncontext_decl);
1005 obj.addmember("authncontext_decl").string(ad.get());
1009 ostringstream namestr;
1011 obj.addmember("nameid").string(namestr.str().c_str());
1015 obj.addmember("assertions").list();
1016 for (vector<const Assertion*>::const_iterator t = tokens->begin(); t!=tokens->end(); ++t) {
1017 auto_ptr_char tokenid((*t)->getID());
1018 DDF tokid = DDF(NULL).string(tokenid.get());
1019 obj["assertions"].add(tokid);
1025 DDF attrlist = obj.addmember("attributes").list();
1026 for (vector<Attribute*>::const_iterator a=attributes->begin(); a!=attributes->end(); ++a) {
1027 attr = (*a)->marshall();
1032 ostringstream record;
1035 m_log.debug("storing new session...");
1036 if (!m_storage->createText(key.get(), "session", record.str().c_str(), now + m_cacheTimeout))
1037 throw FatalProfileException("Attempted to create a session with a duplicate key.");
1039 // Store the reverse mapping for logout.
1042 insert(key.get(), expires, name.get(), index.get());
1044 catch (exception& ex) {
1045 m_log.error("error storing back mapping of NameID for logout: %s", ex.what());
1050 for (vector<const Assertion*>::const_iterator t = tokens->begin(); t!=tokens->end(); ++t) {
1051 ostringstream tokenstr;
1053 auto_ptr_char tokenid((*t)->getID());
1054 if (!m_storage->createText(key.get(), tokenid.get(), tokenstr.str().c_str(), now + m_cacheTimeout))
1055 throw IOException("duplicate assertion ID ($1)", params(1, tokenid.get()));
1058 catch (exception& ex) {
1059 m_log.error("error storing assertion along with session: %s", ex.what());
1063 const char* pid = obj["entity_id"].string();
1064 const char* prot = obj["protocol"].string();
1065 m_log.info("new session created: ID (%s) IdP (%s) Protocol(%s) Address (%s)",
1066 key.get(), pid ? pid : "none", prot ? prot : "none", httpRequest.getRemoteAddr().c_str());
1068 // Transaction Logging
1069 TransactionLog* xlog = application.getServiceProvider().getTransactionLog();
1070 Locker locker(xlog);
1071 xlog->log.infoStream() <<
1072 "New session (ID: " <<
1074 ") with (applicationId: " <<
1075 application.getId() <<
1076 ") for principal from (IdP: " <<
1077 (pid ? pid : "none") <<
1078 ") at (ClientAddress: " <<
1079 httpRequest.getRemoteAddr() <<
1080 ") with (NameIdentifier: " <<
1081 (nameid ? name.get() : "none") <<
1082 ") using (Protocol: " <<
1083 (prot ? prot : "none") <<
1084 ") from (AssertionID: " <<
1085 (tokens ? obj["assertions"].first().string() : "none") <<
1089 xlog->log.infoStream() <<
1090 "Cached the following attributes with session (ID: " <<
1092 ") for (applicationId: " <<
1093 application.getId() <<
1095 for (vector<Attribute*>::const_iterator a=attributes->begin(); a!=attributes->end(); ++a)
1096 xlog->log.infoStream() << "\t" << (*a)->getId() << " (" << (*a)->valueCount() << " values)";
1097 xlog->log.info("}");
1100 time_t cookieLifetime = 0;
1101 pair<string,const char*> shib_cookie = application.getCookieNameProps("_shibsession_", &cookieLifetime);
1102 string k(key.get());
1103 k += shib_cookie.second;
1105 if (cookieLifetime > 0) {
1106 cookieLifetime += now;
1107 #ifndef HAVE_GMTIME_R
1108 ptime=gmtime(&cookieLifetime);
1110 ptime=gmtime_r(&cookieLifetime,&res);
1112 char cookietimebuf[64];
1113 strftime(cookietimebuf,64,"; expires=%a, %d %b %Y %H:%M:%S GMT",ptime);
1117 httpResponse.setCookie(shib_cookie.first.c_str(), k.c_str());
1120 bool SSCache::matches(
1121 const Application& application,
1122 const xmltooling::HTTPRequest& request,
1123 const saml2md::EntityDescriptor* issuer,
1124 const saml2::NameID& nameid,
1125 const set<string>* indexes
1128 auto_ptr_char entityID(issuer ? issuer->getEntityID() : NULL);
1130 Session* session = find(application, request);
1132 Locker locker(session, false);
1133 if (XMLString::equals(session->getEntityID(), entityID.get()) && session->getNameID() &&
1134 stronglyMatches(issuer->getEntityID(), application.getRelyingParty(issuer)->getXMLString("entityID").second, nameid, *session->getNameID())) {
1135 return (!indexes || indexes->empty() || (session->getSessionIndex() ? (indexes->count(session->getSessionIndex())>0) : false));
1139 catch (exception& ex) {
1140 m_log.error("error while matching session: %s", ex.what());
1145 vector<string>::size_type SSCache::logout(
1146 const Application& application,
1147 const saml2md::EntityDescriptor* issuer,
1148 const saml2::NameID& nameid,
1149 const set<string>* indexes,
1151 vector<string>& sessionsKilled
1155 xmltooling::NDC ndc("logout");
1159 throw ConfigurationException("SessionCache insertion requires a StorageService.");
1161 auto_ptr_char entityID(issuer ? issuer->getEntityID() : NULL);
1162 auto_ptr_char name(nameid.getName());
1164 m_log.info("request to logout sessions from (%s) for (%s)", entityID.get() ? entityID.get() : "unknown", name.get());
1166 if (strlen(name.get()) > 255)
1167 const_cast<char*>(name.get())[255] = 0;
1170 DDFJanitor jobj(obj);
1175 // Record the logout to prevent post-delivered assertions.
1176 // On 64-bit Windows, time_t doesn't fit in a long, so I'm using ISO timestamps.
1177 #ifndef HAVE_GMTIME_R
1178 struct tm* ptime=gmtime(&expires);
1181 struct tm* ptime=gmtime_r(&expires,&res);
1184 strftime(timebuf,32,"%Y-%m-%dT%H:%M:%SZ",ptime);
1187 ver = m_storage_lite->readText("Logout", name.get(), &record, &oldexp);
1189 istringstream lin(record);
1193 obj = DDF(NULL).structure();
1196 // Structure is keyed by the IdP and SP, with a member per session index containing the expiration.
1197 DDF root = obj.addmember(issuer ? entityID.get() : "_shibnull").addmember(application.getRelyingParty(issuer)->getString("entityID").second);
1199 for (set<string>::const_iterator x = indexes->begin(); x!=indexes->end(); ++x)
1200 root.addmember(x->c_str()).string(timebuf);
1203 root.addmember("_shibnull").string(timebuf);
1211 ver = m_storage_lite->updateText("Logout", name.get(), lout.str().c_str(), max(expires, oldexp), ver);
1213 // Out of sync, or went missing, so retry.
1214 return logout(application, issuer, nameid, indexes, expires, sessionsKilled);
1217 else if (!m_storage_lite->createText("Logout", name.get(), lout.str().c_str(), expires)) {
1218 // Hit a dup, so just retry, hopefully hitting the other branch.
1219 return logout(application, issuer, nameid, indexes, expires, sessionsKilled);
1226 // Read in potentially matching sessions.
1227 ver = m_storage_lite->readText("NameID", name.get(), &record);
1229 m_log.debug("no active sessions to logout for supplied issuer and subject");
1233 istringstream in(record);
1236 // The record contains child lists for each known session index.
1238 DDF sessions = obj.first();
1239 while (sessions.islist()) {
1240 if (!indexes || indexes->empty() || indexes->count(sessions.name())) {
1241 key = sessions.first();
1242 while (key.isstring()) {
1243 // Fetch the session for comparison.
1244 Session* session = NULL;
1246 session = find(application, key.string());
1248 catch (exception& ex) {
1249 m_log.error("error locating session (%s): %s", key.string(), ex.what());
1253 Locker locker(session, false);
1255 if (XMLString::equals(session->getEntityID(), entityID.get())) {
1257 if (stronglyMatches(issuer->getEntityID(), application.getRelyingParty(issuer)->getXMLString("entityID").second, nameid, *session->getNameID())) {
1258 sessionsKilled.push_back(key.string());
1262 m_log.debug("session (%s) contained a non-matching NameID, leaving it alone", key.string());
1266 m_log.debug("session (%s) established by different IdP, leaving it alone", key.string());
1270 // Session's gone, so...
1271 sessionsKilled.push_back(key.string());
1274 key = sessions.next();
1277 // No sessions left for this index?
1278 if (sessions.first().isnull())
1281 sessions = obj.next();
1284 if (obj.first().isnull())
1287 // If possible, write back the mapping record (this isn't crucial).
1290 m_storage_lite->deleteText("NameID", name.get());
1292 else if (!sessionsKilled.empty()) {
1295 if (m_storage_lite->updateText("NameID", name.get(), out.str().c_str(), 0, ver) <= 0)
1296 m_log.warn("logout mapping record changed behind us, leaving it alone");
1299 catch (exception& ex) {
1300 m_log.error("error updating logout mapping record: %s", ex.what());
1303 return sessionsKilled.size();
1306 bool SSCache::stronglyMatches(const XMLCh* idp, const XMLCh* sp, const saml2::NameID& n1, const saml2::NameID& n2) const
1308 if (!XMLString::equals(n1.getName(), n2.getName()))
1311 const XMLCh* s1 = n1.getFormat();
1312 const XMLCh* s2 = n2.getFormat();
1314 s1 = saml2::NameID::UNSPECIFIED;
1316 s2 = saml2::NameID::UNSPECIFIED;
1317 if (!XMLString::equals(s1,s2))
1320 s1 = n1.getNameQualifier();
1321 s2 = n2.getNameQualifier();
1326 if (!XMLString::equals(s1,s2))
1329 s1 = n1.getSPNameQualifier();
1330 s2 = n2.getSPNameQualifier();
1335 if (!XMLString::equals(s1,s2))
1343 Session* SSCache::find(const Application& application, const char* key, const char* client_addr, time_t* timeout)
1346 xmltooling::NDC ndc("find");
1348 StoredSession* session=NULL;
1351 m_log.debug("searching local cache for session (%s)", key);
1353 map<string,StoredSession*>::const_iterator i=m_hashtable.find(key);
1354 if (i!=m_hashtable.end()) {
1355 // Save off and lock the session.
1356 session = i->second;
1359 m_log.debug("session found locally, validating it for use");
1367 if (!SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess)) {
1368 m_log.debug("session not found locally, remoting the search");
1369 // Remote the request.
1370 DDF in("find::"STORAGESERVICE_SESSION_CACHE"::SessionCache"), out;
1373 in.addmember("key").string(key);
1374 in.addmember("application_id").string(application.getId());
1375 if (timeout && *timeout) {
1376 // On 64-bit Windows, time_t doesn't fit in a long, so I'm using ISO timestamps.
1377 #ifndef HAVE_GMTIME_R
1378 struct tm* ptime=gmtime(timeout);
1381 struct tm* ptime=gmtime_r(timeout,&res);
1384 strftime(timebuf,32,"%Y-%m-%dT%H:%M:%SZ",ptime);
1385 in.addmember("timeout").string(timebuf);
1389 out=application.getServiceProvider().getListenerService()->send(in);
1390 if (!out.isstruct()) {
1392 m_log.debug("session not found in remote cache");
1396 // Wrap the results in a local entry and save it.
1397 session = new StoredSession(this, out);
1398 // The remote end has handled timeout issues, we handle address and expiration checks.
1407 // We're out of process, so we can search the storage service directly.
1410 throw ConfigurationException("SessionCache lookup requires a StorageService.");
1412 m_log.debug("searching for session (%s)", key);
1417 int ver = m_storage->readText(key, "session", &record, &lastAccess);
1421 m_log.debug("reconstituting session and checking validity");
1423 istringstream in(record);
1426 lastAccess -= m_cacheTimeout; // adjusts it back to the last time the record's timestamp was touched
1427 time_t now=time(NULL);
1429 if (timeout && *timeout > 0 && now - lastAccess >= *timeout) {
1430 m_log.info("session timed out (ID: %s)", key);
1431 remove(application, key);
1432 const char* eid = obj["entity_id"].string();
1435 throw RetryableProfileException("Your session has expired, and you must re-authenticate.");
1439 throw RetryableProfileException("Your session has expired, and you must re-authenticate.", namedparams(1, "entityID", eid2.c_str()));
1443 // Update storage expiration, if possible.
1445 m_storage->updateContext(key, now + m_cacheTimeout);
1447 catch (exception& ex) {
1448 m_log.error("failed to update session expiration: %s", ex.what());
1452 // Wrap the results in a local entry and save it.
1453 session = new StoredSession(this, obj);
1454 // We handled timeout issues, still need to handle address and expiration checks.
1457 throw ConfigurationException("SessionCache search requires a StorageService.");
1462 // Lock for writing and repeat the search to avoid duplication.
1464 SharedLock shared(m_lock, false);
1465 if (m_hashtable.count(key)) {
1466 // We're using an existing session entry.
1468 session = m_hashtable[key];
1472 m_hashtable[key]=session;
1478 if (!XMLString::equals(session->getApplicationID(), application.getId())) {
1479 m_log.error("an application (%s) tried to access another application's session", application.getId());
1484 // Verify currency and update the timestamp if indicated by caller.
1486 session->validate(application, client_addr, timeout);
1490 remove(application, key);
1497 void SSCache::remove(const Application& application, const char* key)
1500 xmltooling::NDC ndc("remove");
1502 // Take care of local copy.
1506 if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess)) {
1507 // Remove the session from storage directly.
1509 m_storage->deleteContext(key);
1510 m_log.info("removed session (%s)", key);
1512 TransactionLog* xlog = application.getServiceProvider().getTransactionLog();
1513 Locker locker(xlog);
1514 xlog->log.info("Destroyed session (applicationId: %s) (ID: %s)", application.getId(), key);
1516 throw ConfigurationException("SessionCache removal requires a StorageService.");
1520 // Remote the request.
1521 DDF in("remove::"STORAGESERVICE_SESSION_CACHE"::SessionCache");
1524 in.addmember("key").string(key);
1525 in.addmember("application_id").string(application.getId());
1527 DDF out = application.getServiceProvider().getListenerService()->send(in);
1532 void SSCache::dormant(const char* key)
1535 xmltooling::NDC ndc("dormant");
1538 m_log.debug("deleting local copy of session (%s)", key);
1540 // lock the cache for writing, which means we know nobody is sitting in find()
1543 // grab the entry from the table
1544 map<string,StoredSession*>::const_iterator i=m_hashtable.find(key);
1545 if (i==m_hashtable.end()) {
1550 // ok, remove the entry and lock it
1551 StoredSession* entry=i->second;
1552 m_hashtable.erase(key);
1558 // we can release the cache entry lock because we know we're not in the cache anymore
1564 void SSCache::cleanup()
1567 xmltooling::NDC ndc("cleanup");
1570 Mutex* mutex = Mutex::create();
1572 // Load our configuration details...
1573 static const XMLCh cleanupInterval[] = UNICODE_LITERAL_15(c,l,e,a,n,u,p,I,n,t,e,r,v,a,l);
1574 const XMLCh* tag=m_root ? m_root->getAttributeNS(NULL,cleanupInterval) : NULL;
1575 int rerun_timer = 900;
1577 rerun_timer = XMLString::parseInt(tag);
1578 if (rerun_timer <= 0)
1584 m_log.info("cleanup thread started...run every %d secs; timeout after %d secs", rerun_timer, m_inprocTimeout);
1587 shutdown_wait->timedwait(mutex,rerun_timer);
1591 // Ok, let's run through the cleanup process and clean out
1592 // really old sessions. This is a two-pass process. The
1593 // first pass is done holding a read-lock while we iterate over
1594 // the cache. The second pass doesn't need a lock because
1595 // the 'deletes' will lock the cache.
1597 // Pass 1: iterate over the map and find all entries that have not been
1598 // used in the allotted timeout.
1599 vector<string> stale_keys;
1600 time_t stale = time(NULL) - m_inprocTimeout;
1602 m_log.debug("cleanup thread running");
1605 for (map<string,StoredSession*>::const_iterator i=m_hashtable.begin(); i!=m_hashtable.end(); ++i) {
1606 // If the last access was BEFORE the stale timeout...
1608 time_t last=i->second->getLastAccess();
1609 i->second->unlock();
1611 stale_keys.push_back(i->first);
1615 if (!stale_keys.empty()) {
1616 m_log.info("purging %d old sessions", stale_keys.size());
1618 // Pass 2: walk through the list of stale entries and remove them from the cache
1619 for (vector<string>::const_iterator j = stale_keys.begin(); j != stale_keys.end(); ++j)
1620 dormant(j->c_str());
1623 m_log.debug("cleanup thread completed");
1626 m_log.info("cleanup thread exiting");
1633 void* SSCache::cleanup_fn(void* cache_p)
1636 // First, let's block all signals
1637 Thread::mask_all_signals();
1640 // Now run the cleanup process.
1641 reinterpret_cast<SSCache*>(cache_p)->cleanup();
1647 void SSCache::receive(DDF& in, ostream& out)
1650 xmltooling::NDC ndc("receive");
1653 if (!strcmp(in.name(),"find::"STORAGESERVICE_SESSION_CACHE"::SessionCache")) {
1654 const char* key=in["key"].string();
1656 throw ListenerException("Required parameters missing for session lookup.");
1658 const Application* app = SPConfig::getConfig().getServiceProvider()->getApplication(in["application_id"].string());
1660 throw ListenerException("Application not found, check configuration?");
1662 // Do an unversioned read.
1665 if (!m_storage->readText(key, "session", &record, &lastAccess)) {
1667 DDFJanitor jan(ret);
1672 // Adjust for expiration to recover last access time and check timeout.
1673 lastAccess -= m_cacheTimeout;
1674 time_t now=time(NULL);
1676 // See if we need to check for a timeout.
1677 if (in["timeout"].string()) {
1679 auto_ptr_XMLCh dt(in["timeout"].string());
1680 DateTime dtobj(dt.get());
1681 dtobj.parseDateTime();
1682 timeout = dtobj.getEpoch();
1684 if (timeout > 0 && now - lastAccess >= timeout) {
1685 m_log.info("session timed out (ID: %s)", key);
1687 throw RetryableProfileException("Your session has expired, and you must re-authenticate.");
1690 // Update storage expiration, if possible.
1692 m_storage->updateContext(key, now + m_cacheTimeout);
1694 catch (exception& ex) {
1695 m_log.error("failed to update session expiration: %s", ex.what());
1699 // Send the record back.
1702 else if (!strcmp(in.name(),"touch::"STORAGESERVICE_SESSION_CACHE"::SessionCache")) {
1703 const char* key=in["key"].string();
1705 throw ListenerException("Required parameters missing for session check.");
1707 // Do a versioned read.
1710 int curver = in["version"].integer();
1711 int ver = m_storage->readText(key, "session", &record, &lastAccess, curver);
1713 m_log.warn("unsuccessful versioned read of session (ID: %s), caches out of sync?", key);
1714 throw RetryableProfileException("Your session has expired, and you must re-authenticate.");
1717 // Adjust for expiration to recover last access time and check timeout.
1718 lastAccess -= m_cacheTimeout;
1719 time_t now=time(NULL);
1721 // See if we need to check for a timeout.
1723 auto_ptr_XMLCh dt(in["timeout"].string());
1725 DateTime dtobj(dt.get());
1726 dtobj.parseDateTime();
1727 timeout = dtobj.getEpoch();
1730 if (timeout > 0 && now - lastAccess >= timeout) {
1731 m_log.info("session timed out (ID: %s)", key);
1732 throw RetryableProfileException("Your session has expired, and you must re-authenticate.");
1735 // Update storage expiration, if possible.
1737 m_storage->updateContext(key, now + m_cacheTimeout);
1739 catch (exception& ex) {
1740 m_log.error("failed to update session expiration: %s", ex.what());
1744 // Send the record back.
1749 DDFJanitor jan(ret);
1753 else if (!strcmp(in.name(),"remove::"STORAGESERVICE_SESSION_CACHE"::SessionCache")) {
1754 const char* key=in["key"].string();
1756 throw ListenerException("Required parameter missing for session removal.");
1758 const Application* app = SPConfig::getConfig().getServiceProvider()->getApplication(in["application_id"].string());
1760 throw ConfigurationException("Application not found, check configuration?");
1764 DDFJanitor jan(ret);