2 * Copyright 2001-2007 Internet2
\r
4 * Licensed under the Apache License, Version 2.0 (the "License");
\r
5 * you may not use this file except in compliance with the License.
\r
6 * You may obtain a copy of the License at
\r
8 * http://www.apache.org/licenses/LICENSE-2.0
\r
10 * Unless required by applicable law or agreed to in writing, software
\r
11 * distributed under the License is distributed on an "AS IS" BASIS,
\r
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
\r
13 * See the License for the specific language governing permissions and
\r
14 * limitations under the License.
\r
18 * StorageServiceSessionCache.cpp
\r
20 * StorageService-based SessionCache implementation.
\r
22 * Instead of optimizing this plugin with a buffering scheme that keeps objects around
\r
23 * and avoids extra parsing steps, I'm assuming that systems that require such can
\r
24 * layer their own cache plugin on top of this version either by delegating to it
\r
25 * or using the remoting support. So this version will load sessions directly
\r
26 * from the StorageService, instantiate enough to expose the Session API,
\r
27 * and then delete everything when they're unlocked. All data in memory is always
\r
28 * kept in sync with the StorageService (no lazy updates).
\r
31 #include "internal.h"
\r
32 #include "Application.h"
\r
33 #include "exceptions.h"
\r
34 #include "ServiceProvider.h"
\r
35 #include "SessionCache.h"
\r
36 #include "TransactionLog.h"
\r
37 #include "attribute/Attribute.h"
\r
38 #include "remoting/ListenerService.h"
\r
39 #include "util/SPConstants.h"
\r
41 #include <log4cpp/Category.hh>
\r
42 #include <saml/SAMLConfig.h>
\r
43 #include <xmltooling/util/NDC.h>
\r
44 #include <xmltooling/util/StorageService.h>
\r
45 #include <xmltooling/util/XMLHelper.h>
\r
46 #include <xercesc/util/XMLUniDefs.hpp>
\r
48 using namespace shibsp;
\r
49 using namespace opensaml::saml2md;
\r
50 using namespace opensaml;
\r
51 using namespace xmltooling;
\r
52 using namespace log4cpp;
\r
53 using namespace std;
\r
58 class StoredSession : public virtual Session
\r
61 StoredSession(SSCache* cache, DDF& obj) : m_obj(obj), m_nameid(NULL), m_cache(cache) {
\r
62 const char* nameid = obj["nameid"].string();
\r
64 // Parse and bind the document into an XMLObject.
\r
65 istringstream instr(nameid);
\r
66 DOMDocument* doc = XMLToolingConfig::getConfig().getParser().parse(instr);
\r
67 XercesJanitor<DOMDocument> janitor(doc);
\r
68 auto_ptr<saml2::NameID> n(saml2::NameIDBuilder::buildNameID());
\r
69 n->unmarshall(doc->getDocumentElement(), true);
\r
71 m_nameid = n.release();
\r
84 const char* getID() const {
\r
85 return m_obj.name();
\r
87 const char* getClientAddress() const {
\r
88 return m_obj["client_addr"].string();
\r
90 const char* getEntityID() const {
\r
91 return m_obj["entity_id"].string();
\r
93 const char* getProtocol() const {
\r
94 return m_obj["protocol"].string();
\r
96 const char* getAuthnInstant() const {
\r
97 return m_obj["authn_instant"].string();
\r
99 const opensaml::saml2::NameID* getNameID() const {
\r
102 const char* getSessionIndex() const {
\r
103 return m_obj["session_index"].string();
\r
105 const char* getAuthnContextClassRef() const {
\r
106 return m_obj["authncontext_class"].string();
\r
108 const char* getAuthnContextDeclRef() const {
\r
109 return m_obj["authncontext_decl"].string();
\r
111 const multimap<string,Attribute*>& getAttributes() const {
\r
112 if (m_attributes.empty())
\r
113 unmarshallAttributes();
\r
114 return m_attributes;
\r
116 const vector<const char*>& getAssertionIDs() const {
\r
117 if (m_ids.empty()) {
\r
118 DDF ids = m_obj["assertions"];
\r
119 DDF id = ids.first();
\r
120 while (id.isstring()) {
\r
121 m_ids.push_back(id.string());
\r
128 void addAttributes(const vector<Attribute*>& attributes);
\r
129 const Assertion* getAssertion(const char* id) const;
\r
130 void addAssertion(Assertion* assertion);
\r
133 void unmarshallAttributes() const;
\r
136 saml2::NameID* m_nameid;
\r
137 mutable multimap<string,Attribute*> m_attributes;
\r
138 mutable vector<const char*> m_ids;
\r
139 mutable map<string,Assertion*> m_tokens;
\r
143 class SSCache : public SessionCache, public virtual Remoted
\r
146 SSCache(const DOMElement* e);
\r
149 void receive(DDF& in, ostream& out);
\r
153 const Application& application,
\r
154 const char* client_addr=NULL,
\r
155 const saml2md::EntityDescriptor* issuer=NULL,
\r
156 const XMLCh* protocol=NULL,
\r
157 const saml2::NameID* nameid=NULL,
\r
158 const XMLCh* authn_instant=NULL,
\r
159 const XMLCh* session_index=NULL,
\r
160 const XMLCh* authncontext_class=NULL,
\r
161 const XMLCh* authncontext_decl=NULL,
\r
162 const vector<const Assertion*>* tokens=NULL,
\r
163 const multimap<string,Attribute*>* attributes=NULL
\r
165 Session* find(const char* key, const Application& application, const char* client_addr=NULL, time_t* timeout=NULL);
\r
166 void remove(const char* key, const Application& application);
\r
168 const saml2md::EntityDescriptor* issuer,
\r
169 const saml2::NameID& nameid,
\r
171 const Application& application,
\r
172 vector<string>& sessions
\r
176 StorageService* m_storage;
\r
179 // maintain back-mappings of NameID/SessionIndex -> session key
\r
180 void insert(const char* key, time_t expires, const char* name, const char* index);
\r
182 bool stronglyMatches(const XMLCh* idp, const XMLCh* sp, const saml2::NameID& n1, const saml2::NameID& n2) const;
\r
185 SessionCache* SHIBSP_DLLLOCAL StorageServiceCacheFactory(const DOMElement* const & e)
\r
187 return new SSCache(e);
\r
190 static const XMLCh _StorageService[] = UNICODE_LITERAL_14(S,t,o,r,a,g,e,S,e,r,v,i,c,e);
\r
193 StoredSession::~StoredSession()
\r
197 for_each(m_attributes.begin(), m_attributes.end(), cleanup_pair<string,Attribute>());
\r
198 for_each(m_tokens.begin(), m_tokens.end(), cleanup_pair<string,Assertion>());
\r
201 void StoredSession::unmarshallAttributes() const
\r
203 Attribute* attribute;
\r
204 DDF attrs = m_obj["attributes"];
\r
205 DDF attr = attrs.first();
\r
206 while (!attr.isnull()) {
\r
208 attribute = Attribute::unmarshall(attr);
\r
209 m_attributes.insert(make_pair(attribute->getId(), attribute));
\r
210 if (m_cache->m_log.isDebugEnabled())
\r
211 m_cache->m_log.debug("unmarshalled attribute (ID: %s) with %d value%s",
\r
212 attribute->getId(), attr.first().integer(), attr.first().integer()!=1 ? "s" : "");
\r
214 catch (AttributeException& ex) {
\r
215 const char* id = attr.first().name();
\r
216 m_cache->m_log.error("error unmarshalling attribute (ID: %s): %s", id ? id : "none", ex.what());
\r
218 attr = attrs.next();
\r
222 void StoredSession::addAttributes(const vector<Attribute*>& attributes)
\r
225 xmltooling::NDC ndc("addAttributes");
\r
228 m_cache->m_log.debug("adding attributes to session (%s)", getID());
\r
233 DDF attrs = m_obj["attributes"];
\r
234 if (!attrs.islist())
\r
235 attrs = m_obj.addmember("attributes").list();
\r
236 for (vector<Attribute*>::const_iterator a=attributes.begin(); a!=attributes.end(); ++a) {
\r
237 attr = (*a)->marshall();
\r
241 // Tentatively increment the version.
\r
242 m_obj["version"].integer(m_obj["version"].integer()+1);
\r
246 string record(str.str());
\r
249 ver = m_cache->m_storage->updateText(getID(), "session", record.c_str(), 0, m_obj["version"].integer()-1);
\r
251 catch (exception&) {
\r
252 // Roll back modification to record.
\r
253 m_obj["version"].integer(m_obj["version"].integer()-1);
\r
254 vector<Attribute*>::size_type count = attributes.size();
\r
256 attrs.last().destroy();
\r
261 // Roll back modification to record.
\r
262 m_obj["version"].integer(m_obj["version"].integer()-1);
\r
263 vector<Attribute*>::size_type count = attributes.size();
\r
265 attrs.last().destroy();
\r
268 // Fatal problem with update.
\r
269 throw IOException("Unable to update stored session.");
\r
271 else if (ver < 0) {
\r
273 m_cache->m_log.warn("storage service indicates the record is out of sync, updating with a fresh copy...");
\r
274 ver = m_cache->m_storage->readText(getID(), "session", &record, NULL);
\r
276 m_cache->m_log.error("readText failed on StorageService for session (%s)", getID());
\r
277 throw IOException("Unable to read back stored session.");
\r
282 istringstream in(record);
\r
286 for_each(m_attributes.begin(), m_attributes.end(), cleanup_const_pair<string,Attribute>());
\r
287 m_attributes.clear();
\r
288 newobj["version"].integer(ver);
\r
294 } while (ver < 0); // negative indicates a sync issue so we retry
\r
296 TransactionLog* xlog = SPConfig::getConfig().getServiceProvider()->getTransactionLog();
\r
297 Locker locker(xlog);
\r
298 xlog->log.infoStream() <<
\r
299 "Added the following attributes to session (ID: " <<
\r
301 ") for (applicationId: " <<
\r
302 m_obj["application_id"].string() <<
\r
304 for (vector<Attribute*>::const_iterator a=attributes.begin(); a!=attributes.end(); ++a)
\r
305 xlog->log.infoStream() << "\t" << (*a)->getId() << " (" << (*a)->valueCount() << " values)";
\r
306 xlog->log.info("}");
\r
308 // We own them now, so clean them up.
\r
309 for_each(attributes.begin(), attributes.end(), xmltooling::cleanup<Attribute>());
\r
312 const Assertion* StoredSession::getAssertion(const char* id) const
\r
314 map<string,Assertion*>::const_iterator i = m_tokens.find(id);
\r
315 if (i!=m_tokens.end())
\r
319 if (!m_cache->m_storage->readText(getID(), id, &tokenstr, NULL))
\r
320 throw FatalProfileException("Assertion not found in cache.");
\r
322 // Parse and bind the document into an XMLObject.
\r
323 istringstream instr(tokenstr);
\r
324 DOMDocument* doc = XMLToolingConfig::getConfig().getParser().parse(instr);
\r
325 XercesJanitor<DOMDocument> janitor(doc);
\r
326 auto_ptr<XMLObject> xmlObject(XMLObjectBuilder::buildOneFromElement(doc->getDocumentElement(), true));
\r
329 Assertion* token = dynamic_cast<Assertion*>(xmlObject.get());
\r
331 throw FatalProfileException("Request for cached assertion returned an unknown object type.");
\r
333 // Transfer ownership to us.
\r
334 xmlObject.release();
\r
335 m_tokens[id]=token;
\r
339 void StoredSession::addAssertion(Assertion* assertion)
\r
342 xmltooling::NDC ndc("addAssertion");
\r
346 throw FatalProfileException("Unknown object type passed to session for storage.");
\r
348 auto_ptr_char id(assertion->getID());
\r
350 m_cache->m_log.debug("adding assertion (%s) to session (%s)", id.get(), getID());
\r
353 if (!m_cache->m_storage->readText(getID(), "session", NULL, &exp))
\r
354 throw IOException("Unable to load expiration time for stored session.");
\r
356 ostringstream tokenstr;
\r
357 tokenstr << *assertion;
\r
358 if (!m_cache->m_storage->createText(getID(), id.get(), tokenstr.str().c_str(), exp))
\r
359 throw IOException("Attempted to insert duplicate assertion ID into session.");
\r
363 DDF token = DDF(NULL).string(id.get());
\r
364 m_obj["assertions"].add(token);
\r
366 // Tentatively increment the version.
\r
367 m_obj["version"].integer(m_obj["version"].integer()+1);
\r
371 string record(str.str());
\r
374 ver = m_cache->m_storage->updateText(getID(), "session", record.c_str(), 0, m_obj["version"].integer()-1);
\r
376 catch (exception&) {
\r
378 m_obj["version"].integer(m_obj["version"].integer()-1);
\r
379 m_cache->m_storage->deleteText(getID(), id.get());
\r
385 m_obj["version"].integer(m_obj["version"].integer()-1);
\r
388 // Fatal problem with update.
\r
389 m_cache->m_log.error("updateText failed on StorageService for session (%s)", getID());
\r
390 m_cache->m_storage->deleteText(getID(), id.get());
\r
391 throw IOException("Unable to update stored session.");
\r
393 else if (ver < 0) {
\r
395 m_cache->m_log.warn("storage service indicates the record is out of sync, updating with a fresh copy...");
\r
396 ver = m_cache->m_storage->readText(getID(), "session", &record, NULL);
\r
398 m_cache->m_log.error("readText failed on StorageService for session (%s)", getID());
\r
399 m_cache->m_storage->deleteText(getID(), id.get());
\r
400 throw IOException("Unable to read back stored session.");
\r
405 istringstream in(record);
\r
409 for_each(m_attributes.begin(), m_attributes.end(), cleanup_const_pair<string,Attribute>());
\r
410 m_attributes.clear();
\r
411 newobj["version"].integer(ver);
\r
417 } while (ver < 0); // negative indicates a sync issue so we retry
\r
422 TransactionLog* xlog = SPConfig::getConfig().getServiceProvider()->getTransactionLog();
\r
423 Locker locker(xlog);
\r
425 "Added assertion (ID: %s) to session for (applicationId: %s) with (ID: %s)",
\r
426 id.get(), m_obj["application_id"].string(), getID()
\r
430 SSCache::SSCache(const DOMElement* e)
\r
431 : SessionCache(e), m_log(Category::getInstance(SHIBSP_LOGCAT".SessionCache")), m_storage(NULL)
\r
433 SPConfig& conf = SPConfig::getConfig();
\r
434 const XMLCh* tag = e ? e->getAttributeNS(NULL,_StorageService) : NULL;
\r
436 auto_ptr_char ssid(tag);
\r
437 m_storage = conf.getServiceProvider()->getStorageService(ssid.get());
\r
439 m_log.info("bound to StorageService (%s)", ssid.get());
\r
441 throw ConfigurationException("SessionCache unable to locate StorageService, check configuration.");
\r
444 ListenerService* listener=conf.getServiceProvider()->getListenerService(false);
\r
445 if (listener && conf.isEnabled(SPConfig::OutOfProcess)) {
\r
446 listener->regListener("find::"REMOTED_SESSION_CACHE"::SessionCache",this);
\r
447 listener->regListener("remove::"REMOTED_SESSION_CACHE"::SessionCache",this);
\r
448 listener->regListener("touch::"REMOTED_SESSION_CACHE"::SessionCache",this);
\r
449 listener->regListener("getAssertion::"REMOTED_SESSION_CACHE"::SessionCache",this);
\r
452 m_log.info("no ListenerService available, cache remoting disabled");
\r
456 SSCache::~SSCache()
\r
458 SPConfig& conf = SPConfig::getConfig();
\r
459 ListenerService* listener=conf.getServiceProvider()->getListenerService(false);
\r
460 if (listener && conf.isEnabled(SPConfig::OutOfProcess)) {
\r
461 listener->unregListener("find::"REMOTED_SESSION_CACHE"::SessionCache",this);
\r
462 listener->unregListener("remove::"REMOTED_SESSION_CACHE"::SessionCache",this);
\r
463 listener->unregListener("touch::"REMOTED_SESSION_CACHE"::SessionCache",this);
\r
464 listener->unregListener("getAssertion::"REMOTED_SESSION_CACHE"::SessionCache",this);
\r
468 void SSCache::insert(const char* key, time_t expires, const char* name, const char* index)
\r
471 if (strlen(name) > 255) {
\r
472 dup = string(name).substr(0,255);
\r
473 name = dup.c_str();
\r
477 DDFJanitor jobj(obj);
\r
479 // Since we can't guarantee uniqueness, check for an existing record.
\r
482 int ver = m_storage->readText("NameID", name, &record, &recordexp);
\r
484 // Existing record, so we need to unmarshall it.
\r
485 istringstream in(record);
\r
493 if (!index || !*index)
\r
494 index = "_shibnull";
\r
495 DDF sessions = obj.addmember(index);
\r
496 if (!sessions.islist())
\r
498 DDF session = DDF(NULL).string(key);
\r
499 sessions.add(session);
\r
501 // Remarshall the record.
\r
505 // Try and store it back...
\r
507 ver = m_storage->updateText("NameID", name, out.str().c_str(), max(expires, recordexp), ver);
\r
509 // Out of sync, or went missing, so retry.
\r
510 return insert(key, expires, name, index);
\r
513 else if (!m_storage->createText("NameID", name, out.str().c_str(), expires)) {
\r
514 // Hit a dup, so just retry, hopefully hitting the other branch.
\r
515 return insert(key, expires, name, index);
\r
519 string SSCache::insert(
\r
521 const Application& application,
\r
522 const char* client_addr,
\r
523 const saml2md::EntityDescriptor* issuer,
\r
524 const XMLCh* protocol,
\r
525 const saml2::NameID* nameid,
\r
526 const XMLCh* authn_instant,
\r
527 const XMLCh* session_index,
\r
528 const XMLCh* authncontext_class,
\r
529 const XMLCh* authncontext_decl,
\r
530 const vector<const Assertion*>* tokens,
\r
531 const multimap<string,Attribute*>* attributes
\r
535 xmltooling::NDC ndc("insert");
\r
538 m_log.debug("creating new session");
\r
540 auto_ptr_char key(SAMLConfig::getConfig().generateIdentifier());
\r
542 // Store session properties in DDF.
\r
543 DDF obj = DDF(key.get()).structure();
\r
544 obj.addmember("version").integer(1);
\r
545 obj.addmember("application_id").string(application.getId());
\r
547 // On 64-bit Windows, time_t doesn't fit in a long, so I'm using ISO timestamps.
\r
548 #ifndef HAVE_GMTIME_R
\r
549 struct tm* ptime=gmtime(&expires);
\r
552 struct tm* ptime=gmtime_r(&expires,&res);
\r
555 strftime(timebuf,32,"%Y-%m-%dT%H:%M:%SZ",ptime);
\r
556 obj.addmember("expires").string(timebuf);
\r
559 obj.addmember("client_addr").string(client_addr);
\r
561 auto_ptr_char entity_id(issuer->getEntityID());
\r
562 obj.addmember("entity_id").string(entity_id.get());
\r
565 auto_ptr_char prot(protocol);
\r
566 obj.addmember("protocol").string(prot.get());
\r
568 if (authn_instant) {
\r
569 auto_ptr_char instant(authn_instant);
\r
570 obj.addmember("authn_instant").string(instant.get());
\r
572 auto_ptr_char index(session_index);
\r
574 obj.addmember("session_index").string(index.get());
\r
575 if (authncontext_class) {
\r
576 auto_ptr_char ac(authncontext_class);
\r
577 obj.addmember("authncontext_class").string(ac.get());
\r
579 if (authncontext_decl) {
\r
580 auto_ptr_char ad(authncontext_decl);
\r
581 obj.addmember("authncontext_decl").string(ad.get());
\r
585 ostringstream namestr;
\r
586 namestr << *nameid;
\r
587 obj.addmember("nameid").string(namestr.str().c_str());
\r
591 obj.addmember("assertions").list();
\r
592 for (vector<const Assertion*>::const_iterator t = tokens->begin(); t!=tokens->end(); ++t) {
\r
593 auto_ptr_char tokenid((*t)->getID());
\r
594 DDF tokid = DDF(NULL).string(tokenid.get());
\r
595 obj["assertions"].add(tokid);
\r
601 DDF attrlist = obj.addmember("attributes").list();
\r
602 for (multimap<string,Attribute*>::const_iterator a=attributes->begin(); a!=attributes->end(); ++a) {
\r
603 attr = a->second->marshall();
\r
604 attrlist.add(attr);
\r
608 ostringstream record;
\r
611 m_log.debug("storing new session...");
\r
612 time_t now = time(NULL);
\r
613 if (!m_storage->createText(key.get(), "session", record.str().c_str(), now + m_cacheTimeout))
\r
614 throw FatalProfileException("Attempted to create a session with a duplicate key.");
\r
616 // Store the reverse mapping for logout.
\r
617 auto_ptr_char name(nameid ? nameid->getName() : NULL);
\r
620 insert(key.get(), expires, name.get(), index.get());
\r
622 catch (exception& ex) {
\r
623 m_log.error("error storing back mapping of NameID for logout: %s", ex.what());
\r
628 for (vector<const Assertion*>::const_iterator t = tokens->begin(); t!=tokens->end(); ++t) {
\r
629 ostringstream tokenstr;
\r
631 auto_ptr_char tokenid((*t)->getID());
\r
632 if (!m_storage->createText(key.get(), tokenid.get(), tokenstr.str().c_str(), now + m_cacheTimeout))
\r
633 throw IOException("duplicate assertion ID ($1)", params(1, tokenid.get()));
\r
636 catch (exception& ex) {
\r
637 m_log.error("error storing assertion along with session: %s", ex.what());
\r
641 const char* pid = obj["entity_id"].string();
\r
642 m_log.info("new session created: SessionID (%s) IdP (%s) Address (%s)", key.get(), pid ? pid : "none", client_addr);
\r
644 // Transaction Logging
\r
645 TransactionLog* xlog = application.getServiceProvider().getTransactionLog();
\r
646 Locker locker(xlog);
\r
647 xlog->log.infoStream() <<
\r
648 "New session (ID: " <<
\r
650 ") with (applicationId: " <<
\r
651 application.getId() <<
\r
652 ") for principal from (IdP: " <<
\r
653 (pid ? pid : "none") <<
\r
654 ") at (ClientAddress: " <<
\r
655 (client_addr ? client_addr : "none") <<
\r
656 ") with (NameIdentifier: " <<
\r
657 (name.get() ? name.get() : "none") <<
\r
661 xlog->log.infoStream() <<
\r
662 "Cached the following attributes with session (ID: " <<
\r
664 ") for (applicationId: " <<
\r
665 application.getId() <<
\r
667 for (multimap<string,Attribute*>::const_iterator a=attributes->begin(); a!=attributes->end(); ++a)
\r
668 xlog->log.infoStream() << "\t" << a->second->getId() << " (" << a->second->valueCount() << " values)";
\r
669 xlog->log.info("}");
\r
675 Session* SSCache::find(const char* key, const Application& application, const char* client_addr, time_t* timeout)
\r
678 xmltooling::NDC ndc("find");
\r
681 m_log.debug("searching for session (%s)", key);
\r
685 int ver = m_storage->readText(key, "session", &record, &lastAccess);
\r
689 m_log.debug("reconstituting session and checking validity");
\r
692 istringstream in(record);
\r
695 if (!XMLString::equals(obj["application_id"].string(), application.getId())) {
\r
696 m_log.error("an application (%s) tried to access another application's session", application.getId());
\r
702 if (m_log.isDebugEnabled())
\r
703 m_log.debug("comparing client address %s against %s", client_addr, obj["client_addr"].string());
\r
704 if (strcmp(obj["client_addr"].string(),client_addr)) {
\r
705 m_log.warn("client address mismatch");
\r
706 remove(key, application);
\r
707 RetryableProfileException ex(
\r
708 "Your IP address ($1) does not match the address recorded at the time the session was established.",
\r
709 params(1,client_addr)
\r
711 string eid(obj["entity_id"].string());
\r
715 MetadataProvider* m=application.getMetadataProvider();
\r
717 annotateException(&ex,m->getEntityDescriptor(eid.c_str(),false)); // throws it
\r
721 lastAccess -= m_cacheTimeout; // adjusts it back to the last time the record's timestamp was touched
\r
722 time_t now=time(NULL);
\r
724 if (timeout && *timeout > 0 && now - lastAccess >= *timeout) {
\r
725 m_log.info("session timed out (ID: %s)", key);
\r
726 remove(key, application);
\r
727 RetryableProfileException ex("Your session has expired, and you must re-authenticate.");
\r
728 string eid(obj["entity_id"].string());
\r
732 MetadataProvider* m=application.getMetadataProvider();
\r
734 annotateException(&ex,m->getEntityDescriptor(eid.c_str(),false)); // throws it
\r
737 auto_ptr_XMLCh exp(obj["expires"].string());
\r
739 DateTime iso(exp.get());
\r
740 iso.parseDateTime();
\r
741 if (now > iso.getEpoch()) {
\r
742 m_log.info("session expired (ID: %s)", key);
\r
743 remove(key, application);
\r
744 RetryableProfileException ex("Your session has expired, and you must re-authenticate.");
\r
745 string eid(obj["entity_id"].string());
\r
749 MetadataProvider* m=application.getMetadataProvider();
\r
751 annotateException(&ex,m->getEntityDescriptor(eid.c_str(),false)); // throws it
\r
756 // Update storage expiration, if possible.
\r
758 m_storage->updateContext(key, now + m_cacheTimeout);
\r
760 catch (exception& ex) {
\r
761 m_log.error("failed to update session expiration: %s", ex.what());
\r
765 // Finally build the Session object.
\r
767 return new StoredSession(this, obj);
\r
769 catch (exception&) {
\r
775 void SSCache::remove(const char* key, const Application& application)
\r
778 xmltooling::NDC ndc("remove");
\r
781 m_storage->deleteContext(key);
\r
782 m_log.info("removed session (%s)", key);
\r
784 TransactionLog* xlog = application.getServiceProvider().getTransactionLog();
\r
785 Locker locker(xlog);
\r
786 xlog->log.info("Destroyed session (applicationId: %s) (ID: %s)", application.getId(), key);
\r
789 void SSCache::remove(
\r
790 const saml2md::EntityDescriptor* issuer,
\r
791 const saml2::NameID& nameid,
\r
793 const Application& application,
\r
794 vector<string>& sessionsKilled
\r
798 xmltooling::NDC ndc("remove");
\r
801 auto_ptr_char entityID(issuer ? issuer->getEntityID() : NULL);
\r
802 auto_ptr_char name(nameid.getName());
\r
805 "request to logout sessions from (%s) for (%s) for session index (%s)",
\r
806 entityID.get() ? entityID.get() : "unknown", name.get(), index ? index : "all"
\r
809 if (strlen(name.get()) > 255)
\r
810 const_cast<char*>(name.get())[255] = 0;
\r
812 // Read in potentially matching sessions.
\r
814 int ver = m_storage->readText("NameID", name.get(), &record);
\r
816 m_log.debug("no active sessions to remove for supplied issuer and name identifier");
\r
821 DDFJanitor jobj(obj);
\r
822 istringstream in(record);
\r
825 // The record contains child lists for each known session index.
\r
827 DDF sessions = obj.first();
\r
828 while (sessions.islist()) {
\r
829 if (!index || !strcmp(sessions.name(), index)) {
\r
830 key = sessions.first();
\r
831 while (key.isstring()) {
\r
832 // Fetch the session for comparison and possible removal.
\r
833 Session* session = find(key.string(), application);
\r
834 Locker locker(session);
\r
837 if (XMLString::equals(session->getEntityID(), entityID.get())) {
\r
839 if (stronglyMatches(issuer->getEntityID(), application.getXMLString("entityID").second, nameid, *session->getNameID())) {
\r
840 sessionsKilled.push_back(key.string());
\r
841 remove(key.string(), application); // let this throw to detect errors in case the full logout fails?
\r
845 m_log.debug("session (%s) contained a non-matching NameID, leaving it alone", key.string());
\r
849 m_log.debug("session (%s) established by different IdP, leaving it alone", key.string());
\r
853 // Session's gone, so...
\r
854 sessionsKilled.push_back(key.string());
\r
857 key = sessions.next();
\r
860 // No sessions left for this index?
\r
861 if (sessions.first().isnull())
\r
862 sessions.destroy();
\r
864 sessions = obj.next();
\r
867 if (obj.first().isnull())
\r
870 // If possible, write back the mapping record (this isn't crucial).
\r
872 if (obj.isnull()) {
\r
873 m_storage->deleteText("NameID", name.get());
\r
875 else if (!sessionsKilled.empty()) {
\r
878 if (m_storage->updateText("NameID", name.get(), out.str().c_str(), 0, ver) <= 0)
\r
879 m_log.warn("logout mapping record changed behind us, leaving it alone");
\r
882 catch (exception& ex) {
\r
883 m_log.error("error updating logout mapping record: %s", ex.what());
\r
887 bool SSCache::stronglyMatches(const XMLCh* idp, const XMLCh* sp, const saml2::NameID& n1, const saml2::NameID& n2) const
\r
889 if (!XMLString::equals(n1.getName(), n2.getName()))
\r
892 const XMLCh* s1 = n1.getFormat();
\r
893 const XMLCh* s2 = n2.getFormat();
\r
895 s1 = saml2::NameID::UNSPECIFIED;
\r
897 s2 = saml2::NameID::UNSPECIFIED;
\r
898 if (!XMLString::equals(s1,s2))
\r
901 s1 = n1.getNameQualifier();
\r
902 s2 = n2.getNameQualifier();
\r
907 if (!XMLString::equals(s1,s2))
\r
910 s1 = n1.getSPNameQualifier();
\r
911 s2 = n2.getSPNameQualifier();
\r
916 if (!XMLString::equals(s1,s2))
\r
922 void SSCache::receive(DDF& in, ostream& out)
\r
925 xmltooling::NDC ndc("receive");
\r
928 if (!strcmp(in.name(),"find::"REMOTED_SESSION_CACHE"::SessionCache")) {
\r
929 const char* key=in["key"].string();
\r
931 throw ListenerException("Required parameters missing for session removal.");
\r
933 const Application* app = SPConfig::getConfig().getServiceProvider()->getApplication(in["application_id"].string());
\r
935 throw ListenerException("Application not found, check configuration?");
\r
937 // Do an unversioned read.
\r
940 if (!m_storage->readText(key, "session", &record, &lastAccess)) {
\r
942 DDFJanitor jan(ret);
\r
947 // Adjust for expiration to recover last access time and check timeout.
\r
948 lastAccess -= m_cacheTimeout;
\r
949 time_t now=time(NULL);
\r
951 // See if we need to check for a timeout.
\r
952 if (in["timeout"].string()) {
\r
953 time_t timeout = 0;
\r
954 auto_ptr_XMLCh dt(in["timeout"].string());
\r
955 DateTime dtobj(dt.get());
\r
956 dtobj.parseDateTime();
\r
957 timeout = dtobj.getEpoch();
\r
959 if (timeout > 0 && now - lastAccess >= timeout) {
\r
960 m_log.info("session timed out (ID: %s)", key);
\r
962 throw RetryableProfileException("Your session has expired, and you must re-authenticate.");
\r
965 // Update storage expiration, if possible.
\r
967 m_storage->updateContext(key, now + m_cacheTimeout);
\r
969 catch (exception& ex) {
\r
970 m_log.error("failed to update session expiration: %s", ex.what());
\r
974 // Send the record back.
\r
977 else if (!strcmp(in.name(),"touch::"REMOTED_SESSION_CACHE"::SessionCache")) {
\r
978 const char* key=in["key"].string();
\r
980 throw ListenerException("Required parameters missing for session check.");
\r
982 // Do a versioned read.
\r
985 int curver = in["version"].integer();
\r
986 int ver = m_storage->readText(key, "session", &record, &lastAccess, curver);
\r
988 m_log.warn("unsuccessful versioned read of session (ID: %s), caches out of sync?", key);
\r
989 throw RetryableProfileException("Your session has expired, and you must re-authenticate.");
\r
992 // Adjust for expiration to recover last access time and check timeout.
\r
993 lastAccess -= m_cacheTimeout;
\r
994 time_t now=time(NULL);
\r
996 // See if we need to check for a timeout.
\r
997 time_t timeout = 0;
\r
998 auto_ptr_XMLCh dt(in["timeout"].string());
\r
1000 DateTime dtobj(dt.get());
\r
1001 dtobj.parseDateTime();
\r
1002 timeout = dtobj.getEpoch();
\r
1005 if (timeout > 0 && now - lastAccess >= timeout) {
\r
1006 m_log.info("session timed out (ID: %s)", key);
\r
1007 throw RetryableProfileException("Your session has expired, and you must re-authenticate.");
\r
1010 // Update storage expiration, if possible.
\r
1012 m_storage->updateContext(key, now + m_cacheTimeout);
\r
1014 catch (exception& ex) {
\r
1015 m_log.error("failed to update session expiration: %s", ex.what());
\r
1018 if (ver > curver) {
\r
1019 // Send the record back.
\r
1024 DDFJanitor jan(ret);
\r
1028 else if (!strcmp(in.name(),"remove::"REMOTED_SESSION_CACHE"::SessionCache")) {
\r
1029 const char* key=in["key"].string();
\r
1031 throw ListenerException("Required parameter missing for session removal.");
\r
1033 const Application* app = SPConfig::getConfig().getServiceProvider()->getApplication(in["application_id"].string());
\r
1035 throw ListenerException("Application not found, check configuration?");
\r
1039 DDFJanitor jan(ret);
\r
1042 else if (!strcmp(in.name(),"getAssertion::"REMOTED_SESSION_CACHE"::SessionCache")) {
\r
1043 const char* key=in["key"].string();
\r
1044 const char* id=in["id"].string();
\r
1046 throw ListenerException("Required parameters missing for assertion retrieval.");
\r
1048 if (!m_storage->readText(key, id, &token, NULL))
\r
1049 throw FatalProfileException("Assertion not found in cache.");
\r