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_attributeIndex.empty()) {
116 if (m_attributes.empty())
117 unmarshallAttributes();
118 for (vector<Attribute*>::const_iterator a = m_attributes.begin(); a != m_attributes.end(); ++a) {
119 const vector<string>& aliases = (*a)->getAliases();
120 for (vector<string>::const_iterator alias = aliases.begin(); alias != aliases.end(); ++alias)
121 m_attributeIndex.insert(make_pair(*alias, *a));
124 return m_attributeIndex;
126 const vector<const char*>& getAssertionIDs() const {
128 DDF ids = m_obj["assertions"];
129 DDF id = ids.first();
130 while (id.isstring()) {
131 m_ids.push_back(id.string());
138 void addAttributes(const vector<Attribute*>& attributes);
139 const Assertion* getAssertion(const char* id) const;
140 void addAssertion(Assertion* assertion);
143 void unmarshallAttributes() const;
146 saml2::NameID* m_nameid;
147 mutable vector<Attribute*> m_attributes;
148 mutable multimap<string,const Attribute*> m_attributeIndex;
149 mutable vector<const char*> m_ids;
150 mutable map<string,Assertion*> m_tokens;
154 class SSCache : public SessionCache, public virtual Remoted
157 SSCache(const DOMElement* e);
160 void receive(DDF& in, ostream& out);
164 const Application& application,
165 const char* client_addr=NULL,
166 const saml2md::EntityDescriptor* issuer=NULL,
167 const XMLCh* protocol=NULL,
168 const saml2::NameID* nameid=NULL,
169 const XMLCh* authn_instant=NULL,
170 const XMLCh* session_index=NULL,
171 const XMLCh* authncontext_class=NULL,
172 const XMLCh* authncontext_decl=NULL,
173 const vector<const Assertion*>* tokens=NULL,
174 const vector<Attribute*>* attributes=NULL
176 Session* find(const char* key, const Application& application, const char* client_addr=NULL, time_t* timeout=NULL);
177 void remove(const char* key, const Application& application);
180 const saml2md::EntityDescriptor* issuer,
181 const saml2::NameID& nameid,
182 const set<string>* indexes,
183 const Application& application
185 vector<string>::size_type logout(
186 const saml2md::EntityDescriptor* issuer,
187 const saml2::NameID& nameid,
188 const set<string>* indexes,
190 const Application& application,
191 vector<string>& sessions
195 StorageService* m_storage;
198 // maintain back-mappings of NameID/SessionIndex -> session key
199 void insert(const char* key, time_t expires, const char* name, const char* index);
201 bool stronglyMatches(const XMLCh* idp, const XMLCh* sp, const saml2::NameID& n1, const saml2::NameID& n2) const;
204 SessionCache* SHIBSP_DLLLOCAL StorageServiceCacheFactory(const DOMElement* const & e)
206 return new SSCache(e);
209 static const XMLCh _StorageService[] = UNICODE_LITERAL_14(S,t,o,r,a,g,e,S,e,r,v,i,c,e);
212 StoredSession::~StoredSession()
216 for_each(m_attributes.begin(), m_attributes.end(), xmltooling::cleanup<Attribute>());
217 for_each(m_tokens.begin(), m_tokens.end(), cleanup_pair<string,Assertion>());
220 void StoredSession::unmarshallAttributes() const
222 Attribute* attribute;
223 DDF attrs = m_obj["attributes"];
224 DDF attr = attrs.first();
225 while (!attr.isnull()) {
227 attribute = Attribute::unmarshall(attr);
228 m_attributes.push_back(attribute);
229 m_attributeIndex.insert(make_pair(attribute->getId(), attribute));
230 if (m_cache->m_log.isDebugEnabled())
231 m_cache->m_log.debug("unmarshalled attribute (ID: %s) with %d value%s",
232 attribute->getId(), attr.first().integer(), attr.first().integer()!=1 ? "s" : "");
234 catch (AttributeException& ex) {
235 const char* id = attr.first().name();
236 m_cache->m_log.error("error unmarshalling attribute (ID: %s): %s", id ? id : "none", ex.what());
242 void StoredSession::addAttributes(const vector<Attribute*>& attributes)
245 xmltooling::NDC ndc("addAttributes");
248 m_cache->m_log.debug("adding attributes to session (%s)", getID());
253 DDF attrs = m_obj["attributes"];
255 attrs = m_obj.addmember("attributes").list();
256 for (vector<Attribute*>::const_iterator a=attributes.begin(); a!=attributes.end(); ++a) {
257 attr = (*a)->marshall();
261 // Tentatively increment the version.
262 m_obj["version"].integer(m_obj["version"].integer()+1);
266 string record(str.str());
269 ver = m_cache->m_storage->updateText(getID(), "session", record.c_str(), 0, m_obj["version"].integer()-1);
272 // Roll back modification to record.
273 m_obj["version"].integer(m_obj["version"].integer()-1);
274 vector<Attribute*>::size_type count = attributes.size();
276 attrs.last().destroy();
281 // Roll back modification to record.
282 m_obj["version"].integer(m_obj["version"].integer()-1);
283 vector<Attribute*>::size_type count = attributes.size();
285 attrs.last().destroy();
288 // Fatal problem with update.
289 throw IOException("Unable to update stored session.");
293 m_cache->m_log.warn("storage service indicates the record is out of sync, updating with a fresh copy...");
294 ver = m_cache->m_storage->readText(getID(), "session", &record, NULL);
296 m_cache->m_log.error("readText failed on StorageService for session (%s)", getID());
297 throw IOException("Unable to read back stored session.");
302 istringstream in(record);
306 for_each(m_attributes.begin(), m_attributes.end(), xmltooling::cleanup<Attribute>());
307 m_attributes.clear();
308 m_attributeIndex.clear();
309 newobj["version"].integer(ver);
315 } while (ver < 0); // negative indicates a sync issue so we retry
317 TransactionLog* xlog = SPConfig::getConfig().getServiceProvider()->getTransactionLog();
319 xlog->log.infoStream() <<
320 "Added the following attributes to session (ID: " <<
322 ") for (applicationId: " <<
323 m_obj["application_id"].string() <<
325 for (vector<Attribute*>::const_iterator a=attributes.begin(); a!=attributes.end(); ++a)
326 xlog->log.infoStream() << "\t" << (*a)->getId() << " (" << (*a)->valueCount() << " values)";
329 // We own them now, so clean them up.
330 for_each(attributes.begin(), attributes.end(), xmltooling::cleanup<Attribute>());
333 const Assertion* StoredSession::getAssertion(const char* id) const
335 map<string,Assertion*>::const_iterator i = m_tokens.find(id);
336 if (i!=m_tokens.end())
340 if (!m_cache->m_storage->readText(getID(), id, &tokenstr, NULL))
341 throw FatalProfileException("Assertion not found in cache.");
343 // Parse and bind the document into an XMLObject.
344 istringstream instr(tokenstr);
345 DOMDocument* doc = XMLToolingConfig::getConfig().getParser().parse(instr);
346 XercesJanitor<DOMDocument> janitor(doc);
347 auto_ptr<XMLObject> xmlObject(XMLObjectBuilder::buildOneFromElement(doc->getDocumentElement(), true));
350 Assertion* token = dynamic_cast<Assertion*>(xmlObject.get());
352 throw FatalProfileException("Request for cached assertion returned an unknown object type.");
354 // Transfer ownership to us.
360 void StoredSession::addAssertion(Assertion* assertion)
363 xmltooling::NDC ndc("addAssertion");
367 throw FatalProfileException("Unknown object type passed to session for storage.");
369 auto_ptr_char id(assertion->getID());
371 m_cache->m_log.debug("adding assertion (%s) to session (%s)", id.get(), getID());
374 if (!m_cache->m_storage->readText(getID(), "session", NULL, &exp))
375 throw IOException("Unable to load expiration time for stored session.");
377 ostringstream tokenstr;
378 tokenstr << *assertion;
379 if (!m_cache->m_storage->createText(getID(), id.get(), tokenstr.str().c_str(), exp))
380 throw IOException("Attempted to insert duplicate assertion ID into session.");
384 DDF token = DDF(NULL).string(id.get());
385 m_obj["assertions"].add(token);
387 // Tentatively increment the version.
388 m_obj["version"].integer(m_obj["version"].integer()+1);
392 string record(str.str());
395 ver = m_cache->m_storage->updateText(getID(), "session", record.c_str(), 0, m_obj["version"].integer()-1);
399 m_obj["version"].integer(m_obj["version"].integer()-1);
400 m_cache->m_storage->deleteText(getID(), id.get());
406 m_obj["version"].integer(m_obj["version"].integer()-1);
409 // Fatal problem with update.
410 m_cache->m_log.error("updateText failed on StorageService for session (%s)", getID());
411 m_cache->m_storage->deleteText(getID(), id.get());
412 throw IOException("Unable to update stored session.");
416 m_cache->m_log.warn("storage service indicates the record is out of sync, updating with a fresh copy...");
417 ver = m_cache->m_storage->readText(getID(), "session", &record, NULL);
419 m_cache->m_log.error("readText failed on StorageService for session (%s)", getID());
420 m_cache->m_storage->deleteText(getID(), id.get());
421 throw IOException("Unable to read back stored session.");
426 istringstream in(record);
430 for_each(m_attributes.begin(), m_attributes.end(), xmltooling::cleanup<Attribute>());
431 m_attributes.clear();
432 m_attributeIndex.clear();
433 newobj["version"].integer(ver);
439 } while (ver < 0); // negative indicates a sync issue so we retry
444 TransactionLog* xlog = SPConfig::getConfig().getServiceProvider()->getTransactionLog();
447 "Added assertion (ID: %s) to session for (applicationId: %s) with (ID: %s)",
448 id.get(), m_obj["application_id"].string(), getID()
452 SSCache::SSCache(const DOMElement* e)
453 : SessionCache(e, 3600), m_log(Category::getInstance(SHIBSP_LOGCAT".SessionCache")), m_storage(NULL)
455 SPConfig& conf = SPConfig::getConfig();
456 const XMLCh* tag = e ? e->getAttributeNS(NULL,_StorageService) : NULL;
458 auto_ptr_char ssid(tag);
459 m_storage = conf.getServiceProvider()->getStorageService(ssid.get());
461 m_log.info("bound to StorageService (%s)", ssid.get());
463 throw ConfigurationException("SessionCache unable to locate StorageService, check configuration.");
466 ListenerService* listener=conf.getServiceProvider()->getListenerService(false);
467 if (listener && conf.isEnabled(SPConfig::OutOfProcess)) {
468 listener->regListener("find::"REMOTED_SESSION_CACHE"::SessionCache",this);
469 listener->regListener("remove::"REMOTED_SESSION_CACHE"::SessionCache",this);
470 listener->regListener("touch::"REMOTED_SESSION_CACHE"::SessionCache",this);
471 listener->regListener("getAssertion::"REMOTED_SESSION_CACHE"::SessionCache",this);
474 m_log.info("no ListenerService available, cache remoting disabled");
480 SPConfig& conf = SPConfig::getConfig();
481 ListenerService* listener=conf.getServiceProvider()->getListenerService(false);
482 if (listener && conf.isEnabled(SPConfig::OutOfProcess)) {
483 listener->unregListener("find::"REMOTED_SESSION_CACHE"::SessionCache",this);
484 listener->unregListener("remove::"REMOTED_SESSION_CACHE"::SessionCache",this);
485 listener->unregListener("touch::"REMOTED_SESSION_CACHE"::SessionCache",this);
486 listener->unregListener("getAssertion::"REMOTED_SESSION_CACHE"::SessionCache",this);
490 void SSCache::insert(const char* key, time_t expires, const char* name, const char* index)
493 if (strlen(name) > 255) {
494 dup = string(name).substr(0,255);
499 DDFJanitor jobj(obj);
501 // Since we can't guarantee uniqueness, check for an existing record.
504 int ver = m_storage->readText("NameID", name, &record, &recordexp);
506 // Existing record, so we need to unmarshall it.
507 istringstream in(record);
515 if (!index || !*index)
517 DDF sessions = obj.addmember(index);
518 if (!sessions.islist())
520 DDF session = DDF(NULL).string(key);
521 sessions.add(session);
523 // Remarshall the record.
527 // Try and store it back...
529 ver = m_storage->updateText("NameID", name, out.str().c_str(), max(expires, recordexp), ver);
531 // Out of sync, or went missing, so retry.
532 return insert(key, expires, name, index);
535 else if (!m_storage->createText("NameID", name, out.str().c_str(), expires)) {
536 // Hit a dup, so just retry, hopefully hitting the other branch.
537 return insert(key, expires, name, index);
541 string SSCache::insert(
543 const Application& application,
544 const char* client_addr,
545 const saml2md::EntityDescriptor* issuer,
546 const XMLCh* protocol,
547 const saml2::NameID* nameid,
548 const XMLCh* authn_instant,
549 const XMLCh* session_index,
550 const XMLCh* authncontext_class,
551 const XMLCh* authncontext_decl,
552 const vector<const Assertion*>* tokens,
553 const vector<Attribute*>* attributes
557 xmltooling::NDC ndc("insert");
560 m_log.debug("creating new session");
562 time_t now = time(NULL);
563 auto_ptr_char index(session_index);
564 auto_ptr_char entity_id(issuer ? issuer->getEntityID() : NULL);
565 auto_ptr_char name(nameid ? nameid->getName() : NULL);
568 // Check for a pending logout.
569 if (strlen(name.get()) > 255)
570 const_cast<char*>(name.get())[255] = 0;
572 int ver = m_storage->readText("Logout", name.get(), &pending);
575 DDFJanitor jpend(pendobj);
576 istringstream pstr(pending);
578 // IdP.SP.index contains logout expiration, if any.
579 DDF deadmenwalking = pendobj[issuer ? entity_id.get() : "_shibnull"][application.getString("entityID").second];
580 const char* logexpstr = deadmenwalking[session_index ? index.get() : "_shibnull"].string();
581 if (!logexpstr && session_index) // we tried an exact session match, now try for NULL
582 logexpstr = deadmenwalking["_shibnull"].string();
584 auto_ptr_XMLCh dt(logexpstr);
585 DateTime dtobj(dt.get());
586 dtobj.parseDateTime();
587 time_t logexp = dtobj.getEpoch();
588 if (now - XMLToolingConfig::getConfig().clock_skew_secs < logexp)
589 throw FatalProfileException("A logout message from your identity provider has blocked your login attempt.");
594 auto_ptr_char key(SAMLConfig::getConfig().generateIdentifier());
596 // Store session properties in DDF.
597 DDF obj = DDF(key.get()).structure();
598 obj.addmember("version").integer(1);
599 obj.addmember("application_id").string(application.getId());
601 // On 64-bit Windows, time_t doesn't fit in a long, so I'm using ISO timestamps.
602 #ifndef HAVE_GMTIME_R
603 struct tm* ptime=gmtime(&expires);
606 struct tm* ptime=gmtime_r(&expires,&res);
609 strftime(timebuf,32,"%Y-%m-%dT%H:%M:%SZ",ptime);
610 obj.addmember("expires").string(timebuf);
613 obj.addmember("client_addr").string(client_addr);
615 obj.addmember("entity_id").string(entity_id.get());
617 auto_ptr_char prot(protocol);
618 obj.addmember("protocol").string(prot.get());
621 auto_ptr_char instant(authn_instant);
622 obj.addmember("authn_instant").string(instant.get());
625 obj.addmember("session_index").string(index.get());
626 if (authncontext_class) {
627 auto_ptr_char ac(authncontext_class);
628 obj.addmember("authncontext_class").string(ac.get());
630 if (authncontext_decl) {
631 auto_ptr_char ad(authncontext_decl);
632 obj.addmember("authncontext_decl").string(ad.get());
636 ostringstream namestr;
638 obj.addmember("nameid").string(namestr.str().c_str());
642 obj.addmember("assertions").list();
643 for (vector<const Assertion*>::const_iterator t = tokens->begin(); t!=tokens->end(); ++t) {
644 auto_ptr_char tokenid((*t)->getID());
645 DDF tokid = DDF(NULL).string(tokenid.get());
646 obj["assertions"].add(tokid);
652 DDF attrlist = obj.addmember("attributes").list();
653 for (vector<Attribute*>::const_iterator a=attributes->begin(); a!=attributes->end(); ++a) {
654 attr = (*a)->marshall();
659 ostringstream record;
662 m_log.debug("storing new session...");
663 if (!m_storage->createText(key.get(), "session", record.str().c_str(), now + m_cacheTimeout))
664 throw FatalProfileException("Attempted to create a session with a duplicate key.");
666 // Store the reverse mapping for logout.
669 insert(key.get(), expires, name.get(), index.get());
671 catch (exception& ex) {
672 m_log.error("error storing back mapping of NameID for logout: %s", ex.what());
677 for (vector<const Assertion*>::const_iterator t = tokens->begin(); t!=tokens->end(); ++t) {
678 ostringstream tokenstr;
680 auto_ptr_char tokenid((*t)->getID());
681 if (!m_storage->createText(key.get(), tokenid.get(), tokenstr.str().c_str(), now + m_cacheTimeout))
682 throw IOException("duplicate assertion ID ($1)", params(1, tokenid.get()));
685 catch (exception& ex) {
686 m_log.error("error storing assertion along with session: %s", ex.what());
690 const char* pid = obj["entity_id"].string();
691 m_log.info("new session created: SessionID (%s) IdP (%s) Address (%s)", key.get(), pid ? pid : "none", client_addr);
693 // Transaction Logging
694 TransactionLog* xlog = application.getServiceProvider().getTransactionLog();
696 xlog->log.infoStream() <<
697 "New session (ID: " <<
699 ") with (applicationId: " <<
700 application.getId() <<
701 ") for principal from (IdP: " <<
702 (pid ? pid : "none") <<
703 ") at (ClientAddress: " <<
704 (client_addr ? client_addr : "none") <<
705 ") with (NameIdentifier: " <<
706 (nameid ? name.get() : "none") <<
710 xlog->log.infoStream() <<
711 "Cached the following attributes with session (ID: " <<
713 ") for (applicationId: " <<
714 application.getId() <<
716 for (vector<Attribute*>::const_iterator a=attributes->begin(); a!=attributes->end(); ++a)
717 xlog->log.infoStream() << "\t" << (*a)->getId() << " (" << (*a)->valueCount() << " values)";
724 Session* SSCache::find(const char* key, const Application& application, const char* client_addr, time_t* timeout)
727 xmltooling::NDC ndc("find");
730 m_log.debug("searching for session (%s)", key);
734 int ver = m_storage->readText(key, "session", &record, &lastAccess);
738 m_log.debug("reconstituting session and checking validity");
741 istringstream in(record);
744 if (!XMLString::equals(obj["application_id"].string(), application.getId())) {
745 m_log.error("an application (%s) tried to access another application's session", application.getId());
751 if (m_log.isDebugEnabled())
752 m_log.debug("comparing client address %s against %s", client_addr, obj["client_addr"].string());
753 if (strcmp(obj["client_addr"].string(),client_addr)) {
754 m_log.warn("client address mismatch");
755 remove(key, application);
756 RetryableProfileException ex(
757 "Your IP address ($1) does not match the address recorded at the time the session was established.",
758 params(1,client_addr)
760 string eid(obj["entity_id"].string());
764 MetadataProvider* m=application.getMetadataProvider();
766 annotateException(&ex,m->getEntityDescriptor(eid.c_str(),false)); // throws it
770 lastAccess -= m_cacheTimeout; // adjusts it back to the last time the record's timestamp was touched
771 time_t now=time(NULL);
773 if (timeout && *timeout > 0 && now - lastAccess >= *timeout) {
774 m_log.info("session timed out (ID: %s)", key);
775 remove(key, application);
776 RetryableProfileException ex("Your session has expired, and you must re-authenticate.");
777 string eid(obj["entity_id"].string());
781 MetadataProvider* m=application.getMetadataProvider();
783 annotateException(&ex,m->getEntityDescriptor(eid.c_str(),false)); // throws it
786 auto_ptr_XMLCh exp(obj["expires"].string());
788 DateTime iso(exp.get());
790 if (now > iso.getEpoch()) {
791 m_log.info("session expired (ID: %s)", key);
792 remove(key, application);
793 RetryableProfileException ex("Your session has expired, and you must re-authenticate.");
794 string eid(obj["entity_id"].string());
798 MetadataProvider* m=application.getMetadataProvider();
800 annotateException(&ex,m->getEntityDescriptor(eid.c_str(),false)); // throws it
805 // Update storage expiration, if possible.
807 m_storage->updateContext(key, now + m_cacheTimeout);
809 catch (exception& ex) {
810 m_log.error("failed to update session expiration: %s", ex.what());
814 // Finally build the Session object.
816 return new StoredSession(this, obj);
824 void SSCache::remove(const char* key, const Application& application)
827 xmltooling::NDC ndc("remove");
830 m_storage->deleteContext(key);
831 m_log.info("removed session (%s)", key);
833 TransactionLog* xlog = application.getServiceProvider().getTransactionLog();
835 xlog->log.info("Destroyed session (applicationId: %s) (ID: %s)", application.getId(), key);
838 bool SSCache::matches(
840 const saml2md::EntityDescriptor* issuer,
841 const saml2::NameID& nameid,
842 const set<string>* indexes,
843 const Application& application
846 auto_ptr_char entityID(issuer ? issuer->getEntityID() : NULL);
848 Session* session = find(key, application);
850 Locker locker(session);
851 if (XMLString::equals(session->getEntityID(), entityID.get()) && session->getNameID() &&
852 stronglyMatches(issuer->getEntityID(), application.getXMLString("entityID").second, nameid, *session->getNameID())) {
853 return (!indexes || indexes->empty() || (session->getSessionIndex() ? (indexes->count(session->getSessionIndex())>0) : false));
857 catch (exception& ex) {
858 m_log.error("error while matching session (%s): %s", key, ex.what());
863 vector<string>::size_type SSCache::logout(
864 const saml2md::EntityDescriptor* issuer,
865 const saml2::NameID& nameid,
866 const set<string>* indexes,
868 const Application& application,
869 vector<string>& sessionsKilled
873 xmltooling::NDC ndc("logout");
876 auto_ptr_char entityID(issuer ? issuer->getEntityID() : NULL);
877 auto_ptr_char name(nameid.getName());
879 m_log.info("request to logout sessions from (%s) for (%s)", entityID.get() ? entityID.get() : "unknown", name.get());
881 if (strlen(name.get()) > 255)
882 const_cast<char*>(name.get())[255] = 0;
885 DDFJanitor jobj(obj);
890 // Record the logout to prevent post-delivered assertions.
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);
902 ver = m_storage->readText("Logout", name.get(), &record, &oldexp);
904 istringstream lin(record);
908 obj = DDF(NULL).structure();
911 // Structure is keyed by the IdP and SP, with a member per session index containing the expiration.
912 DDF root = obj.addmember(issuer ? entityID.get() : "_shibnull").addmember(application.getString("entityID").second);
914 for (set<string>::const_iterator x = indexes->begin(); x!=indexes->end(); ++x)
915 root.addmember(x->c_str()).string(timebuf);
918 root.addmember("_shibnull").string(timebuf);
926 ver = m_storage->updateText("Logout", name.get(), lout.str().c_str(), max(expires, oldexp), ver);
928 // Out of sync, or went missing, so retry.
929 return logout(issuer, nameid, indexes, expires, application, sessionsKilled);
932 else if (!m_storage->createText("Logout", name.get(), lout.str().c_str(), expires)) {
933 // Hit a dup, so just retry, hopefully hitting the other branch.
934 return logout(issuer, nameid, indexes, expires, application, sessionsKilled);
941 // Read in potentially matching sessions.
942 ver = m_storage->readText("NameID", name.get(), &record);
944 m_log.debug("no active sessions to logout for supplied issuer and subject");
948 istringstream in(record);
951 // The record contains child lists for each known session index.
953 DDF sessions = obj.first();
954 while (sessions.islist()) {
955 if (!indexes || indexes->empty() || indexes->count(sessions.name())) {
956 key = sessions.first();
957 while (key.isstring()) {
958 // Fetch the session for comparison.
959 Session* session = NULL;
961 session = find(key.string(), application);
963 catch (exception& ex) {
964 m_log.error("error locating session (%s): %s", key.string(), ex.what());
968 Locker locker(session);
970 if (XMLString::equals(session->getEntityID(), entityID.get())) {
972 if (stronglyMatches(issuer->getEntityID(), application.getXMLString("entityID").second, nameid, *session->getNameID())) {
973 sessionsKilled.push_back(key.string());
977 m_log.debug("session (%s) contained a non-matching NameID, leaving it alone", key.string());
981 m_log.debug("session (%s) established by different IdP, leaving it alone", key.string());
985 // Session's gone, so...
986 sessionsKilled.push_back(key.string());
989 key = sessions.next();
992 // No sessions left for this index?
993 if (sessions.first().isnull())
996 sessions = obj.next();
999 if (obj.first().isnull())
1002 // If possible, write back the mapping record (this isn't crucial).
1005 m_storage->deleteText("NameID", name.get());
1007 else if (!sessionsKilled.empty()) {
1010 if (m_storage->updateText("NameID", name.get(), out.str().c_str(), 0, ver) <= 0)
1011 m_log.warn("logout mapping record changed behind us, leaving it alone");
1014 catch (exception& ex) {
1015 m_log.error("error updating logout mapping record: %s", ex.what());
1018 return sessionsKilled.size();
1021 bool SSCache::stronglyMatches(const XMLCh* idp, const XMLCh* sp, const saml2::NameID& n1, const saml2::NameID& n2) const
1023 if (!XMLString::equals(n1.getName(), n2.getName()))
1026 const XMLCh* s1 = n1.getFormat();
1027 const XMLCh* s2 = n2.getFormat();
1029 s1 = saml2::NameID::UNSPECIFIED;
1031 s2 = saml2::NameID::UNSPECIFIED;
1032 if (!XMLString::equals(s1,s2))
1035 s1 = n1.getNameQualifier();
1036 s2 = n2.getNameQualifier();
1041 if (!XMLString::equals(s1,s2))
1044 s1 = n1.getSPNameQualifier();
1045 s2 = n2.getSPNameQualifier();
1050 if (!XMLString::equals(s1,s2))
1056 void SSCache::receive(DDF& in, ostream& out)
1059 xmltooling::NDC ndc("receive");
1062 if (!strcmp(in.name(),"find::"REMOTED_SESSION_CACHE"::SessionCache")) {
1063 const char* key=in["key"].string();
1065 throw ListenerException("Required parameters missing for session removal.");
1067 const Application* app = SPConfig::getConfig().getServiceProvider()->getApplication(in["application_id"].string());
1069 throw ListenerException("Application not found, check configuration?");
1071 // Do an unversioned read.
1074 if (!m_storage->readText(key, "session", &record, &lastAccess)) {
1076 DDFJanitor jan(ret);
1081 // Adjust for expiration to recover last access time and check timeout.
1082 lastAccess -= m_cacheTimeout;
1083 time_t now=time(NULL);
1085 // See if we need to check for a timeout.
1086 if (in["timeout"].string()) {
1088 auto_ptr_XMLCh dt(in["timeout"].string());
1089 DateTime dtobj(dt.get());
1090 dtobj.parseDateTime();
1091 timeout = dtobj.getEpoch();
1093 if (timeout > 0 && now - lastAccess >= timeout) {
1094 m_log.info("session timed out (ID: %s)", key);
1096 throw RetryableProfileException("Your session has expired, and you must re-authenticate.");
1099 // Update storage expiration, if possible.
1101 m_storage->updateContext(key, now + m_cacheTimeout);
1103 catch (exception& ex) {
1104 m_log.error("failed to update session expiration: %s", ex.what());
1108 // Send the record back.
1111 else if (!strcmp(in.name(),"touch::"REMOTED_SESSION_CACHE"::SessionCache")) {
1112 const char* key=in["key"].string();
1114 throw ListenerException("Required parameters missing for session check.");
1116 // Do a versioned read.
1119 int curver = in["version"].integer();
1120 int ver = m_storage->readText(key, "session", &record, &lastAccess, curver);
1122 m_log.warn("unsuccessful versioned read of session (ID: %s), caches out of sync?", key);
1123 throw RetryableProfileException("Your session has expired, and you must re-authenticate.");
1126 // Adjust for expiration to recover last access time and check timeout.
1127 lastAccess -= m_cacheTimeout;
1128 time_t now=time(NULL);
1130 // See if we need to check for a timeout.
1132 auto_ptr_XMLCh dt(in["timeout"].string());
1134 DateTime dtobj(dt.get());
1135 dtobj.parseDateTime();
1136 timeout = dtobj.getEpoch();
1139 if (timeout > 0 && now - lastAccess >= timeout) {
1140 m_log.info("session timed out (ID: %s)", key);
1141 throw RetryableProfileException("Your session has expired, and you must re-authenticate.");
1144 // Update storage expiration, if possible.
1146 m_storage->updateContext(key, now + m_cacheTimeout);
1148 catch (exception& ex) {
1149 m_log.error("failed to update session expiration: %s", ex.what());
1153 // Send the record back.
1158 DDFJanitor jan(ret);
1162 else if (!strcmp(in.name(),"remove::"REMOTED_SESSION_CACHE"::SessionCache")) {
1163 const char* key=in["key"].string();
1165 throw ListenerException("Required parameter missing for session removal.");
1167 const Application* app = SPConfig::getConfig().getServiceProvider()->getApplication(in["application_id"].string());
1169 throw ListenerException("Application not found, check configuration?");
1173 DDFJanitor jan(ret);
1176 else if (!strcmp(in.name(),"getAssertion::"REMOTED_SESSION_CACHE"::SessionCache")) {
1177 const char* key=in["key"].string();
1178 const char* id=in["id"].string();
1180 throw ListenerException("Required parameters missing for assertion retrieval.");
1182 if (!m_storage->readText(key, id, &token, NULL))
1183 throw FatalProfileException("Assertion not found in cache.");