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/util/NDC.h>
43 #include <xmltooling/util/XMLHelper.h>
44 #include <xercesc/util/XMLUniDefs.hpp>
47 # include <saml/SAMLConfig.h>
48 # include <xmltooling/XMLToolingConfig.h>
49 # include <xmltooling/util/StorageService.h>
50 using namespace opensaml::saml2md;
53 # include <xmltooling/util/DateTime.h>
56 using namespace shibsp;
57 using namespace opensaml;
58 using namespace xmltooling;
64 class SSCache : public SessionCacheEx
66 ,public virtual Remoted
70 SSCache(const DOMElement* e);
74 void receive(DDF& in, ostream& out);
77 const Application& application,
78 const HTTPRequest& httpRequest,
79 HTTPResponse& httpResponse,
81 const saml2md::EntityDescriptor* issuer=NULL,
82 const XMLCh* protocol=NULL,
83 const saml2::NameID* nameid=NULL,
84 const XMLCh* authn_instant=NULL,
85 const XMLCh* session_index=NULL,
86 const XMLCh* authncontext_class=NULL,
87 const XMLCh* authncontext_decl=NULL,
88 const vector<const Assertion*>* tokens=NULL,
89 const vector<Attribute*>* attributes=NULL
91 vector<string>::size_type logout(
92 const Application& application,
93 const saml2md::EntityDescriptor* issuer,
94 const saml2::NameID& nameid,
95 const set<string>* indexes,
97 vector<string>& sessions
100 const Application& application,
101 const xmltooling::HTTPRequest& request,
102 const saml2md::EntityDescriptor* issuer,
103 const saml2::NameID& nameid,
104 const set<string>* indexes
107 Session* find(const Application& application, const char* key, const char* client_addr=NULL, time_t* timeout=NULL);
108 void remove(const Application& application, const char* key);
111 string active(const Application& application, const xmltooling::HTTPRequest& request) {
112 pair<string,const char*> shib_cookie = application.getCookieNameProps("_shibsession_");
113 const char* session_id = request.getCookie(shib_cookie.first.c_str());
114 return (session_id ? session_id : "");
117 Session* find(const Application& application, const HTTPRequest& request, const char* client_addr=NULL, time_t* timeout=NULL) {
118 string id = active(application, request);
120 return find(application, id.c_str(), client_addr, timeout);
124 Session* find(const Application& application, HTTPRequest& request, const char* client_addr=NULL, time_t* timeout=NULL) {
125 string id = active(application, request);
129 Session* session = find(application, id.c_str(), client_addr, timeout);
132 HTTPResponse* response = dynamic_cast<HTTPResponse*>(&request);
134 pair<string,const char*> shib_cookie = application.getCookieNameProps("_shibsession_");
135 string exp(shib_cookie.second);
136 exp += "; expires=Mon, 01 Jan 2001 00:00:00 GMT";
137 response->setCookie(shib_cookie.first.c_str(), exp.c_str());
141 HTTPResponse* response = dynamic_cast<HTTPResponse*>(&request);
143 pair<string,const char*> shib_cookie = application.getCookieNameProps("_shibsession_");
144 string exp(shib_cookie.second);
145 exp += "; expires=Mon, 01 Jan 2001 00:00:00 GMT";
146 response->setCookie(shib_cookie.first.c_str(), exp.c_str());
153 void remove(const Application& application, const HTTPRequest& request, HTTPResponse* response=NULL) {
154 pair<string,const char*> shib_cookie = application.getCookieNameProps("_shibsession_");
155 const char* session_id = request.getCookie(shib_cookie.first.c_str());
156 if (session_id && *session_id) {
158 string exp(shib_cookie.second);
159 exp += "; expires=Mon, 01 Jan 2001 00:00:00 GMT";
160 response->setCookie(shib_cookie.first.c_str(), exp.c_str());
162 remove(application, session_id);
170 unsigned long m_cacheTimeout;
172 StorageService* m_storage;
173 StorageService* m_storage_lite;
178 // maintain back-mappings of NameID/SessionIndex -> session key
179 void insert(const char* key, time_t expires, const char* name, const char* index);
180 bool stronglyMatches(const XMLCh* idp, const XMLCh* sp, const saml2::NameID& n1, const saml2::NameID& n2) const;
183 const DOMElement* m_root; // Only valid during initialization
184 unsigned long m_inprocTimeout;
186 // inproc means we buffer sessions in memory
188 map<string,StoredSession*> m_hashtable;
190 // management of buffered sessions
191 void dormant(const char* key);
192 static void* cleanup_fn(void*);
194 CondWait* shutdown_wait;
195 Thread* cleanup_thread;
198 class StoredSession : public virtual Session
201 StoredSession(SSCache* cache, DDF& obj) : m_obj(obj),
205 m_cache(cache), m_expires(0), m_lastAccess(time(NULL)), m_lock(NULL) {
206 auto_ptr_XMLCh exp(m_obj["expires"].string());
208 DateTime iso(exp.get());
210 m_expires = iso.getEpoch();
214 const char* nameid = obj["nameid"].string();
216 // Parse and bind the document into an XMLObject.
217 istringstream instr(nameid);
218 DOMDocument* doc = XMLToolingConfig::getConfig().getParser().parse(instr);
219 XercesJanitor<DOMDocument> janitor(doc);
220 auto_ptr<saml2::NameID> n(saml2::NameIDBuilder::buildNameID());
221 n->unmarshall(doc->getDocumentElement(), true);
223 m_nameid = n.release();
227 m_lock = Mutex::create();
233 for_each(m_attributes.begin(), m_attributes.end(), xmltooling::cleanup<Attribute>());
236 for_each(m_tokens.begin(), m_tokens.end(), cleanup_pair<string,Assertion>());
252 const char* getID() const {
255 const char* getApplicationID() const {
256 return m_obj["application_id"].string();
258 const char* getClientAddress() const {
259 return m_obj["client_addr"].string();
261 const char* getEntityID() const {
262 return m_obj["entity_id"].string();
264 const char* getProtocol() const {
265 return m_obj["protocol"].string();
267 const char* getAuthnInstant() const {
268 return m_obj["authn_instant"].string();
271 const saml2::NameID* getNameID() const {
275 const char* getSessionIndex() const {
276 return m_obj["session_index"].string();
278 const char* getAuthnContextClassRef() const {
279 return m_obj["authncontext_class"].string();
281 const char* getAuthnContextDeclRef() const {
282 return m_obj["authncontext_decl"].string();
284 const vector<Attribute*>& getAttributes() const {
285 if (m_attributes.empty())
286 unmarshallAttributes();
289 const multimap<string,const Attribute*>& getIndexedAttributes() const {
290 if (m_attributeIndex.empty()) {
291 if (m_attributes.empty())
292 unmarshallAttributes();
293 for (vector<Attribute*>::const_iterator a = m_attributes.begin(); a != m_attributes.end(); ++a) {
294 const vector<string>& aliases = (*a)->getAliases();
295 for (vector<string>::const_iterator alias = aliases.begin(); alias != aliases.end(); ++alias)
296 m_attributeIndex.insert(multimap<string,const Attribute*>::value_type(*alias, *a));
299 return m_attributeIndex;
301 const vector<const char*>& getAssertionIDs() const {
303 DDF ids = m_obj["assertions"];
304 DDF id = ids.first();
305 while (id.isstring()) {
306 m_ids.push_back(id.string());
313 void validate(const Application& application, const char* client_addr, time_t* timeout);
316 void addAttributes(const vector<Attribute*>& attributes);
317 const Assertion* getAssertion(const char* id) const;
318 void addAssertion(Assertion* assertion);
321 time_t getExpiration() const { return m_expires; }
322 time_t getLastAccess() const { return m_lastAccess; }
325 void unmarshallAttributes() const;
329 saml2::NameID* m_nameid;
330 mutable map<string,Assertion*> m_tokens;
332 mutable vector<Attribute*> m_attributes;
333 mutable multimap<string,const Attribute*> m_attributeIndex;
334 mutable vector<const char*> m_ids;
337 time_t m_expires,m_lastAccess;
341 SessionCache* SHIBSP_DLLLOCAL StorageServiceCacheFactory(const DOMElement* const & e)
343 return new SSCache(e);
347 Session* SessionCache::find(const Application& application, HTTPRequest& request, const char* client_addr, time_t* timeout)
349 return find(application, const_cast<const HTTPRequest&>(request), client_addr, timeout);
352 void SHIBSP_API shibsp::registerSessionCaches()
354 SPConfig::getConfig().SessionCacheManager.registerFactory(STORAGESERVICE_SESSION_CACHE, StorageServiceCacheFactory);
357 void StoredSession::unmarshallAttributes() const
359 Attribute* attribute;
360 DDF attrs = m_obj["attributes"];
361 DDF attr = attrs.first();
362 while (!attr.isnull()) {
364 attribute = Attribute::unmarshall(attr);
365 m_attributes.push_back(attribute);
366 if (m_cache->m_log.isDebugEnabled())
367 m_cache->m_log.debug("unmarshalled attribute (ID: %s) with %d value%s",
368 attribute->getId(), attr.first().integer(), attr.first().integer()!=1 ? "s" : "");
370 catch (AttributeException& ex) {
371 const char* id = attr.first().name();
372 m_cache->m_log.error("error unmarshalling attribute (ID: %s): %s", id ? id : "none", ex.what());
378 void StoredSession::validate(const Application& application, const char* client_addr, time_t* timeout)
380 time_t now = time(NULL);
384 if (now > m_expires) {
385 m_cache->m_log.info("session expired (ID: %s)", getID());
386 throw RetryableProfileException("Your session has expired, and you must re-authenticate.");
392 if (m_cache->m_log.isDebugEnabled())
393 m_cache->m_log.debug("comparing client address %s against %s", client_addr, getClientAddress());
394 if (!XMLString::equals(getClientAddress(),client_addr)) {
395 m_cache->m_log.warn("client address mismatch");
396 throw RetryableProfileException(
397 "Your IP address ($1) does not match the address recorded at the time the session was established.",
398 params(1,client_addr)
406 if (!SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess)) {
407 DDF in("touch::"STORAGESERVICE_SESSION_CACHE"::SessionCache"), out;
410 in.addmember("key").string(getID());
411 in.addmember("version").integer(m_obj["version"].integer());
413 // On 64-bit Windows, time_t doesn't fit in a long, so I'm using ISO timestamps.
414 #ifndef HAVE_GMTIME_R
415 struct tm* ptime=gmtime(timeout);
418 struct tm* ptime=gmtime_r(timeout,&res);
421 strftime(timebuf,32,"%Y-%m-%dT%H:%M:%SZ",ptime);
422 in.addmember("timeout").string(timebuf);
426 out=application.getServiceProvider().getListenerService()->send(in);
433 if (out.isstruct()) {
434 // We got an updated record back.
436 for_each(m_attributes.begin(), m_attributes.end(), xmltooling::cleanup<Attribute>());
437 m_attributes.clear();
438 m_attributeIndex.clear();
445 if (!m_cache->m_storage)
446 throw ConfigurationException("Session touch requires a StorageService.");
448 // Do a versioned read.
451 int curver = m_obj["version"].integer();
452 int ver = m_cache->m_storage->readText(getID(), "session", &record, &lastAccess, curver);
454 m_cache->m_log.warn("unsuccessful versioned read of session (ID: %s), cache out of sync?", getID());
455 throw RetryableProfileException("Your session has expired, and you must re-authenticate.");
458 // Adjust for expiration to recover last access time and check timeout.
459 lastAccess -= m_cache->m_cacheTimeout;
460 if (*timeout > 0 && now - lastAccess >= *timeout) {
461 m_cache->m_log.info("session timed out (ID: %s)", getID());
462 throw RetryableProfileException("Your session has expired, and you must re-authenticate.");
465 // Update storage expiration, if possible.
467 m_cache->m_storage->updateContext(getID(), now + m_cache->m_cacheTimeout);
469 catch (exception& ex) {
470 m_cache->m_log.error("failed to update session expiration: %s", ex.what());
474 // We got an updated record back.
476 istringstream in(record);
479 for_each(m_attributes.begin(), m_attributes.end(), xmltooling::cleanup<Attribute>());
480 m_attributes.clear();
481 m_attributeIndex.clear();
486 throw ConfigurationException("Session touch requires a StorageService.");
495 void StoredSession::addAttributes(const vector<Attribute*>& attributes)
498 xmltooling::NDC ndc("addAttributes");
501 if (!m_cache->m_storage)
502 throw ConfigurationException("Session modification requires a StorageService.");
504 m_cache->m_log.debug("adding attributes to session (%s)", getID());
509 DDF attrs = m_obj["attributes"];
511 attrs = m_obj.addmember("attributes").list();
512 for (vector<Attribute*>::const_iterator a=attributes.begin(); a!=attributes.end(); ++a) {
513 attr = (*a)->marshall();
517 // Tentatively increment the version.
518 m_obj["version"].integer(m_obj["version"].integer()+1);
522 string record(str.str());
525 ver = m_cache->m_storage->updateText(getID(), "session", record.c_str(), 0, m_obj["version"].integer()-1);
528 // Roll back modification to record.
529 m_obj["version"].integer(m_obj["version"].integer()-1);
530 vector<Attribute*>::size_type count = attributes.size();
532 attrs.last().destroy();
537 // Roll back modification to record.
538 m_obj["version"].integer(m_obj["version"].integer()-1);
539 vector<Attribute*>::size_type count = attributes.size();
541 attrs.last().destroy();
544 // Fatal problem with update.
545 throw IOException("Unable to update stored session.");
549 m_cache->m_log.warn("storage service indicates the record is out of sync, updating with a fresh copy...");
550 ver = m_cache->m_storage->readText(getID(), "session", &record, NULL);
552 m_cache->m_log.error("readText failed on StorageService for session (%s)", getID());
553 throw IOException("Unable to read back stored session.");
558 istringstream in(record);
562 for_each(m_attributes.begin(), m_attributes.end(), xmltooling::cleanup<Attribute>());
563 m_attributes.clear();
564 m_attributeIndex.clear();
565 newobj["version"].integer(ver);
571 } while (ver < 0); // negative indicates a sync issue so we retry
573 TransactionLog* xlog = SPConfig::getConfig().getServiceProvider()->getTransactionLog();
575 xlog->log.infoStream() <<
576 "Added the following attributes to session (ID: " <<
578 ") for (applicationId: " <<
579 m_obj["application_id"].string() <<
581 for (vector<Attribute*>::const_iterator a=attributes.begin(); a!=attributes.end(); ++a)
582 xlog->log.infoStream() << "\t" << (*a)->getId() << " (" << (*a)->valueCount() << " values)";
585 // We own them now, so clean them up.
586 for_each(attributes.begin(), attributes.end(), xmltooling::cleanup<Attribute>());
589 const Assertion* StoredSession::getAssertion(const char* id) const
591 if (!m_cache->m_storage)
592 throw ConfigurationException("Assertion retrieval requires a StorageService.");
594 map<string,Assertion*>::const_iterator i = m_tokens.find(id);
595 if (i!=m_tokens.end())
599 if (!m_cache->m_storage->readText(getID(), id, &tokenstr, NULL))
600 throw FatalProfileException("Assertion not found in cache.");
602 // Parse and bind the document into an XMLObject.
603 istringstream instr(tokenstr);
604 DOMDocument* doc = XMLToolingConfig::getConfig().getParser().parse(instr);
605 XercesJanitor<DOMDocument> janitor(doc);
606 auto_ptr<XMLObject> xmlObject(XMLObjectBuilder::buildOneFromElement(doc->getDocumentElement(), true));
609 Assertion* token = dynamic_cast<Assertion*>(xmlObject.get());
611 throw FatalProfileException("Request for cached assertion returned an unknown object type.");
613 // Transfer ownership to us.
619 void StoredSession::addAssertion(Assertion* assertion)
622 xmltooling::NDC ndc("addAssertion");
625 if (!m_cache->m_storage)
626 throw ConfigurationException("Session modification requires a StorageService.");
629 throw FatalProfileException("Unknown object type passed to session for storage.");
631 auto_ptr_char id(assertion->getID());
633 m_cache->m_log.debug("adding assertion (%s) to session (%s)", id.get(), getID());
636 if (!m_cache->m_storage->readText(getID(), "session", NULL, &exp))
637 throw IOException("Unable to load expiration time for stored session.");
639 ostringstream tokenstr;
640 tokenstr << *assertion;
641 if (!m_cache->m_storage->createText(getID(), id.get(), tokenstr.str().c_str(), exp))
642 throw IOException("Attempted to insert duplicate assertion ID into session.");
646 DDF token = DDF(NULL).string(id.get());
647 m_obj["assertions"].add(token);
649 // Tentatively increment the version.
650 m_obj["version"].integer(m_obj["version"].integer()+1);
654 string record(str.str());
657 ver = m_cache->m_storage->updateText(getID(), "session", record.c_str(), 0, m_obj["version"].integer()-1);
661 m_obj["version"].integer(m_obj["version"].integer()-1);
662 m_cache->m_storage->deleteText(getID(), id.get());
668 m_obj["version"].integer(m_obj["version"].integer()-1);
671 // Fatal problem with update.
672 m_cache->m_log.error("updateText failed on StorageService for session (%s)", getID());
673 m_cache->m_storage->deleteText(getID(), id.get());
674 throw IOException("Unable to update stored session.");
678 m_cache->m_log.warn("storage service indicates the record is out of sync, updating with a fresh copy...");
679 ver = m_cache->m_storage->readText(getID(), "session", &record, NULL);
681 m_cache->m_log.error("readText failed on StorageService for session (%s)", getID());
682 m_cache->m_storage->deleteText(getID(), id.get());
683 throw IOException("Unable to read back stored session.");
688 istringstream in(record);
692 for_each(m_attributes.begin(), m_attributes.end(), xmltooling::cleanup<Attribute>());
693 m_attributes.clear();
694 m_attributeIndex.clear();
695 newobj["version"].integer(ver);
701 } while (ver < 0); // negative indicates a sync issue so we retry
706 TransactionLog* xlog = SPConfig::getConfig().getServiceProvider()->getTransactionLog();
709 "Added assertion (ID: %s) to session for (applicationId: %s) with (ID: %s)",
710 id.get(), m_obj["application_id"].string(), getID()
716 SSCache::SSCache(const DOMElement* e)
717 : m_log(Category::getInstance(SHIBSP_LOGCAT".SessionCache")), inproc(true), m_cacheTimeout(28800),
719 m_storage(NULL), m_storage_lite(NULL),
721 m_root(e), m_inprocTimeout(900), m_lock(NULL), shutdown(false), shutdown_wait(NULL), cleanup_thread(NULL)
723 static const XMLCh cacheTimeout[] = UNICODE_LITERAL_12(c,a,c,h,e,T,i,m,e,o,u,t);
724 static const XMLCh inprocTimeout[] = UNICODE_LITERAL_13(i,n,p,r,o,c,T,i,m,e,o,u,t);
725 static const XMLCh _StorageService[] = UNICODE_LITERAL_14(S,t,o,r,a,g,e,S,e,r,v,i,c,e);
726 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);
728 SPConfig& conf = SPConfig::getConfig();
729 inproc = conf.isEnabled(SPConfig::InProcess);
732 const XMLCh* tag=e->getAttributeNS(NULL,cacheTimeout);
734 m_cacheTimeout = XMLString::parseInt(tag);
736 m_cacheTimeout=28800;
739 const XMLCh* tag=e->getAttributeNS(NULL,inprocTimeout);
741 m_inprocTimeout = XMLString::parseInt(tag);
742 if (!m_inprocTimeout)
749 if (conf.isEnabled(SPConfig::OutOfProcess)) {
750 const XMLCh* tag = e ? e->getAttributeNS(NULL,_StorageService) : NULL;
752 auto_ptr_char ssid(tag);
753 m_storage = conf.getServiceProvider()->getStorageService(ssid.get());
755 m_log.info("bound to StorageService (%s)", ssid.get());
758 throw ConfigurationException("SessionCache unable to locate StorageService, check configuration.");
760 tag = e ? e->getAttributeNS(NULL,_StorageServiceLite) : NULL;
762 auto_ptr_char ssid(tag);
763 m_storage_lite = conf.getServiceProvider()->getStorageService(ssid.get());
765 m_log.info("bound to StorageServiceLite (%s)", ssid.get());
767 if (!m_storage_lite) {
768 m_log.info("No StorageServiceLite specified. Using standard StorageService.");
769 m_storage_lite = m_storage;
774 ListenerService* listener=conf.getServiceProvider()->getListenerService(false);
776 if (!conf.isEnabled(SPConfig::OutOfProcess) && !listener)
777 throw ConfigurationException("SessionCache requires a ListenerService, but none available.");
778 m_lock = RWLock::create();
779 shutdown_wait = CondWait::create();
780 cleanup_thread = Thread::create(&cleanup_fn, (void*)this);
784 if (listener && conf.isEnabled(SPConfig::OutOfProcess)) {
785 listener->regListener("find::"STORAGESERVICE_SESSION_CACHE"::SessionCache",this);
786 listener->regListener("remove::"STORAGESERVICE_SESSION_CACHE"::SessionCache",this);
787 listener->regListener("touch::"STORAGESERVICE_SESSION_CACHE"::SessionCache",this);
790 m_log.info("no ListenerService available, cache remoting disabled");
799 // Shut down the cleanup thread and let it know...
801 shutdown_wait->signal();
802 cleanup_thread->join(NULL);
804 for_each(m_hashtable.begin(),m_hashtable.end(),cleanup_pair<string,StoredSession>());
806 delete shutdown_wait;
810 SPConfig& conf = SPConfig::getConfig();
811 ListenerService* listener=conf.getServiceProvider()->getListenerService(false);
812 if (listener && conf.isEnabled(SPConfig::OutOfProcess)) {
813 listener->unregListener("find::"STORAGESERVICE_SESSION_CACHE"::SessionCache",this);
814 listener->unregListener("remove::"STORAGESERVICE_SESSION_CACHE"::SessionCache",this);
815 listener->unregListener("touch::"STORAGESERVICE_SESSION_CACHE"::SessionCache",this);
825 auto_ptr_char temp(SAMLConfig::getConfig().generateIdentifier());
826 m_storage->createString("SessionCacheTest", temp.get(), "Test", time(NULL) + 60);
827 m_storage->deleteString("SessionCacheTest", temp.get());
830 void SSCache::insert(const char* key, time_t expires, const char* name, const char* index)
833 if (strlen(name) > 255) {
834 dup = string(name).substr(0,255);
839 DDFJanitor jobj(obj);
841 // Since we can't guarantee uniqueness, check for an existing record.
844 int ver = m_storage_lite->readText("NameID", name, &record, &recordexp);
846 // Existing record, so we need to unmarshall it.
847 istringstream in(record);
852 obj = DDF(NULL).structure();
855 if (!index || !*index)
857 DDF sessions = obj.addmember(index);
858 if (!sessions.islist())
860 DDF session = DDF(NULL).string(key);
861 sessions.add(session);
863 // Remarshall the record.
867 // Try and store it back...
869 ver = m_storage_lite->updateText("NameID", name, out.str().c_str(), max(expires, recordexp), ver);
871 // Out of sync, or went missing, so retry.
872 return insert(key, expires, name, index);
875 else if (!m_storage_lite->createText("NameID", name, out.str().c_str(), expires)) {
876 // Hit a dup, so just retry, hopefully hitting the other branch.
877 return insert(key, expires, name, index);
881 void SSCache::insert(
882 const Application& application,
883 const HTTPRequest& httpRequest,
884 HTTPResponse& httpResponse,
886 const saml2md::EntityDescriptor* issuer,
887 const XMLCh* protocol,
888 const saml2::NameID* nameid,
889 const XMLCh* authn_instant,
890 const XMLCh* session_index,
891 const XMLCh* authncontext_class,
892 const XMLCh* authncontext_decl,
893 const vector<const Assertion*>* tokens,
894 const vector<Attribute*>* attributes
898 xmltooling::NDC ndc("insert");
901 throw ConfigurationException("SessionCache insertion requires a StorageService.");
903 m_log.debug("creating new session");
905 time_t now = time(NULL);
906 auto_ptr_char index(session_index);
907 auto_ptr_char entity_id(issuer ? issuer->getEntityID() : NULL);
908 auto_ptr_char name(nameid ? nameid->getName() : NULL);
911 // Check for a pending logout.
912 if (strlen(name.get()) > 255)
913 const_cast<char*>(name.get())[255] = 0;
915 int ver = m_storage_lite->readText("Logout", name.get(), &pending);
918 DDFJanitor jpend(pendobj);
919 istringstream pstr(pending);
921 // IdP.SP.index contains logout expiration, if any.
922 DDF deadmenwalking = pendobj[issuer ? entity_id.get() : "_shibnull"][application.getRelyingParty(issuer)->getString("entityID").second];
923 const char* logexpstr = deadmenwalking[session_index ? index.get() : "_shibnull"].string();
924 if (!logexpstr && session_index) // we tried an exact session match, now try for NULL
925 logexpstr = deadmenwalking["_shibnull"].string();
927 auto_ptr_XMLCh dt(logexpstr);
928 DateTime dtobj(dt.get());
929 dtobj.parseDateTime();
930 time_t logexp = dtobj.getEpoch();
931 if (now - XMLToolingConfig::getConfig().clock_skew_secs < logexp)
932 throw FatalProfileException("A logout message from your identity provider has blocked your login attempt.");
937 auto_ptr_char key(SAMLConfig::getConfig().generateIdentifier());
939 // Store session properties in DDF.
940 DDF obj = DDF(key.get()).structure();
941 DDFJanitor entryobj(obj);
942 obj.addmember("version").integer(1);
943 obj.addmember("application_id").string(application.getId());
945 // On 64-bit Windows, time_t doesn't fit in a long, so I'm using ISO timestamps.
946 #ifndef HAVE_GMTIME_R
947 struct tm* ptime=gmtime(&expires);
950 struct tm* ptime=gmtime_r(&expires,&res);
953 strftime(timebuf,32,"%Y-%m-%dT%H:%M:%SZ",ptime);
954 obj.addmember("expires").string(timebuf);
956 obj.addmember("client_addr").string(httpRequest.getRemoteAddr().c_str());
958 obj.addmember("entity_id").string(entity_id.get());
960 auto_ptr_char prot(protocol);
961 obj.addmember("protocol").string(prot.get());
964 auto_ptr_char instant(authn_instant);
965 obj.addmember("authn_instant").string(instant.get());
968 obj.addmember("session_index").string(index.get());
969 if (authncontext_class) {
970 auto_ptr_char ac(authncontext_class);
971 obj.addmember("authncontext_class").string(ac.get());
973 if (authncontext_decl) {
974 auto_ptr_char ad(authncontext_decl);
975 obj.addmember("authncontext_decl").string(ad.get());
979 ostringstream namestr;
981 obj.addmember("nameid").string(namestr.str().c_str());
985 obj.addmember("assertions").list();
986 for (vector<const Assertion*>::const_iterator t = tokens->begin(); t!=tokens->end(); ++t) {
987 auto_ptr_char tokenid((*t)->getID());
988 DDF tokid = DDF(NULL).string(tokenid.get());
989 obj["assertions"].add(tokid);
995 DDF attrlist = obj.addmember("attributes").list();
996 for (vector<Attribute*>::const_iterator a=attributes->begin(); a!=attributes->end(); ++a) {
997 attr = (*a)->marshall();
1002 ostringstream record;
1005 m_log.debug("storing new session...");
1006 if (!m_storage->createText(key.get(), "session", record.str().c_str(), now + m_cacheTimeout))
1007 throw FatalProfileException("Attempted to create a session with a duplicate key.");
1009 // Store the reverse mapping for logout.
1012 insert(key.get(), expires, name.get(), index.get());
1014 catch (exception& ex) {
1015 m_log.error("error storing back mapping of NameID for logout: %s", ex.what());
1020 for (vector<const Assertion*>::const_iterator t = tokens->begin(); t!=tokens->end(); ++t) {
1021 ostringstream tokenstr;
1023 auto_ptr_char tokenid((*t)->getID());
1024 if (!m_storage->createText(key.get(), tokenid.get(), tokenstr.str().c_str(), now + m_cacheTimeout))
1025 throw IOException("duplicate assertion ID ($1)", params(1, tokenid.get()));
1028 catch (exception& ex) {
1029 m_log.error("error storing assertion along with session: %s", ex.what());
1033 const char* pid = obj["entity_id"].string();
1034 const char* prot = obj["protocol"].string();
1035 m_log.info("new session created: ID (%s) IdP (%s) Protocol(%s) Address (%s)",
1036 key.get(), pid ? pid : "none", prot ? prot : "none", httpRequest.getRemoteAddr().c_str());
1038 // Transaction Logging
1039 TransactionLog* xlog = application.getServiceProvider().getTransactionLog();
1040 Locker locker(xlog);
1041 xlog->log.infoStream() <<
1042 "New session (ID: " <<
1044 ") with (applicationId: " <<
1045 application.getId() <<
1046 ") for principal from (IdP: " <<
1047 (pid ? pid : "none") <<
1048 ") at (ClientAddress: " <<
1049 httpRequest.getRemoteAddr() <<
1050 ") with (NameIdentifier: " <<
1051 (nameid ? name.get() : "none") <<
1052 ") using (Protocol: " <<
1053 (prot ? prot : "none") <<
1054 ") from (AssertionID: " <<
1055 (tokens ? obj["assertions"].first().string() : "none") <<
1059 xlog->log.infoStream() <<
1060 "Cached the following attributes with session (ID: " <<
1062 ") for (applicationId: " <<
1063 application.getId() <<
1065 for (vector<Attribute*>::const_iterator a=attributes->begin(); a!=attributes->end(); ++a)
1066 xlog->log.infoStream() << "\t" << (*a)->getId() << " (" << (*a)->valueCount() << " values)";
1067 xlog->log.info("}");
1070 time_t cookieLifetime = 0;
1071 pair<string,const char*> shib_cookie = application.getCookieNameProps("_shibsession_", &cookieLifetime);
1072 string k(key.get());
1073 k += shib_cookie.second;
1075 if (cookieLifetime > 0) {
1076 cookieLifetime += now;
1077 #ifndef HAVE_GMTIME_R
1078 ptime=gmtime(&cookieLifetime);
1080 ptime=gmtime_r(&cookieLifetime,&res);
1082 char cookietimebuf[64];
1083 strftime(cookietimebuf,64,"; expires=%a, %d %b %Y %H:%M:%S GMT",ptime);
1087 httpResponse.setCookie(shib_cookie.first.c_str(), k.c_str());
1090 bool SSCache::matches(
1091 const Application& application,
1092 const xmltooling::HTTPRequest& request,
1093 const saml2md::EntityDescriptor* issuer,
1094 const saml2::NameID& nameid,
1095 const set<string>* indexes
1098 auto_ptr_char entityID(issuer ? issuer->getEntityID() : NULL);
1100 Session* session = find(application, request);
1102 Locker locker(session, false);
1103 if (XMLString::equals(session->getEntityID(), entityID.get()) && session->getNameID() &&
1104 stronglyMatches(issuer->getEntityID(), application.getRelyingParty(issuer)->getXMLString("entityID").second, nameid, *session->getNameID())) {
1105 return (!indexes || indexes->empty() || (session->getSessionIndex() ? (indexes->count(session->getSessionIndex())>0) : false));
1109 catch (exception& ex) {
1110 m_log.error("error while matching session: %s", ex.what());
1115 vector<string>::size_type SSCache::logout(
1116 const Application& application,
1117 const saml2md::EntityDescriptor* issuer,
1118 const saml2::NameID& nameid,
1119 const set<string>* indexes,
1121 vector<string>& sessionsKilled
1125 xmltooling::NDC ndc("logout");
1129 throw ConfigurationException("SessionCache insertion requires a StorageService.");
1131 auto_ptr_char entityID(issuer ? issuer->getEntityID() : NULL);
1132 auto_ptr_char name(nameid.getName());
1134 m_log.info("request to logout sessions from (%s) for (%s)", entityID.get() ? entityID.get() : "unknown", name.get());
1136 if (strlen(name.get()) > 255)
1137 const_cast<char*>(name.get())[255] = 0;
1140 DDFJanitor jobj(obj);
1145 // Record the logout to prevent post-delivered assertions.
1146 // On 64-bit Windows, time_t doesn't fit in a long, so I'm using ISO timestamps.
1147 #ifndef HAVE_GMTIME_R
1148 struct tm* ptime=gmtime(&expires);
1151 struct tm* ptime=gmtime_r(&expires,&res);
1154 strftime(timebuf,32,"%Y-%m-%dT%H:%M:%SZ",ptime);
1157 ver = m_storage_lite->readText("Logout", name.get(), &record, &oldexp);
1159 istringstream lin(record);
1163 obj = DDF(NULL).structure();
1166 // Structure is keyed by the IdP and SP, with a member per session index containing the expiration.
1167 DDF root = obj.addmember(issuer ? entityID.get() : "_shibnull").addmember(application.getRelyingParty(issuer)->getString("entityID").second);
1169 for (set<string>::const_iterator x = indexes->begin(); x!=indexes->end(); ++x)
1170 root.addmember(x->c_str()).string(timebuf);
1173 root.addmember("_shibnull").string(timebuf);
1181 ver = m_storage_lite->updateText("Logout", name.get(), lout.str().c_str(), max(expires, oldexp), ver);
1183 // Out of sync, or went missing, so retry.
1184 return logout(application, issuer, nameid, indexes, expires, sessionsKilled);
1187 else if (!m_storage_lite->createText("Logout", name.get(), lout.str().c_str(), expires)) {
1188 // Hit a dup, so just retry, hopefully hitting the other branch.
1189 return logout(application, issuer, nameid, indexes, expires, sessionsKilled);
1196 // Read in potentially matching sessions.
1197 ver = m_storage_lite->readText("NameID", name.get(), &record);
1199 m_log.debug("no active sessions to logout for supplied issuer and subject");
1203 istringstream in(record);
1206 // The record contains child lists for each known session index.
1208 DDF sessions = obj.first();
1209 while (sessions.islist()) {
1210 if (!indexes || indexes->empty() || indexes->count(sessions.name())) {
1211 key = sessions.first();
1212 while (key.isstring()) {
1213 // Fetch the session for comparison.
1214 Session* session = NULL;
1216 session = find(application, key.string());
1218 catch (exception& ex) {
1219 m_log.error("error locating session (%s): %s", key.string(), ex.what());
1223 Locker locker(session, false);
1225 if (XMLString::equals(session->getEntityID(), entityID.get())) {
1227 if (stronglyMatches(issuer->getEntityID(), application.getRelyingParty(issuer)->getXMLString("entityID").second, nameid, *session->getNameID())) {
1228 sessionsKilled.push_back(key.string());
1232 m_log.debug("session (%s) contained a non-matching NameID, leaving it alone", key.string());
1236 m_log.debug("session (%s) established by different IdP, leaving it alone", key.string());
1240 // Session's gone, so...
1241 sessionsKilled.push_back(key.string());
1244 key = sessions.next();
1247 // No sessions left for this index?
1248 if (sessions.first().isnull())
1251 sessions = obj.next();
1254 if (obj.first().isnull())
1257 // If possible, write back the mapping record (this isn't crucial).
1260 m_storage_lite->deleteText("NameID", name.get());
1262 else if (!sessionsKilled.empty()) {
1265 if (m_storage_lite->updateText("NameID", name.get(), out.str().c_str(), 0, ver) <= 0)
1266 m_log.warn("logout mapping record changed behind us, leaving it alone");
1269 catch (exception& ex) {
1270 m_log.error("error updating logout mapping record: %s", ex.what());
1273 return sessionsKilled.size();
1276 bool SSCache::stronglyMatches(const XMLCh* idp, const XMLCh* sp, const saml2::NameID& n1, const saml2::NameID& n2) const
1278 if (!XMLString::equals(n1.getName(), n2.getName()))
1281 const XMLCh* s1 = n1.getFormat();
1282 const XMLCh* s2 = n2.getFormat();
1284 s1 = saml2::NameID::UNSPECIFIED;
1286 s2 = saml2::NameID::UNSPECIFIED;
1287 if (!XMLString::equals(s1,s2))
1290 s1 = n1.getNameQualifier();
1291 s2 = n2.getNameQualifier();
1296 if (!XMLString::equals(s1,s2))
1299 s1 = n1.getSPNameQualifier();
1300 s2 = n2.getSPNameQualifier();
1305 if (!XMLString::equals(s1,s2))
1313 Session* SSCache::find(const Application& application, const char* key, const char* client_addr, time_t* timeout)
1316 xmltooling::NDC ndc("find");
1318 StoredSession* session=NULL;
1321 m_log.debug("searching local cache for session (%s)", key);
1323 map<string,StoredSession*>::const_iterator i=m_hashtable.find(key);
1324 if (i!=m_hashtable.end()) {
1325 // Save off and lock the session.
1326 session = i->second;
1329 m_log.debug("session found locally, validating it for use");
1337 if (!SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess)) {
1338 m_log.debug("session not found locally, remoting the search");
1339 // Remote the request.
1340 DDF in("find::"STORAGESERVICE_SESSION_CACHE"::SessionCache"), out;
1343 in.addmember("key").string(key);
1344 in.addmember("application_id").string(application.getId());
1345 if (timeout && *timeout) {
1346 // On 64-bit Windows, time_t doesn't fit in a long, so I'm using ISO timestamps.
1347 #ifndef HAVE_GMTIME_R
1348 struct tm* ptime=gmtime(timeout);
1351 struct tm* ptime=gmtime_r(timeout,&res);
1354 strftime(timebuf,32,"%Y-%m-%dT%H:%M:%SZ",ptime);
1355 in.addmember("timeout").string(timebuf);
1359 out=application.getServiceProvider().getListenerService()->send(in);
1360 if (!out.isstruct()) {
1362 m_log.debug("session not found in remote cache");
1366 // Wrap the results in a local entry and save it.
1367 session = new StoredSession(this, out);
1368 // The remote end has handled timeout issues, we handle address and expiration checks.
1377 // We're out of process, so we can search the storage service directly.
1380 throw ConfigurationException("SessionCache lookup requires a StorageService.");
1382 m_log.debug("searching for session (%s)", key);
1387 int ver = m_storage->readText(key, "session", &record, &lastAccess);
1391 m_log.debug("reconstituting session and checking validity");
1393 istringstream in(record);
1396 lastAccess -= m_cacheTimeout; // adjusts it back to the last time the record's timestamp was touched
1397 time_t now=time(NULL);
1399 if (timeout && *timeout > 0 && now - lastAccess >= *timeout) {
1400 m_log.info("session timed out (ID: %s)", key);
1401 remove(application, key);
1402 const char* eid = obj["entity_id"].string();
1405 throw RetryableProfileException("Your session has expired, and you must re-authenticate.");
1409 throw RetryableProfileException("Your session has expired, and you must re-authenticate.", namedparams(1, "entityID", eid2.c_str()));
1413 // Update storage expiration, if possible.
1415 m_storage->updateContext(key, now + m_cacheTimeout);
1417 catch (exception& ex) {
1418 m_log.error("failed to update session expiration: %s", ex.what());
1422 // Wrap the results in a local entry and save it.
1423 session = new StoredSession(this, obj);
1424 // We handled timeout issues, still need to handle address and expiration checks.
1427 throw ConfigurationException("SessionCache search requires a StorageService.");
1432 // Lock for writing and repeat the search to avoid duplication.
1434 SharedLock shared(m_lock, false);
1435 if (m_hashtable.count(key)) {
1436 // We're using an existing session entry.
1438 session = m_hashtable[key];
1442 m_hashtable[key]=session;
1448 if (!XMLString::equals(session->getApplicationID(), application.getId())) {
1449 m_log.error("an application (%s) tried to access another application's session", application.getId());
1454 // Verify currency and update the timestamp if indicated by caller.
1456 session->validate(application, client_addr, timeout);
1460 remove(application, key);
1467 void SSCache::remove(const Application& application, const char* key)
1470 xmltooling::NDC ndc("remove");
1472 // Take care of local copy.
1476 if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess)) {
1477 // Remove the session from storage directly.
1479 m_storage->deleteContext(key);
1480 m_log.info("removed session (%s)", key);
1482 TransactionLog* xlog = application.getServiceProvider().getTransactionLog();
1483 Locker locker(xlog);
1484 xlog->log.info("Destroyed session (applicationId: %s) (ID: %s)", application.getId(), key);
1486 throw ConfigurationException("SessionCache removal requires a StorageService.");
1490 // Remote the request.
1491 DDF in("remove::"STORAGESERVICE_SESSION_CACHE"::SessionCache");
1494 in.addmember("key").string(key);
1495 in.addmember("application_id").string(application.getId());
1497 DDF out = application.getServiceProvider().getListenerService()->send(in);
1502 void SSCache::dormant(const char* key)
1505 xmltooling::NDC ndc("dormant");
1508 m_log.debug("deleting local copy of session (%s)", key);
1510 // lock the cache for writing, which means we know nobody is sitting in find()
1513 // grab the entry from the table
1514 map<string,StoredSession*>::const_iterator i=m_hashtable.find(key);
1515 if (i==m_hashtable.end()) {
1520 // ok, remove the entry and lock it
1521 StoredSession* entry=i->second;
1522 m_hashtable.erase(key);
1528 // we can release the cache entry lock because we know we're not in the cache anymore
1534 void SSCache::cleanup()
1537 xmltooling::NDC ndc("cleanup");
1540 Mutex* mutex = Mutex::create();
1542 // Load our configuration details...
1543 static const XMLCh cleanupInterval[] = UNICODE_LITERAL_15(c,l,e,a,n,u,p,I,n,t,e,r,v,a,l);
1544 const XMLCh* tag=m_root ? m_root->getAttributeNS(NULL,cleanupInterval) : NULL;
1545 int rerun_timer = 900;
1547 rerun_timer = XMLString::parseInt(tag);
1548 if (rerun_timer <= 0)
1554 m_log.info("cleanup thread started...run every %d secs; timeout after %d secs", rerun_timer, m_inprocTimeout);
1557 shutdown_wait->timedwait(mutex,rerun_timer);
1561 // Ok, let's run through the cleanup process and clean out
1562 // really old sessions. This is a two-pass process. The
1563 // first pass is done holding a read-lock while we iterate over
1564 // the cache. The second pass doesn't need a lock because
1565 // the 'deletes' will lock the cache.
1567 // Pass 1: iterate over the map and find all entries that have not been
1568 // used in the allotted timeout.
1569 vector<string> stale_keys;
1570 time_t stale = time(NULL) - m_inprocTimeout;
1572 m_log.debug("cleanup thread running");
1575 for (map<string,StoredSession*>::const_iterator i=m_hashtable.begin(); i!=m_hashtable.end(); ++i) {
1576 // If the last access was BEFORE the stale timeout...
1578 time_t last=i->second->getLastAccess();
1579 i->second->unlock();
1581 stale_keys.push_back(i->first);
1585 if (!stale_keys.empty()) {
1586 m_log.info("purging %d old sessions", stale_keys.size());
1588 // Pass 2: walk through the list of stale entries and remove them from the cache
1589 for (vector<string>::const_iterator j = stale_keys.begin(); j != stale_keys.end(); ++j)
1590 dormant(j->c_str());
1593 m_log.debug("cleanup thread completed");
1596 m_log.info("cleanup thread exiting");
1603 void* SSCache::cleanup_fn(void* cache_p)
1606 // First, let's block all signals
1607 Thread::mask_all_signals();
1610 // Now run the cleanup process.
1611 reinterpret_cast<SSCache*>(cache_p)->cleanup();
1617 void SSCache::receive(DDF& in, ostream& out)
1620 xmltooling::NDC ndc("receive");
1623 if (!strcmp(in.name(),"find::"STORAGESERVICE_SESSION_CACHE"::SessionCache")) {
1624 const char* key=in["key"].string();
1626 throw ListenerException("Required parameters missing for session lookup.");
1628 const Application* app = SPConfig::getConfig().getServiceProvider()->getApplication(in["application_id"].string());
1630 throw ListenerException("Application not found, check configuration?");
1632 // Do an unversioned read.
1635 if (!m_storage->readText(key, "session", &record, &lastAccess)) {
1637 DDFJanitor jan(ret);
1642 // Adjust for expiration to recover last access time and check timeout.
1643 lastAccess -= m_cacheTimeout;
1644 time_t now=time(NULL);
1646 // See if we need to check for a timeout.
1647 if (in["timeout"].string()) {
1649 auto_ptr_XMLCh dt(in["timeout"].string());
1650 DateTime dtobj(dt.get());
1651 dtobj.parseDateTime();
1652 timeout = dtobj.getEpoch();
1654 if (timeout > 0 && now - lastAccess >= timeout) {
1655 m_log.info("session timed out (ID: %s)", key);
1657 throw RetryableProfileException("Your session has expired, and you must re-authenticate.");
1660 // Update storage expiration, if possible.
1662 m_storage->updateContext(key, now + m_cacheTimeout);
1664 catch (exception& ex) {
1665 m_log.error("failed to update session expiration: %s", ex.what());
1669 // Send the record back.
1672 else if (!strcmp(in.name(),"touch::"STORAGESERVICE_SESSION_CACHE"::SessionCache")) {
1673 const char* key=in["key"].string();
1675 throw ListenerException("Required parameters missing for session check.");
1677 // Do a versioned read.
1680 int curver = in["version"].integer();
1681 int ver = m_storage->readText(key, "session", &record, &lastAccess, curver);
1683 m_log.warn("unsuccessful versioned read of session (ID: %s), caches out of sync?", key);
1684 throw RetryableProfileException("Your session has expired, and you must re-authenticate.");
1687 // Adjust for expiration to recover last access time and check timeout.
1688 lastAccess -= m_cacheTimeout;
1689 time_t now=time(NULL);
1691 // See if we need to check for a timeout.
1693 auto_ptr_XMLCh dt(in["timeout"].string());
1695 DateTime dtobj(dt.get());
1696 dtobj.parseDateTime();
1697 timeout = dtobj.getEpoch();
1700 if (timeout > 0 && now - lastAccess >= timeout) {
1701 m_log.info("session timed out (ID: %s)", key);
1702 throw RetryableProfileException("Your session has expired, and you must re-authenticate.");
1705 // Update storage expiration, if possible.
1707 m_storage->updateContext(key, now + m_cacheTimeout);
1709 catch (exception& ex) {
1710 m_log.error("failed to update session expiration: %s", ex.what());
1714 // Send the record back.
1719 DDFJanitor jan(ret);
1723 else if (!strcmp(in.name(),"remove::"STORAGESERVICE_SESSION_CACHE"::SessionCache")) {
1724 const char* key=in["key"].string();
1726 throw ListenerException("Required parameter missing for session removal.");
1728 const Application* app = SPConfig::getConfig().getServiceProvider()->getApplication(in["application_id"].string());
1730 throw ConfigurationException("Application not found, check configuration?");
1734 DDFJanitor jan(ret);