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/util/StorageService.h>
49 using namespace opensaml::saml2md;
52 # include <xmltooling/util/DateTime.h>
55 using namespace shibsp;
56 using namespace opensaml;
57 using namespace xmltooling;
63 class SSCache : public SessionCacheEx
65 ,public virtual Remoted
69 SSCache(const DOMElement* e);
73 void receive(DDF& in, ostream& out);
76 const Application& application,
77 const HTTPRequest& httpRequest,
78 HTTPResponse& httpResponse,
80 const saml2md::EntityDescriptor* issuer=NULL,
81 const XMLCh* protocol=NULL,
82 const saml2::NameID* nameid=NULL,
83 const XMLCh* authn_instant=NULL,
84 const XMLCh* session_index=NULL,
85 const XMLCh* authncontext_class=NULL,
86 const XMLCh* authncontext_decl=NULL,
87 const vector<const Assertion*>* tokens=NULL,
88 const vector<Attribute*>* attributes=NULL
90 vector<string>::size_type logout(
91 const Application& application,
92 const saml2md::EntityDescriptor* issuer,
93 const saml2::NameID& nameid,
94 const set<string>* indexes,
96 vector<string>& sessions
99 const Application& application,
100 const xmltooling::HTTPRequest& request,
101 const saml2md::EntityDescriptor* issuer,
102 const saml2::NameID& nameid,
103 const set<string>* indexes
106 Session* find(const Application& application, const char* key, const char* client_addr=NULL, time_t* timeout=NULL);
107 void remove(const Application& application, const char* key);
110 string active(const Application& application, const xmltooling::HTTPRequest& request) {
111 pair<string,const char*> shib_cookie = application.getCookieNameProps("_shibsession_");
112 const char* session_id = request.getCookie(shib_cookie.first.c_str());
113 return (session_id ? session_id : "");
116 Session* find(const Application& application, const HTTPRequest& request, const char* client_addr=NULL, time_t* timeout=NULL) {
117 string id = active(application, request);
119 return find(application, id.c_str(), client_addr, timeout);
123 Session* find(const Application& application, HTTPRequest& request, const char* client_addr=NULL, time_t* timeout=NULL) {
124 string id = active(application, request);
128 Session* session = find(application, id.c_str(), client_addr, timeout);
131 HTTPResponse* response = dynamic_cast<HTTPResponse*>(&request);
133 pair<string,const char*> shib_cookie = application.getCookieNameProps("_shibsession_");
134 string exp(shib_cookie.second);
135 exp += "; expires=Mon, 01 Jan 2001 00:00:00 GMT";
136 response->setCookie(shib_cookie.first.c_str(), exp.c_str());
140 HTTPResponse* response = dynamic_cast<HTTPResponse*>(&request);
142 pair<string,const char*> shib_cookie = application.getCookieNameProps("_shibsession_");
143 string exp(shib_cookie.second);
144 exp += "; expires=Mon, 01 Jan 2001 00:00:00 GMT";
145 response->setCookie(shib_cookie.first.c_str(), exp.c_str());
152 void remove(const Application& application, const HTTPRequest& request, HTTPResponse* response=NULL) {
153 pair<string,const char*> shib_cookie = application.getCookieNameProps("_shibsession_");
154 const char* session_id = request.getCookie(shib_cookie.first.c_str());
155 if (session_id && *session_id) {
157 string exp(shib_cookie.second);
158 exp += "; expires=Mon, 01 Jan 2001 00:00:00 GMT";
159 response->setCookie(shib_cookie.first.c_str(), exp.c_str());
161 remove(application, session_id);
169 unsigned long m_cacheTimeout;
171 StorageService* m_storage;
172 StorageService* m_storage_lite;
177 // maintain back-mappings of NameID/SessionIndex -> session key
178 void insert(const char* key, time_t expires, const char* name, const char* index);
179 bool stronglyMatches(const XMLCh* idp, const XMLCh* sp, const saml2::NameID& n1, const saml2::NameID& n2) const;
182 const DOMElement* m_root; // Only valid during initialization
183 unsigned long m_inprocTimeout;
185 // inproc means we buffer sessions in memory
187 map<string,StoredSession*> m_hashtable;
189 // management of buffered sessions
190 void dormant(const char* key);
191 static void* cleanup_fn(void*);
193 CondWait* shutdown_wait;
194 Thread* cleanup_thread;
197 class StoredSession : public virtual Session
200 StoredSession(SSCache* cache, DDF& obj) : m_obj(obj),
204 m_cache(cache), m_expires(0), m_lastAccess(time(NULL)), m_lock(NULL) {
205 auto_ptr_XMLCh exp(m_obj["expires"].string());
207 DateTime iso(exp.get());
209 m_expires = iso.getEpoch();
213 const char* nameid = obj["nameid"].string();
215 // Parse and bind the document into an XMLObject.
216 istringstream instr(nameid);
217 DOMDocument* doc = XMLToolingConfig::getConfig().getParser().parse(instr);
218 XercesJanitor<DOMDocument> janitor(doc);
219 auto_ptr<saml2::NameID> n(saml2::NameIDBuilder::buildNameID());
220 n->unmarshall(doc->getDocumentElement(), true);
222 m_nameid = n.release();
226 m_lock = Mutex::create();
232 for_each(m_attributes.begin(), m_attributes.end(), xmltooling::cleanup<Attribute>());
235 for_each(m_tokens.begin(), m_tokens.end(), cleanup_pair<string,Assertion>());
251 const char* getID() const {
254 const char* getApplicationID() const {
255 return m_obj["application_id"].string();
257 const char* getClientAddress() const {
258 return m_obj["client_addr"].string();
260 const char* getEntityID() const {
261 return m_obj["entity_id"].string();
263 const char* getProtocol() const {
264 return m_obj["protocol"].string();
266 const char* getAuthnInstant() const {
267 return m_obj["authn_instant"].string();
270 const saml2::NameID* getNameID() const {
274 const char* getSessionIndex() const {
275 return m_obj["session_index"].string();
277 const char* getAuthnContextClassRef() const {
278 return m_obj["authncontext_class"].string();
280 const char* getAuthnContextDeclRef() const {
281 return m_obj["authncontext_decl"].string();
283 const vector<Attribute*>& getAttributes() const {
284 if (m_attributes.empty())
285 unmarshallAttributes();
288 const multimap<string,const Attribute*>& getIndexedAttributes() const {
289 if (m_attributeIndex.empty()) {
290 if (m_attributes.empty())
291 unmarshallAttributes();
292 for (vector<Attribute*>::const_iterator a = m_attributes.begin(); a != m_attributes.end(); ++a) {
293 const vector<string>& aliases = (*a)->getAliases();
294 for (vector<string>::const_iterator alias = aliases.begin(); alias != aliases.end(); ++alias)
295 m_attributeIndex.insert(multimap<string,const Attribute*>::value_type(*alias, *a));
298 return m_attributeIndex;
300 const vector<const char*>& getAssertionIDs() const {
302 DDF ids = m_obj["assertions"];
303 DDF id = ids.first();
304 while (id.isstring()) {
305 m_ids.push_back(id.string());
312 void validate(const Application& application, const char* client_addr, time_t* timeout);
315 void addAttributes(const vector<Attribute*>& attributes);
316 const Assertion* getAssertion(const char* id) const;
317 void addAssertion(Assertion* assertion);
320 time_t getExpiration() const { return m_expires; }
321 time_t getLastAccess() const { return m_lastAccess; }
324 void unmarshallAttributes() const;
328 saml2::NameID* m_nameid;
329 mutable map<string,Assertion*> m_tokens;
331 mutable vector<Attribute*> m_attributes;
332 mutable multimap<string,const Attribute*> m_attributeIndex;
333 mutable vector<const char*> m_ids;
336 time_t m_expires,m_lastAccess;
340 SessionCache* SHIBSP_DLLLOCAL StorageServiceCacheFactory(const DOMElement* const & e)
342 return new SSCache(e);
346 Session* SessionCache::find(const Application& application, HTTPRequest& request, const char* client_addr, time_t* timeout)
348 return find(application, const_cast<const HTTPRequest&>(request), client_addr, timeout);
351 void SHIBSP_API shibsp::registerSessionCaches()
353 SPConfig::getConfig().SessionCacheManager.registerFactory(STORAGESERVICE_SESSION_CACHE, StorageServiceCacheFactory);
356 void StoredSession::unmarshallAttributes() const
358 Attribute* attribute;
359 DDF attrs = m_obj["attributes"];
360 DDF attr = attrs.first();
361 while (!attr.isnull()) {
363 attribute = Attribute::unmarshall(attr);
364 m_attributes.push_back(attribute);
365 if (m_cache->m_log.isDebugEnabled())
366 m_cache->m_log.debug("unmarshalled attribute (ID: %s) with %d value%s",
367 attribute->getId(), attr.first().integer(), attr.first().integer()!=1 ? "s" : "");
369 catch (AttributeException& ex) {
370 const char* id = attr.first().name();
371 m_cache->m_log.error("error unmarshalling attribute (ID: %s): %s", id ? id : "none", ex.what());
377 void StoredSession::validate(const Application& application, const char* client_addr, time_t* timeout)
379 time_t now = time(NULL);
383 if (now > m_expires) {
384 m_cache->m_log.info("session expired (ID: %s)", getID());
385 throw RetryableProfileException("Your session has expired, and you must re-authenticate.");
391 if (m_cache->m_log.isDebugEnabled())
392 m_cache->m_log.debug("comparing client address %s against %s", client_addr, getClientAddress());
393 if (!XMLString::equals(getClientAddress(),client_addr)) {
394 m_cache->m_log.warn("client address mismatch");
395 throw RetryableProfileException(
396 "Your IP address ($1) does not match the address recorded at the time the session was established.",
397 params(1,client_addr)
405 if (!SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess)) {
406 DDF in("touch::"STORAGESERVICE_SESSION_CACHE"::SessionCache"), out;
409 in.addmember("key").string(getID());
410 in.addmember("version").integer(m_obj["version"].integer());
412 // On 64-bit Windows, time_t doesn't fit in a long, so I'm using ISO timestamps.
413 #ifndef HAVE_GMTIME_R
414 struct tm* ptime=gmtime(timeout);
417 struct tm* ptime=gmtime_r(timeout,&res);
420 strftime(timebuf,32,"%Y-%m-%dT%H:%M:%SZ",ptime);
421 in.addmember("timeout").string(timebuf);
425 out=application.getServiceProvider().getListenerService()->send(in);
432 if (out.isstruct()) {
433 // We got an updated record back.
435 for_each(m_attributes.begin(), m_attributes.end(), xmltooling::cleanup<Attribute>());
436 m_attributes.clear();
437 m_attributeIndex.clear();
444 if (!m_cache->m_storage)
445 throw ConfigurationException("Session touch requires a StorageService.");
447 // Do a versioned read.
450 int curver = m_obj["version"].integer();
451 int ver = m_cache->m_storage->readText(getID(), "session", &record, &lastAccess, curver);
453 m_cache->m_log.warn("unsuccessful versioned read of session (ID: %s), cache out of sync?", getID());
454 throw RetryableProfileException("Your session has expired, and you must re-authenticate.");
457 // Adjust for expiration to recover last access time and check timeout.
458 lastAccess -= m_cache->m_cacheTimeout;
459 if (*timeout > 0 && now - lastAccess >= *timeout) {
460 m_cache->m_log.info("session timed out (ID: %s)", getID());
461 throw RetryableProfileException("Your session has expired, and you must re-authenticate.");
464 // Update storage expiration, if possible.
466 m_cache->m_storage->updateContext(getID(), now + m_cache->m_cacheTimeout);
468 catch (exception& ex) {
469 m_cache->m_log.error("failed to update session expiration: %s", ex.what());
473 // We got an updated record back.
475 istringstream in(record);
478 for_each(m_attributes.begin(), m_attributes.end(), xmltooling::cleanup<Attribute>());
479 m_attributes.clear();
480 m_attributeIndex.clear();
485 throw ConfigurationException("Session touch requires a StorageService.");
494 void StoredSession::addAttributes(const vector<Attribute*>& attributes)
497 xmltooling::NDC ndc("addAttributes");
500 if (!m_cache->m_storage)
501 throw ConfigurationException("Session modification requires a StorageService.");
503 m_cache->m_log.debug("adding attributes to session (%s)", getID());
508 DDF attrs = m_obj["attributes"];
510 attrs = m_obj.addmember("attributes").list();
511 for (vector<Attribute*>::const_iterator a=attributes.begin(); a!=attributes.end(); ++a) {
512 attr = (*a)->marshall();
516 // Tentatively increment the version.
517 m_obj["version"].integer(m_obj["version"].integer()+1);
521 string record(str.str());
524 ver = m_cache->m_storage->updateText(getID(), "session", record.c_str(), 0, m_obj["version"].integer()-1);
527 // Roll back modification to record.
528 m_obj["version"].integer(m_obj["version"].integer()-1);
529 vector<Attribute*>::size_type count = attributes.size();
531 attrs.last().destroy();
536 // Roll back modification to record.
537 m_obj["version"].integer(m_obj["version"].integer()-1);
538 vector<Attribute*>::size_type count = attributes.size();
540 attrs.last().destroy();
543 // Fatal problem with update.
544 throw IOException("Unable to update stored session.");
548 m_cache->m_log.warn("storage service indicates the record is out of sync, updating with a fresh copy...");
549 ver = m_cache->m_storage->readText(getID(), "session", &record, NULL);
551 m_cache->m_log.error("readText failed on StorageService for session (%s)", getID());
552 throw IOException("Unable to read back stored session.");
557 istringstream in(record);
561 for_each(m_attributes.begin(), m_attributes.end(), xmltooling::cleanup<Attribute>());
562 m_attributes.clear();
563 m_attributeIndex.clear();
564 newobj["version"].integer(ver);
570 } while (ver < 0); // negative indicates a sync issue so we retry
572 TransactionLog* xlog = SPConfig::getConfig().getServiceProvider()->getTransactionLog();
574 xlog->log.infoStream() <<
575 "Added the following attributes to session (ID: " <<
577 ") for (applicationId: " <<
578 m_obj["application_id"].string() <<
580 for (vector<Attribute*>::const_iterator a=attributes.begin(); a!=attributes.end(); ++a)
581 xlog->log.infoStream() << "\t" << (*a)->getId() << " (" << (*a)->valueCount() << " values)";
584 // We own them now, so clean them up.
585 for_each(attributes.begin(), attributes.end(), xmltooling::cleanup<Attribute>());
588 const Assertion* StoredSession::getAssertion(const char* id) const
590 if (!m_cache->m_storage)
591 throw ConfigurationException("Assertion retrieval requires a StorageService.");
593 map<string,Assertion*>::const_iterator i = m_tokens.find(id);
594 if (i!=m_tokens.end())
598 if (!m_cache->m_storage->readText(getID(), id, &tokenstr, NULL))
599 throw FatalProfileException("Assertion not found in cache.");
601 // Parse and bind the document into an XMLObject.
602 istringstream instr(tokenstr);
603 DOMDocument* doc = XMLToolingConfig::getConfig().getParser().parse(instr);
604 XercesJanitor<DOMDocument> janitor(doc);
605 auto_ptr<XMLObject> xmlObject(XMLObjectBuilder::buildOneFromElement(doc->getDocumentElement(), true));
608 Assertion* token = dynamic_cast<Assertion*>(xmlObject.get());
610 throw FatalProfileException("Request for cached assertion returned an unknown object type.");
612 // Transfer ownership to us.
618 void StoredSession::addAssertion(Assertion* assertion)
621 xmltooling::NDC ndc("addAssertion");
624 if (!m_cache->m_storage)
625 throw ConfigurationException("Session modification requires a StorageService.");
628 throw FatalProfileException("Unknown object type passed to session for storage.");
630 auto_ptr_char id(assertion->getID());
632 m_cache->m_log.debug("adding assertion (%s) to session (%s)", id.get(), getID());
635 if (!m_cache->m_storage->readText(getID(), "session", NULL, &exp))
636 throw IOException("Unable to load expiration time for stored session.");
638 ostringstream tokenstr;
639 tokenstr << *assertion;
640 if (!m_cache->m_storage->createText(getID(), id.get(), tokenstr.str().c_str(), exp))
641 throw IOException("Attempted to insert duplicate assertion ID into session.");
645 DDF token = DDF(NULL).string(id.get());
646 m_obj["assertions"].add(token);
648 // Tentatively increment the version.
649 m_obj["version"].integer(m_obj["version"].integer()+1);
653 string record(str.str());
656 ver = m_cache->m_storage->updateText(getID(), "session", record.c_str(), 0, m_obj["version"].integer()-1);
660 m_obj["version"].integer(m_obj["version"].integer()-1);
661 m_cache->m_storage->deleteText(getID(), id.get());
667 m_obj["version"].integer(m_obj["version"].integer()-1);
670 // Fatal problem with update.
671 m_cache->m_log.error("updateText failed on StorageService for session (%s)", getID());
672 m_cache->m_storage->deleteText(getID(), id.get());
673 throw IOException("Unable to update stored session.");
677 m_cache->m_log.warn("storage service indicates the record is out of sync, updating with a fresh copy...");
678 ver = m_cache->m_storage->readText(getID(), "session", &record, NULL);
680 m_cache->m_log.error("readText failed on StorageService for session (%s)", getID());
681 m_cache->m_storage->deleteText(getID(), id.get());
682 throw IOException("Unable to read back stored session.");
687 istringstream in(record);
691 for_each(m_attributes.begin(), m_attributes.end(), xmltooling::cleanup<Attribute>());
692 m_attributes.clear();
693 m_attributeIndex.clear();
694 newobj["version"].integer(ver);
700 } while (ver < 0); // negative indicates a sync issue so we retry
705 TransactionLog* xlog = SPConfig::getConfig().getServiceProvider()->getTransactionLog();
708 "Added assertion (ID: %s) to session for (applicationId: %s) with (ID: %s)",
709 id.get(), m_obj["application_id"].string(), getID()
715 SSCache::SSCache(const DOMElement* e)
716 : m_log(Category::getInstance(SHIBSP_LOGCAT".SessionCache")), inproc(true), m_cacheTimeout(28800),
718 m_storage(NULL), m_storage_lite(NULL),
720 m_root(e), m_inprocTimeout(900), m_lock(NULL), shutdown(false), shutdown_wait(NULL), cleanup_thread(NULL)
722 static const XMLCh cacheTimeout[] = UNICODE_LITERAL_12(c,a,c,h,e,T,i,m,e,o,u,t);
723 static const XMLCh inprocTimeout[] = UNICODE_LITERAL_13(i,n,p,r,o,c,T,i,m,e,o,u,t);
724 static const XMLCh _StorageService[] = UNICODE_LITERAL_14(S,t,o,r,a,g,e,S,e,r,v,i,c,e);
725 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);
727 SPConfig& conf = SPConfig::getConfig();
728 inproc = conf.isEnabled(SPConfig::InProcess);
731 const XMLCh* tag=e->getAttributeNS(NULL,cacheTimeout);
733 m_cacheTimeout = XMLString::parseInt(tag);
735 m_cacheTimeout=28800;
738 const XMLCh* tag=e->getAttributeNS(NULL,inprocTimeout);
740 m_inprocTimeout = XMLString::parseInt(tag);
741 if (!m_inprocTimeout)
748 if (conf.isEnabled(SPConfig::OutOfProcess)) {
749 const XMLCh* tag = e ? e->getAttributeNS(NULL,_StorageService) : NULL;
751 auto_ptr_char ssid(tag);
752 m_storage = conf.getServiceProvider()->getStorageService(ssid.get());
754 m_log.info("bound to StorageService (%s)", ssid.get());
757 throw ConfigurationException("SessionCache unable to locate StorageService, check configuration.");
759 tag = e ? e->getAttributeNS(NULL,_StorageServiceLite) : NULL;
761 auto_ptr_char ssid(tag);
762 m_storage_lite = conf.getServiceProvider()->getStorageService(ssid.get());
764 m_log.info("bound to StorageServiceLite (%s)", ssid.get());
766 if (!m_storage_lite) {
767 m_log.info("No StorageServiceLite specified. Using standard StorageService.");
768 m_storage_lite = m_storage;
773 ListenerService* listener=conf.getServiceProvider()->getListenerService(false);
775 if (!conf.isEnabled(SPConfig::OutOfProcess) && !listener)
776 throw ConfigurationException("SessionCache requires a ListenerService, but none available.");
777 m_lock = RWLock::create();
778 shutdown_wait = CondWait::create();
779 cleanup_thread = Thread::create(&cleanup_fn, (void*)this);
783 if (listener && conf.isEnabled(SPConfig::OutOfProcess)) {
784 listener->regListener("find::"STORAGESERVICE_SESSION_CACHE"::SessionCache",this);
785 listener->regListener("remove::"STORAGESERVICE_SESSION_CACHE"::SessionCache",this);
786 listener->regListener("touch::"STORAGESERVICE_SESSION_CACHE"::SessionCache",this);
789 m_log.info("no ListenerService available, cache remoting disabled");
798 // Shut down the cleanup thread and let it know...
800 shutdown_wait->signal();
801 cleanup_thread->join(NULL);
803 for_each(m_hashtable.begin(),m_hashtable.end(),cleanup_pair<string,StoredSession>());
805 delete shutdown_wait;
809 SPConfig& conf = SPConfig::getConfig();
810 ListenerService* listener=conf.getServiceProvider()->getListenerService(false);
811 if (listener && conf.isEnabled(SPConfig::OutOfProcess)) {
812 listener->unregListener("find::"STORAGESERVICE_SESSION_CACHE"::SessionCache",this);
813 listener->unregListener("remove::"STORAGESERVICE_SESSION_CACHE"::SessionCache",this);
814 listener->unregListener("touch::"STORAGESERVICE_SESSION_CACHE"::SessionCache",this);
824 auto_ptr_char temp(SAMLConfig::getConfig().generateIdentifier());
825 m_storage->createString("SessionCacheTest", temp.get(), "Test", time(NULL) + 60);
826 m_storage->deleteString("SessionCacheTest", temp.get());
829 void SSCache::insert(const char* key, time_t expires, const char* name, const char* index)
832 if (strlen(name) > 255) {
833 dup = string(name).substr(0,255);
838 DDFJanitor jobj(obj);
840 // Since we can't guarantee uniqueness, check for an existing record.
843 int ver = m_storage_lite->readText("NameID", name, &record, &recordexp);
845 // Existing record, so we need to unmarshall it.
846 istringstream in(record);
851 obj = DDF(NULL).structure();
854 if (!index || !*index)
856 DDF sessions = obj.addmember(index);
857 if (!sessions.islist())
859 DDF session = DDF(NULL).string(key);
860 sessions.add(session);
862 // Remarshall the record.
866 // Try and store it back...
868 ver = m_storage_lite->updateText("NameID", name, out.str().c_str(), max(expires, recordexp), ver);
870 // Out of sync, or went missing, so retry.
871 return insert(key, expires, name, index);
874 else if (!m_storage_lite->createText("NameID", name, out.str().c_str(), expires)) {
875 // Hit a dup, so just retry, hopefully hitting the other branch.
876 return insert(key, expires, name, index);
880 void SSCache::insert(
881 const Application& application,
882 const HTTPRequest& httpRequest,
883 HTTPResponse& httpResponse,
885 const saml2md::EntityDescriptor* issuer,
886 const XMLCh* protocol,
887 const saml2::NameID* nameid,
888 const XMLCh* authn_instant,
889 const XMLCh* session_index,
890 const XMLCh* authncontext_class,
891 const XMLCh* authncontext_decl,
892 const vector<const Assertion*>* tokens,
893 const vector<Attribute*>* attributes
897 xmltooling::NDC ndc("insert");
900 throw ConfigurationException("SessionCache insertion requires a StorageService.");
902 m_log.debug("creating new session");
904 time_t now = time(NULL);
905 auto_ptr_char index(session_index);
906 auto_ptr_char entity_id(issuer ? issuer->getEntityID() : NULL);
907 auto_ptr_char name(nameid ? nameid->getName() : NULL);
910 // Check for a pending logout.
911 if (strlen(name.get()) > 255)
912 const_cast<char*>(name.get())[255] = 0;
914 int ver = m_storage_lite->readText("Logout", name.get(), &pending);
917 DDFJanitor jpend(pendobj);
918 istringstream pstr(pending);
920 // IdP.SP.index contains logout expiration, if any.
921 DDF deadmenwalking = pendobj[issuer ? entity_id.get() : "_shibnull"][application.getRelyingParty(issuer)->getString("entityID").second];
922 const char* logexpstr = deadmenwalking[session_index ? index.get() : "_shibnull"].string();
923 if (!logexpstr && session_index) // we tried an exact session match, now try for NULL
924 logexpstr = deadmenwalking["_shibnull"].string();
926 auto_ptr_XMLCh dt(logexpstr);
927 DateTime dtobj(dt.get());
928 dtobj.parseDateTime();
929 time_t logexp = dtobj.getEpoch();
930 if (now - XMLToolingConfig::getConfig().clock_skew_secs < logexp)
931 throw FatalProfileException("A logout message from your identity provider has blocked your login attempt.");
936 auto_ptr_char key(SAMLConfig::getConfig().generateIdentifier());
938 // Store session properties in DDF.
939 DDF obj = DDF(key.get()).structure();
940 DDFJanitor entryobj(obj);
941 obj.addmember("version").integer(1);
942 obj.addmember("application_id").string(application.getId());
944 // On 64-bit Windows, time_t doesn't fit in a long, so I'm using ISO timestamps.
945 #ifndef HAVE_GMTIME_R
946 struct tm* ptime=gmtime(&expires);
949 struct tm* ptime=gmtime_r(&expires,&res);
952 strftime(timebuf,32,"%Y-%m-%dT%H:%M:%SZ",ptime);
953 obj.addmember("expires").string(timebuf);
955 obj.addmember("client_addr").string(httpRequest.getRemoteAddr().c_str());
957 obj.addmember("entity_id").string(entity_id.get());
959 auto_ptr_char prot(protocol);
960 obj.addmember("protocol").string(prot.get());
963 auto_ptr_char instant(authn_instant);
964 obj.addmember("authn_instant").string(instant.get());
967 obj.addmember("session_index").string(index.get());
968 if (authncontext_class) {
969 auto_ptr_char ac(authncontext_class);
970 obj.addmember("authncontext_class").string(ac.get());
972 if (authncontext_decl) {
973 auto_ptr_char ad(authncontext_decl);
974 obj.addmember("authncontext_decl").string(ad.get());
978 ostringstream namestr;
980 obj.addmember("nameid").string(namestr.str().c_str());
984 obj.addmember("assertions").list();
985 for (vector<const Assertion*>::const_iterator t = tokens->begin(); t!=tokens->end(); ++t) {
986 auto_ptr_char tokenid((*t)->getID());
987 DDF tokid = DDF(NULL).string(tokenid.get());
988 obj["assertions"].add(tokid);
994 DDF attrlist = obj.addmember("attributes").list();
995 for (vector<Attribute*>::const_iterator a=attributes->begin(); a!=attributes->end(); ++a) {
996 attr = (*a)->marshall();
1001 ostringstream record;
1004 m_log.debug("storing new session...");
1005 if (!m_storage->createText(key.get(), "session", record.str().c_str(), now + m_cacheTimeout))
1006 throw FatalProfileException("Attempted to create a session with a duplicate key.");
1008 // Store the reverse mapping for logout.
1011 insert(key.get(), expires, name.get(), index.get());
1013 catch (exception& ex) {
1014 m_log.error("error storing back mapping of NameID for logout: %s", ex.what());
1019 for (vector<const Assertion*>::const_iterator t = tokens->begin(); t!=tokens->end(); ++t) {
1020 ostringstream tokenstr;
1022 auto_ptr_char tokenid((*t)->getID());
1023 if (!m_storage->createText(key.get(), tokenid.get(), tokenstr.str().c_str(), now + m_cacheTimeout))
1024 throw IOException("duplicate assertion ID ($1)", params(1, tokenid.get()));
1027 catch (exception& ex) {
1028 m_log.error("error storing assertion along with session: %s", ex.what());
1032 const char* pid = obj["entity_id"].string();
1033 const char* prot = obj["protocol"].string();
1034 m_log.info("new session created: ID (%s) IdP (%s) Protocol(%s) Address (%s)",
1035 key.get(), pid ? pid : "none", prot ? prot : "none", httpRequest.getRemoteAddr().c_str());
1037 // Transaction Logging
1038 TransactionLog* xlog = application.getServiceProvider().getTransactionLog();
1039 Locker locker(xlog);
1040 xlog->log.infoStream() <<
1041 "New session (ID: " <<
1043 ") with (applicationId: " <<
1044 application.getId() <<
1045 ") for principal from (IdP: " <<
1046 (pid ? pid : "none") <<
1047 ") at (ClientAddress: " <<
1048 httpRequest.getRemoteAddr() <<
1049 ") with (NameIdentifier: " <<
1050 (nameid ? name.get() : "none") <<
1051 ") using (Protocol: " <<
1052 (prot ? prot : "none") <<
1053 ") from (AssertionID: " <<
1054 (tokens ? obj["assertions"].first().string() : "none") <<
1058 xlog->log.infoStream() <<
1059 "Cached the following attributes with session (ID: " <<
1061 ") for (applicationId: " <<
1062 application.getId() <<
1064 for (vector<Attribute*>::const_iterator a=attributes->begin(); a!=attributes->end(); ++a)
1065 xlog->log.infoStream() << "\t" << (*a)->getId() << " (" << (*a)->valueCount() << " values)";
1066 xlog->log.info("}");
1069 time_t cookieLifetime = 0;
1070 pair<string,const char*> shib_cookie = application.getCookieNameProps("_shibsession_", &cookieLifetime);
1071 string k(key.get());
1072 k += shib_cookie.second;
1074 if (cookieLifetime > 0) {
1075 cookieLifetime += now;
1076 #ifndef HAVE_GMTIME_R
1077 ptime=gmtime(&cookieLifetime);
1079 ptime=gmtime_r(&cookieLifetime,&res);
1081 char cookietimebuf[64];
1082 strftime(cookietimebuf,64,"; expires=%a, %d %b %Y %H:%M:%S GMT",ptime);
1086 httpResponse.setCookie(shib_cookie.first.c_str(), k.c_str());
1089 bool SSCache::matches(
1090 const Application& application,
1091 const xmltooling::HTTPRequest& request,
1092 const saml2md::EntityDescriptor* issuer,
1093 const saml2::NameID& nameid,
1094 const set<string>* indexes
1097 auto_ptr_char entityID(issuer ? issuer->getEntityID() : NULL);
1099 Session* session = find(application, request);
1101 Locker locker(session, false);
1102 if (XMLString::equals(session->getEntityID(), entityID.get()) && session->getNameID() &&
1103 stronglyMatches(issuer->getEntityID(), application.getRelyingParty(issuer)->getXMLString("entityID").second, nameid, *session->getNameID())) {
1104 return (!indexes || indexes->empty() || (session->getSessionIndex() ? (indexes->count(session->getSessionIndex())>0) : false));
1108 catch (exception& ex) {
1109 m_log.error("error while matching session: %s", ex.what());
1114 vector<string>::size_type SSCache::logout(
1115 const Application& application,
1116 const saml2md::EntityDescriptor* issuer,
1117 const saml2::NameID& nameid,
1118 const set<string>* indexes,
1120 vector<string>& sessionsKilled
1124 xmltooling::NDC ndc("logout");
1128 throw ConfigurationException("SessionCache insertion requires a StorageService.");
1130 auto_ptr_char entityID(issuer ? issuer->getEntityID() : NULL);
1131 auto_ptr_char name(nameid.getName());
1133 m_log.info("request to logout sessions from (%s) for (%s)", entityID.get() ? entityID.get() : "unknown", name.get());
1135 if (strlen(name.get()) > 255)
1136 const_cast<char*>(name.get())[255] = 0;
1139 DDFJanitor jobj(obj);
1144 // Record the logout to prevent post-delivered assertions.
1145 // On 64-bit Windows, time_t doesn't fit in a long, so I'm using ISO timestamps.
1146 #ifndef HAVE_GMTIME_R
1147 struct tm* ptime=gmtime(&expires);
1150 struct tm* ptime=gmtime_r(&expires,&res);
1153 strftime(timebuf,32,"%Y-%m-%dT%H:%M:%SZ",ptime);
1156 ver = m_storage_lite->readText("Logout", name.get(), &record, &oldexp);
1158 istringstream lin(record);
1162 obj = DDF(NULL).structure();
1165 // Structure is keyed by the IdP and SP, with a member per session index containing the expiration.
1166 DDF root = obj.addmember(issuer ? entityID.get() : "_shibnull").addmember(application.getRelyingParty(issuer)->getString("entityID").second);
1168 for (set<string>::const_iterator x = indexes->begin(); x!=indexes->end(); ++x)
1169 root.addmember(x->c_str()).string(timebuf);
1172 root.addmember("_shibnull").string(timebuf);
1180 ver = m_storage_lite->updateText("Logout", name.get(), lout.str().c_str(), max(expires, oldexp), ver);
1182 // Out of sync, or went missing, so retry.
1183 return logout(application, issuer, nameid, indexes, expires, sessionsKilled);
1186 else if (!m_storage_lite->createText("Logout", name.get(), lout.str().c_str(), expires)) {
1187 // Hit a dup, so just retry, hopefully hitting the other branch.
1188 return logout(application, issuer, nameid, indexes, expires, sessionsKilled);
1195 // Read in potentially matching sessions.
1196 ver = m_storage_lite->readText("NameID", name.get(), &record);
1198 m_log.debug("no active sessions to logout for supplied issuer and subject");
1202 istringstream in(record);
1205 // The record contains child lists for each known session index.
1207 DDF sessions = obj.first();
1208 while (sessions.islist()) {
1209 if (!indexes || indexes->empty() || indexes->count(sessions.name())) {
1210 key = sessions.first();
1211 while (key.isstring()) {
1212 // Fetch the session for comparison.
1213 Session* session = NULL;
1215 session = find(application, key.string());
1217 catch (exception& ex) {
1218 m_log.error("error locating session (%s): %s", key.string(), ex.what());
1222 Locker locker(session, false);
1224 if (XMLString::equals(session->getEntityID(), entityID.get())) {
1226 if (stronglyMatches(issuer->getEntityID(), application.getRelyingParty(issuer)->getXMLString("entityID").second, nameid, *session->getNameID())) {
1227 sessionsKilled.push_back(key.string());
1231 m_log.debug("session (%s) contained a non-matching NameID, leaving it alone", key.string());
1235 m_log.debug("session (%s) established by different IdP, leaving it alone", key.string());
1239 // Session's gone, so...
1240 sessionsKilled.push_back(key.string());
1243 key = sessions.next();
1246 // No sessions left for this index?
1247 if (sessions.first().isnull())
1250 sessions = obj.next();
1253 if (obj.first().isnull())
1256 // If possible, write back the mapping record (this isn't crucial).
1259 m_storage_lite->deleteText("NameID", name.get());
1261 else if (!sessionsKilled.empty()) {
1264 if (m_storage_lite->updateText("NameID", name.get(), out.str().c_str(), 0, ver) <= 0)
1265 m_log.warn("logout mapping record changed behind us, leaving it alone");
1268 catch (exception& ex) {
1269 m_log.error("error updating logout mapping record: %s", ex.what());
1272 return sessionsKilled.size();
1275 bool SSCache::stronglyMatches(const XMLCh* idp, const XMLCh* sp, const saml2::NameID& n1, const saml2::NameID& n2) const
1277 if (!XMLString::equals(n1.getName(), n2.getName()))
1280 const XMLCh* s1 = n1.getFormat();
1281 const XMLCh* s2 = n2.getFormat();
1283 s1 = saml2::NameID::UNSPECIFIED;
1285 s2 = saml2::NameID::UNSPECIFIED;
1286 if (!XMLString::equals(s1,s2))
1289 s1 = n1.getNameQualifier();
1290 s2 = n2.getNameQualifier();
1295 if (!XMLString::equals(s1,s2))
1298 s1 = n1.getSPNameQualifier();
1299 s2 = n2.getSPNameQualifier();
1304 if (!XMLString::equals(s1,s2))
1312 Session* SSCache::find(const Application& application, const char* key, const char* client_addr, time_t* timeout)
1315 xmltooling::NDC ndc("find");
1317 StoredSession* session=NULL;
1320 m_log.debug("searching local cache for session (%s)", key);
1322 map<string,StoredSession*>::const_iterator i=m_hashtable.find(key);
1323 if (i!=m_hashtable.end()) {
1324 // Save off and lock the session.
1325 session = i->second;
1328 m_log.debug("session found locally, validating it for use");
1336 if (!SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess)) {
1337 m_log.debug("session not found locally, remoting the search");
1338 // Remote the request.
1339 DDF in("find::"STORAGESERVICE_SESSION_CACHE"::SessionCache"), out;
1342 in.addmember("key").string(key);
1343 in.addmember("application_id").string(application.getId());
1344 if (timeout && *timeout) {
1345 // On 64-bit Windows, time_t doesn't fit in a long, so I'm using ISO timestamps.
1346 #ifndef HAVE_GMTIME_R
1347 struct tm* ptime=gmtime(timeout);
1350 struct tm* ptime=gmtime_r(timeout,&res);
1353 strftime(timebuf,32,"%Y-%m-%dT%H:%M:%SZ",ptime);
1354 in.addmember("timeout").string(timebuf);
1358 out=application.getServiceProvider().getListenerService()->send(in);
1359 if (!out.isstruct()) {
1361 m_log.debug("session not found in remote cache");
1365 // Wrap the results in a local entry and save it.
1366 session = new StoredSession(this, out);
1367 // The remote end has handled timeout issues, we handle address and expiration checks.
1376 // We're out of process, so we can search the storage service directly.
1379 throw ConfigurationException("SessionCache lookup requires a StorageService.");
1381 m_log.debug("searching for session (%s)", key);
1386 int ver = m_storage->readText(key, "session", &record, &lastAccess);
1390 m_log.debug("reconstituting session and checking validity");
1392 istringstream in(record);
1395 lastAccess -= m_cacheTimeout; // adjusts it back to the last time the record's timestamp was touched
1396 time_t now=time(NULL);
1398 if (timeout && *timeout > 0 && now - lastAccess >= *timeout) {
1399 m_log.info("session timed out (ID: %s)", key);
1400 remove(application, key);
1401 const char* eid = obj["entity_id"].string();
1404 throw RetryableProfileException("Your session has expired, and you must re-authenticate.");
1408 throw RetryableProfileException("Your session has expired, and you must re-authenticate.", namedparams(1, "entityID", eid2.c_str()));
1412 // Update storage expiration, if possible.
1414 m_storage->updateContext(key, now + m_cacheTimeout);
1416 catch (exception& ex) {
1417 m_log.error("failed to update session expiration: %s", ex.what());
1421 // Wrap the results in a local entry and save it.
1422 session = new StoredSession(this, obj);
1423 // We handled timeout issues, still need to handle address and expiration checks.
1426 throw ConfigurationException("SessionCache search requires a StorageService.");
1431 // Lock for writing and repeat the search to avoid duplication.
1433 SharedLock shared(m_lock, false);
1434 if (m_hashtable.count(key)) {
1435 // We're using an existing session entry.
1437 session = m_hashtable[key];
1441 m_hashtable[key]=session;
1447 if (!XMLString::equals(session->getApplicationID(), application.getId())) {
1448 m_log.error("an application (%s) tried to access another application's session", application.getId());
1453 // Verify currency and update the timestamp if indicated by caller.
1455 session->validate(application, client_addr, timeout);
1459 remove(application, key);
1466 void SSCache::remove(const Application& application, const char* key)
1469 xmltooling::NDC ndc("remove");
1471 // Take care of local copy.
1475 if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess)) {
1476 // Remove the session from storage directly.
1478 m_storage->deleteContext(key);
1479 m_log.info("removed session (%s)", key);
1481 TransactionLog* xlog = application.getServiceProvider().getTransactionLog();
1482 Locker locker(xlog);
1483 xlog->log.info("Destroyed session (applicationId: %s) (ID: %s)", application.getId(), key);
1485 throw ConfigurationException("SessionCache removal requires a StorageService.");
1489 // Remote the request.
1490 DDF in("remove::"STORAGESERVICE_SESSION_CACHE"::SessionCache");
1493 in.addmember("key").string(key);
1494 in.addmember("application_id").string(application.getId());
1496 DDF out = application.getServiceProvider().getListenerService()->send(in);
1501 void SSCache::dormant(const char* key)
1504 xmltooling::NDC ndc("dormant");
1507 m_log.debug("deleting local copy of session (%s)", key);
1509 // lock the cache for writing, which means we know nobody is sitting in find()
1512 // grab the entry from the table
1513 map<string,StoredSession*>::const_iterator i=m_hashtable.find(key);
1514 if (i==m_hashtable.end()) {
1519 // ok, remove the entry and lock it
1520 StoredSession* entry=i->second;
1521 m_hashtable.erase(key);
1527 // we can release the cache entry lock because we know we're not in the cache anymore
1533 void SSCache::cleanup()
1536 xmltooling::NDC ndc("cleanup");
1539 Mutex* mutex = Mutex::create();
1541 // Load our configuration details...
1542 static const XMLCh cleanupInterval[] = UNICODE_LITERAL_15(c,l,e,a,n,u,p,I,n,t,e,r,v,a,l);
1543 const XMLCh* tag=m_root ? m_root->getAttributeNS(NULL,cleanupInterval) : NULL;
1544 int rerun_timer = 900;
1546 rerun_timer = XMLString::parseInt(tag);
1547 if (rerun_timer <= 0)
1553 m_log.info("cleanup thread started...run every %d secs; timeout after %d secs", rerun_timer, m_inprocTimeout);
1556 shutdown_wait->timedwait(mutex,rerun_timer);
1560 // Ok, let's run through the cleanup process and clean out
1561 // really old sessions. This is a two-pass process. The
1562 // first pass is done holding a read-lock while we iterate over
1563 // the cache. The second pass doesn't need a lock because
1564 // the 'deletes' will lock the cache.
1566 // Pass 1: iterate over the map and find all entries that have not been
1567 // used in the allotted timeout.
1568 vector<string> stale_keys;
1569 time_t stale = time(NULL) - m_inprocTimeout;
1571 m_log.debug("cleanup thread running");
1574 for (map<string,StoredSession*>::const_iterator i=m_hashtable.begin(); i!=m_hashtable.end(); ++i) {
1575 // If the last access was BEFORE the stale timeout...
1577 time_t last=i->second->getLastAccess();
1578 i->second->unlock();
1580 stale_keys.push_back(i->first);
1584 if (!stale_keys.empty()) {
1585 m_log.info("purging %d old sessions", stale_keys.size());
1587 // Pass 2: walk through the list of stale entries and remove them from the cache
1588 for (vector<string>::const_iterator j = stale_keys.begin(); j != stale_keys.end(); ++j)
1589 dormant(j->c_str());
1592 m_log.debug("cleanup thread completed");
1595 m_log.info("cleanup thread exiting");
1602 void* SSCache::cleanup_fn(void* cache_p)
1605 // First, let's block all signals
1606 Thread::mask_all_signals();
1609 // Now run the cleanup process.
1610 reinterpret_cast<SSCache*>(cache_p)->cleanup();
1616 void SSCache::receive(DDF& in, ostream& out)
1619 xmltooling::NDC ndc("receive");
1622 if (!strcmp(in.name(),"find::"STORAGESERVICE_SESSION_CACHE"::SessionCache")) {
1623 const char* key=in["key"].string();
1625 throw ListenerException("Required parameters missing for session lookup.");
1627 const Application* app = SPConfig::getConfig().getServiceProvider()->getApplication(in["application_id"].string());
1629 throw ListenerException("Application not found, check configuration?");
1631 // Do an unversioned read.
1634 if (!m_storage->readText(key, "session", &record, &lastAccess)) {
1636 DDFJanitor jan(ret);
1641 // Adjust for expiration to recover last access time and check timeout.
1642 lastAccess -= m_cacheTimeout;
1643 time_t now=time(NULL);
1645 // See if we need to check for a timeout.
1646 if (in["timeout"].string()) {
1648 auto_ptr_XMLCh dt(in["timeout"].string());
1649 DateTime dtobj(dt.get());
1650 dtobj.parseDateTime();
1651 timeout = dtobj.getEpoch();
1653 if (timeout > 0 && now - lastAccess >= timeout) {
1654 m_log.info("session timed out (ID: %s)", key);
1656 throw RetryableProfileException("Your session has expired, and you must re-authenticate.");
1659 // Update storage expiration, if possible.
1661 m_storage->updateContext(key, now + m_cacheTimeout);
1663 catch (exception& ex) {
1664 m_log.error("failed to update session expiration: %s", ex.what());
1668 // Send the record back.
1671 else if (!strcmp(in.name(),"touch::"STORAGESERVICE_SESSION_CACHE"::SessionCache")) {
1672 const char* key=in["key"].string();
1674 throw ListenerException("Required parameters missing for session check.");
1676 // Do a versioned read.
1679 int curver = in["version"].integer();
1680 int ver = m_storage->readText(key, "session", &record, &lastAccess, curver);
1682 m_log.warn("unsuccessful versioned read of session (ID: %s), caches out of sync?", key);
1683 throw RetryableProfileException("Your session has expired, and you must re-authenticate.");
1686 // Adjust for expiration to recover last access time and check timeout.
1687 lastAccess -= m_cacheTimeout;
1688 time_t now=time(NULL);
1690 // See if we need to check for a timeout.
1692 auto_ptr_XMLCh dt(in["timeout"].string());
1694 DateTime dtobj(dt.get());
1695 dtobj.parseDateTime();
1696 timeout = dtobj.getEpoch();
1699 if (timeout > 0 && now - lastAccess >= timeout) {
1700 m_log.info("session timed out (ID: %s)", key);
1701 throw RetryableProfileException("Your session has expired, and you must re-authenticate.");
1704 // Update storage expiration, if possible.
1706 m_storage->updateContext(key, now + m_cacheTimeout);
1708 catch (exception& ex) {
1709 m_log.error("failed to update session expiration: %s", ex.what());
1713 // Send the record back.
1718 DDFJanitor jan(ret);
1722 else if (!strcmp(in.name(),"remove::"STORAGESERVICE_SESSION_CACHE"::SessionCache")) {
1723 const char* key=in["key"].string();
1725 throw ListenerException("Required parameter missing for session removal.");
1727 const Application* app = SPConfig::getConfig().getServiceProvider()->getApplication(in["application_id"].string());
1729 throw ConfigurationException("Application not found, check configuration?");
1733 DDFJanitor jan(ret);