2 * Copyright 2001-2007 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 "SessionCache.h"
36 #include "TransactionLog.h"
37 #include "attribute/Attribute.h"
38 #include "remoting/ListenerService.h"
39 #include "util/SPConstants.h"
41 #include <xmltooling/util/NDC.h>
42 #include <xmltooling/util/XMLHelper.h>
43 #include <xercesc/util/XMLUniDefs.hpp>
46 # include <saml/SAMLConfig.h>
47 # include <xmltooling/util/StorageService.h>
48 using namespace opensaml::saml2md;
51 # include <xmltooling/util/DateTime.h>
54 using namespace shibsp;
55 using namespace opensaml;
56 using namespace xmltooling;
62 class SSCache : public SessionCache
64 ,public virtual Remoted
68 SSCache(const DOMElement* e);
72 void receive(DDF& in, ostream& out);
76 const Application& application,
77 const HTTPRequest& httpRequest,
78 HTTPResponse& httpResponse,
79 const saml2md::EntityDescriptor* issuer=NULL,
80 const XMLCh* protocol=NULL,
81 const saml2::NameID* nameid=NULL,
82 const XMLCh* authn_instant=NULL,
83 const XMLCh* session_index=NULL,
84 const XMLCh* authncontext_class=NULL,
85 const XMLCh* authncontext_decl=NULL,
86 const vector<const Assertion*>* tokens=NULL,
87 const vector<Attribute*>* attributes=NULL
89 vector<string>::size_type logout(
90 const saml2md::EntityDescriptor* issuer,
91 const saml2::NameID& nameid,
92 const set<string>* indexes,
94 const Application& application,
95 vector<string>& sessions
98 const xmltooling::HTTPRequest& request,
99 const saml2md::EntityDescriptor* issuer,
100 const saml2::NameID& nameid,
101 const set<string>* indexes,
102 const Application& application
105 Session* find(const char* key, const Application& application, const char* client_addr=NULL, time_t* timeout=NULL);
106 void remove(const char* key, const Application& application);
109 string active(const xmltooling::HTTPRequest& request, const Application& application) const {
110 pair<string,const char*> shib_cookie = application.getCookieNameProps("_shibsession_");
111 const char* session_id = request.getCookie(shib_cookie.first.c_str());
112 return (session_id ? session_id : "");
115 Session* find(const HTTPRequest& request, const Application& application, const char* client_addr=NULL, time_t* timeout=NULL) {
116 string id = active(request, application);
118 return find(id.c_str(), application, client_addr, timeout);
122 void remove(const HTTPRequest& request, HTTPResponse* response, const Application& application) {
123 pair<string,const char*> shib_cookie = application.getCookieNameProps("_shibsession_");
124 const char* session_id = request.getCookie(shib_cookie.first.c_str());
125 if (session_id && *session_id) {
127 response->setCookie(shib_cookie.first.c_str(), shib_cookie.second);
128 remove(session_id, application);
136 unsigned long m_cacheTimeout;
138 StorageService* m_storage;
143 // maintain back-mappings of NameID/SessionIndex -> session key
144 void insert(const char* key, time_t expires, const char* name, const char* index);
145 bool stronglyMatches(const XMLCh* idp, const XMLCh* sp, const saml2::NameID& n1, const saml2::NameID& n2) const;
148 const DOMElement* m_root; // Only valid during initialization
149 unsigned long m_inprocTimeout;
151 // inproc means we buffer sessions in memory
153 map<string,StoredSession*> m_hashtable;
155 // management of buffered sessions
156 void dormant(const char* key);
157 static void* cleanup_fn(void*);
159 CondWait* shutdown_wait;
160 Thread* cleanup_thread;
163 class StoredSession : public virtual Session
166 StoredSession(SSCache* cache, DDF& obj) : m_obj(obj),
170 m_cache(cache), m_expires(0), m_lastAccess(time(NULL)), m_lock(NULL) {
171 auto_ptr_XMLCh exp(m_obj["expires"].string());
173 DateTime iso(exp.get());
175 m_expires = iso.getEpoch();
179 const char* nameid = obj["nameid"].string();
181 // Parse and bind the document into an XMLObject.
182 istringstream instr(nameid);
183 DOMDocument* doc = XMLToolingConfig::getConfig().getParser().parse(instr);
184 XercesJanitor<DOMDocument> janitor(doc);
185 auto_ptr<saml2::NameID> n(saml2::NameIDBuilder::buildNameID());
186 n->unmarshall(doc->getDocumentElement(), true);
188 m_nameid = n.release();
192 m_lock = Mutex::create();
198 for_each(m_attributes.begin(), m_attributes.end(), xmltooling::cleanup<Attribute>());
201 for_each(m_tokens.begin(), m_tokens.end(), cleanup_pair<string,Assertion>());
217 const char* getID() const {
220 const char* getApplicationID() const {
221 return m_obj["application_id"].string();
223 const char* getClientAddress() const {
224 return m_obj["client_addr"].string();
226 const char* getEntityID() const {
227 return m_obj["entity_id"].string();
229 const char* getProtocol() const {
230 return m_obj["protocol"].string();
232 const char* getAuthnInstant() const {
233 return m_obj["authn_instant"].string();
236 const saml2::NameID* getNameID() const {
240 const char* getSessionIndex() const {
241 return m_obj["session_index"].string();
243 const char* getAuthnContextClassRef() const {
244 return m_obj["authncontext_class"].string();
246 const char* getAuthnContextDeclRef() const {
247 return m_obj["authncontext_decl"].string();
249 const vector<Attribute*>& getAttributes() const {
250 if (m_attributes.empty())
251 unmarshallAttributes();
254 const multimap<string,const Attribute*>& getIndexedAttributes() const {
255 if (m_attributeIndex.empty()) {
256 if (m_attributes.empty())
257 unmarshallAttributes();
258 for (vector<Attribute*>::const_iterator a = m_attributes.begin(); a != m_attributes.end(); ++a) {
259 const vector<string>& aliases = (*a)->getAliases();
260 for (vector<string>::const_iterator alias = aliases.begin(); alias != aliases.end(); ++alias)
261 m_attributeIndex.insert(multimap<string,const Attribute*>::value_type(*alias, *a));
264 return m_attributeIndex;
266 const vector<const char*>& getAssertionIDs() const {
268 DDF ids = m_obj["assertions"];
269 DDF id = ids.first();
270 while (id.isstring()) {
271 m_ids.push_back(id.string());
278 void validate(const Application& application, const char* client_addr, time_t* timeout);
281 void addAttributes(const vector<Attribute*>& attributes);
282 const Assertion* getAssertion(const char* id) const;
283 void addAssertion(Assertion* assertion);
286 time_t getExpiration() const { return m_expires; }
287 time_t getLastAccess() const { return m_lastAccess; }
290 void unmarshallAttributes() const;
294 saml2::NameID* m_nameid;
295 mutable map<string,Assertion*> m_tokens;
297 mutable vector<Attribute*> m_attributes;
298 mutable multimap<string,const Attribute*> m_attributeIndex;
299 mutable vector<const char*> m_ids;
302 time_t m_expires,m_lastAccess;
306 SessionCache* SHIBSP_DLLLOCAL StorageServiceCacheFactory(const DOMElement* const & e)
308 return new SSCache(e);
312 void SHIBSP_API shibsp::registerSessionCaches()
314 SPConfig::getConfig().SessionCacheManager.registerFactory(STORAGESERVICE_SESSION_CACHE, StorageServiceCacheFactory);
317 void StoredSession::unmarshallAttributes() const
319 Attribute* attribute;
320 DDF attrs = m_obj["attributes"];
321 DDF attr = attrs.first();
322 while (!attr.isnull()) {
324 attribute = Attribute::unmarshall(attr);
325 m_attributes.push_back(attribute);
326 if (m_cache->m_log.isDebugEnabled())
327 m_cache->m_log.debug("unmarshalled attribute (ID: %s) with %d value%s",
328 attribute->getId(), attr.first().integer(), attr.first().integer()!=1 ? "s" : "");
330 catch (AttributeException& ex) {
331 const char* id = attr.first().name();
332 m_cache->m_log.error("error unmarshalling attribute (ID: %s): %s", id ? id : "none", ex.what());
338 void StoredSession::validate(const Application& application, const char* client_addr, time_t* timeout)
340 time_t now = time(NULL);
344 if (now > m_expires) {
345 m_cache->m_log.info("session expired (ID: %s)", getID());
346 throw RetryableProfileException("Your session has expired, and you must re-authenticate.");
352 if (m_cache->m_log.isDebugEnabled())
353 m_cache->m_log.debug("comparing client address %s against %s", client_addr, getClientAddress());
354 if (!XMLString::equals(getClientAddress(),client_addr)) {
355 m_cache->m_log.warn("client address mismatch");
356 throw RetryableProfileException(
357 "Your IP address ($1) does not match the address recorded at the time the session was established.",
358 params(1,client_addr)
366 if (!SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess)) {
367 DDF in("touch::"STORAGESERVICE_SESSION_CACHE"::SessionCache"), out;
370 in.addmember("key").string(getID());
371 in.addmember("version").integer(m_obj["version"].integer());
373 // On 64-bit Windows, time_t doesn't fit in a long, so I'm using ISO timestamps.
374 #ifndef HAVE_GMTIME_R
375 struct tm* ptime=gmtime(timeout);
378 struct tm* ptime=gmtime_r(timeout,&res);
381 strftime(timebuf,32,"%Y-%m-%dT%H:%M:%SZ",ptime);
382 in.addmember("timeout").string(timebuf);
386 out=application.getServiceProvider().getListenerService()->send(in);
393 if (out.isstruct()) {
394 // We got an updated record back.
396 for_each(m_attributes.begin(), m_attributes.end(), xmltooling::cleanup<Attribute>());
397 m_attributes.clear();
398 m_attributeIndex.clear();
405 if (!m_cache->m_storage)
406 throw ConfigurationException("Session touch requires a StorageService.");
408 // Do a versioned read.
411 int curver = m_obj["version"].integer();
412 int ver = m_cache->m_storage->readText(getID(), "session", &record, &lastAccess, curver);
414 m_cache->m_log.warn("unsuccessful versioned read of session (ID: %s), cache out of sync?", getID());
415 throw RetryableProfileException("Your session has expired, and you must re-authenticate.");
418 // Adjust for expiration to recover last access time and check timeout.
419 lastAccess -= m_cache->m_cacheTimeout;
420 if (*timeout > 0 && now - lastAccess >= *timeout) {
421 m_cache->m_log.info("session timed out (ID: %s)", getID());
422 throw RetryableProfileException("Your session has expired, and you must re-authenticate.");
425 // Update storage expiration, if possible.
427 m_cache->m_storage->updateContext(getID(), now + m_cache->m_cacheTimeout);
429 catch (exception& ex) {
430 m_cache->m_log.error("failed to update session expiration: %s", ex.what());
434 // We got an updated record back.
436 istringstream in(record);
439 for_each(m_attributes.begin(), m_attributes.end(), xmltooling::cleanup<Attribute>());
440 m_attributes.clear();
441 m_attributeIndex.clear();
446 throw ConfigurationException("Session touch requires a StorageService.");
455 void StoredSession::addAttributes(const vector<Attribute*>& attributes)
458 xmltooling::NDC ndc("addAttributes");
461 if (!m_cache->m_storage)
462 throw ConfigurationException("Session modification requires a StorageService.");
464 m_cache->m_log.debug("adding attributes to session (%s)", getID());
469 DDF attrs = m_obj["attributes"];
471 attrs = m_obj.addmember("attributes").list();
472 for (vector<Attribute*>::const_iterator a=attributes.begin(); a!=attributes.end(); ++a) {
473 attr = (*a)->marshall();
477 // Tentatively increment the version.
478 m_obj["version"].integer(m_obj["version"].integer()+1);
482 string record(str.str());
485 ver = m_cache->m_storage->updateText(getID(), "session", record.c_str(), 0, m_obj["version"].integer()-1);
488 // Roll back modification to record.
489 m_obj["version"].integer(m_obj["version"].integer()-1);
490 vector<Attribute*>::size_type count = attributes.size();
492 attrs.last().destroy();
497 // Roll back modification to record.
498 m_obj["version"].integer(m_obj["version"].integer()-1);
499 vector<Attribute*>::size_type count = attributes.size();
501 attrs.last().destroy();
504 // Fatal problem with update.
505 throw IOException("Unable to update stored session.");
509 m_cache->m_log.warn("storage service indicates the record is out of sync, updating with a fresh copy...");
510 ver = m_cache->m_storage->readText(getID(), "session", &record, NULL);
512 m_cache->m_log.error("readText failed on StorageService for session (%s)", getID());
513 throw IOException("Unable to read back stored session.");
518 istringstream in(record);
522 for_each(m_attributes.begin(), m_attributes.end(), xmltooling::cleanup<Attribute>());
523 m_attributes.clear();
524 m_attributeIndex.clear();
525 newobj["version"].integer(ver);
531 } while (ver < 0); // negative indicates a sync issue so we retry
533 TransactionLog* xlog = SPConfig::getConfig().getServiceProvider()->getTransactionLog();
535 xlog->log.infoStream() <<
536 "Added the following attributes to session (ID: " <<
538 ") for (applicationId: " <<
539 m_obj["application_id"].string() <<
541 for (vector<Attribute*>::const_iterator a=attributes.begin(); a!=attributes.end(); ++a)
542 xlog->log.infoStream() << "\t" << (*a)->getId() << " (" << (*a)->valueCount() << " values)";
545 // We own them now, so clean them up.
546 for_each(attributes.begin(), attributes.end(), xmltooling::cleanup<Attribute>());
549 const Assertion* StoredSession::getAssertion(const char* id) const
551 if (!m_cache->m_storage)
552 throw ConfigurationException("Assertion retrieval requires a StorageService.");
554 map<string,Assertion*>::const_iterator i = m_tokens.find(id);
555 if (i!=m_tokens.end())
559 if (!m_cache->m_storage->readText(getID(), id, &tokenstr, NULL))
560 throw FatalProfileException("Assertion not found in cache.");
562 // Parse and bind the document into an XMLObject.
563 istringstream instr(tokenstr);
564 DOMDocument* doc = XMLToolingConfig::getConfig().getParser().parse(instr);
565 XercesJanitor<DOMDocument> janitor(doc);
566 auto_ptr<XMLObject> xmlObject(XMLObjectBuilder::buildOneFromElement(doc->getDocumentElement(), true));
569 Assertion* token = dynamic_cast<Assertion*>(xmlObject.get());
571 throw FatalProfileException("Request for cached assertion returned an unknown object type.");
573 // Transfer ownership to us.
579 void StoredSession::addAssertion(Assertion* assertion)
582 xmltooling::NDC ndc("addAssertion");
585 if (!m_cache->m_storage)
586 throw ConfigurationException("Session modification requires a StorageService.");
589 throw FatalProfileException("Unknown object type passed to session for storage.");
591 auto_ptr_char id(assertion->getID());
593 m_cache->m_log.debug("adding assertion (%s) to session (%s)", id.get(), getID());
596 if (!m_cache->m_storage->readText(getID(), "session", NULL, &exp))
597 throw IOException("Unable to load expiration time for stored session.");
599 ostringstream tokenstr;
600 tokenstr << *assertion;
601 if (!m_cache->m_storage->createText(getID(), id.get(), tokenstr.str().c_str(), exp))
602 throw IOException("Attempted to insert duplicate assertion ID into session.");
606 DDF token = DDF(NULL).string(id.get());
607 m_obj["assertions"].add(token);
609 // Tentatively increment the version.
610 m_obj["version"].integer(m_obj["version"].integer()+1);
614 string record(str.str());
617 ver = m_cache->m_storage->updateText(getID(), "session", record.c_str(), 0, m_obj["version"].integer()-1);
621 m_obj["version"].integer(m_obj["version"].integer()-1);
622 m_cache->m_storage->deleteText(getID(), id.get());
628 m_obj["version"].integer(m_obj["version"].integer()-1);
631 // Fatal problem with update.
632 m_cache->m_log.error("updateText failed on StorageService for session (%s)", getID());
633 m_cache->m_storage->deleteText(getID(), id.get());
634 throw IOException("Unable to update stored session.");
638 m_cache->m_log.warn("storage service indicates the record is out of sync, updating with a fresh copy...");
639 ver = m_cache->m_storage->readText(getID(), "session", &record, NULL);
641 m_cache->m_log.error("readText failed on StorageService for session (%s)", getID());
642 m_cache->m_storage->deleteText(getID(), id.get());
643 throw IOException("Unable to read back stored session.");
648 istringstream in(record);
652 for_each(m_attributes.begin(), m_attributes.end(), xmltooling::cleanup<Attribute>());
653 m_attributes.clear();
654 m_attributeIndex.clear();
655 newobj["version"].integer(ver);
661 } while (ver < 0); // negative indicates a sync issue so we retry
666 TransactionLog* xlog = SPConfig::getConfig().getServiceProvider()->getTransactionLog();
669 "Added assertion (ID: %s) to session for (applicationId: %s) with (ID: %s)",
670 id.get(), m_obj["application_id"].string(), getID()
676 SSCache::SSCache(const DOMElement* e)
677 : m_log(Category::getInstance(SHIBSP_LOGCAT".SessionCache")), inproc(true), m_cacheTimeout(3600),
681 m_root(e), m_inprocTimeout(900), m_lock(NULL), shutdown(false), shutdown_wait(NULL), cleanup_thread(NULL)
683 static const XMLCh cacheTimeout[] = UNICODE_LITERAL_12(c,a,c,h,e,T,i,m,e,o,u,t);
684 static const XMLCh inprocTimeout[] = UNICODE_LITERAL_13(i,n,p,r,o,c,T,i,m,e,o,u,t);
685 static const XMLCh _StorageService[] = UNICODE_LITERAL_14(S,t,o,r,a,g,e,S,e,r,v,i,c,e);
687 SPConfig& conf = SPConfig::getConfig();
688 inproc = conf.isEnabled(SPConfig::InProcess);
691 const XMLCh* tag=e->getAttributeNS(NULL,cacheTimeout);
693 m_cacheTimeout = XMLString::parseInt(tag);
698 const XMLCh* tag=e->getAttributeNS(NULL,inprocTimeout);
700 m_inprocTimeout = XMLString::parseInt(tag);
701 if (!m_inprocTimeout)
708 if (conf.isEnabled(SPConfig::OutOfProcess)) {
709 const XMLCh* tag = e ? e->getAttributeNS(NULL,_StorageService) : NULL;
711 auto_ptr_char ssid(tag);
712 m_storage = conf.getServiceProvider()->getStorageService(ssid.get());
714 m_log.info("bound to StorageService (%s)", ssid.get());
717 throw ConfigurationException("SessionCache unable to locate StorageService, check configuration.");
721 ListenerService* listener=conf.getServiceProvider()->getListenerService(false);
723 if (!conf.isEnabled(SPConfig::OutOfProcess) && !listener)
724 throw ConfigurationException("SessionCache requires a ListenerService, but none available.");
725 m_lock = RWLock::create();
726 shutdown_wait = CondWait::create();
727 cleanup_thread = Thread::create(&cleanup_fn, (void*)this);
731 if (listener && conf.isEnabled(SPConfig::OutOfProcess)) {
732 listener->regListener("find::"STORAGESERVICE_SESSION_CACHE"::SessionCache",this);
733 listener->regListener("remove::"STORAGESERVICE_SESSION_CACHE"::SessionCache",this);
734 listener->regListener("touch::"STORAGESERVICE_SESSION_CACHE"::SessionCache",this);
737 m_log.info("no ListenerService available, cache remoting disabled");
746 // Shut down the cleanup thread and let it know...
748 shutdown_wait->signal();
749 cleanup_thread->join(NULL);
751 for_each(m_hashtable.begin(),m_hashtable.end(),cleanup_pair<string,StoredSession>());
753 delete shutdown_wait;
757 SPConfig& conf = SPConfig::getConfig();
758 ListenerService* listener=conf.getServiceProvider()->getListenerService(false);
759 if (listener && conf.isEnabled(SPConfig::OutOfProcess)) {
760 listener->unregListener("find::"STORAGESERVICE_SESSION_CACHE"::SessionCache",this);
761 listener->unregListener("remove::"STORAGESERVICE_SESSION_CACHE"::SessionCache",this);
762 listener->unregListener("touch::"STORAGESERVICE_SESSION_CACHE"::SessionCache",this);
772 auto_ptr_char temp(SAMLConfig::getConfig().generateIdentifier());
773 m_storage->createString("SessionCacheTest", temp.get(), "Test", time(NULL) + 60);
774 m_storage->deleteString("SessionCacheTest", temp.get());
777 void SSCache::insert(const char* key, time_t expires, const char* name, const char* index)
780 if (strlen(name) > 255) {
781 dup = string(name).substr(0,255);
786 DDFJanitor jobj(obj);
788 // Since we can't guarantee uniqueness, check for an existing record.
791 int ver = m_storage->readText("NameID", name, &record, &recordexp);
793 // Existing record, so we need to unmarshall it.
794 istringstream in(record);
802 if (!index || !*index)
804 DDF sessions = obj.addmember(index);
805 if (!sessions.islist())
807 DDF session = DDF(NULL).string(key);
808 sessions.add(session);
810 // Remarshall the record.
814 // Try and store it back...
816 ver = m_storage->updateText("NameID", name, out.str().c_str(), max(expires, recordexp), ver);
818 // Out of sync, or went missing, so retry.
819 return insert(key, expires, name, index);
822 else if (!m_storage->createText("NameID", name, out.str().c_str(), expires)) {
823 // Hit a dup, so just retry, hopefully hitting the other branch.
824 return insert(key, expires, name, index);
828 void SSCache::insert(
830 const Application& application,
831 const HTTPRequest& httpRequest,
832 HTTPResponse& httpResponse,
833 const saml2md::EntityDescriptor* issuer,
834 const XMLCh* protocol,
835 const saml2::NameID* nameid,
836 const XMLCh* authn_instant,
837 const XMLCh* session_index,
838 const XMLCh* authncontext_class,
839 const XMLCh* authncontext_decl,
840 const vector<const Assertion*>* tokens,
841 const vector<Attribute*>* attributes
845 xmltooling::NDC ndc("insert");
848 throw ConfigurationException("SessionCache insertion requires a StorageService.");
850 m_log.debug("creating new session");
852 time_t now = time(NULL);
853 auto_ptr_char index(session_index);
854 auto_ptr_char entity_id(issuer ? issuer->getEntityID() : NULL);
855 auto_ptr_char name(nameid ? nameid->getName() : NULL);
858 // Check for a pending logout.
859 if (strlen(name.get()) > 255)
860 const_cast<char*>(name.get())[255] = 0;
862 int ver = m_storage->readText("Logout", name.get(), &pending);
865 DDFJanitor jpend(pendobj);
866 istringstream pstr(pending);
868 // IdP.SP.index contains logout expiration, if any.
869 DDF deadmenwalking = pendobj[issuer ? entity_id.get() : "_shibnull"][application.getString("entityID").second];
870 const char* logexpstr = deadmenwalking[session_index ? index.get() : "_shibnull"].string();
871 if (!logexpstr && session_index) // we tried an exact session match, now try for NULL
872 logexpstr = deadmenwalking["_shibnull"].string();
874 auto_ptr_XMLCh dt(logexpstr);
875 DateTime dtobj(dt.get());
876 dtobj.parseDateTime();
877 time_t logexp = dtobj.getEpoch();
878 if (now - XMLToolingConfig::getConfig().clock_skew_secs < logexp)
879 throw FatalProfileException("A logout message from your identity provider has blocked your login attempt.");
884 auto_ptr_char key(SAMLConfig::getConfig().generateIdentifier());
886 // Store session properties in DDF.
887 DDF obj = DDF(key.get()).structure();
888 obj.addmember("version").integer(1);
889 obj.addmember("application_id").string(application.getId());
891 // On 64-bit Windows, time_t doesn't fit in a long, so I'm using ISO timestamps.
892 #ifndef HAVE_GMTIME_R
893 struct tm* ptime=gmtime(&expires);
896 struct tm* ptime=gmtime_r(&expires,&res);
899 strftime(timebuf,32,"%Y-%m-%dT%H:%M:%SZ",ptime);
900 obj.addmember("expires").string(timebuf);
902 obj.addmember("client_addr").string(httpRequest.getRemoteAddr().c_str());
904 obj.addmember("entity_id").string(entity_id.get());
906 auto_ptr_char prot(protocol);
907 obj.addmember("protocol").string(prot.get());
910 auto_ptr_char instant(authn_instant);
911 obj.addmember("authn_instant").string(instant.get());
914 obj.addmember("session_index").string(index.get());
915 if (authncontext_class) {
916 auto_ptr_char ac(authncontext_class);
917 obj.addmember("authncontext_class").string(ac.get());
919 if (authncontext_decl) {
920 auto_ptr_char ad(authncontext_decl);
921 obj.addmember("authncontext_decl").string(ad.get());
925 ostringstream namestr;
927 obj.addmember("nameid").string(namestr.str().c_str());
931 obj.addmember("assertions").list();
932 for (vector<const Assertion*>::const_iterator t = tokens->begin(); t!=tokens->end(); ++t) {
933 auto_ptr_char tokenid((*t)->getID());
934 DDF tokid = DDF(NULL).string(tokenid.get());
935 obj["assertions"].add(tokid);
941 DDF attrlist = obj.addmember("attributes").list();
942 for (vector<Attribute*>::const_iterator a=attributes->begin(); a!=attributes->end(); ++a) {
943 attr = (*a)->marshall();
948 ostringstream record;
951 m_log.debug("storing new session...");
952 if (!m_storage->createText(key.get(), "session", record.str().c_str(), now + m_cacheTimeout))
953 throw FatalProfileException("Attempted to create a session with a duplicate key.");
955 // Store the reverse mapping for logout.
958 insert(key.get(), expires, name.get(), index.get());
960 catch (exception& ex) {
961 m_log.error("error storing back mapping of NameID for logout: %s", ex.what());
966 for (vector<const Assertion*>::const_iterator t = tokens->begin(); t!=tokens->end(); ++t) {
967 ostringstream tokenstr;
969 auto_ptr_char tokenid((*t)->getID());
970 if (!m_storage->createText(key.get(), tokenid.get(), tokenstr.str().c_str(), now + m_cacheTimeout))
971 throw IOException("duplicate assertion ID ($1)", params(1, tokenid.get()));
974 catch (exception& ex) {
975 m_log.error("error storing assertion along with session: %s", ex.what());
979 const char* pid = obj["entity_id"].string();
980 m_log.info("new session created: SessionID (%s) IdP (%s) Address (%s)", key.get(), pid ? pid : "none", httpRequest.getRemoteAddr().c_str());
982 // Transaction Logging
983 TransactionLog* xlog = application.getServiceProvider().getTransactionLog();
985 xlog->log.infoStream() <<
986 "New session (ID: " <<
988 ") with (applicationId: " <<
989 application.getId() <<
990 ") for principal from (IdP: " <<
991 (pid ? pid : "none") <<
992 ") at (ClientAddress: " <<
993 httpRequest.getRemoteAddr() <<
994 ") with (NameIdentifier: " <<
995 (nameid ? name.get() : "none") <<
999 xlog->log.infoStream() <<
1000 "Cached the following attributes with session (ID: " <<
1002 ") for (applicationId: " <<
1003 application.getId() <<
1005 for (vector<Attribute*>::const_iterator a=attributes->begin(); a!=attributes->end(); ++a)
1006 xlog->log.infoStream() << "\t" << (*a)->getId() << " (" << (*a)->valueCount() << " values)";
1007 xlog->log.info("}");
1010 pair<string,const char*> shib_cookie = application.getCookieNameProps("_shibsession_");
1011 string k(key.get());
\r
1012 k += shib_cookie.second;
1013 httpResponse.setCookie(shib_cookie.first.c_str(), k.c_str());
1016 bool SSCache::matches(
1017 const xmltooling::HTTPRequest& request,
1018 const saml2md::EntityDescriptor* issuer,
1019 const saml2::NameID& nameid,
1020 const set<string>* indexes,
1021 const Application& application
1024 auto_ptr_char entityID(issuer ? issuer->getEntityID() : NULL);
1026 Session* session = find(request, application);
1028 Locker locker(session, false);
1029 if (XMLString::equals(session->getEntityID(), entityID.get()) && session->getNameID() &&
1030 stronglyMatches(issuer->getEntityID(), application.getXMLString("entityID").second, nameid, *session->getNameID())) {
1031 return (!indexes || indexes->empty() || (session->getSessionIndex() ? (indexes->count(session->getSessionIndex())>0) : false));
1035 catch (exception& ex) {
1036 m_log.error("error while matching session: %s", ex.what());
1041 vector<string>::size_type SSCache::logout(
1042 const saml2md::EntityDescriptor* issuer,
1043 const saml2::NameID& nameid,
1044 const set<string>* indexes,
1046 const Application& application,
1047 vector<string>& sessionsKilled
1051 xmltooling::NDC ndc("logout");
1055 throw ConfigurationException("SessionCache insertion requires a StorageService.");
1057 auto_ptr_char entityID(issuer ? issuer->getEntityID() : NULL);
1058 auto_ptr_char name(nameid.getName());
1060 m_log.info("request to logout sessions from (%s) for (%s)", entityID.get() ? entityID.get() : "unknown", name.get());
1062 if (strlen(name.get()) > 255)
1063 const_cast<char*>(name.get())[255] = 0;
1066 DDFJanitor jobj(obj);
1071 // Record the logout to prevent post-delivered assertions.
1072 // On 64-bit Windows, time_t doesn't fit in a long, so I'm using ISO timestamps.
1073 #ifndef HAVE_GMTIME_R
1074 struct tm* ptime=gmtime(&expires);
1077 struct tm* ptime=gmtime_r(&expires,&res);
1080 strftime(timebuf,32,"%Y-%m-%dT%H:%M:%SZ",ptime);
1083 ver = m_storage->readText("Logout", name.get(), &record, &oldexp);
1085 istringstream lin(record);
1089 obj = DDF(NULL).structure();
1092 // Structure is keyed by the IdP and SP, with a member per session index containing the expiration.
1093 DDF root = obj.addmember(issuer ? entityID.get() : "_shibnull").addmember(application.getString("entityID").second);
1095 for (set<string>::const_iterator x = indexes->begin(); x!=indexes->end(); ++x)
1096 root.addmember(x->c_str()).string(timebuf);
1099 root.addmember("_shibnull").string(timebuf);
1107 ver = m_storage->updateText("Logout", name.get(), lout.str().c_str(), max(expires, oldexp), ver);
1109 // Out of sync, or went missing, so retry.
1110 return logout(issuer, nameid, indexes, expires, application, sessionsKilled);
1113 else if (!m_storage->createText("Logout", name.get(), lout.str().c_str(), expires)) {
1114 // Hit a dup, so just retry, hopefully hitting the other branch.
1115 return logout(issuer, nameid, indexes, expires, application, sessionsKilled);
1122 // Read in potentially matching sessions.
1123 ver = m_storage->readText("NameID", name.get(), &record);
1125 m_log.debug("no active sessions to logout for supplied issuer and subject");
1129 istringstream in(record);
1132 // The record contains child lists for each known session index.
1134 DDF sessions = obj.first();
1135 while (sessions.islist()) {
1136 if (!indexes || indexes->empty() || indexes->count(sessions.name())) {
1137 key = sessions.first();
1138 while (key.isstring()) {
1139 // Fetch the session for comparison.
1140 Session* session = NULL;
1142 session = find(key.string(), application);
1144 catch (exception& ex) {
1145 m_log.error("error locating session (%s): %s", key.string(), ex.what());
1149 Locker locker(session, false);
1151 if (XMLString::equals(session->getEntityID(), entityID.get())) {
1153 if (stronglyMatches(issuer->getEntityID(), application.getXMLString("entityID").second, nameid, *session->getNameID())) {
1154 sessionsKilled.push_back(key.string());
1158 m_log.debug("session (%s) contained a non-matching NameID, leaving it alone", key.string());
1162 m_log.debug("session (%s) established by different IdP, leaving it alone", key.string());
1166 // Session's gone, so...
1167 sessionsKilled.push_back(key.string());
1170 key = sessions.next();
1173 // No sessions left for this index?
1174 if (sessions.first().isnull())
1177 sessions = obj.next();
1180 if (obj.first().isnull())
1183 // If possible, write back the mapping record (this isn't crucial).
1186 m_storage->deleteText("NameID", name.get());
1188 else if (!sessionsKilled.empty()) {
1191 if (m_storage->updateText("NameID", name.get(), out.str().c_str(), 0, ver) <= 0)
1192 m_log.warn("logout mapping record changed behind us, leaving it alone");
1195 catch (exception& ex) {
1196 m_log.error("error updating logout mapping record: %s", ex.what());
1199 return sessionsKilled.size();
1202 bool SSCache::stronglyMatches(const XMLCh* idp, const XMLCh* sp, const saml2::NameID& n1, const saml2::NameID& n2) const
1204 if (!XMLString::equals(n1.getName(), n2.getName()))
1207 const XMLCh* s1 = n1.getFormat();
1208 const XMLCh* s2 = n2.getFormat();
1210 s1 = saml2::NameID::UNSPECIFIED;
1212 s2 = saml2::NameID::UNSPECIFIED;
1213 if (!XMLString::equals(s1,s2))
1216 s1 = n1.getNameQualifier();
1217 s2 = n2.getNameQualifier();
1222 if (!XMLString::equals(s1,s2))
1225 s1 = n1.getSPNameQualifier();
1226 s2 = n2.getSPNameQualifier();
1231 if (!XMLString::equals(s1,s2))
1239 Session* SSCache::find(const char* key, const Application& application, const char* client_addr, time_t* timeout)
1242 xmltooling::NDC ndc("find");
1244 StoredSession* session=NULL;
1247 m_log.debug("searching local cache for session (%s)", key);
1249 map<string,StoredSession*>::const_iterator i=m_hashtable.find(key);
1250 if (i!=m_hashtable.end()) {
1251 // Save off and lock the session.
1252 session = i->second;
1255 m_log.debug("session found locally, validating it for use");
1263 if (!SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess)) {
1264 m_log.debug("session not found locally, remoting the search");
1265 // Remote the request.
1266 DDF in("find::"STORAGESERVICE_SESSION_CACHE"::SessionCache"), out;
1269 in.addmember("key").string(key);
1270 in.addmember("application_id").string(application.getId());
1271 if (timeout && *timeout) {
1272 // On 64-bit Windows, time_t doesn't fit in a long, so I'm using ISO timestamps.
1273 #ifndef HAVE_GMTIME_R
1274 struct tm* ptime=gmtime(timeout);
1277 struct tm* ptime=gmtime_r(timeout,&res);
1280 strftime(timebuf,32,"%Y-%m-%dT%H:%M:%SZ",ptime);
1281 in.addmember("timeout").string(timebuf);
1285 out=application.getServiceProvider().getListenerService()->send(in);
1286 if (!out.isstruct()) {
1288 m_log.debug("session not found in remote cache");
1292 // Wrap the results in a local entry and save it.
1293 session = new StoredSession(this, out);
1294 // The remote end has handled timeout issues, we handle address and expiration checks.
1303 // We're out of process, so we can search the storage service directly.
1306 throw ConfigurationException("SessionCache lookup requires a StorageService.");
1308 m_log.debug("searching for session (%s)", key);
1313 int ver = m_storage->readText(key, "session", &record, &lastAccess);
1317 m_log.debug("reconstituting session and checking validity");
1319 istringstream in(record);
1322 lastAccess -= m_cacheTimeout; // adjusts it back to the last time the record's timestamp was touched
1323 time_t now=time(NULL);
1325 if (timeout && *timeout > 0 && now - lastAccess >= *timeout) {
1326 m_log.info("session timed out (ID: %s)", key);
1327 remove(key, application);
1328 RetryableProfileException ex("Your session has expired, and you must re-authenticate.");
1329 const char* eid = obj["entity_id"].string();
1336 MetadataProvider* m=application.getMetadataProvider();
1338 annotateException(&ex,m->getEntityDescriptor(MetadataProvider::Criteria(eid2.c_str(),NULL,NULL,false)).first); // throws it
1342 // Update storage expiration, if possible.
1344 m_storage->updateContext(key, now + m_cacheTimeout);
1346 catch (exception& ex) {
1347 m_log.error("failed to update session expiration: %s", ex.what());
1351 // Wrap the results in a local entry and save it.
1352 session = new StoredSession(this, obj);
1353 // We handled timeout issues, still need to handle address and expiration checks.
1356 throw ConfigurationException("SessionCache search requires a StorageService.");
1361 // Lock for writing and repeat the search to avoid duplication.
1363 SharedLock shared(m_lock, false);
1364 if (m_hashtable.count(key)) {
1365 // We're using an existing session entry.
1367 session = m_hashtable[key];
1371 m_hashtable[key]=session;
1377 if (!XMLString::equals(session->getApplicationID(), application.getId())) {
1378 m_log.error("an application (%s) tried to access another application's session", application.getId());
1383 // Verify currency and update the timestamp if indicated by caller.
1385 session->validate(application, client_addr, timeout);
1389 remove(key, application);
1396 void SSCache::remove(const char* key, const Application& application)
1399 xmltooling::NDC ndc("remove");
1401 // Take care of local copy.
1405 if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess)) {
1406 // Remove the session from storage directly.
1408 m_storage->deleteContext(key);
1409 m_log.info("removed session (%s)", key);
1411 TransactionLog* xlog = application.getServiceProvider().getTransactionLog();
1412 Locker locker(xlog);
1413 xlog->log.info("Destroyed session (applicationId: %s) (ID: %s)", application.getId(), key);
1415 throw ConfigurationException("SessionCache removal requires a StorageService.");
1419 // Remote the request.
1420 DDF in("remove::"STORAGESERVICE_SESSION_CACHE"::SessionCache");
1423 in.addmember("key").string(key);
1424 in.addmember("application_id").string(application.getId());
1426 DDF out = application.getServiceProvider().getListenerService()->send(in);
1431 void SSCache::dormant(const char* key)
1434 xmltooling::NDC ndc("dormant");
1437 m_log.debug("deleting local copy of session (%s)", key);
1439 // lock the cache for writing, which means we know nobody is sitting in find()
1442 // grab the entry from the table
1443 map<string,StoredSession*>::const_iterator i=m_hashtable.find(key);
1444 if (i==m_hashtable.end()) {
1449 // ok, remove the entry and lock it
1450 StoredSession* entry=i->second;
1451 m_hashtable.erase(key);
1457 // we can release the cache entry lock because we know we're not in the cache anymore
1463 void SSCache::cleanup()
1466 xmltooling::NDC ndc("cleanup");
1469 Mutex* mutex = Mutex::create();
1471 // Load our configuration details...
1472 static const XMLCh cleanupInterval[] = UNICODE_LITERAL_15(c,l,e,a,n,u,p,I,n,t,e,r,v,a,l);
1473 const XMLCh* tag=m_root ? m_root->getAttributeNS(NULL,cleanupInterval) : NULL;
1474 int rerun_timer = 900;
1476 rerun_timer = XMLString::parseInt(tag);
1477 if (rerun_timer <= 0)
1482 m_log.info("cleanup thread started...run every %d secs; timeout after %d secs", rerun_timer, m_inprocTimeout);
1485 shutdown_wait->timedwait(mutex,rerun_timer);
1489 // Ok, let's run through the cleanup process and clean out
1490 // really old sessions. This is a two-pass process. The
1491 // first pass is done holding a read-lock while we iterate over
1492 // the cache. The second pass doesn't need a lock because
1493 // the 'deletes' will lock the cache.
1495 // Pass 1: iterate over the map and find all entries that have not been
1496 // used in the allotted timeout.
1497 vector<string> stale_keys;
1498 time_t stale = time(NULL) - m_inprocTimeout;
1500 m_log.debug("cleanup thread running");
1503 for (map<string,StoredSession*>::const_iterator i=m_hashtable.begin(); i!=m_hashtable.end(); ++i) {
1504 // If the last access was BEFORE the stale timeout...
1506 time_t last=i->second->getLastAccess();
1507 i->second->unlock();
1509 stale_keys.push_back(i->first);
1513 if (!stale_keys.empty()) {
1514 m_log.info("purging %d old sessions", stale_keys.size());
1516 // Pass 2: walk through the list of stale entries and remove them from the cache
1517 for (vector<string>::const_iterator j = stale_keys.begin(); j != stale_keys.end(); ++j)
1518 dormant(j->c_str());
1521 m_log.debug("cleanup thread completed");
1524 m_log.info("cleanup thread exiting");
1531 void* SSCache::cleanup_fn(void* cache_p)
1534 // First, let's block all signals
1535 Thread::mask_all_signals();
1538 // Now run the cleanup process.
1539 reinterpret_cast<SSCache*>(cache_p)->cleanup();
1545 void SSCache::receive(DDF& in, ostream& out)
1548 xmltooling::NDC ndc("receive");
1551 if (!strcmp(in.name(),"find::"STORAGESERVICE_SESSION_CACHE"::SessionCache")) {
1552 const char* key=in["key"].string();
1554 throw ListenerException("Required parameters missing for session lookup.");
1556 const Application* app = SPConfig::getConfig().getServiceProvider()->getApplication(in["application_id"].string());
1558 throw ListenerException("Application not found, check configuration?");
1560 // Do an unversioned read.
1563 if (!m_storage->readText(key, "session", &record, &lastAccess)) {
1565 DDFJanitor jan(ret);
1570 // Adjust for expiration to recover last access time and check timeout.
1571 lastAccess -= m_cacheTimeout;
1572 time_t now=time(NULL);
1574 // See if we need to check for a timeout.
1575 if (in["timeout"].string()) {
1577 auto_ptr_XMLCh dt(in["timeout"].string());
1578 DateTime dtobj(dt.get());
1579 dtobj.parseDateTime();
1580 timeout = dtobj.getEpoch();
1582 if (timeout > 0 && now - lastAccess >= timeout) {
1583 m_log.info("session timed out (ID: %s)", key);
1585 throw RetryableProfileException("Your session has expired, and you must re-authenticate.");
1588 // Update storage expiration, if possible.
1590 m_storage->updateContext(key, now + m_cacheTimeout);
1592 catch (exception& ex) {
1593 m_log.error("failed to update session expiration: %s", ex.what());
1597 // Send the record back.
1600 else if (!strcmp(in.name(),"touch::"STORAGESERVICE_SESSION_CACHE"::SessionCache")) {
1601 const char* key=in["key"].string();
1603 throw ListenerException("Required parameters missing for session check.");
1605 // Do a versioned read.
1608 int curver = in["version"].integer();
1609 int ver = m_storage->readText(key, "session", &record, &lastAccess, curver);
1611 m_log.warn("unsuccessful versioned read of session (ID: %s), caches out of sync?", key);
1612 throw RetryableProfileException("Your session has expired, and you must re-authenticate.");
1615 // Adjust for expiration to recover last access time and check timeout.
1616 lastAccess -= m_cacheTimeout;
1617 time_t now=time(NULL);
1619 // See if we need to check for a timeout.
1621 auto_ptr_XMLCh dt(in["timeout"].string());
1623 DateTime dtobj(dt.get());
1624 dtobj.parseDateTime();
1625 timeout = dtobj.getEpoch();
1628 if (timeout > 0 && now - lastAccess >= timeout) {
1629 m_log.info("session timed out (ID: %s)", key);
1630 throw RetryableProfileException("Your session has expired, and you must re-authenticate.");
1633 // Update storage expiration, if possible.
1635 m_storage->updateContext(key, now + m_cacheTimeout);
1637 catch (exception& ex) {
1638 m_log.error("failed to update session expiration: %s", ex.what());
1642 // Send the record back.
1647 DDFJanitor jan(ret);
1651 else if (!strcmp(in.name(),"remove::"STORAGESERVICE_SESSION_CACHE"::SessionCache")) {
1652 const char* key=in["key"].string();
1654 throw ListenerException("Required parameter missing for session removal.");
1656 const Application* app = SPConfig::getConfig().getServiceProvider()->getApplication(in["application_id"].string());
1658 throw ConfigurationException("Application not found, check configuration?");
1662 DDFJanitor jan(ret);