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 <saml/SAMLConfig.h>
42 #include <xmltooling/util/NDC.h>
43 #include <xmltooling/util/StorageService.h>
44 #include <xmltooling/util/XMLHelper.h>
45 #include <xercesc/util/XMLUniDefs.hpp>
47 using namespace shibsp;
48 using namespace opensaml::saml2md;
49 using namespace opensaml;
50 using namespace xmltooling;
56 class StoredSession : public virtual Session
59 StoredSession(SSCache* cache, DDF& obj) : m_obj(obj), m_nameid(NULL), m_cache(cache) {
60 const char* nameid = obj["nameid"].string();
62 // Parse and bind the document into an XMLObject.
63 istringstream instr(nameid);
64 DOMDocument* doc = XMLToolingConfig::getConfig().getParser().parse(instr);
65 XercesJanitor<DOMDocument> janitor(doc);
66 auto_ptr<saml2::NameID> n(saml2::NameIDBuilder::buildNameID());
67 n->unmarshall(doc->getDocumentElement(), true);
69 m_nameid = n.release();
82 const char* getID() const {
85 const char* getClientAddress() const {
86 return m_obj["client_addr"].string();
88 const char* getEntityID() const {
89 return m_obj["entity_id"].string();
91 const char* getProtocol() const {
92 return m_obj["protocol"].string();
94 const char* getAuthnInstant() const {
95 return m_obj["authn_instant"].string();
97 const opensaml::saml2::NameID* getNameID() const {
100 const char* getSessionIndex() const {
101 return m_obj["session_index"].string();
103 const char* getAuthnContextClassRef() const {
104 return m_obj["authncontext_class"].string();
106 const char* getAuthnContextDeclRef() const {
107 return m_obj["authncontext_decl"].string();
109 const vector<Attribute*>& getAttributes() const {
110 if (m_attributes.empty())
111 unmarshallAttributes();
114 const multimap<string,const Attribute*>& getIndexedAttributes() const {
115 if (m_attributes.empty())
116 unmarshallAttributes();
117 return m_attributeIndex;
119 const vector<const char*>& getAssertionIDs() const {
121 DDF ids = m_obj["assertions"];
122 DDF id = ids.first();
123 while (id.isstring()) {
124 m_ids.push_back(id.string());
131 void addAttributes(const vector<Attribute*>& attributes);
132 const Assertion* getAssertion(const char* id) const;
133 void addAssertion(Assertion* assertion);
136 void unmarshallAttributes() const;
139 saml2::NameID* m_nameid;
140 mutable vector<Attribute*> m_attributes;
141 mutable multimap<string,const Attribute*> m_attributeIndex;
142 mutable vector<const char*> m_ids;
143 mutable map<string,Assertion*> m_tokens;
147 class SSCache : public SessionCache, public virtual Remoted
150 SSCache(const DOMElement* e);
153 void receive(DDF& in, ostream& out);
157 const Application& application,
158 const char* client_addr=NULL,
159 const saml2md::EntityDescriptor* issuer=NULL,
160 const XMLCh* protocol=NULL,
161 const saml2::NameID* nameid=NULL,
162 const XMLCh* authn_instant=NULL,
163 const XMLCh* session_index=NULL,
164 const XMLCh* authncontext_class=NULL,
165 const XMLCh* authncontext_decl=NULL,
166 const vector<const Assertion*>* tokens=NULL,
167 const vector<Attribute*>* attributes=NULL
169 Session* find(const char* key, const Application& application, const char* client_addr=NULL, time_t* timeout=NULL);
170 void remove(const char* key, const Application& application);
173 const saml2md::EntityDescriptor* issuer,
174 const saml2::NameID& nameid,
175 const set<string>* indexes,
176 const Application& application
178 vector<string>::size_type logout(
179 const saml2md::EntityDescriptor* issuer,
180 const saml2::NameID& nameid,
181 const set<string>* indexes,
183 const Application& application,
184 vector<string>& sessions
188 StorageService* m_storage;
191 // maintain back-mappings of NameID/SessionIndex -> session key
192 void insert(const char* key, time_t expires, const char* name, const char* index);
194 bool stronglyMatches(const XMLCh* idp, const XMLCh* sp, const saml2::NameID& n1, const saml2::NameID& n2) const;
197 SessionCache* SHIBSP_DLLLOCAL StorageServiceCacheFactory(const DOMElement* const & e)
199 return new SSCache(e);
202 static const XMLCh _StorageService[] = UNICODE_LITERAL_14(S,t,o,r,a,g,e,S,e,r,v,i,c,e);
205 StoredSession::~StoredSession()
209 for_each(m_attributes.begin(), m_attributes.end(), xmltooling::cleanup<Attribute>());
210 for_each(m_tokens.begin(), m_tokens.end(), cleanup_pair<string,Assertion>());
213 void StoredSession::unmarshallAttributes() const
215 Attribute* attribute;
216 DDF attrs = m_obj["attributes"];
217 DDF attr = attrs.first();
218 while (!attr.isnull()) {
220 attribute = Attribute::unmarshall(attr);
221 m_attributes.push_back(attribute);
222 m_attributeIndex.insert(make_pair(attribute->getId(), attribute));
223 if (m_cache->m_log.isDebugEnabled())
224 m_cache->m_log.debug("unmarshalled attribute (ID: %s) with %d value%s",
225 attribute->getId(), attr.first().integer(), attr.first().integer()!=1 ? "s" : "");
227 catch (AttributeException& ex) {
228 const char* id = attr.first().name();
229 m_cache->m_log.error("error unmarshalling attribute (ID: %s): %s", id ? id : "none", ex.what());
235 void StoredSession::addAttributes(const vector<Attribute*>& attributes)
238 xmltooling::NDC ndc("addAttributes");
241 m_cache->m_log.debug("adding attributes to session (%s)", getID());
246 DDF attrs = m_obj["attributes"];
248 attrs = m_obj.addmember("attributes").list();
249 for (vector<Attribute*>::const_iterator a=attributes.begin(); a!=attributes.end(); ++a) {
250 attr = (*a)->marshall();
254 // Tentatively increment the version.
255 m_obj["version"].integer(m_obj["version"].integer()+1);
259 string record(str.str());
262 ver = m_cache->m_storage->updateText(getID(), "session", record.c_str(), 0, m_obj["version"].integer()-1);
265 // Roll back modification to record.
266 m_obj["version"].integer(m_obj["version"].integer()-1);
267 vector<Attribute*>::size_type count = attributes.size();
269 attrs.last().destroy();
274 // Roll back modification to record.
275 m_obj["version"].integer(m_obj["version"].integer()-1);
276 vector<Attribute*>::size_type count = attributes.size();
278 attrs.last().destroy();
281 // Fatal problem with update.
282 throw IOException("Unable to update stored session.");
286 m_cache->m_log.warn("storage service indicates the record is out of sync, updating with a fresh copy...");
287 ver = m_cache->m_storage->readText(getID(), "session", &record, NULL);
289 m_cache->m_log.error("readText failed on StorageService for session (%s)", getID());
290 throw IOException("Unable to read back stored session.");
295 istringstream in(record);
299 for_each(m_attributes.begin(), m_attributes.end(), xmltooling::cleanup<Attribute>());
300 m_attributes.clear();
301 m_attributeIndex.clear();
302 newobj["version"].integer(ver);
308 } while (ver < 0); // negative indicates a sync issue so we retry
310 TransactionLog* xlog = SPConfig::getConfig().getServiceProvider()->getTransactionLog();
312 xlog->log.infoStream() <<
313 "Added the following attributes to session (ID: " <<
315 ") for (applicationId: " <<
316 m_obj["application_id"].string() <<
318 for (vector<Attribute*>::const_iterator a=attributes.begin(); a!=attributes.end(); ++a)
319 xlog->log.infoStream() << "\t" << (*a)->getId() << " (" << (*a)->valueCount() << " values)";
322 // We own them now, so clean them up.
323 for_each(attributes.begin(), attributes.end(), xmltooling::cleanup<Attribute>());
326 const Assertion* StoredSession::getAssertion(const char* id) const
328 map<string,Assertion*>::const_iterator i = m_tokens.find(id);
329 if (i!=m_tokens.end())
333 if (!m_cache->m_storage->readText(getID(), id, &tokenstr, NULL))
334 throw FatalProfileException("Assertion not found in cache.");
336 // Parse and bind the document into an XMLObject.
337 istringstream instr(tokenstr);
338 DOMDocument* doc = XMLToolingConfig::getConfig().getParser().parse(instr);
339 XercesJanitor<DOMDocument> janitor(doc);
340 auto_ptr<XMLObject> xmlObject(XMLObjectBuilder::buildOneFromElement(doc->getDocumentElement(), true));
343 Assertion* token = dynamic_cast<Assertion*>(xmlObject.get());
345 throw FatalProfileException("Request for cached assertion returned an unknown object type.");
347 // Transfer ownership to us.
353 void StoredSession::addAssertion(Assertion* assertion)
356 xmltooling::NDC ndc("addAssertion");
360 throw FatalProfileException("Unknown object type passed to session for storage.");
362 auto_ptr_char id(assertion->getID());
364 m_cache->m_log.debug("adding assertion (%s) to session (%s)", id.get(), getID());
367 if (!m_cache->m_storage->readText(getID(), "session", NULL, &exp))
368 throw IOException("Unable to load expiration time for stored session.");
370 ostringstream tokenstr;
371 tokenstr << *assertion;
372 if (!m_cache->m_storage->createText(getID(), id.get(), tokenstr.str().c_str(), exp))
373 throw IOException("Attempted to insert duplicate assertion ID into session.");
377 DDF token = DDF(NULL).string(id.get());
378 m_obj["assertions"].add(token);
380 // Tentatively increment the version.
381 m_obj["version"].integer(m_obj["version"].integer()+1);
385 string record(str.str());
388 ver = m_cache->m_storage->updateText(getID(), "session", record.c_str(), 0, m_obj["version"].integer()-1);
392 m_obj["version"].integer(m_obj["version"].integer()-1);
393 m_cache->m_storage->deleteText(getID(), id.get());
399 m_obj["version"].integer(m_obj["version"].integer()-1);
402 // Fatal problem with update.
403 m_cache->m_log.error("updateText failed on StorageService for session (%s)", getID());
404 m_cache->m_storage->deleteText(getID(), id.get());
405 throw IOException("Unable to update stored session.");
409 m_cache->m_log.warn("storage service indicates the record is out of sync, updating with a fresh copy...");
410 ver = m_cache->m_storage->readText(getID(), "session", &record, NULL);
412 m_cache->m_log.error("readText failed on StorageService for session (%s)", getID());
413 m_cache->m_storage->deleteText(getID(), id.get());
414 throw IOException("Unable to read back stored session.");
419 istringstream in(record);
423 for_each(m_attributes.begin(), m_attributes.end(), xmltooling::cleanup<Attribute>());
424 m_attributes.clear();
425 m_attributeIndex.clear();
426 newobj["version"].integer(ver);
432 } while (ver < 0); // negative indicates a sync issue so we retry
437 TransactionLog* xlog = SPConfig::getConfig().getServiceProvider()->getTransactionLog();
440 "Added assertion (ID: %s) to session for (applicationId: %s) with (ID: %s)",
441 id.get(), m_obj["application_id"].string(), getID()
445 SSCache::SSCache(const DOMElement* e)
446 : SessionCache(e), m_log(Category::getInstance(SHIBSP_LOGCAT".SessionCache")), m_storage(NULL)
448 SPConfig& conf = SPConfig::getConfig();
449 const XMLCh* tag = e ? e->getAttributeNS(NULL,_StorageService) : NULL;
451 auto_ptr_char ssid(tag);
452 m_storage = conf.getServiceProvider()->getStorageService(ssid.get());
454 m_log.info("bound to StorageService (%s)", ssid.get());
456 throw ConfigurationException("SessionCache unable to locate StorageService, check configuration.");
459 ListenerService* listener=conf.getServiceProvider()->getListenerService(false);
460 if (listener && conf.isEnabled(SPConfig::OutOfProcess)) {
461 listener->regListener("find::"REMOTED_SESSION_CACHE"::SessionCache",this);
462 listener->regListener("remove::"REMOTED_SESSION_CACHE"::SessionCache",this);
463 listener->regListener("touch::"REMOTED_SESSION_CACHE"::SessionCache",this);
464 listener->regListener("getAssertion::"REMOTED_SESSION_CACHE"::SessionCache",this);
467 m_log.info("no ListenerService available, cache remoting disabled");
473 SPConfig& conf = SPConfig::getConfig();
474 ListenerService* listener=conf.getServiceProvider()->getListenerService(false);
475 if (listener && conf.isEnabled(SPConfig::OutOfProcess)) {
476 listener->unregListener("find::"REMOTED_SESSION_CACHE"::SessionCache",this);
477 listener->unregListener("remove::"REMOTED_SESSION_CACHE"::SessionCache",this);
478 listener->unregListener("touch::"REMOTED_SESSION_CACHE"::SessionCache",this);
479 listener->unregListener("getAssertion::"REMOTED_SESSION_CACHE"::SessionCache",this);
483 void SSCache::insert(const char* key, time_t expires, const char* name, const char* index)
486 if (strlen(name) > 255) {
487 dup = string(name).substr(0,255);
492 DDFJanitor jobj(obj);
494 // Since we can't guarantee uniqueness, check for an existing record.
497 int ver = m_storage->readText("NameID", name, &record, &recordexp);
499 // Existing record, so we need to unmarshall it.
500 istringstream in(record);
508 if (!index || !*index)
510 DDF sessions = obj.addmember(index);
511 if (!sessions.islist())
513 DDF session = DDF(NULL).string(key);
514 sessions.add(session);
516 // Remarshall the record.
520 // Try and store it back...
522 ver = m_storage->updateText("NameID", name, out.str().c_str(), max(expires, recordexp), ver);
524 // Out of sync, or went missing, so retry.
525 return insert(key, expires, name, index);
528 else if (!m_storage->createText("NameID", name, out.str().c_str(), expires)) {
529 // Hit a dup, so just retry, hopefully hitting the other branch.
530 return insert(key, expires, name, index);
534 string SSCache::insert(
536 const Application& application,
537 const char* client_addr,
538 const saml2md::EntityDescriptor* issuer,
539 const XMLCh* protocol,
540 const saml2::NameID* nameid,
541 const XMLCh* authn_instant,
542 const XMLCh* session_index,
543 const XMLCh* authncontext_class,
544 const XMLCh* authncontext_decl,
545 const vector<const Assertion*>* tokens,
546 const vector<Attribute*>* attributes
550 xmltooling::NDC ndc("insert");
553 m_log.debug("creating new session");
555 time_t now = time(NULL);
556 auto_ptr_char index(session_index);
557 auto_ptr_char entity_id(issuer ? issuer->getEntityID() : NULL);
558 auto_ptr_char name(nameid ? nameid->getName() : NULL);
561 // Check for a pending logout.
562 if (strlen(name.get()) > 255)
563 const_cast<char*>(name.get())[255] = 0;
565 int ver = m_storage->readText("Logout", name.get(), &pending);
568 DDFJanitor jpend(pendobj);
569 istringstream pstr(pending);
571 // IdP.SP.index contains logout expiration, if any.
572 DDF deadmenwalking = pendobj[issuer ? entity_id.get() : "_shibnull"][application.getString("entityID").second];
573 const char* logexpstr = deadmenwalking[session_index ? index.get() : "_shibnull"].string();
574 if (!logexpstr && session_index) // we tried an exact session match, now try for NULL
575 logexpstr = deadmenwalking["_shibnull"].string();
577 auto_ptr_XMLCh dt(logexpstr);
578 DateTime dtobj(dt.get());
579 dtobj.parseDateTime();
580 time_t logexp = dtobj.getEpoch();
581 if (now - XMLToolingConfig::getConfig().clock_skew_secs < logexp)
582 throw FatalProfileException("A logout message from your identity provider has blocked your login attempt.");
587 auto_ptr_char key(SAMLConfig::getConfig().generateIdentifier());
589 // Store session properties in DDF.
590 DDF obj = DDF(key.get()).structure();
591 obj.addmember("version").integer(1);
592 obj.addmember("application_id").string(application.getId());
594 // On 64-bit Windows, time_t doesn't fit in a long, so I'm using ISO timestamps.
595 #ifndef HAVE_GMTIME_R
596 struct tm* ptime=gmtime(&expires);
599 struct tm* ptime=gmtime_r(&expires,&res);
602 strftime(timebuf,32,"%Y-%m-%dT%H:%M:%SZ",ptime);
603 obj.addmember("expires").string(timebuf);
606 obj.addmember("client_addr").string(client_addr);
608 obj.addmember("entity_id").string(entity_id.get());
610 auto_ptr_char prot(protocol);
611 obj.addmember("protocol").string(prot.get());
614 auto_ptr_char instant(authn_instant);
615 obj.addmember("authn_instant").string(instant.get());
618 obj.addmember("session_index").string(index.get());
619 if (authncontext_class) {
620 auto_ptr_char ac(authncontext_class);
621 obj.addmember("authncontext_class").string(ac.get());
623 if (authncontext_decl) {
624 auto_ptr_char ad(authncontext_decl);
625 obj.addmember("authncontext_decl").string(ad.get());
629 ostringstream namestr;
631 obj.addmember("nameid").string(namestr.str().c_str());
635 obj.addmember("assertions").list();
636 for (vector<const Assertion*>::const_iterator t = tokens->begin(); t!=tokens->end(); ++t) {
637 auto_ptr_char tokenid((*t)->getID());
638 DDF tokid = DDF(NULL).string(tokenid.get());
639 obj["assertions"].add(tokid);
645 DDF attrlist = obj.addmember("attributes").list();
646 for (vector<Attribute*>::const_iterator a=attributes->begin(); a!=attributes->end(); ++a) {
647 attr = (*a)->marshall();
652 ostringstream record;
655 m_log.debug("storing new session...");
656 if (!m_storage->createText(key.get(), "session", record.str().c_str(), now + m_cacheTimeout))
657 throw FatalProfileException("Attempted to create a session with a duplicate key.");
659 // Store the reverse mapping for logout.
662 insert(key.get(), expires, name.get(), index.get());
664 catch (exception& ex) {
665 m_log.error("error storing back mapping of NameID for logout: %s", ex.what());
670 for (vector<const Assertion*>::const_iterator t = tokens->begin(); t!=tokens->end(); ++t) {
671 ostringstream tokenstr;
673 auto_ptr_char tokenid((*t)->getID());
674 if (!m_storage->createText(key.get(), tokenid.get(), tokenstr.str().c_str(), now + m_cacheTimeout))
675 throw IOException("duplicate assertion ID ($1)", params(1, tokenid.get()));
678 catch (exception& ex) {
679 m_log.error("error storing assertion along with session: %s", ex.what());
683 const char* pid = obj["entity_id"].string();
684 m_log.info("new session created: SessionID (%s) IdP (%s) Address (%s)", key.get(), pid ? pid : "none", client_addr);
686 // Transaction Logging
687 TransactionLog* xlog = application.getServiceProvider().getTransactionLog();
689 xlog->log.infoStream() <<
690 "New session (ID: " <<
692 ") with (applicationId: " <<
693 application.getId() <<
694 ") for principal from (IdP: " <<
695 (pid ? pid : "none") <<
696 ") at (ClientAddress: " <<
697 (client_addr ? client_addr : "none") <<
698 ") with (NameIdentifier: " <<
699 (nameid ? name.get() : "none") <<
703 xlog->log.infoStream() <<
704 "Cached the following attributes with session (ID: " <<
706 ") for (applicationId: " <<
707 application.getId() <<
709 for (vector<Attribute*>::const_iterator a=attributes->begin(); a!=attributes->end(); ++a)
710 xlog->log.infoStream() << "\t" << (*a)->getId() << " (" << (*a)->valueCount() << " values)";
717 Session* SSCache::find(const char* key, const Application& application, const char* client_addr, time_t* timeout)
720 xmltooling::NDC ndc("find");
723 m_log.debug("searching for session (%s)", key);
727 int ver = m_storage->readText(key, "session", &record, &lastAccess);
731 m_log.debug("reconstituting session and checking validity");
734 istringstream in(record);
737 if (!XMLString::equals(obj["application_id"].string(), application.getId())) {
738 m_log.error("an application (%s) tried to access another application's session", application.getId());
744 if (m_log.isDebugEnabled())
745 m_log.debug("comparing client address %s against %s", client_addr, obj["client_addr"].string());
746 if (strcmp(obj["client_addr"].string(),client_addr)) {
747 m_log.warn("client address mismatch");
748 remove(key, application);
749 RetryableProfileException ex(
750 "Your IP address ($1) does not match the address recorded at the time the session was established.",
751 params(1,client_addr)
753 string eid(obj["entity_id"].string());
757 MetadataProvider* m=application.getMetadataProvider();
759 annotateException(&ex,m->getEntityDescriptor(eid.c_str(),false)); // throws it
763 lastAccess -= m_cacheTimeout; // adjusts it back to the last time the record's timestamp was touched
764 time_t now=time(NULL);
766 if (timeout && *timeout > 0 && now - lastAccess >= *timeout) {
767 m_log.info("session timed out (ID: %s)", key);
768 remove(key, application);
769 RetryableProfileException ex("Your session has expired, and you must re-authenticate.");
770 string eid(obj["entity_id"].string());
774 MetadataProvider* m=application.getMetadataProvider();
776 annotateException(&ex,m->getEntityDescriptor(eid.c_str(),false)); // throws it
779 auto_ptr_XMLCh exp(obj["expires"].string());
781 DateTime iso(exp.get());
783 if (now > iso.getEpoch()) {
784 m_log.info("session expired (ID: %s)", key);
785 remove(key, application);
786 RetryableProfileException ex("Your session has expired, and you must re-authenticate.");
787 string eid(obj["entity_id"].string());
791 MetadataProvider* m=application.getMetadataProvider();
793 annotateException(&ex,m->getEntityDescriptor(eid.c_str(),false)); // throws it
798 // Update storage expiration, if possible.
800 m_storage->updateContext(key, now + m_cacheTimeout);
802 catch (exception& ex) {
803 m_log.error("failed to update session expiration: %s", ex.what());
807 // Finally build the Session object.
809 return new StoredSession(this, obj);
817 void SSCache::remove(const char* key, const Application& application)
820 xmltooling::NDC ndc("remove");
823 m_storage->deleteContext(key);
824 m_log.info("removed session (%s)", key);
826 TransactionLog* xlog = application.getServiceProvider().getTransactionLog();
828 xlog->log.info("Destroyed session (applicationId: %s) (ID: %s)", application.getId(), key);
831 bool SSCache::matches(
833 const saml2md::EntityDescriptor* issuer,
834 const saml2::NameID& nameid,
835 const set<string>* indexes,
836 const Application& application
839 auto_ptr_char entityID(issuer ? issuer->getEntityID() : NULL);
841 Session* session = find(key, application);
843 Locker locker(session);
844 if (XMLString::equals(session->getEntityID(), entityID.get()) && session->getNameID() &&
845 stronglyMatches(issuer->getEntityID(), application.getXMLString("entityID").second, nameid, *session->getNameID())) {
846 return (!indexes || indexes->empty() || (session->getSessionIndex() ? (indexes->count(session->getSessionIndex())>0) : false));
850 catch (exception& ex) {
851 m_log.error("error while matching session (%s): %s", key, ex.what());
856 vector<string>::size_type SSCache::logout(
857 const saml2md::EntityDescriptor* issuer,
858 const saml2::NameID& nameid,
859 const set<string>* indexes,
861 const Application& application,
862 vector<string>& sessionsKilled
866 xmltooling::NDC ndc("logout");
869 auto_ptr_char entityID(issuer ? issuer->getEntityID() : NULL);
870 auto_ptr_char name(nameid.getName());
872 m_log.info("request to logout sessions from (%s) for (%s)", entityID.get() ? entityID.get() : "unknown", name.get());
874 if (strlen(name.get()) > 255)
875 const_cast<char*>(name.get())[255] = 0;
878 DDFJanitor jobj(obj);
883 // Record the logout to prevent post-delivered assertions.
884 // On 64-bit Windows, time_t doesn't fit in a long, so I'm using ISO timestamps.
885 #ifndef HAVE_GMTIME_R
886 struct tm* ptime=gmtime(&expires);
889 struct tm* ptime=gmtime_r(&expires,&res);
892 strftime(timebuf,32,"%Y-%m-%dT%H:%M:%SZ",ptime);
895 ver = m_storage->readText("Logout", name.get(), &record, &oldexp);
897 istringstream lin(record);
901 obj = DDF(NULL).structure();
904 // Structure is keyed by the IdP and SP, with a member per session index containing the expiration.
905 DDF root = obj.addmember(issuer ? entityID.get() : "_shibnull").addmember(application.getString("entityID").second);
907 for (set<string>::const_iterator x = indexes->begin(); x!=indexes->end(); ++x)
908 root.addmember(x->c_str()).string(timebuf);
911 root.addmember("_shibnull").string(timebuf);
919 ver = m_storage->updateText("Logout", name.get(), lout.str().c_str(), max(expires, oldexp), ver);
921 // Out of sync, or went missing, so retry.
922 return logout(issuer, nameid, indexes, expires, application, sessionsKilled);
925 else if (!m_storage->createText("Logout", name.get(), lout.str().c_str(), expires)) {
926 // Hit a dup, so just retry, hopefully hitting the other branch.
927 return logout(issuer, nameid, indexes, expires, application, sessionsKilled);
934 // Read in potentially matching sessions.
935 ver = m_storage->readText("NameID", name.get(), &record);
937 m_log.debug("no active sessions to logout for supplied issuer and subject");
941 istringstream in(record);
944 // The record contains child lists for each known session index.
946 DDF sessions = obj.first();
947 while (sessions.islist()) {
948 if (!indexes || indexes->empty() || indexes->count(sessions.name())) {
949 key = sessions.first();
950 while (key.isstring()) {
951 // Fetch the session for comparison.
952 Session* session = NULL;
954 session = find(key.string(), application);
956 catch (exception& ex) {
957 m_log.error("error locating session (%s): %s", key.string(), ex.what());
961 Locker locker(session);
963 if (XMLString::equals(session->getEntityID(), entityID.get())) {
965 if (stronglyMatches(issuer->getEntityID(), application.getXMLString("entityID").second, nameid, *session->getNameID())) {
966 sessionsKilled.push_back(key.string());
970 m_log.debug("session (%s) contained a non-matching NameID, leaving it alone", key.string());
974 m_log.debug("session (%s) established by different IdP, leaving it alone", key.string());
978 // Session's gone, so...
979 sessionsKilled.push_back(key.string());
982 key = sessions.next();
985 // No sessions left for this index?
986 if (sessions.first().isnull())
989 sessions = obj.next();
992 if (obj.first().isnull())
995 // If possible, write back the mapping record (this isn't crucial).
998 m_storage->deleteText("NameID", name.get());
1000 else if (!sessionsKilled.empty()) {
1003 if (m_storage->updateText("NameID", name.get(), out.str().c_str(), 0, ver) <= 0)
1004 m_log.warn("logout mapping record changed behind us, leaving it alone");
1007 catch (exception& ex) {
1008 m_log.error("error updating logout mapping record: %s", ex.what());
1011 return sessionsKilled.size();
1014 bool SSCache::stronglyMatches(const XMLCh* idp, const XMLCh* sp, const saml2::NameID& n1, const saml2::NameID& n2) const
1016 if (!XMLString::equals(n1.getName(), n2.getName()))
1019 const XMLCh* s1 = n1.getFormat();
1020 const XMLCh* s2 = n2.getFormat();
1022 s1 = saml2::NameID::UNSPECIFIED;
1024 s2 = saml2::NameID::UNSPECIFIED;
1025 if (!XMLString::equals(s1,s2))
1028 s1 = n1.getNameQualifier();
1029 s2 = n2.getNameQualifier();
1034 if (!XMLString::equals(s1,s2))
1037 s1 = n1.getSPNameQualifier();
1038 s2 = n2.getSPNameQualifier();
1043 if (!XMLString::equals(s1,s2))
1049 void SSCache::receive(DDF& in, ostream& out)
1052 xmltooling::NDC ndc("receive");
1055 if (!strcmp(in.name(),"find::"REMOTED_SESSION_CACHE"::SessionCache")) {
1056 const char* key=in["key"].string();
1058 throw ListenerException("Required parameters missing for session removal.");
1060 const Application* app = SPConfig::getConfig().getServiceProvider()->getApplication(in["application_id"].string());
1062 throw ListenerException("Application not found, check configuration?");
1064 // Do an unversioned read.
1067 if (!m_storage->readText(key, "session", &record, &lastAccess)) {
1069 DDFJanitor jan(ret);
1074 // Adjust for expiration to recover last access time and check timeout.
1075 lastAccess -= m_cacheTimeout;
1076 time_t now=time(NULL);
1078 // See if we need to check for a timeout.
1079 if (in["timeout"].string()) {
1081 auto_ptr_XMLCh dt(in["timeout"].string());
1082 DateTime dtobj(dt.get());
1083 dtobj.parseDateTime();
1084 timeout = dtobj.getEpoch();
1086 if (timeout > 0 && now - lastAccess >= timeout) {
1087 m_log.info("session timed out (ID: %s)", key);
1089 throw RetryableProfileException("Your session has expired, and you must re-authenticate.");
1092 // Update storage expiration, if possible.
1094 m_storage->updateContext(key, now + m_cacheTimeout);
1096 catch (exception& ex) {
1097 m_log.error("failed to update session expiration: %s", ex.what());
1101 // Send the record back.
1104 else if (!strcmp(in.name(),"touch::"REMOTED_SESSION_CACHE"::SessionCache")) {
1105 const char* key=in["key"].string();
1107 throw ListenerException("Required parameters missing for session check.");
1109 // Do a versioned read.
1112 int curver = in["version"].integer();
1113 int ver = m_storage->readText(key, "session", &record, &lastAccess, curver);
1115 m_log.warn("unsuccessful versioned read of session (ID: %s), caches out of sync?", key);
1116 throw RetryableProfileException("Your session has expired, and you must re-authenticate.");
1119 // Adjust for expiration to recover last access time and check timeout.
1120 lastAccess -= m_cacheTimeout;
1121 time_t now=time(NULL);
1123 // See if we need to check for a timeout.
1125 auto_ptr_XMLCh dt(in["timeout"].string());
1127 DateTime dtobj(dt.get());
1128 dtobj.parseDateTime();
1129 timeout = dtobj.getEpoch();
1132 if (timeout > 0 && now - lastAccess >= timeout) {
1133 m_log.info("session timed out (ID: %s)", key);
1134 throw RetryableProfileException("Your session has expired, and you must re-authenticate.");
1137 // Update storage expiration, if possible.
1139 m_storage->updateContext(key, now + m_cacheTimeout);
1141 catch (exception& ex) {
1142 m_log.error("failed to update session expiration: %s", ex.what());
1146 // Send the record back.
1151 DDFJanitor jan(ret);
1155 else if (!strcmp(in.name(),"remove::"REMOTED_SESSION_CACHE"::SessionCache")) {
1156 const char* key=in["key"].string();
1158 throw ListenerException("Required parameter missing for session removal.");
1160 const Application* app = SPConfig::getConfig().getServiceProvider()->getApplication(in["application_id"].string());
1162 throw ListenerException("Application not found, check configuration?");
1166 DDFJanitor jan(ret);
1169 else if (!strcmp(in.name(),"getAssertion::"REMOTED_SESSION_CACHE"::SessionCache")) {
1170 const char* key=in["key"].string();
1171 const char* id=in["id"].string();
1173 throw ListenerException("Required parameters missing for assertion retrieval.");
1175 if (!m_storage->readText(key, id, &token, NULL))
1176 throw FatalProfileException("Assertion not found in cache.");