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 multimap<string,Attribute*>& getAttributes() const {
110 if (m_attributes.empty())
111 unmarshallAttributes();
114 const vector<const char*>& getAssertionIDs() const {
116 DDF ids = m_obj["assertions"];
117 DDF id = ids.first();
118 while (id.isstring()) {
119 m_ids.push_back(id.string());
126 void addAttributes(const vector<Attribute*>& attributes);
127 const Assertion* getAssertion(const char* id) const;
128 void addAssertion(Assertion* assertion);
131 void unmarshallAttributes() const;
134 saml2::NameID* m_nameid;
135 mutable multimap<string,Attribute*> m_attributes;
136 mutable vector<const char*> m_ids;
137 mutable map<string,Assertion*> m_tokens;
141 class SSCache : public SessionCache, public virtual Remoted
144 SSCache(const DOMElement* e);
147 void receive(DDF& in, ostream& out);
151 const Application& application,
152 const char* client_addr=NULL,
153 const saml2md::EntityDescriptor* issuer=NULL,
154 const XMLCh* protocol=NULL,
155 const saml2::NameID* nameid=NULL,
156 const XMLCh* authn_instant=NULL,
157 const XMLCh* session_index=NULL,
158 const XMLCh* authncontext_class=NULL,
159 const XMLCh* authncontext_decl=NULL,
160 const vector<const Assertion*>* tokens=NULL,
161 const multimap<string,Attribute*>* attributes=NULL
163 Session* find(const char* key, const Application& application, const char* client_addr=NULL, time_t* timeout=NULL);
164 void remove(const char* key, const Application& application);
167 const saml2md::EntityDescriptor* issuer,
168 const saml2::NameID& nameid,
169 const set<string>* indexes,
170 const Application& application
172 vector<string>::size_type logout(
173 const saml2md::EntityDescriptor* issuer,
174 const saml2::NameID& nameid,
175 const set<string>* indexes,
177 const Application& application,
178 vector<string>& sessions
182 StorageService* m_storage;
185 // maintain back-mappings of NameID/SessionIndex -> session key
186 void insert(const char* key, time_t expires, const char* name, const char* index);
188 bool stronglyMatches(const XMLCh* idp, const XMLCh* sp, const saml2::NameID& n1, const saml2::NameID& n2) const;
191 SessionCache* SHIBSP_DLLLOCAL StorageServiceCacheFactory(const DOMElement* const & e)
193 return new SSCache(e);
196 static const XMLCh _StorageService[] = UNICODE_LITERAL_14(S,t,o,r,a,g,e,S,e,r,v,i,c,e);
199 StoredSession::~StoredSession()
203 for_each(m_attributes.begin(), m_attributes.end(), cleanup_pair<string,Attribute>());
204 for_each(m_tokens.begin(), m_tokens.end(), cleanup_pair<string,Assertion>());
207 void StoredSession::unmarshallAttributes() const
209 Attribute* attribute;
210 DDF attrs = m_obj["attributes"];
211 DDF attr = attrs.first();
212 while (!attr.isnull()) {
214 attribute = Attribute::unmarshall(attr);
215 m_attributes.insert(make_pair(attribute->getId(), attribute));
216 if (m_cache->m_log.isDebugEnabled())
217 m_cache->m_log.debug("unmarshalled attribute (ID: %s) with %d value%s",
218 attribute->getId(), attr.first().integer(), attr.first().integer()!=1 ? "s" : "");
220 catch (AttributeException& ex) {
221 const char* id = attr.first().name();
222 m_cache->m_log.error("error unmarshalling attribute (ID: %s): %s", id ? id : "none", ex.what());
228 void StoredSession::addAttributes(const vector<Attribute*>& attributes)
231 xmltooling::NDC ndc("addAttributes");
234 m_cache->m_log.debug("adding attributes to session (%s)", getID());
239 DDF attrs = m_obj["attributes"];
241 attrs = m_obj.addmember("attributes").list();
242 for (vector<Attribute*>::const_iterator a=attributes.begin(); a!=attributes.end(); ++a) {
243 attr = (*a)->marshall();
247 // Tentatively increment the version.
248 m_obj["version"].integer(m_obj["version"].integer()+1);
252 string record(str.str());
255 ver = m_cache->m_storage->updateText(getID(), "session", record.c_str(), 0, m_obj["version"].integer()-1);
258 // Roll back modification to record.
259 m_obj["version"].integer(m_obj["version"].integer()-1);
260 vector<Attribute*>::size_type count = attributes.size();
262 attrs.last().destroy();
267 // Roll back modification to record.
268 m_obj["version"].integer(m_obj["version"].integer()-1);
269 vector<Attribute*>::size_type count = attributes.size();
271 attrs.last().destroy();
274 // Fatal problem with update.
275 throw IOException("Unable to update stored session.");
279 m_cache->m_log.warn("storage service indicates the record is out of sync, updating with a fresh copy...");
280 ver = m_cache->m_storage->readText(getID(), "session", &record, NULL);
282 m_cache->m_log.error("readText failed on StorageService for session (%s)", getID());
283 throw IOException("Unable to read back stored session.");
288 istringstream in(record);
292 for_each(m_attributes.begin(), m_attributes.end(), cleanup_const_pair<string,Attribute>());
293 m_attributes.clear();
294 newobj["version"].integer(ver);
300 } while (ver < 0); // negative indicates a sync issue so we retry
302 TransactionLog* xlog = SPConfig::getConfig().getServiceProvider()->getTransactionLog();
304 xlog->log.infoStream() <<
305 "Added the following attributes to session (ID: " <<
307 ") for (applicationId: " <<
308 m_obj["application_id"].string() <<
310 for (vector<Attribute*>::const_iterator a=attributes.begin(); a!=attributes.end(); ++a)
311 xlog->log.infoStream() << "\t" << (*a)->getId() << " (" << (*a)->valueCount() << " values)";
314 // We own them now, so clean them up.
315 for_each(attributes.begin(), attributes.end(), xmltooling::cleanup<Attribute>());
318 const Assertion* StoredSession::getAssertion(const char* id) const
320 map<string,Assertion*>::const_iterator i = m_tokens.find(id);
321 if (i!=m_tokens.end())
325 if (!m_cache->m_storage->readText(getID(), id, &tokenstr, NULL))
326 throw FatalProfileException("Assertion not found in cache.");
328 // Parse and bind the document into an XMLObject.
329 istringstream instr(tokenstr);
330 DOMDocument* doc = XMLToolingConfig::getConfig().getParser().parse(instr);
331 XercesJanitor<DOMDocument> janitor(doc);
332 auto_ptr<XMLObject> xmlObject(XMLObjectBuilder::buildOneFromElement(doc->getDocumentElement(), true));
335 Assertion* token = dynamic_cast<Assertion*>(xmlObject.get());
337 throw FatalProfileException("Request for cached assertion returned an unknown object type.");
339 // Transfer ownership to us.
345 void StoredSession::addAssertion(Assertion* assertion)
348 xmltooling::NDC ndc("addAssertion");
352 throw FatalProfileException("Unknown object type passed to session for storage.");
354 auto_ptr_char id(assertion->getID());
356 m_cache->m_log.debug("adding assertion (%s) to session (%s)", id.get(), getID());
359 if (!m_cache->m_storage->readText(getID(), "session", NULL, &exp))
360 throw IOException("Unable to load expiration time for stored session.");
362 ostringstream tokenstr;
363 tokenstr << *assertion;
364 if (!m_cache->m_storage->createText(getID(), id.get(), tokenstr.str().c_str(), exp))
365 throw IOException("Attempted to insert duplicate assertion ID into session.");
369 DDF token = DDF(NULL).string(id.get());
370 m_obj["assertions"].add(token);
372 // Tentatively increment the version.
373 m_obj["version"].integer(m_obj["version"].integer()+1);
377 string record(str.str());
380 ver = m_cache->m_storage->updateText(getID(), "session", record.c_str(), 0, m_obj["version"].integer()-1);
384 m_obj["version"].integer(m_obj["version"].integer()-1);
385 m_cache->m_storage->deleteText(getID(), id.get());
391 m_obj["version"].integer(m_obj["version"].integer()-1);
394 // Fatal problem with update.
395 m_cache->m_log.error("updateText failed on StorageService for session (%s)", getID());
396 m_cache->m_storage->deleteText(getID(), id.get());
397 throw IOException("Unable to update stored session.");
401 m_cache->m_log.warn("storage service indicates the record is out of sync, updating with a fresh copy...");
402 ver = m_cache->m_storage->readText(getID(), "session", &record, NULL);
404 m_cache->m_log.error("readText failed on StorageService for session (%s)", getID());
405 m_cache->m_storage->deleteText(getID(), id.get());
406 throw IOException("Unable to read back stored session.");
411 istringstream in(record);
415 for_each(m_attributes.begin(), m_attributes.end(), cleanup_const_pair<string,Attribute>());
416 m_attributes.clear();
417 newobj["version"].integer(ver);
423 } while (ver < 0); // negative indicates a sync issue so we retry
428 TransactionLog* xlog = SPConfig::getConfig().getServiceProvider()->getTransactionLog();
431 "Added assertion (ID: %s) to session for (applicationId: %s) with (ID: %s)",
432 id.get(), m_obj["application_id"].string(), getID()
436 SSCache::SSCache(const DOMElement* e)
437 : SessionCache(e), m_log(Category::getInstance(SHIBSP_LOGCAT".SessionCache")), m_storage(NULL)
439 SPConfig& conf = SPConfig::getConfig();
440 const XMLCh* tag = e ? e->getAttributeNS(NULL,_StorageService) : NULL;
442 auto_ptr_char ssid(tag);
443 m_storage = conf.getServiceProvider()->getStorageService(ssid.get());
445 m_log.info("bound to StorageService (%s)", ssid.get());
447 throw ConfigurationException("SessionCache unable to locate StorageService, check configuration.");
450 ListenerService* listener=conf.getServiceProvider()->getListenerService(false);
451 if (listener && conf.isEnabled(SPConfig::OutOfProcess)) {
452 listener->regListener("find::"REMOTED_SESSION_CACHE"::SessionCache",this);
453 listener->regListener("remove::"REMOTED_SESSION_CACHE"::SessionCache",this);
454 listener->regListener("touch::"REMOTED_SESSION_CACHE"::SessionCache",this);
455 listener->regListener("getAssertion::"REMOTED_SESSION_CACHE"::SessionCache",this);
458 m_log.info("no ListenerService available, cache remoting disabled");
464 SPConfig& conf = SPConfig::getConfig();
465 ListenerService* listener=conf.getServiceProvider()->getListenerService(false);
466 if (listener && conf.isEnabled(SPConfig::OutOfProcess)) {
467 listener->unregListener("find::"REMOTED_SESSION_CACHE"::SessionCache",this);
468 listener->unregListener("remove::"REMOTED_SESSION_CACHE"::SessionCache",this);
469 listener->unregListener("touch::"REMOTED_SESSION_CACHE"::SessionCache",this);
470 listener->unregListener("getAssertion::"REMOTED_SESSION_CACHE"::SessionCache",this);
474 void SSCache::insert(const char* key, time_t expires, const char* name, const char* index)
477 if (strlen(name) > 255) {
478 dup = string(name).substr(0,255);
483 DDFJanitor jobj(obj);
485 // Since we can't guarantee uniqueness, check for an existing record.
488 int ver = m_storage->readText("NameID", name, &record, &recordexp);
490 // Existing record, so we need to unmarshall it.
491 istringstream in(record);
499 if (!index || !*index)
501 DDF sessions = obj.addmember(index);
502 if (!sessions.islist())
504 DDF session = DDF(NULL).string(key);
505 sessions.add(session);
507 // Remarshall the record.
511 // Try and store it back...
513 ver = m_storage->updateText("NameID", name, out.str().c_str(), max(expires, recordexp), ver);
515 // Out of sync, or went missing, so retry.
516 return insert(key, expires, name, index);
519 else if (!m_storage->createText("NameID", name, out.str().c_str(), expires)) {
520 // Hit a dup, so just retry, hopefully hitting the other branch.
521 return insert(key, expires, name, index);
525 string SSCache::insert(
527 const Application& application,
528 const char* client_addr,
529 const saml2md::EntityDescriptor* issuer,
530 const XMLCh* protocol,
531 const saml2::NameID* nameid,
532 const XMLCh* authn_instant,
533 const XMLCh* session_index,
534 const XMLCh* authncontext_class,
535 const XMLCh* authncontext_decl,
536 const vector<const Assertion*>* tokens,
537 const multimap<string,Attribute*>* attributes
541 xmltooling::NDC ndc("insert");
544 m_log.debug("creating new session");
546 time_t now = time(NULL);
547 auto_ptr_char index(session_index);
548 auto_ptr_char entity_id(issuer ? issuer->getEntityID() : NULL);
549 auto_ptr_char name(nameid ? nameid->getName() : NULL);
552 // Check for a pending logout.
553 if (strlen(name.get()) > 255)
554 const_cast<char*>(name.get())[255] = 0;
556 int ver = m_storage->readText("Logout", name.get(), &pending);
559 DDFJanitor jpend(pendobj);
560 istringstream pstr(pending);
562 // IdP.SP.index contains logout expiration, if any.
563 DDF deadmenwalking = pendobj[issuer ? entity_id.get() : "_shibnull"][application.getString("entityID").second];
564 const char* logexpstr = deadmenwalking[session_index ? index.get() : "_shibnull"].string();
565 if (!logexpstr && session_index) // we tried an exact session match, now try for NULL
566 logexpstr = deadmenwalking["_shibnull"].string();
568 auto_ptr_XMLCh dt(logexpstr);
569 DateTime dtobj(dt.get());
570 dtobj.parseDateTime();
571 time_t logexp = dtobj.getEpoch();
572 if (now - XMLToolingConfig::getConfig().clock_skew_secs < logexp)
573 throw FatalProfileException("A logout message from your identity provider has blocked your login attempt.");
578 auto_ptr_char key(SAMLConfig::getConfig().generateIdentifier());
580 // Store session properties in DDF.
581 DDF obj = DDF(key.get()).structure();
582 obj.addmember("version").integer(1);
583 obj.addmember("application_id").string(application.getId());
585 // On 64-bit Windows, time_t doesn't fit in a long, so I'm using ISO timestamps.
586 #ifndef HAVE_GMTIME_R
587 struct tm* ptime=gmtime(&expires);
590 struct tm* ptime=gmtime_r(&expires,&res);
593 strftime(timebuf,32,"%Y-%m-%dT%H:%M:%SZ",ptime);
594 obj.addmember("expires").string(timebuf);
597 obj.addmember("client_addr").string(client_addr);
599 obj.addmember("entity_id").string(entity_id.get());
601 auto_ptr_char prot(protocol);
602 obj.addmember("protocol").string(prot.get());
605 auto_ptr_char instant(authn_instant);
606 obj.addmember("authn_instant").string(instant.get());
609 obj.addmember("session_index").string(index.get());
610 if (authncontext_class) {
611 auto_ptr_char ac(authncontext_class);
612 obj.addmember("authncontext_class").string(ac.get());
614 if (authncontext_decl) {
615 auto_ptr_char ad(authncontext_decl);
616 obj.addmember("authncontext_decl").string(ad.get());
620 ostringstream namestr;
622 obj.addmember("nameid").string(namestr.str().c_str());
626 obj.addmember("assertions").list();
627 for (vector<const Assertion*>::const_iterator t = tokens->begin(); t!=tokens->end(); ++t) {
628 auto_ptr_char tokenid((*t)->getID());
629 DDF tokid = DDF(NULL).string(tokenid.get());
630 obj["assertions"].add(tokid);
636 DDF attrlist = obj.addmember("attributes").list();
637 for (multimap<string,Attribute*>::const_iterator a=attributes->begin(); a!=attributes->end(); ++a) {
638 attr = a->second->marshall();
643 ostringstream record;
646 m_log.debug("storing new session...");
647 if (!m_storage->createText(key.get(), "session", record.str().c_str(), now + m_cacheTimeout))
648 throw FatalProfileException("Attempted to create a session with a duplicate key.");
650 // Store the reverse mapping for logout.
653 insert(key.get(), expires, name.get(), index.get());
655 catch (exception& ex) {
656 m_log.error("error storing back mapping of NameID for logout: %s", ex.what());
661 for (vector<const Assertion*>::const_iterator t = tokens->begin(); t!=tokens->end(); ++t) {
662 ostringstream tokenstr;
664 auto_ptr_char tokenid((*t)->getID());
665 if (!m_storage->createText(key.get(), tokenid.get(), tokenstr.str().c_str(), now + m_cacheTimeout))
666 throw IOException("duplicate assertion ID ($1)", params(1, tokenid.get()));
669 catch (exception& ex) {
670 m_log.error("error storing assertion along with session: %s", ex.what());
674 const char* pid = obj["entity_id"].string();
675 m_log.info("new session created: SessionID (%s) IdP (%s) Address (%s)", key.get(), pid ? pid : "none", client_addr);
677 // Transaction Logging
678 TransactionLog* xlog = application.getServiceProvider().getTransactionLog();
680 xlog->log.infoStream() <<
681 "New session (ID: " <<
683 ") with (applicationId: " <<
684 application.getId() <<
685 ") for principal from (IdP: " <<
686 (pid ? pid : "none") <<
687 ") at (ClientAddress: " <<
688 (client_addr ? client_addr : "none") <<
689 ") with (NameIdentifier: " <<
690 (nameid ? name.get() : "none") <<
694 xlog->log.infoStream() <<
695 "Cached the following attributes with session (ID: " <<
697 ") for (applicationId: " <<
698 application.getId() <<
700 for (multimap<string,Attribute*>::const_iterator a=attributes->begin(); a!=attributes->end(); ++a)
701 xlog->log.infoStream() << "\t" << a->second->getId() << " (" << a->second->valueCount() << " values)";
708 Session* SSCache::find(const char* key, const Application& application, const char* client_addr, time_t* timeout)
711 xmltooling::NDC ndc("find");
714 m_log.debug("searching for session (%s)", key);
718 int ver = m_storage->readText(key, "session", &record, &lastAccess);
722 m_log.debug("reconstituting session and checking validity");
725 istringstream in(record);
728 if (!XMLString::equals(obj["application_id"].string(), application.getId())) {
729 m_log.error("an application (%s) tried to access another application's session", application.getId());
735 if (m_log.isDebugEnabled())
736 m_log.debug("comparing client address %s against %s", client_addr, obj["client_addr"].string());
737 if (strcmp(obj["client_addr"].string(),client_addr)) {
738 m_log.warn("client address mismatch");
739 remove(key, application);
740 RetryableProfileException ex(
741 "Your IP address ($1) does not match the address recorded at the time the session was established.",
742 params(1,client_addr)
744 string eid(obj["entity_id"].string());
748 MetadataProvider* m=application.getMetadataProvider();
750 annotateException(&ex,m->getEntityDescriptor(eid.c_str(),false)); // throws it
754 lastAccess -= m_cacheTimeout; // adjusts it back to the last time the record's timestamp was touched
755 time_t now=time(NULL);
757 if (timeout && *timeout > 0 && now - lastAccess >= *timeout) {
758 m_log.info("session timed out (ID: %s)", key);
759 remove(key, application);
760 RetryableProfileException ex("Your session has expired, and you must re-authenticate.");
761 string eid(obj["entity_id"].string());
765 MetadataProvider* m=application.getMetadataProvider();
767 annotateException(&ex,m->getEntityDescriptor(eid.c_str(),false)); // throws it
770 auto_ptr_XMLCh exp(obj["expires"].string());
772 DateTime iso(exp.get());
774 if (now > iso.getEpoch()) {
775 m_log.info("session expired (ID: %s)", key);
776 remove(key, application);
777 RetryableProfileException ex("Your session has expired, and you must re-authenticate.");
778 string eid(obj["entity_id"].string());
782 MetadataProvider* m=application.getMetadataProvider();
784 annotateException(&ex,m->getEntityDescriptor(eid.c_str(),false)); // throws it
789 // Update storage expiration, if possible.
791 m_storage->updateContext(key, now + m_cacheTimeout);
793 catch (exception& ex) {
794 m_log.error("failed to update session expiration: %s", ex.what());
798 // Finally build the Session object.
800 return new StoredSession(this, obj);
808 void SSCache::remove(const char* key, const Application& application)
811 xmltooling::NDC ndc("remove");
814 m_storage->deleteContext(key);
815 m_log.info("removed session (%s)", key);
817 TransactionLog* xlog = application.getServiceProvider().getTransactionLog();
819 xlog->log.info("Destroyed session (applicationId: %s) (ID: %s)", application.getId(), key);
822 bool SSCache::matches(
824 const saml2md::EntityDescriptor* issuer,
825 const saml2::NameID& nameid,
826 const set<string>* indexes,
827 const Application& application
830 auto_ptr_char entityID(issuer ? issuer->getEntityID() : NULL);
832 Session* session = find(key, application);
834 Locker locker(session);
835 if (XMLString::equals(session->getEntityID(), entityID.get()) && session->getNameID() &&
836 stronglyMatches(issuer->getEntityID(), application.getXMLString("entityID").second, nameid, *session->getNameID())) {
837 return (!indexes || indexes->empty() || (session->getSessionIndex() ? (indexes->count(session->getSessionIndex())>0) : false));
841 catch (exception& ex) {
842 m_log.error("error while matching session (%s): %s", key, ex.what());
847 vector<string>::size_type SSCache::logout(
848 const saml2md::EntityDescriptor* issuer,
849 const saml2::NameID& nameid,
850 const set<string>* indexes,
852 const Application& application,
853 vector<string>& sessionsKilled
857 xmltooling::NDC ndc("logout");
860 auto_ptr_char entityID(issuer ? issuer->getEntityID() : NULL);
861 auto_ptr_char name(nameid.getName());
863 m_log.info("request to logout sessions from (%s) for (%s)", entityID.get() ? entityID.get() : "unknown", name.get());
865 if (strlen(name.get()) > 255)
866 const_cast<char*>(name.get())[255] = 0;
869 DDFJanitor jobj(obj);
874 // Record the logout to prevent post-delivered assertions.
875 // On 64-bit Windows, time_t doesn't fit in a long, so I'm using ISO timestamps.
876 #ifndef HAVE_GMTIME_R
877 struct tm* ptime=gmtime(&expires);
880 struct tm* ptime=gmtime_r(&expires,&res);
883 strftime(timebuf,32,"%Y-%m-%dT%H:%M:%SZ",ptime);
886 ver = m_storage->readText("Logout", name.get(), &record, &oldexp);
888 istringstream lin(record);
892 obj = DDF(NULL).structure();
895 // Structure is keyed by the IdP and SP, with a member per session index containing the expiration.
896 DDF root = obj.addmember(issuer ? entityID.get() : "_shibnull").addmember(application.getString("entityID").second);
898 for (set<string>::const_iterator x = indexes->begin(); x!=indexes->end(); ++x)
899 root.addmember(x->c_str()).string(timebuf);
902 root.addmember("_shibnull").string(timebuf);
910 ver = m_storage->updateText("Logout", name.get(), lout.str().c_str(), max(expires, oldexp), ver);
912 // Out of sync, or went missing, so retry.
913 return logout(issuer, nameid, indexes, expires, application, sessionsKilled);
916 else if (!m_storage->createText("Logout", name.get(), lout.str().c_str(), expires)) {
917 // Hit a dup, so just retry, hopefully hitting the other branch.
918 return logout(issuer, nameid, indexes, expires, application, sessionsKilled);
925 // Read in potentially matching sessions.
926 ver = m_storage->readText("NameID", name.get(), &record);
928 m_log.debug("no active sessions to logout for supplied issuer and subject");
932 istringstream in(record);
935 // The record contains child lists for each known session index.
937 DDF sessions = obj.first();
938 while (sessions.islist()) {
939 if (!indexes || indexes->empty() || indexes->count(sessions.name())) {
940 key = sessions.first();
941 while (key.isstring()) {
942 // Fetch the session for comparison.
943 Session* session = NULL;
945 session = find(key.string(), application);
947 catch (exception& ex) {
948 m_log.error("error locating session (%s): %s", key.string(), ex.what());
952 Locker locker(session);
954 if (XMLString::equals(session->getEntityID(), entityID.get())) {
956 if (stronglyMatches(issuer->getEntityID(), application.getXMLString("entityID").second, nameid, *session->getNameID())) {
957 sessionsKilled.push_back(key.string());
961 m_log.debug("session (%s) contained a non-matching NameID, leaving it alone", key.string());
965 m_log.debug("session (%s) established by different IdP, leaving it alone", key.string());
969 // Session's gone, so...
970 sessionsKilled.push_back(key.string());
973 key = sessions.next();
976 // No sessions left for this index?
977 if (sessions.first().isnull())
980 sessions = obj.next();
983 if (obj.first().isnull())
986 // If possible, write back the mapping record (this isn't crucial).
989 m_storage->deleteText("NameID", name.get());
991 else if (!sessionsKilled.empty()) {
994 if (m_storage->updateText("NameID", name.get(), out.str().c_str(), 0, ver) <= 0)
995 m_log.warn("logout mapping record changed behind us, leaving it alone");
998 catch (exception& ex) {
999 m_log.error("error updating logout mapping record: %s", ex.what());
1002 return sessionsKilled.size();
1005 bool SSCache::stronglyMatches(const XMLCh* idp, const XMLCh* sp, const saml2::NameID& n1, const saml2::NameID& n2) const
1007 if (!XMLString::equals(n1.getName(), n2.getName()))
1010 const XMLCh* s1 = n1.getFormat();
1011 const XMLCh* s2 = n2.getFormat();
1013 s1 = saml2::NameID::UNSPECIFIED;
1015 s2 = saml2::NameID::UNSPECIFIED;
1016 if (!XMLString::equals(s1,s2))
1019 s1 = n1.getNameQualifier();
1020 s2 = n2.getNameQualifier();
1025 if (!XMLString::equals(s1,s2))
1028 s1 = n1.getSPNameQualifier();
1029 s2 = n2.getSPNameQualifier();
1034 if (!XMLString::equals(s1,s2))
1040 void SSCache::receive(DDF& in, ostream& out)
1043 xmltooling::NDC ndc("receive");
1046 if (!strcmp(in.name(),"find::"REMOTED_SESSION_CACHE"::SessionCache")) {
1047 const char* key=in["key"].string();
1049 throw ListenerException("Required parameters missing for session removal.");
1051 const Application* app = SPConfig::getConfig().getServiceProvider()->getApplication(in["application_id"].string());
1053 throw ListenerException("Application not found, check configuration?");
1055 // Do an unversioned read.
1058 if (!m_storage->readText(key, "session", &record, &lastAccess)) {
1060 DDFJanitor jan(ret);
1065 // Adjust for expiration to recover last access time and check timeout.
1066 lastAccess -= m_cacheTimeout;
1067 time_t now=time(NULL);
1069 // See if we need to check for a timeout.
1070 if (in["timeout"].string()) {
1072 auto_ptr_XMLCh dt(in["timeout"].string());
1073 DateTime dtobj(dt.get());
1074 dtobj.parseDateTime();
1075 timeout = dtobj.getEpoch();
1077 if (timeout > 0 && now - lastAccess >= timeout) {
1078 m_log.info("session timed out (ID: %s)", key);
1080 throw RetryableProfileException("Your session has expired, and you must re-authenticate.");
1083 // Update storage expiration, if possible.
1085 m_storage->updateContext(key, now + m_cacheTimeout);
1087 catch (exception& ex) {
1088 m_log.error("failed to update session expiration: %s", ex.what());
1092 // Send the record back.
1095 else if (!strcmp(in.name(),"touch::"REMOTED_SESSION_CACHE"::SessionCache")) {
1096 const char* key=in["key"].string();
1098 throw ListenerException("Required parameters missing for session check.");
1100 // Do a versioned read.
1103 int curver = in["version"].integer();
1104 int ver = m_storage->readText(key, "session", &record, &lastAccess, curver);
1106 m_log.warn("unsuccessful versioned read of session (ID: %s), caches out of sync?", key);
1107 throw RetryableProfileException("Your session has expired, and you must re-authenticate.");
1110 // Adjust for expiration to recover last access time and check timeout.
1111 lastAccess -= m_cacheTimeout;
1112 time_t now=time(NULL);
1114 // See if we need to check for a timeout.
1116 auto_ptr_XMLCh dt(in["timeout"].string());
1118 DateTime dtobj(dt.get());
1119 dtobj.parseDateTime();
1120 timeout = dtobj.getEpoch();
1123 if (timeout > 0 && now - lastAccess >= timeout) {
1124 m_log.info("session timed out (ID: %s)", key);
1125 throw RetryableProfileException("Your session has expired, and you must re-authenticate.");
1128 // Update storage expiration, if possible.
1130 m_storage->updateContext(key, now + m_cacheTimeout);
1132 catch (exception& ex) {
1133 m_log.error("failed to update session expiration: %s", ex.what());
1137 // Send the record back.
1142 DDFJanitor jan(ret);
1146 else if (!strcmp(in.name(),"remove::"REMOTED_SESSION_CACHE"::SessionCache")) {
1147 const char* key=in["key"].string();
1149 throw ListenerException("Required parameter missing for session removal.");
1151 const Application* app = SPConfig::getConfig().getServiceProvider()->getApplication(in["application_id"].string());
1153 throw ListenerException("Application not found, check configuration?");
1157 DDFJanitor jan(ret);
1160 else if (!strcmp(in.name(),"getAssertion::"REMOTED_SESSION_CACHE"::SessionCache")) {
1161 const char* key=in["key"].string();
1162 const char* id=in["id"].string();
1164 throw ListenerException("Required parameters missing for assertion retrieval.");
1166 if (!m_storage->readText(key, id, &token, NULL))
1167 throw FatalProfileException("Assertion not found in cache.");