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/ParserPool.h>
47 #include <xmltooling/util/XMLHelper.h>
48 #include <xercesc/util/XMLUniDefs.hpp>
51 # include <saml/exceptions.h>
52 # include <saml/SAMLConfig.h>
53 # include <saml/saml2/core/Assertions.h>
54 # include <saml/saml2/metadata/Metadata.h>
55 # include <xmltooling/XMLToolingConfig.h>
56 # include <xmltooling/util/StorageService.h>
57 using namespace opensaml::saml2md;
60 # include <xmltooling/util/DateTime.h>
63 using namespace shibsp;
64 using namespace opensaml;
65 using namespace xmltooling;
71 class SSCache : public SessionCacheEx
73 ,public virtual Remoted
77 SSCache(const DOMElement* e);
81 void receive(DDF& in, ostream& out);
84 const Application& application,
85 const HTTPRequest& httpRequest,
86 HTTPResponse& httpResponse,
88 const saml2md::EntityDescriptor* issuer=NULL,
89 const XMLCh* protocol=NULL,
90 const saml2::NameID* nameid=NULL,
91 const XMLCh* authn_instant=NULL,
92 const XMLCh* session_index=NULL,
93 const XMLCh* authncontext_class=NULL,
94 const XMLCh* authncontext_decl=NULL,
95 const vector<const Assertion*>* tokens=NULL,
96 const vector<Attribute*>* attributes=NULL
98 vector<string>::size_type logout(
99 const Application& application,
100 const saml2md::EntityDescriptor* issuer,
101 const saml2::NameID& nameid,
102 const set<string>* indexes,
104 vector<string>& sessions
107 const Application& application,
108 const xmltooling::HTTPRequest& request,
109 const saml2md::EntityDescriptor* issuer,
110 const saml2::NameID& nameid,
111 const set<string>* indexes
114 Session* find(const Application& application, const char* key, const char* client_addr=NULL, time_t* timeout=NULL);
115 void remove(const Application& application, const char* key);
118 string active(const Application& application, const xmltooling::HTTPRequest& request) {
119 pair<string,const char*> shib_cookie = application.getCookieNameProps("_shibsession_");
120 const char* session_id = request.getCookie(shib_cookie.first.c_str());
121 return (session_id ? session_id : "");
124 Session* find(const Application& application, const HTTPRequest& request, const char* client_addr=NULL, time_t* timeout=NULL) {
125 string id = active(application, request);
127 return find(application, id.c_str(), client_addr, timeout);
131 Session* find(const Application& application, HTTPRequest& request, const char* client_addr=NULL, time_t* timeout=NULL) {
132 string id = active(application, request);
136 Session* session = find(application, id.c_str(), client_addr, timeout);
139 HTTPResponse* response = dynamic_cast<HTTPResponse*>(&request);
141 pair<string,const char*> shib_cookie = application.getCookieNameProps("_shibsession_");
142 string exp(shib_cookie.second);
143 exp += "; expires=Mon, 01 Jan 2001 00:00:00 GMT";
144 response->setCookie(shib_cookie.first.c_str(), exp.c_str());
148 HTTPResponse* response = dynamic_cast<HTTPResponse*>(&request);
150 pair<string,const char*> shib_cookie = application.getCookieNameProps("_shibsession_");
151 string exp(shib_cookie.second);
152 exp += "; expires=Mon, 01 Jan 2001 00:00:00 GMT";
153 response->setCookie(shib_cookie.first.c_str(), exp.c_str());
160 void remove(const Application& application, const HTTPRequest& request, HTTPResponse* response=NULL) {
161 pair<string,const char*> shib_cookie = application.getCookieNameProps("_shibsession_");
162 const char* session_id = request.getCookie(shib_cookie.first.c_str());
163 if (session_id && *session_id) {
165 string exp(shib_cookie.second);
166 exp += "; expires=Mon, 01 Jan 2001 00:00:00 GMT";
167 response->setCookie(shib_cookie.first.c_str(), exp.c_str());
169 remove(application, session_id);
177 unsigned long m_cacheTimeout;
179 StorageService* m_storage;
180 StorageService* m_storage_lite;
185 // maintain back-mappings of NameID/SessionIndex -> session key
186 void insert(const char* key, time_t expires, const char* name, const char* index);
187 bool stronglyMatches(const XMLCh* idp, const XMLCh* sp, const saml2::NameID& n1, const saml2::NameID& n2) const;
190 const DOMElement* m_root; // Only valid during initialization
191 unsigned long m_inprocTimeout;
193 // inproc means we buffer sessions in memory
195 map<string,StoredSession*> m_hashtable;
197 // management of buffered sessions
198 void dormant(const char* key);
199 static void* cleanup_fn(void*);
201 CondWait* shutdown_wait;
202 Thread* cleanup_thread;
205 class StoredSession : public virtual Session
208 StoredSession(SSCache* cache, DDF& obj) : m_obj(obj),
212 m_cache(cache), m_expires(0), m_lastAccess(time(NULL)), m_lock(NULL) {
213 auto_ptr_XMLCh exp(m_obj["expires"].string());
215 DateTime iso(exp.get());
217 m_expires = iso.getEpoch();
221 const char* nameid = obj["nameid"].string();
223 // Parse and bind the document into an XMLObject.
224 istringstream instr(nameid);
225 DOMDocument* doc = XMLToolingConfig::getConfig().getParser().parse(instr);
226 XercesJanitor<DOMDocument> janitor(doc);
227 auto_ptr<saml2::NameID> n(saml2::NameIDBuilder::buildNameID());
228 n->unmarshall(doc->getDocumentElement(), true);
230 m_nameid = n.release();
234 m_lock = Mutex::create();
240 for_each(m_attributes.begin(), m_attributes.end(), xmltooling::cleanup<Attribute>());
243 for_each(m_tokens.begin(), m_tokens.end(), cleanup_pair<string,Assertion>());
259 const char* getID() const {
262 const char* getApplicationID() const {
263 return m_obj["application_id"].string();
265 const char* getClientAddress() const {
266 return m_obj["client_addr"].string();
268 const char* getEntityID() const {
269 return m_obj["entity_id"].string();
271 const char* getProtocol() const {
272 return m_obj["protocol"].string();
274 const char* getAuthnInstant() const {
275 return m_obj["authn_instant"].string();
278 const saml2::NameID* getNameID() const {
282 const char* getSessionIndex() const {
283 return m_obj["session_index"].string();
285 const char* getAuthnContextClassRef() const {
286 return m_obj["authncontext_class"].string();
288 const char* getAuthnContextDeclRef() const {
289 return m_obj["authncontext_decl"].string();
291 const vector<Attribute*>& getAttributes() const {
292 if (m_attributes.empty())
293 unmarshallAttributes();
296 const multimap<string,const Attribute*>& getIndexedAttributes() const {
297 if (m_attributeIndex.empty()) {
298 if (m_attributes.empty())
299 unmarshallAttributes();
300 for (vector<Attribute*>::const_iterator a = m_attributes.begin(); a != m_attributes.end(); ++a) {
301 const vector<string>& aliases = (*a)->getAliases();
302 for (vector<string>::const_iterator alias = aliases.begin(); alias != aliases.end(); ++alias)
303 m_attributeIndex.insert(multimap<string,const Attribute*>::value_type(*alias, *a));
306 return m_attributeIndex;
308 const vector<const char*>& getAssertionIDs() const {
310 DDF ids = m_obj["assertions"];
311 DDF id = ids.first();
312 while (id.isstring()) {
313 m_ids.push_back(id.string());
320 void validate(const Application& application, const char* client_addr, time_t* timeout);
323 void addAttributes(const vector<Attribute*>& attributes);
324 const Assertion* getAssertion(const char* id) const;
325 void addAssertion(Assertion* assertion);
328 time_t getExpiration() const { return m_expires; }
329 time_t getLastAccess() const { return m_lastAccess; }
332 void unmarshallAttributes() const;
336 saml2::NameID* m_nameid;
337 mutable map<string,Assertion*> m_tokens;
339 mutable vector<Attribute*> m_attributes;
340 mutable multimap<string,const Attribute*> m_attributeIndex;
341 mutable vector<const char*> m_ids;
344 time_t m_expires,m_lastAccess;
348 SessionCache* SHIBSP_DLLLOCAL StorageServiceCacheFactory(const DOMElement* const & e)
350 return new SSCache(e);
354 Session* SessionCache::find(const Application& application, HTTPRequest& request, const char* client_addr, time_t* timeout)
356 return find(application, const_cast<const HTTPRequest&>(request), client_addr, timeout);
359 void SHIBSP_API shibsp::registerSessionCaches()
361 SPConfig::getConfig().SessionCacheManager.registerFactory(STORAGESERVICE_SESSION_CACHE, StorageServiceCacheFactory);
372 void StoredSession::unmarshallAttributes() const
374 Attribute* attribute;
375 DDF attrs = m_obj["attributes"];
376 DDF attr = attrs.first();
377 while (!attr.isnull()) {
379 attribute = Attribute::unmarshall(attr);
380 m_attributes.push_back(attribute);
381 if (m_cache->m_log.isDebugEnabled())
382 m_cache->m_log.debug("unmarshalled attribute (ID: %s) with %d value%s",
383 attribute->getId(), attr.first().integer(), attr.first().integer()!=1 ? "s" : "");
385 catch (AttributeException& ex) {
386 const char* id = attr.first().name();
387 m_cache->m_log.error("error unmarshalling attribute (ID: %s): %s", id ? id : "none", ex.what());
393 void StoredSession::validate(const Application& application, const char* client_addr, time_t* timeout)
395 time_t now = time(NULL);
399 if (now > m_expires) {
400 m_cache->m_log.info("session expired (ID: %s)", getID());
401 throw RetryableProfileException("Your session has expired, and you must re-authenticate.");
407 if (m_cache->m_log.isDebugEnabled())
408 m_cache->m_log.debug("comparing client address %s against %s", client_addr, getClientAddress());
409 if (!XMLString::equals(getClientAddress(),client_addr)) {
410 m_cache->m_log.warn("client address mismatch");
411 throw RetryableProfileException(
412 "Your IP address ($1) does not match the address recorded at the time the session was established.",
413 params(1,client_addr)
421 if (!SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess)) {
422 DDF in("touch::"STORAGESERVICE_SESSION_CACHE"::SessionCache"), out;
425 in.addmember("key").string(getID());
426 in.addmember("version").integer(m_obj["version"].integer());
428 // On 64-bit Windows, time_t doesn't fit in a long, so I'm using ISO timestamps.
429 #ifndef HAVE_GMTIME_R
430 struct tm* ptime=gmtime(timeout);
433 struct tm* ptime=gmtime_r(timeout,&res);
436 strftime(timebuf,32,"%Y-%m-%dT%H:%M:%SZ",ptime);
437 in.addmember("timeout").string(timebuf);
441 out=application.getServiceProvider().getListenerService()->send(in);
448 if (out.isstruct()) {
449 // We got an updated record back.
451 for_each(m_attributes.begin(), m_attributes.end(), xmltooling::cleanup<Attribute>());
452 m_attributes.clear();
453 m_attributeIndex.clear();
460 if (!m_cache->m_storage)
461 throw ConfigurationException("Session touch requires a StorageService.");
463 // Do a versioned read.
466 int curver = m_obj["version"].integer();
467 int ver = m_cache->m_storage->readText(getID(), "session", &record, &lastAccess, curver);
469 m_cache->m_log.warn("unsuccessful versioned read of session (ID: %s), cache out of sync?", getID());
470 throw RetryableProfileException("Your session has expired, and you must re-authenticate.");
473 // Adjust for expiration to recover last access time and check timeout.
474 lastAccess -= m_cache->m_cacheTimeout;
475 if (*timeout > 0 && now - lastAccess >= *timeout) {
476 m_cache->m_log.info("session timed out (ID: %s)", getID());
477 throw RetryableProfileException("Your session has expired, and you must re-authenticate.");
480 // Update storage expiration, if possible.
482 m_cache->m_storage->updateContext(getID(), now + m_cache->m_cacheTimeout);
484 catch (exception& ex) {
485 m_cache->m_log.error("failed to update session expiration: %s", ex.what());
489 // We got an updated record back.
491 istringstream in(record);
494 for_each(m_attributes.begin(), m_attributes.end(), xmltooling::cleanup<Attribute>());
495 m_attributes.clear();
496 m_attributeIndex.clear();
501 throw ConfigurationException("Session touch requires a StorageService.");
510 void StoredSession::addAttributes(const vector<Attribute*>& attributes)
513 xmltooling::NDC ndc("addAttributes");
516 if (!m_cache->m_storage)
517 throw ConfigurationException("Session modification requires a StorageService.");
519 m_cache->m_log.debug("adding attributes to session (%s)", getID());
524 DDF attrs = m_obj["attributes"];
526 attrs = m_obj.addmember("attributes").list();
527 for (vector<Attribute*>::const_iterator a=attributes.begin(); a!=attributes.end(); ++a) {
528 attr = (*a)->marshall();
532 // Tentatively increment the version.
533 m_obj["version"].integer(m_obj["version"].integer()+1);
537 string record(str.str());
540 ver = m_cache->m_storage->updateText(getID(), "session", record.c_str(), 0, m_obj["version"].integer()-1);
543 // Roll back modification to record.
544 m_obj["version"].integer(m_obj["version"].integer()-1);
545 vector<Attribute*>::size_type count = attributes.size();
547 attrs.last().destroy();
552 // Roll back modification to record.
553 m_obj["version"].integer(m_obj["version"].integer()-1);
554 vector<Attribute*>::size_type count = attributes.size();
556 attrs.last().destroy();
559 // Fatal problem with update.
560 throw IOException("Unable to update stored session.");
564 m_cache->m_log.warn("storage service indicates the record is out of sync, updating with a fresh copy...");
565 ver = m_cache->m_storage->readText(getID(), "session", &record, NULL);
567 m_cache->m_log.error("readText failed on StorageService for session (%s)", getID());
568 throw IOException("Unable to read back stored session.");
573 istringstream in(record);
577 for_each(m_attributes.begin(), m_attributes.end(), xmltooling::cleanup<Attribute>());
578 m_attributes.clear();
579 m_attributeIndex.clear();
580 newobj["version"].integer(ver);
586 } while (ver < 0); // negative indicates a sync issue so we retry
588 TransactionLog* xlog = SPConfig::getConfig().getServiceProvider()->getTransactionLog();
590 xlog->log.infoStream() <<
591 "Added the following attributes to session (ID: " <<
593 ") for (applicationId: " <<
594 m_obj["application_id"].string() <<
596 for (vector<Attribute*>::const_iterator a=attributes.begin(); a!=attributes.end(); ++a)
597 xlog->log.infoStream() << "\t" << (*a)->getId() << " (" << (*a)->valueCount() << " values)";
600 // We own them now, so clean them up.
601 for_each(attributes.begin(), attributes.end(), xmltooling::cleanup<Attribute>());
604 const Assertion* StoredSession::getAssertion(const char* id) const
606 if (!m_cache->m_storage)
607 throw ConfigurationException("Assertion retrieval requires a StorageService.");
609 map<string,Assertion*>::const_iterator i = m_tokens.find(id);
610 if (i!=m_tokens.end())
614 if (!m_cache->m_storage->readText(getID(), id, &tokenstr, NULL))
615 throw FatalProfileException("Assertion not found in cache.");
617 // Parse and bind the document into an XMLObject.
618 istringstream instr(tokenstr);
619 DOMDocument* doc = XMLToolingConfig::getConfig().getParser().parse(instr);
620 XercesJanitor<DOMDocument> janitor(doc);
621 auto_ptr<XMLObject> xmlObject(XMLObjectBuilder::buildOneFromElement(doc->getDocumentElement(), true));
624 Assertion* token = dynamic_cast<Assertion*>(xmlObject.get());
626 throw FatalProfileException("Request for cached assertion returned an unknown object type.");
628 // Transfer ownership to us.
634 void StoredSession::addAssertion(Assertion* assertion)
637 xmltooling::NDC ndc("addAssertion");
640 if (!m_cache->m_storage)
641 throw ConfigurationException("Session modification requires a StorageService.");
644 throw FatalProfileException("Unknown object type passed to session for storage.");
646 auto_ptr_char id(assertion->getID());
648 m_cache->m_log.debug("adding assertion (%s) to session (%s)", id.get(), getID());
651 if (!m_cache->m_storage->readText(getID(), "session", NULL, &exp))
652 throw IOException("Unable to load expiration time for stored session.");
654 ostringstream tokenstr;
655 tokenstr << *assertion;
656 if (!m_cache->m_storage->createText(getID(), id.get(), tokenstr.str().c_str(), exp))
657 throw IOException("Attempted to insert duplicate assertion ID into session.");
661 DDF token = DDF(NULL).string(id.get());
662 m_obj["assertions"].add(token);
664 // Tentatively increment the version.
665 m_obj["version"].integer(m_obj["version"].integer()+1);
669 string record(str.str());
672 ver = m_cache->m_storage->updateText(getID(), "session", record.c_str(), 0, m_obj["version"].integer()-1);
676 m_obj["version"].integer(m_obj["version"].integer()-1);
677 m_cache->m_storage->deleteText(getID(), id.get());
683 m_obj["version"].integer(m_obj["version"].integer()-1);
686 // Fatal problem with update.
687 m_cache->m_log.error("updateText failed on StorageService for session (%s)", getID());
688 m_cache->m_storage->deleteText(getID(), id.get());
689 throw IOException("Unable to update stored session.");
693 m_cache->m_log.warn("storage service indicates the record is out of sync, updating with a fresh copy...");
694 ver = m_cache->m_storage->readText(getID(), "session", &record, NULL);
696 m_cache->m_log.error("readText failed on StorageService for session (%s)", getID());
697 m_cache->m_storage->deleteText(getID(), id.get());
698 throw IOException("Unable to read back stored session.");
703 istringstream in(record);
707 for_each(m_attributes.begin(), m_attributes.end(), xmltooling::cleanup<Attribute>());
708 m_attributes.clear();
709 m_attributeIndex.clear();
710 newobj["version"].integer(ver);
716 } while (ver < 0); // negative indicates a sync issue so we retry
721 TransactionLog* xlog = SPConfig::getConfig().getServiceProvider()->getTransactionLog();
724 "Added assertion (ID: %s) to session for (applicationId: %s) with (ID: %s)",
725 id.get(), m_obj["application_id"].string(), getID()
731 SessionCache::SessionCache()
735 SessionCache::~SessionCache()
739 SessionCacheEx::SessionCacheEx()
743 SessionCacheEx::~SessionCacheEx()
747 SSCache::SSCache(const DOMElement* e)
748 : m_log(Category::getInstance(SHIBSP_LOGCAT".SessionCache")), inproc(true), m_cacheTimeout(28800),
750 m_storage(NULL), m_storage_lite(NULL),
752 m_root(e), m_inprocTimeout(900), m_lock(NULL), shutdown(false), shutdown_wait(NULL), cleanup_thread(NULL)
754 static const XMLCh cacheTimeout[] = UNICODE_LITERAL_12(c,a,c,h,e,T,i,m,e,o,u,t);
755 static const XMLCh inprocTimeout[] = UNICODE_LITERAL_13(i,n,p,r,o,c,T,i,m,e,o,u,t);
756 static const XMLCh _StorageService[] = UNICODE_LITERAL_14(S,t,o,r,a,g,e,S,e,r,v,i,c,e);
757 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);
759 SPConfig& conf = SPConfig::getConfig();
760 inproc = conf.isEnabled(SPConfig::InProcess);
763 const XMLCh* tag=e->getAttributeNS(NULL,cacheTimeout);
765 m_cacheTimeout = XMLString::parseInt(tag);
767 m_cacheTimeout=28800;
770 const XMLCh* tag=e->getAttributeNS(NULL,inprocTimeout);
772 m_inprocTimeout = XMLString::parseInt(tag);
773 if (!m_inprocTimeout)
780 if (conf.isEnabled(SPConfig::OutOfProcess)) {
781 const XMLCh* tag = e ? e->getAttributeNS(NULL,_StorageService) : NULL;
783 auto_ptr_char ssid(tag);
784 m_storage = conf.getServiceProvider()->getStorageService(ssid.get());
786 m_log.info("bound to StorageService (%s)", ssid.get());
789 throw ConfigurationException("SessionCache unable to locate StorageService, check configuration.");
791 tag = e ? e->getAttributeNS(NULL,_StorageServiceLite) : NULL;
793 auto_ptr_char ssid(tag);
794 m_storage_lite = conf.getServiceProvider()->getStorageService(ssid.get());
796 m_log.info("bound to StorageServiceLite (%s)", ssid.get());
798 if (!m_storage_lite) {
799 m_log.info("No StorageServiceLite specified. Using standard StorageService.");
800 m_storage_lite = m_storage;
805 ListenerService* listener=conf.getServiceProvider()->getListenerService(false);
807 if (!conf.isEnabled(SPConfig::OutOfProcess) && !listener)
808 throw ConfigurationException("SessionCache requires a ListenerService, but none available.");
809 m_lock = RWLock::create();
810 shutdown_wait = CondWait::create();
811 cleanup_thread = Thread::create(&cleanup_fn, (void*)this);
815 if (listener && conf.isEnabled(SPConfig::OutOfProcess)) {
816 listener->regListener("find::"STORAGESERVICE_SESSION_CACHE"::SessionCache",this);
817 listener->regListener("remove::"STORAGESERVICE_SESSION_CACHE"::SessionCache",this);
818 listener->regListener("touch::"STORAGESERVICE_SESSION_CACHE"::SessionCache",this);
821 m_log.info("no ListenerService available, cache remoting disabled");
830 // Shut down the cleanup thread and let it know...
832 shutdown_wait->signal();
833 cleanup_thread->join(NULL);
835 for_each(m_hashtable.begin(),m_hashtable.end(),cleanup_pair<string,StoredSession>());
837 delete shutdown_wait;
841 SPConfig& conf = SPConfig::getConfig();
842 ListenerService* listener=conf.getServiceProvider()->getListenerService(false);
843 if (listener && conf.isEnabled(SPConfig::OutOfProcess)) {
844 listener->unregListener("find::"STORAGESERVICE_SESSION_CACHE"::SessionCache",this);
845 listener->unregListener("remove::"STORAGESERVICE_SESSION_CACHE"::SessionCache",this);
846 listener->unregListener("touch::"STORAGESERVICE_SESSION_CACHE"::SessionCache",this);
856 auto_ptr_char temp(SAMLConfig::getConfig().generateIdentifier());
857 m_storage->createString("SessionCacheTest", temp.get(), "Test", time(NULL) + 60);
858 m_storage->deleteString("SessionCacheTest", temp.get());
861 void SSCache::insert(const char* key, time_t expires, const char* name, const char* index)
864 if (strlen(name) > 255) {
865 dup = string(name).substr(0,255);
870 DDFJanitor jobj(obj);
872 // Since we can't guarantee uniqueness, check for an existing record.
875 int ver = m_storage_lite->readText("NameID", name, &record, &recordexp);
877 // Existing record, so we need to unmarshall it.
878 istringstream in(record);
883 obj = DDF(NULL).structure();
886 if (!index || !*index)
888 DDF sessions = obj.addmember(index);
889 if (!sessions.islist())
891 DDF session = DDF(NULL).string(key);
892 sessions.add(session);
894 // Remarshall the record.
898 // Try and store it back...
900 ver = m_storage_lite->updateText("NameID", name, out.str().c_str(), max(expires, recordexp), ver);
902 // Out of sync, or went missing, so retry.
903 return insert(key, expires, name, index);
906 else if (!m_storage_lite->createText("NameID", name, out.str().c_str(), expires)) {
907 // Hit a dup, so just retry, hopefully hitting the other branch.
908 return insert(key, expires, name, index);
912 void SSCache::insert(
913 const Application& application,
914 const HTTPRequest& httpRequest,
915 HTTPResponse& httpResponse,
917 const saml2md::EntityDescriptor* issuer,
918 const XMLCh* protocol,
919 const saml2::NameID* nameid,
920 const XMLCh* authn_instant,
921 const XMLCh* session_index,
922 const XMLCh* authncontext_class,
923 const XMLCh* authncontext_decl,
924 const vector<const Assertion*>* tokens,
925 const vector<Attribute*>* attributes
929 xmltooling::NDC ndc("insert");
932 throw ConfigurationException("SessionCache insertion requires a StorageService.");
934 m_log.debug("creating new session");
936 time_t now = time(NULL);
937 auto_ptr_char index(session_index);
938 auto_ptr_char entity_id(issuer ? issuer->getEntityID() : NULL);
939 auto_ptr_char name(nameid ? nameid->getName() : NULL);
942 // Check for a pending logout.
943 if (strlen(name.get()) > 255)
944 const_cast<char*>(name.get())[255] = 0;
946 int ver = m_storage_lite->readText("Logout", name.get(), &pending);
949 DDFJanitor jpend(pendobj);
950 istringstream pstr(pending);
952 // IdP.SP.index contains logout expiration, if any.
953 DDF deadmenwalking = pendobj[issuer ? entity_id.get() : "_shibnull"][application.getRelyingParty(issuer)->getString("entityID").second];
954 const char* logexpstr = deadmenwalking[session_index ? index.get() : "_shibnull"].string();
955 if (!logexpstr && session_index) // we tried an exact session match, now try for NULL
956 logexpstr = deadmenwalking["_shibnull"].string();
958 auto_ptr_XMLCh dt(logexpstr);
959 DateTime dtobj(dt.get());
960 dtobj.parseDateTime();
961 time_t logexp = dtobj.getEpoch();
962 if (now - XMLToolingConfig::getConfig().clock_skew_secs < logexp)
963 throw FatalProfileException("A logout message from your identity provider has blocked your login attempt.");
968 auto_ptr_char key(SAMLConfig::getConfig().generateIdentifier());
970 // Store session properties in DDF.
971 DDF obj = DDF(key.get()).structure();
972 DDFJanitor entryobj(obj);
973 obj.addmember("version").integer(1);
974 obj.addmember("application_id").string(application.getId());
976 // On 64-bit Windows, time_t doesn't fit in a long, so I'm using ISO timestamps.
977 #ifndef HAVE_GMTIME_R
978 struct tm* ptime=gmtime(&expires);
981 struct tm* ptime=gmtime_r(&expires,&res);
984 strftime(timebuf,32,"%Y-%m-%dT%H:%M:%SZ",ptime);
985 obj.addmember("expires").string(timebuf);
987 obj.addmember("client_addr").string(httpRequest.getRemoteAddr().c_str());
989 obj.addmember("entity_id").string(entity_id.get());
991 auto_ptr_char prot(protocol);
992 obj.addmember("protocol").string(prot.get());
995 auto_ptr_char instant(authn_instant);
996 obj.addmember("authn_instant").string(instant.get());
999 obj.addmember("session_index").string(index.get());
1000 if (authncontext_class) {
1001 auto_ptr_char ac(authncontext_class);
1002 obj.addmember("authncontext_class").string(ac.get());
1004 if (authncontext_decl) {
1005 auto_ptr_char ad(authncontext_decl);
1006 obj.addmember("authncontext_decl").string(ad.get());
1010 ostringstream namestr;
1012 obj.addmember("nameid").string(namestr.str().c_str());
1016 obj.addmember("assertions").list();
1017 for (vector<const Assertion*>::const_iterator t = tokens->begin(); t!=tokens->end(); ++t) {
1018 auto_ptr_char tokenid((*t)->getID());
1019 DDF tokid = DDF(NULL).string(tokenid.get());
1020 obj["assertions"].add(tokid);
1026 DDF attrlist = obj.addmember("attributes").list();
1027 for (vector<Attribute*>::const_iterator a=attributes->begin(); a!=attributes->end(); ++a) {
1028 attr = (*a)->marshall();
1033 ostringstream record;
1036 m_log.debug("storing new session...");
1037 if (!m_storage->createText(key.get(), "session", record.str().c_str(), now + m_cacheTimeout))
1038 throw FatalProfileException("Attempted to create a session with a duplicate key.");
1040 // Store the reverse mapping for logout.
1043 insert(key.get(), expires, name.get(), index.get());
1045 catch (exception& ex) {
1046 m_log.error("error storing back mapping of NameID for logout: %s", ex.what());
1051 for (vector<const Assertion*>::const_iterator t = tokens->begin(); t!=tokens->end(); ++t) {
1052 ostringstream tokenstr;
1054 auto_ptr_char tokenid((*t)->getID());
1055 if (!m_storage->createText(key.get(), tokenid.get(), tokenstr.str().c_str(), now + m_cacheTimeout))
1056 throw IOException("duplicate assertion ID ($1)", params(1, tokenid.get()));
1059 catch (exception& ex) {
1060 m_log.error("error storing assertion along with session: %s", ex.what());
1064 const char* pid = obj["entity_id"].string();
1065 const char* prot = obj["protocol"].string();
1066 m_log.info("new session created: ID (%s) IdP (%s) Protocol(%s) Address (%s)",
1067 key.get(), pid ? pid : "none", prot ? prot : "none", httpRequest.getRemoteAddr().c_str());
1069 // Transaction Logging
1070 TransactionLog* xlog = application.getServiceProvider().getTransactionLog();
1071 Locker locker(xlog);
1072 xlog->log.infoStream() <<
1073 "New session (ID: " <<
1075 ") with (applicationId: " <<
1076 application.getId() <<
1077 ") for principal from (IdP: " <<
1078 (pid ? pid : "none") <<
1079 ") at (ClientAddress: " <<
1080 httpRequest.getRemoteAddr() <<
1081 ") with (NameIdentifier: " <<
1082 (nameid ? name.get() : "none") <<
1083 ") using (Protocol: " <<
1084 (prot ? prot : "none") <<
1085 ") from (AssertionID: " <<
1086 (tokens ? obj["assertions"].first().string() : "none") <<
1090 xlog->log.infoStream() <<
1091 "Cached the following attributes with session (ID: " <<
1093 ") for (applicationId: " <<
1094 application.getId() <<
1096 for (vector<Attribute*>::const_iterator a=attributes->begin(); a!=attributes->end(); ++a)
1097 xlog->log.infoStream() << "\t" << (*a)->getId() << " (" << (*a)->valueCount() << " values)";
1098 xlog->log.info("}");
1101 time_t cookieLifetime = 0;
1102 pair<string,const char*> shib_cookie = application.getCookieNameProps("_shibsession_", &cookieLifetime);
1103 string k(key.get());
1104 k += shib_cookie.second;
1106 if (cookieLifetime > 0) {
1107 cookieLifetime += now;
1108 #ifndef HAVE_GMTIME_R
1109 ptime=gmtime(&cookieLifetime);
1111 ptime=gmtime_r(&cookieLifetime,&res);
1113 char cookietimebuf[64];
1114 strftime(cookietimebuf,64,"; expires=%a, %d %b %Y %H:%M:%S GMT",ptime);
1118 httpResponse.setCookie(shib_cookie.first.c_str(), k.c_str());
1121 bool SSCache::matches(
1122 const Application& application,
1123 const xmltooling::HTTPRequest& request,
1124 const saml2md::EntityDescriptor* issuer,
1125 const saml2::NameID& nameid,
1126 const set<string>* indexes
1129 auto_ptr_char entityID(issuer ? issuer->getEntityID() : NULL);
1131 Session* session = find(application, request);
1133 Locker locker(session, false);
1134 if (XMLString::equals(session->getEntityID(), entityID.get()) && session->getNameID() &&
1135 stronglyMatches(issuer->getEntityID(), application.getRelyingParty(issuer)->getXMLString("entityID").second, nameid, *session->getNameID())) {
1136 return (!indexes || indexes->empty() || (session->getSessionIndex() ? (indexes->count(session->getSessionIndex())>0) : false));
1140 catch (exception& ex) {
1141 m_log.error("error while matching session: %s", ex.what());
1146 vector<string>::size_type SSCache::logout(
1147 const Application& application,
1148 const saml2md::EntityDescriptor* issuer,
1149 const saml2::NameID& nameid,
1150 const set<string>* indexes,
1152 vector<string>& sessionsKilled
1156 xmltooling::NDC ndc("logout");
1160 throw ConfigurationException("SessionCache insertion requires a StorageService.");
1162 auto_ptr_char entityID(issuer ? issuer->getEntityID() : NULL);
1163 auto_ptr_char name(nameid.getName());
1165 m_log.info("request to logout sessions from (%s) for (%s)", entityID.get() ? entityID.get() : "unknown", name.get());
1167 if (strlen(name.get()) > 255)
1168 const_cast<char*>(name.get())[255] = 0;
1171 DDFJanitor jobj(obj);
1176 // Record the logout to prevent post-delivered assertions.
1177 // On 64-bit Windows, time_t doesn't fit in a long, so I'm using ISO timestamps.
1178 #ifndef HAVE_GMTIME_R
1179 struct tm* ptime=gmtime(&expires);
1182 struct tm* ptime=gmtime_r(&expires,&res);
1185 strftime(timebuf,32,"%Y-%m-%dT%H:%M:%SZ",ptime);
1188 ver = m_storage_lite->readText("Logout", name.get(), &record, &oldexp);
1190 istringstream lin(record);
1194 obj = DDF(NULL).structure();
1197 // Structure is keyed by the IdP and SP, with a member per session index containing the expiration.
1198 DDF root = obj.addmember(issuer ? entityID.get() : "_shibnull").addmember(application.getRelyingParty(issuer)->getString("entityID").second);
1200 for (set<string>::const_iterator x = indexes->begin(); x!=indexes->end(); ++x)
1201 root.addmember(x->c_str()).string(timebuf);
1204 root.addmember("_shibnull").string(timebuf);
1212 ver = m_storage_lite->updateText("Logout", name.get(), lout.str().c_str(), max(expires, oldexp), ver);
1214 // Out of sync, or went missing, so retry.
1215 return logout(application, issuer, nameid, indexes, expires, sessionsKilled);
1218 else if (!m_storage_lite->createText("Logout", name.get(), lout.str().c_str(), expires)) {
1219 // Hit a dup, so just retry, hopefully hitting the other branch.
1220 return logout(application, issuer, nameid, indexes, expires, sessionsKilled);
1227 // Read in potentially matching sessions.
1228 ver = m_storage_lite->readText("NameID", name.get(), &record);
1230 m_log.debug("no active sessions to logout for supplied issuer and subject");
1234 istringstream in(record);
1237 // The record contains child lists for each known session index.
1239 DDF sessions = obj.first();
1240 while (sessions.islist()) {
1241 if (!indexes || indexes->empty() || indexes->count(sessions.name())) {
1242 key = sessions.first();
1243 while (key.isstring()) {
1244 // Fetch the session for comparison.
1245 Session* session = NULL;
1247 session = find(application, key.string());
1249 catch (exception& ex) {
1250 m_log.error("error locating session (%s): %s", key.string(), ex.what());
1254 Locker locker(session, false);
1256 if (XMLString::equals(session->getEntityID(), entityID.get())) {
1258 if (stronglyMatches(issuer->getEntityID(), application.getRelyingParty(issuer)->getXMLString("entityID").second, nameid, *session->getNameID())) {
1259 sessionsKilled.push_back(key.string());
1263 m_log.debug("session (%s) contained a non-matching NameID, leaving it alone", key.string());
1267 m_log.debug("session (%s) established by different IdP, leaving it alone", key.string());
1271 // Session's gone, so...
1272 sessionsKilled.push_back(key.string());
1275 key = sessions.next();
1278 // No sessions left for this index?
1279 if (sessions.first().isnull())
1282 sessions = obj.next();
1285 if (obj.first().isnull())
1288 // If possible, write back the mapping record (this isn't crucial).
1291 m_storage_lite->deleteText("NameID", name.get());
1293 else if (!sessionsKilled.empty()) {
1296 if (m_storage_lite->updateText("NameID", name.get(), out.str().c_str(), 0, ver) <= 0)
1297 m_log.warn("logout mapping record changed behind us, leaving it alone");
1300 catch (exception& ex) {
1301 m_log.error("error updating logout mapping record: %s", ex.what());
1304 return sessionsKilled.size();
1307 bool SSCache::stronglyMatches(const XMLCh* idp, const XMLCh* sp, const saml2::NameID& n1, const saml2::NameID& n2) const
1309 if (!XMLString::equals(n1.getName(), n2.getName()))
1312 const XMLCh* s1 = n1.getFormat();
1313 const XMLCh* s2 = n2.getFormat();
1315 s1 = saml2::NameID::UNSPECIFIED;
1317 s2 = saml2::NameID::UNSPECIFIED;
1318 if (!XMLString::equals(s1,s2))
1321 s1 = n1.getNameQualifier();
1322 s2 = n2.getNameQualifier();
1327 if (!XMLString::equals(s1,s2))
1330 s1 = n1.getSPNameQualifier();
1331 s2 = n2.getSPNameQualifier();
1336 if (!XMLString::equals(s1,s2))
1344 Session* SSCache::find(const Application& application, const char* key, const char* client_addr, time_t* timeout)
1347 xmltooling::NDC ndc("find");
1349 StoredSession* session=NULL;
1352 m_log.debug("searching local cache for session (%s)", key);
1354 map<string,StoredSession*>::const_iterator i=m_hashtable.find(key);
1355 if (i!=m_hashtable.end()) {
1356 // Save off and lock the session.
1357 session = i->second;
1360 m_log.debug("session found locally, validating it for use");
1368 if (!SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess)) {
1369 m_log.debug("session not found locally, remoting the search");
1370 // Remote the request.
1371 DDF in("find::"STORAGESERVICE_SESSION_CACHE"::SessionCache"), out;
1374 in.addmember("key").string(key);
1375 in.addmember("application_id").string(application.getId());
1376 if (timeout && *timeout) {
1377 // On 64-bit Windows, time_t doesn't fit in a long, so I'm using ISO timestamps.
1378 #ifndef HAVE_GMTIME_R
1379 struct tm* ptime=gmtime(timeout);
1382 struct tm* ptime=gmtime_r(timeout,&res);
1385 strftime(timebuf,32,"%Y-%m-%dT%H:%M:%SZ",ptime);
1386 in.addmember("timeout").string(timebuf);
1390 out=application.getServiceProvider().getListenerService()->send(in);
1391 if (!out.isstruct()) {
1393 m_log.debug("session not found in remote cache");
1397 // Wrap the results in a local entry and save it.
1398 session = new StoredSession(this, out);
1399 // The remote end has handled timeout issues, we handle address and expiration checks.
1408 // We're out of process, so we can search the storage service directly.
1411 throw ConfigurationException("SessionCache lookup requires a StorageService.");
1413 m_log.debug("searching for session (%s)", key);
1418 int ver = m_storage->readText(key, "session", &record, &lastAccess);
1422 m_log.debug("reconstituting session and checking validity");
1424 istringstream in(record);
1427 lastAccess -= m_cacheTimeout; // adjusts it back to the last time the record's timestamp was touched
1428 time_t now=time(NULL);
1430 if (timeout && *timeout > 0 && now - lastAccess >= *timeout) {
1431 m_log.info("session timed out (ID: %s)", key);
1432 remove(application, key);
1433 const char* eid = obj["entity_id"].string();
1436 throw RetryableProfileException("Your session has expired, and you must re-authenticate.");
1440 throw RetryableProfileException("Your session has expired, and you must re-authenticate.", namedparams(1, "entityID", eid2.c_str()));
1444 // Update storage expiration, if possible.
1446 m_storage->updateContext(key, now + m_cacheTimeout);
1448 catch (exception& ex) {
1449 m_log.error("failed to update session expiration: %s", ex.what());
1453 // Wrap the results in a local entry and save it.
1454 session = new StoredSession(this, obj);
1455 // We handled timeout issues, still need to handle address and expiration checks.
1458 throw ConfigurationException("SessionCache search requires a StorageService.");
1463 // Lock for writing and repeat the search to avoid duplication.
1465 SharedLock shared(m_lock, false);
1466 if (m_hashtable.count(key)) {
1467 // We're using an existing session entry.
1469 session = m_hashtable[key];
1473 m_hashtable[key]=session;
1479 if (!XMLString::equals(session->getApplicationID(), application.getId())) {
1480 m_log.error("an application (%s) tried to access another application's session", application.getId());
1485 // Verify currency and update the timestamp if indicated by caller.
1487 session->validate(application, client_addr, timeout);
1491 remove(application, key);
1498 void SSCache::remove(const Application& application, const char* key)
1501 xmltooling::NDC ndc("remove");
1503 // Take care of local copy.
1507 if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess)) {
1508 // Remove the session from storage directly.
1510 m_storage->deleteContext(key);
1511 m_log.info("removed session (%s)", key);
1513 TransactionLog* xlog = application.getServiceProvider().getTransactionLog();
1514 Locker locker(xlog);
1515 xlog->log.info("Destroyed session (applicationId: %s) (ID: %s)", application.getId(), key);
1517 throw ConfigurationException("SessionCache removal requires a StorageService.");
1521 // Remote the request.
1522 DDF in("remove::"STORAGESERVICE_SESSION_CACHE"::SessionCache");
1525 in.addmember("key").string(key);
1526 in.addmember("application_id").string(application.getId());
1528 DDF out = application.getServiceProvider().getListenerService()->send(in);
1533 void SSCache::dormant(const char* key)
1536 xmltooling::NDC ndc("dormant");
1539 m_log.debug("deleting local copy of session (%s)", key);
1541 // lock the cache for writing, which means we know nobody is sitting in find()
1544 // grab the entry from the table
1545 map<string,StoredSession*>::const_iterator i=m_hashtable.find(key);
1546 if (i==m_hashtable.end()) {
1551 // ok, remove the entry and lock it
1552 StoredSession* entry=i->second;
1553 m_hashtable.erase(key);
1559 // we can release the cache entry lock because we know we're not in the cache anymore
1565 void SSCache::cleanup()
1568 xmltooling::NDC ndc("cleanup");
1571 Mutex* mutex = Mutex::create();
1573 // Load our configuration details...
1574 static const XMLCh cleanupInterval[] = UNICODE_LITERAL_15(c,l,e,a,n,u,p,I,n,t,e,r,v,a,l);
1575 const XMLCh* tag=m_root ? m_root->getAttributeNS(NULL,cleanupInterval) : NULL;
1576 int rerun_timer = 900;
1578 rerun_timer = XMLString::parseInt(tag);
1579 if (rerun_timer <= 0)
1585 m_log.info("cleanup thread started...run every %d secs; timeout after %d secs", rerun_timer, m_inprocTimeout);
1588 shutdown_wait->timedwait(mutex,rerun_timer);
1592 // Ok, let's run through the cleanup process and clean out
1593 // really old sessions. This is a two-pass process. The
1594 // first pass is done holding a read-lock while we iterate over
1595 // the cache. The second pass doesn't need a lock because
1596 // the 'deletes' will lock the cache.
1598 // Pass 1: iterate over the map and find all entries that have not been
1599 // used in the allotted timeout.
1600 vector<string> stale_keys;
1601 time_t stale = time(NULL) - m_inprocTimeout;
1603 m_log.debug("cleanup thread running");
1606 for (map<string,StoredSession*>::const_iterator i=m_hashtable.begin(); i!=m_hashtable.end(); ++i) {
1607 // If the last access was BEFORE the stale timeout...
1609 time_t last=i->second->getLastAccess();
1610 i->second->unlock();
1612 stale_keys.push_back(i->first);
1616 if (!stale_keys.empty()) {
1617 m_log.info("purging %d old sessions", stale_keys.size());
1619 // Pass 2: walk through the list of stale entries and remove them from the cache
1620 for (vector<string>::const_iterator j = stale_keys.begin(); j != stale_keys.end(); ++j)
1621 dormant(j->c_str());
1624 m_log.debug("cleanup thread completed");
1627 m_log.info("cleanup thread exiting");
1634 void* SSCache::cleanup_fn(void* cache_p)
1637 // First, let's block all signals
1638 Thread::mask_all_signals();
1641 // Now run the cleanup process.
1642 reinterpret_cast<SSCache*>(cache_p)->cleanup();
1648 void SSCache::receive(DDF& in, ostream& out)
1651 xmltooling::NDC ndc("receive");
1654 if (!strcmp(in.name(),"find::"STORAGESERVICE_SESSION_CACHE"::SessionCache")) {
1655 const char* key=in["key"].string();
1657 throw ListenerException("Required parameters missing for session lookup.");
1659 const Application* app = SPConfig::getConfig().getServiceProvider()->getApplication(in["application_id"].string());
1661 throw ListenerException("Application not found, check configuration?");
1663 // Do an unversioned read.
1666 if (!m_storage->readText(key, "session", &record, &lastAccess)) {
1668 DDFJanitor jan(ret);
1673 // Adjust for expiration to recover last access time and check timeout.
1674 lastAccess -= m_cacheTimeout;
1675 time_t now=time(NULL);
1677 // See if we need to check for a timeout.
1678 if (in["timeout"].string()) {
1680 auto_ptr_XMLCh dt(in["timeout"].string());
1681 DateTime dtobj(dt.get());
1682 dtobj.parseDateTime();
1683 timeout = dtobj.getEpoch();
1685 if (timeout > 0 && now - lastAccess >= timeout) {
1686 m_log.info("session timed out (ID: %s)", key);
1688 throw RetryableProfileException("Your session has expired, and you must re-authenticate.");
1691 // Update storage expiration, if possible.
1693 m_storage->updateContext(key, now + m_cacheTimeout);
1695 catch (exception& ex) {
1696 m_log.error("failed to update session expiration: %s", ex.what());
1700 // Send the record back.
1703 else if (!strcmp(in.name(),"touch::"STORAGESERVICE_SESSION_CACHE"::SessionCache")) {
1704 const char* key=in["key"].string();
1706 throw ListenerException("Required parameters missing for session check.");
1708 // Do a versioned read.
1711 int curver = in["version"].integer();
1712 int ver = m_storage->readText(key, "session", &record, &lastAccess, curver);
1714 m_log.warn("unsuccessful versioned read of session (ID: %s), caches out of sync?", key);
1715 throw RetryableProfileException("Your session has expired, and you must re-authenticate.");
1718 // Adjust for expiration to recover last access time and check timeout.
1719 lastAccess -= m_cacheTimeout;
1720 time_t now=time(NULL);
1722 // See if we need to check for a timeout.
1724 auto_ptr_XMLCh dt(in["timeout"].string());
1726 DateTime dtobj(dt.get());
1727 dtobj.parseDateTime();
1728 timeout = dtobj.getEpoch();
1731 if (timeout > 0 && now - lastAccess >= timeout) {
1732 m_log.info("session timed out (ID: %s)", key);
1733 throw RetryableProfileException("Your session has expired, and you must re-authenticate.");
1736 // Update storage expiration, if possible.
1738 m_storage->updateContext(key, now + m_cacheTimeout);
1740 catch (exception& ex) {
1741 m_log.error("failed to update session expiration: %s", ex.what());
1745 // Send the record back.
1750 DDFJanitor jan(ret);
1754 else if (!strcmp(in.name(),"remove::"STORAGESERVICE_SESSION_CACHE"::SessionCache")) {
1755 const char* key=in["key"].string();
1757 throw ListenerException("Required parameter missing for session removal.");
1759 const Application* app = SPConfig::getConfig().getServiceProvider()->getApplication(in["application_id"].string());
1761 throw ConfigurationException("Application not found, check configuration?");
1765 DDFJanitor jan(ret);