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* getAuthnInstant() const {
\r
94 return m_obj["authn_instant"].string();
\r
96 const opensaml::saml2::NameID* getNameID() const {
\r
99 const char* getSessionIndex() const {
\r
100 return m_obj["session_index"].string();
\r
102 const char* getAuthnContextClassRef() const {
\r
103 return m_obj["authncontext_class"].string();
\r
105 const char* getAuthnContextDeclRef() const {
\r
106 return m_obj["authncontext_decl"].string();
\r
108 const multimap<string,Attribute*>& getAttributes() const {
\r
109 if (m_attributes.empty())
\r
110 unmarshallAttributes();
\r
111 return m_attributes;
\r
113 const vector<const char*>& getAssertionIDs() const {
\r
114 if (m_ids.empty()) {
\r
115 DDF ids = m_obj["assertions"];
\r
116 DDF id = ids.first();
\r
117 while (id.isstring()) {
\r
118 m_ids.push_back(id.string());
\r
125 void addAttributes(const vector<Attribute*>& attributes);
\r
126 const Assertion* getAssertion(const char* id) const;
\r
127 void addAssertion(Assertion* assertion);
\r
130 void unmarshallAttributes() const;
\r
133 saml2::NameID* m_nameid;
\r
134 mutable multimap<string,Attribute*> m_attributes;
\r
135 mutable vector<const char*> m_ids;
\r
136 mutable map<string,Assertion*> m_tokens;
\r
140 class SSCache : public SessionCache, public virtual Remoted
\r
143 SSCache(const DOMElement* e);
\r
146 void receive(DDF& in, ostream& out);
\r
150 const Application& application,
\r
151 const char* client_addr=NULL,
\r
152 const saml2md::EntityDescriptor* issuer=NULL,
\r
153 const saml2::NameID* nameid=NULL,
\r
154 const char* authn_instant=NULL,
\r
155 const char* session_index=NULL,
\r
156 const char* authncontext_class=NULL,
\r
157 const char* authncontext_decl=NULL,
\r
158 const vector<const Assertion*>* tokens=NULL,
\r
159 const multimap<string,Attribute*>* attributes=NULL
\r
161 Session* find(const char* key, const Application& application, const char* client_addr=NULL, time_t* timeout=NULL);
\r
162 void remove(const char* key, const Application& application);
\r
164 const saml2md::EntityDescriptor& issuer,
\r
165 const saml2::NameID& nameid,
\r
167 const Application& application,
\r
168 vector<string>& sessions
\r
170 byname(issuer, nameid, index, application, sessions, false);
\r
173 const saml2md::EntityDescriptor& issuer,
\r
174 const saml2::NameID& nameid,
\r
176 const Application& application,
\r
177 vector<string>& sessions
\r
179 byname(issuer, nameid, index, application, sessions, true);
\r
183 StorageService* m_storage;
\r
186 // maintain back-mappings of NameID/SessionIndex -> session key
\r
187 void insert(const char* key, time_t expires, const char* name, const char* index);
\r
189 const saml2md::EntityDescriptor& issuer,
\r
190 const saml2::NameID& nameid,
\r
192 const Application& application,
\r
193 vector<string>& sessions,
\r
197 bool stronglyMatches(const XMLCh* idp, const XMLCh* sp, const saml2::NameID& n1, const saml2::NameID& n2) const;
\r
200 SessionCache* SHIBSP_DLLLOCAL StorageServiceCacheFactory(const DOMElement* const & e)
\r
202 return new SSCache(e);
\r
205 static const XMLCh _StorageService[] = UNICODE_LITERAL_14(S,t,o,r,a,g,e,S,e,r,v,i,c,e);
\r
208 StoredSession::~StoredSession()
\r
212 for_each(m_attributes.begin(), m_attributes.end(), cleanup_pair<string,Attribute>());
\r
213 for_each(m_tokens.begin(), m_tokens.end(), cleanup_pair<string,Assertion>());
\r
216 void StoredSession::unmarshallAttributes() const
\r
218 Attribute* attribute;
\r
219 DDF attrs = m_obj["attributes"];
\r
220 DDF attr = attrs.first();
\r
221 while (!attr.isnull()) {
\r
223 attribute = Attribute::unmarshall(attr);
\r
224 m_attributes.insert(make_pair(attribute->getId(), attribute));
\r
225 if (m_cache->m_log.isDebugEnabled())
\r
226 m_cache->m_log.debug("unmarshalled attribute (ID: %s) with %d value%s",
\r
227 attribute->getId(), attr.first().integer(), attr.first().integer()!=1 ? "s" : "");
\r
229 catch (AttributeException& ex) {
\r
230 const char* id = attr.first().name();
\r
231 m_cache->m_log.error("error unmarshalling attribute (ID: %s): %s", id ? id : "none", ex.what());
\r
233 attr = attrs.next();
\r
237 void StoredSession::addAttributes(const vector<Attribute*>& attributes)
\r
240 xmltooling::NDC ndc("addAttributes");
\r
243 m_cache->m_log.debug("adding attributes to session (%s)", getID());
\r
248 DDF attrs = m_obj["attributes"];
\r
249 if (!attrs.islist())
\r
250 attrs = m_obj.addmember("attributes").list();
\r
251 for (vector<Attribute*>::const_iterator a=attributes.begin(); a!=attributes.end(); ++a) {
\r
252 attr = (*a)->marshall();
\r
256 // Tentatively increment the version.
\r
257 m_obj["version"].integer(m_obj["version"].integer()+1);
\r
261 string record(str.str());
\r
264 ver = m_cache->m_storage->updateText(getID(), "session", record.c_str(), 0, m_obj["version"].integer()-1);
\r
266 catch (exception&) {
\r
267 // Roll back modification to record.
\r
268 m_obj["version"].integer(m_obj["version"].integer()-1);
\r
269 vector<Attribute*>::size_type count = attributes.size();
\r
271 attrs.last().destroy();
\r
276 // Roll back modification to record.
\r
277 m_obj["version"].integer(m_obj["version"].integer()-1);
\r
278 vector<Attribute*>::size_type count = attributes.size();
\r
280 attrs.last().destroy();
\r
283 // Fatal problem with update.
\r
284 throw IOException("Unable to update stored session.");
\r
286 else if (ver < 0) {
\r
288 m_cache->m_log.warn("storage service indicates the record is out of sync, updating with a fresh copy...");
\r
289 ver = m_cache->m_storage->readText(getID(), "session", &record, NULL);
\r
291 m_cache->m_log.error("readText failed on StorageService for session (%s)", getID());
\r
292 throw IOException("Unable to read back stored session.");
\r
297 istringstream in(record);
\r
301 for_each(m_attributes.begin(), m_attributes.end(), cleanup_const_pair<string,Attribute>());
\r
302 m_attributes.clear();
\r
303 newobj["version"].integer(ver);
\r
309 } while (ver < 0); // negative indicates a sync issue so we retry
\r
311 TransactionLog* xlog = SPConfig::getConfig().getServiceProvider()->getTransactionLog();
\r
312 Locker locker(xlog);
\r
313 xlog->log.infoStream() <<
\r
314 "Added the following attributes to session (ID: " <<
\r
316 ") for (applicationId: " <<
\r
317 m_obj["application_id"].string() <<
\r
319 for (vector<Attribute*>::const_iterator a=attributes.begin(); a!=attributes.end(); ++a)
\r
320 xlog->log.infoStream() << "\t" << (*a)->getId() << " (" << (*a)->valueCount() << " values)";
\r
321 xlog->log.info("}");
\r
323 // We own them now, so clean them up.
\r
324 for_each(attributes.begin(), attributes.end(), xmltooling::cleanup<Attribute>());
\r
327 const Assertion* StoredSession::getAssertion(const char* id) const
\r
329 map<string,Assertion*>::const_iterator i = m_tokens.find(id);
\r
330 if (i!=m_tokens.end())
\r
334 if (!m_cache->m_storage->readText(getID(), id, &tokenstr, NULL))
\r
335 throw FatalProfileException("Assertion not found in cache.");
\r
337 // Parse and bind the document into an XMLObject.
\r
338 istringstream instr(tokenstr);
\r
339 DOMDocument* doc = XMLToolingConfig::getConfig().getParser().parse(instr);
\r
340 XercesJanitor<DOMDocument> janitor(doc);
\r
341 auto_ptr<XMLObject> xmlObject(XMLObjectBuilder::buildOneFromElement(doc->getDocumentElement(), true));
\r
344 Assertion* token = dynamic_cast<Assertion*>(xmlObject.get());
\r
346 throw FatalProfileException("Request for cached assertion returned an unknown object type.");
\r
348 // Transfer ownership to us.
\r
349 xmlObject.release();
\r
350 m_tokens[id]=token;
\r
354 void StoredSession::addAssertion(Assertion* assertion)
\r
357 xmltooling::NDC ndc("addAssertion");
\r
361 throw FatalProfileException("Unknown object type passed to session for storage.");
\r
363 auto_ptr_char id(assertion->getID());
\r
365 m_cache->m_log.debug("adding assertion (%s) to session (%s)", id.get(), getID());
\r
368 if (!m_cache->m_storage->readText(getID(), "session", NULL, &exp))
\r
369 throw IOException("Unable to load expiration time for stored session.");
\r
371 ostringstream tokenstr;
\r
372 tokenstr << *assertion;
\r
373 if (!m_cache->m_storage->createText(getID(), id.get(), tokenstr.str().c_str(), exp))
\r
374 throw IOException("Attempted to insert duplicate assertion ID into session.");
\r
378 DDF token = DDF(NULL).string(id.get());
\r
379 m_obj["assertions"].add(token);
\r
381 // Tentatively increment the version.
\r
382 m_obj["version"].integer(m_obj["version"].integer()+1);
\r
386 string record(str.str());
\r
389 ver = m_cache->m_storage->updateText(getID(), "session", record.c_str(), 0, m_obj["version"].integer()-1);
\r
391 catch (exception&) {
\r
393 m_obj["version"].integer(m_obj["version"].integer()-1);
\r
394 m_cache->m_storage->deleteText(getID(), id.get());
\r
400 m_obj["version"].integer(m_obj["version"].integer()-1);
\r
403 // Fatal problem with update.
\r
404 m_cache->m_log.error("updateText failed on StorageService for session (%s)", getID());
\r
405 m_cache->m_storage->deleteText(getID(), id.get());
\r
406 throw IOException("Unable to update stored session.");
\r
408 else if (ver < 0) {
\r
410 m_cache->m_log.warn("storage service indicates the record is out of sync, updating with a fresh copy...");
\r
411 ver = m_cache->m_storage->readText(getID(), "session", &record, NULL);
\r
413 m_cache->m_log.error("readText failed on StorageService for session (%s)", getID());
\r
414 m_cache->m_storage->deleteText(getID(), id.get());
\r
415 throw IOException("Unable to read back stored session.");
\r
420 istringstream in(record);
\r
424 for_each(m_attributes.begin(), m_attributes.end(), cleanup_const_pair<string,Attribute>());
\r
425 m_attributes.clear();
\r
426 newobj["version"].integer(ver);
\r
432 } while (ver < 0); // negative indicates a sync issue so we retry
\r
437 TransactionLog* xlog = SPConfig::getConfig().getServiceProvider()->getTransactionLog();
\r
438 Locker locker(xlog);
\r
440 "Added assertion (ID: %s) to session for (applicationId: %s) with (ID: %s)",
\r
441 id.get(), m_obj["application_id"].string(), getID()
\r
445 SSCache::SSCache(const DOMElement* e)
\r
446 : SessionCache(e), m_log(Category::getInstance(SHIBSP_LOGCAT".SessionCache")), m_storage(NULL)
\r
448 SPConfig& conf = SPConfig::getConfig();
\r
449 const XMLCh* tag = e ? e->getAttributeNS(NULL,_StorageService) : NULL;
\r
451 auto_ptr_char ssid(tag);
\r
452 m_storage = conf.getServiceProvider()->getStorageService(ssid.get());
\r
454 m_log.info("bound to StorageService (%s)", ssid.get());
\r
456 throw ConfigurationException("SessionCache unable to locate StorageService, check configuration.");
\r
459 ListenerService* listener=conf.getServiceProvider()->getListenerService(false);
\r
460 if (listener && conf.isEnabled(SPConfig::OutOfProcess)) {
\r
461 listener->regListener("find::"REMOTED_SESSION_CACHE"::SessionCache",this);
\r
462 listener->regListener("remove::"REMOTED_SESSION_CACHE"::SessionCache",this);
\r
463 listener->regListener("touch::"REMOTED_SESSION_CACHE"::SessionCache",this);
\r
464 listener->regListener("getAssertion::"REMOTED_SESSION_CACHE"::SessionCache",this);
\r
467 m_log.info("no ListenerService available, cache remoting disabled");
\r
471 SSCache::~SSCache()
\r
473 SPConfig& conf = SPConfig::getConfig();
\r
474 ListenerService* listener=conf.getServiceProvider()->getListenerService(false);
\r
475 if (listener && conf.isEnabled(SPConfig::OutOfProcess)) {
\r
476 listener->unregListener("find::"REMOTED_SESSION_CACHE"::SessionCache",this);
\r
477 listener->unregListener("remove::"REMOTED_SESSION_CACHE"::SessionCache",this);
\r
478 listener->unregListener("touch::"REMOTED_SESSION_CACHE"::SessionCache",this);
\r
479 listener->unregListener("getAssertion::"REMOTED_SESSION_CACHE"::SessionCache",this);
\r
483 void SSCache::insert(const char* key, time_t expires, const char* name, const char* index)
\r
486 if (strlen(name) > 255) {
\r
487 dup = string(name).substr(0,255);
\r
488 name = dup.c_str();
\r
492 DDFJanitor jobj(obj);
\r
494 // Since we can't guarantee uniqueness, check for an existing record.
\r
497 int ver = m_storage->readText("Logout", name, &record, &recordexp);
\r
499 // Existing record, so we need to unmarshall it.
\r
500 istringstream in(record);
\r
509 index = "_shibnull";
\r
510 DDF sessions = obj.addmember(index);
\r
511 if (!sessions.islist())
\r
513 DDF session = DDF(NULL).string(key);
\r
514 sessions.add(session);
\r
516 // Remarshall the record.
\r
520 // Try and store it back...
\r
522 ver = m_storage->updateText("Logout", name, out.str().c_str(), max(expires, recordexp), ver);
\r
524 // Out of sync, or went missing, so retry.
\r
525 return insert(key, expires, name, index);
\r
528 else if (!m_storage->createText("Logout", name, out.str().c_str(), expires)) {
\r
529 // Hit a dup, so just retry, hopefully hitting the other branch.
\r
530 return insert(key, expires, name, index);
\r
534 string SSCache::insert(
\r
536 const Application& application,
\r
537 const char* client_addr,
\r
538 const saml2md::EntityDescriptor* issuer,
\r
539 const saml2::NameID* nameid,
\r
540 const char* authn_instant,
\r
541 const char* session_index,
\r
542 const char* authncontext_class,
\r
543 const char* authncontext_decl,
\r
544 const vector<const Assertion*>* tokens,
\r
545 const multimap<string,Attribute*>* attributes
\r
549 xmltooling::NDC ndc("insert");
\r
552 m_log.debug("creating new session");
\r
554 auto_ptr_char key(SAMLConfig::getConfig().generateIdentifier());
\r
556 // Store session properties in DDF.
\r
557 DDF obj = DDF(key.get()).structure();
\r
558 obj.addmember("version").integer(1);
\r
559 obj.addmember("application_id").string(application.getId());
\r
561 // On 64-bit Windows, time_t doesn't fit in a long, so I'm using ISO timestamps.
\r
562 #ifndef HAVE_GMTIME_R
\r
563 struct tm* ptime=gmtime(&expires);
\r
566 struct tm* ptime=gmtime_r(&expires,&res);
\r
569 strftime(timebuf,32,"%Y-%m-%dT%H:%M:%SZ",ptime);
\r
570 obj.addmember("expires").string(timebuf);
\r
573 obj.addmember("client_addr").string(client_addr);
\r
575 auto_ptr_char entity_id(issuer->getEntityID());
\r
576 obj.addmember("entity_id").string(entity_id.get());
\r
579 obj.addmember("authn_instant").string(authn_instant);
\r
581 obj.addmember("session_index").string(session_index);
\r
582 if (authncontext_class)
\r
583 obj.addmember("authncontext_class").string(authncontext_class);
\r
584 if (authncontext_decl)
\r
585 obj.addmember("authncontext_decl").string(authncontext_decl);
\r
588 ostringstream namestr;
\r
589 namestr << *nameid;
\r
590 obj.addmember("nameid").string(namestr.str().c_str());
\r
594 obj.addmember("assertions").list();
\r
595 for (vector<const Assertion*>::const_iterator t = tokens->begin(); t!=tokens->end(); ++t) {
\r
596 auto_ptr_char tokenid((*t)->getID());
\r
597 DDF tokid = DDF(NULL).string(tokenid.get());
\r
598 obj["assertions"].add(tokid);
\r
604 DDF attrlist = obj.addmember("attributes").list();
\r
605 for (multimap<string,Attribute*>::const_iterator a=attributes->begin(); a!=attributes->end(); ++a) {
\r
606 attr = a->second->marshall();
\r
607 attrlist.add(attr);
\r
611 ostringstream record;
\r
614 m_log.debug("storing new session...");
\r
615 time_t now = time(NULL);
\r
616 if (!m_storage->createText(key.get(), "session", record.str().c_str(), now + m_cacheTimeout))
\r
617 throw FatalProfileException("Attempted to create a session with a duplicate key.");
\r
619 // Store the reverse mapping for logout.
\r
620 auto_ptr_char name(nameid ? nameid->getName() : NULL);
\r
623 insert(key.get(), expires, name.get(), session_index);
\r
625 catch (exception& ex) {
\r
626 m_log.error("error storing back mapping of NameID for logout: %s", ex.what());
\r
631 for (vector<const Assertion*>::const_iterator t = tokens->begin(); t!=tokens->end(); ++t) {
\r
632 ostringstream tokenstr;
\r
634 auto_ptr_char tokenid((*t)->getID());
\r
635 if (!m_storage->createText(key.get(), tokenid.get(), tokenstr.str().c_str(), now + m_cacheTimeout))
\r
636 throw IOException("duplicate assertion ID ($1)", params(1, tokenid.get()));
\r
639 catch (exception& ex) {
\r
640 m_log.error("error storing assertion along with session: %s", ex.what());
\r
644 const char* pid = obj["entity_id"].string();
\r
645 m_log.info("new session created: SessionID (%s) IdP (%s) Address (%s)", key.get(), pid ? pid : "none", client_addr);
\r
647 // Transaction Logging
\r
648 TransactionLog* xlog = application.getServiceProvider().getTransactionLog();
\r
649 Locker locker(xlog);
\r
650 xlog->log.infoStream() <<
\r
651 "New session (ID: " <<
\r
653 ") with (applicationId: " <<
\r
654 application.getId() <<
\r
655 ") for principal from (IdP: " <<
\r
656 (pid ? pid : "none") <<
\r
657 ") at (ClientAddress: " <<
\r
658 (client_addr ? client_addr : "none") <<
\r
659 ") with (NameIdentifier: " <<
\r
660 (name.get() ? name.get() : "none") <<
\r
664 xlog->log.infoStream() <<
\r
665 "Cached the following attributes with session (ID: " <<
\r
667 ") for (applicationId: " <<
\r
668 application.getId() <<
\r
670 for (multimap<string,Attribute*>::const_iterator a=attributes->begin(); a!=attributes->end(); ++a)
\r
671 xlog->log.infoStream() << "\t" << a->second->getId() << " (" << a->second->valueCount() << " values)";
\r
672 xlog->log.info("}");
\r
678 Session* SSCache::find(const char* key, const Application& application, const char* client_addr, time_t* timeout)
\r
681 xmltooling::NDC ndc("find");
\r
684 m_log.debug("searching for session (%s)", key);
\r
688 int ver = m_storage->readText(key, "session", &record, &lastAccess);
\r
692 m_log.debug("reconstituting session and checking validity");
\r
695 istringstream in(record);
\r
698 if (!XMLString::equals(obj["application_id"].string(), application.getId())) {
\r
699 m_log.error("an application (%s) tried to access another application's session", application.getId());
\r
705 if (m_log.isDebugEnabled())
\r
706 m_log.debug("comparing client address %s against %s", client_addr, obj["client_addr"].string());
\r
707 if (strcmp(obj["client_addr"].string(),client_addr)) {
\r
708 m_log.warn("client address mismatch");
\r
709 remove(key, application);
\r
710 RetryableProfileException ex(
\r
711 "Your IP address ($1) does not match the address recorded at the time the session was established.",
\r
712 params(1,client_addr)
\r
714 string eid(obj["entity_id"].string());
\r
718 MetadataProvider* m=application.getMetadataProvider();
\r
720 annotateException(&ex,m->getEntityDescriptor(eid.c_str(),false)); // throws it
\r
724 lastAccess -= m_cacheTimeout; // adjusts it back to the last time the record's timestamp was touched
\r
725 time_t now=time(NULL);
\r
727 if (timeout && *timeout > 0 && now - lastAccess >= *timeout) {
\r
728 m_log.info("session timed out (ID: %s)", key);
\r
729 remove(key, application);
\r
730 RetryableProfileException ex("Your session has expired, and you must re-authenticate.");
\r
731 string eid(obj["entity_id"].string());
\r
735 MetadataProvider* m=application.getMetadataProvider();
\r
737 annotateException(&ex,m->getEntityDescriptor(eid.c_str(),false)); // throws it
\r
740 auto_ptr_XMLCh exp(obj["expires"].string());
\r
742 DateTime iso(exp.get());
\r
743 iso.parseDateTime();
\r
744 if (now > iso.getEpoch()) {
\r
745 m_log.info("session expired (ID: %s)", key);
\r
746 remove(key, application);
\r
747 RetryableProfileException ex("Your session has expired, and you must re-authenticate.");
\r
748 string eid(obj["entity_id"].string());
\r
752 MetadataProvider* m=application.getMetadataProvider();
\r
754 annotateException(&ex,m->getEntityDescriptor(eid.c_str(),false)); // throws it
\r
759 // Update storage expiration, if possible.
\r
761 m_storage->updateContext(key, now + m_cacheTimeout);
\r
763 catch (exception& ex) {
\r
764 m_log.error("failed to update session expiration: %s", ex.what());
\r
768 // Finally build the Session object.
\r
770 return new StoredSession(this, obj);
\r
772 catch (exception&) {
\r
778 void SSCache::remove(const char* key, const Application& application)
\r
781 xmltooling::NDC ndc("remove");
\r
784 m_storage->deleteContext(key);
\r
785 m_log.info("removed session (%s)", key);
\r
787 TransactionLog* xlog = application.getServiceProvider().getTransactionLog();
\r
788 Locker locker(xlog);
\r
789 xlog->log.info("Destroyed session (applicationId: %s) (ID: %s)", application.getId(), key);
\r
792 void SSCache::byname(
\r
793 const saml2md::EntityDescriptor& issuer,
\r
794 const saml2::NameID& nameid,
\r
796 const Application& application,
\r
797 vector<string>& sessionsKilled,
\r
802 xmltooling::NDC ndc("remove");
\r
805 auto_ptr_char entityID(issuer.getEntityID());
\r
806 auto_ptr_char name(nameid.getName());
\r
809 "request to %s sessions from (%s) for (%s) for session index (%s)",
\r
810 logout ? "logout" : "locate", entityID.get(), name.get(), index ? index : "all"
\r
813 if (strlen(name.get()) > 255)
\r
814 const_cast<char*>(name.get())[255] = 0;
\r
816 // Read in potentially matching sessions.
\r
818 int ver = m_storage->readText("Logout", name.get(), &record);
\r
820 m_log.debug("no active sessions to remove for supplied issuer and name identifier");
\r
825 DDFJanitor jobj(obj);
\r
826 istringstream in(record);
\r
829 // The record contains child lists for each known session index.
\r
831 DDF sessions = obj.first();
\r
832 while (sessions.islist()) {
\r
833 if (!index || !strcmp(sessions.name(), index)) {
\r
834 key = sessions.first();
\r
835 while (key.isstring()) {
\r
836 // Fetch the session for comparison and possible removal.
\r
837 Session* session = find(key.string(), application);
\r
838 Locker locker(session);
\r
841 if (session->getEntityID() && !strcmp(session->getEntityID(), entityID.get())) {
\r
843 if (stronglyMatches(issuer.getEntityID(), application.getXMLString("entityID").second, nameid, *session->getNameID())) {
\r
845 remove(key.string(), application); // let this throw to detect errors in case the full logout fails?
\r
848 sessionsKilled.push_back(key.string());
\r
851 m_log.debug("session (%s) contained a non-matching NameID, leaving it alone", key.string());
\r
855 m_log.debug("session (%s) established by different IdP, leaving it alone", key.string());
\r
859 // Session's gone, so...
\r
860 sessionsKilled.push_back(key.string());
\r
863 key = sessions.next();
\r
866 // No sessions left for this index?
\r
867 if (sessions.first().isnull())
\r
868 sessions.destroy();
\r
870 sessions = obj.next();
\r
873 if (obj.first().isnull())
\r
876 // If possible, write back the mapping record (this isn't crucial).
\r
878 if (obj.isnull()) {
\r
879 m_storage->deleteText("Logout", name.get());
\r
881 else if (!sessionsKilled.empty()) {
\r
884 if (m_storage->updateText("Logout", name.get(), out.str().c_str(), 0, ver) <= 0)
\r
885 m_log.warn("logout mapping record changed behind us, leaving it alone");
\r
888 catch (exception& ex) {
\r
889 m_log.error("error updating logout mapping record: %s", ex.what());
\r
893 bool SSCache::stronglyMatches(const XMLCh* idp, const XMLCh* sp, const saml2::NameID& n1, const saml2::NameID& n2) const
\r
895 if (!XMLString::equals(n1.getName(), n2.getName()))
\r
898 const XMLCh* s1 = n1.getFormat();
\r
899 const XMLCh* s2 = n2.getFormat();
\r
901 s1 = saml2::NameID::UNSPECIFIED;
\r
903 s2 = saml2::NameID::UNSPECIFIED;
\r
904 if (!XMLString::equals(s1,s2))
\r
907 s1 = n1.getNameQualifier();
\r
908 s2 = n2.getNameQualifier();
\r
913 if (!XMLString::equals(s1,s2))
\r
916 s1 = n1.getSPNameQualifier();
\r
917 s2 = n2.getSPNameQualifier();
\r
922 if (!XMLString::equals(s1,s2))
\r
928 void SSCache::receive(DDF& in, ostream& out)
\r
931 xmltooling::NDC ndc("receive");
\r
934 if (!strcmp(in.name(),"find::"REMOTED_SESSION_CACHE"::SessionCache")) {
\r
935 const char* key=in["key"].string();
\r
937 throw ListenerException("Required parameters missing for session removal.");
\r
939 const Application* app = SPConfig::getConfig().getServiceProvider()->getApplication(in["application_id"].string());
\r
941 throw ListenerException("Application not found, check configuration?");
\r
943 // Do an unversioned read.
\r
946 if (!m_storage->readText(key, "session", &record, &lastAccess)) {
\r
948 DDFJanitor jan(ret);
\r
953 // Adjust for expiration to recover last access time and check timeout.
\r
954 lastAccess -= m_cacheTimeout;
\r
955 time_t now=time(NULL);
\r
957 // See if we need to check for a timeout.
\r
958 if (in["timeout"].string()) {
\r
959 time_t timeout = 0;
\r
960 auto_ptr_XMLCh dt(in["timeout"].string());
\r
961 DateTime dtobj(dt.get());
\r
962 dtobj.parseDateTime();
\r
963 timeout = dtobj.getEpoch();
\r
965 if (timeout > 0 && now - lastAccess >= timeout) {
\r
966 m_log.info("session timed out (ID: %s)", key);
\r
968 throw RetryableProfileException("Your session has expired, and you must re-authenticate.");
\r
971 // Update storage expiration, if possible.
\r
973 m_storage->updateContext(key, now + m_cacheTimeout);
\r
975 catch (exception& ex) {
\r
976 m_log.error("failed to update session expiration: %s", ex.what());
\r
980 // Send the record back.
\r
983 else if (!strcmp(in.name(),"touch::"REMOTED_SESSION_CACHE"::SessionCache")) {
\r
984 const char* key=in["key"].string();
\r
986 throw ListenerException("Required parameters missing for session check.");
\r
988 // Do a versioned read.
\r
991 int curver = in["version"].integer();
\r
992 int ver = m_storage->readText(key, "session", &record, &lastAccess, curver);
\r
994 m_log.warn("unsuccessful versioned read of session (ID: %s), caches out of sync?", key);
\r
995 throw RetryableProfileException("Your session has expired, and you must re-authenticate.");
\r
998 // Adjust for expiration to recover last access time and check timeout.
\r
999 lastAccess -= m_cacheTimeout;
\r
1000 time_t now=time(NULL);
\r
1002 // See if we need to check for a timeout.
\r
1003 time_t timeout = 0;
\r
1004 auto_ptr_XMLCh dt(in["timeout"].string());
\r
1006 DateTime dtobj(dt.get());
\r
1007 dtobj.parseDateTime();
\r
1008 timeout = dtobj.getEpoch();
\r
1011 if (timeout > 0 && now - lastAccess >= timeout) {
\r
1012 m_log.info("session timed out (ID: %s)", key);
\r
1013 throw RetryableProfileException("Your session has expired, and you must re-authenticate.");
\r
1016 // Update storage expiration, if possible.
\r
1018 m_storage->updateContext(key, now + m_cacheTimeout);
\r
1020 catch (exception& ex) {
\r
1021 m_log.error("failed to update session expiration: %s", ex.what());
\r
1024 if (ver > curver) {
\r
1025 // Send the record back.
\r
1030 DDFJanitor jan(ret);
\r
1034 else if (!strcmp(in.name(),"remove::"REMOTED_SESSION_CACHE"::SessionCache")) {
\r
1035 const char* key=in["key"].string();
\r
1037 throw ListenerException("Required parameter missing for session removal.");
\r
1039 const Application* app = SPConfig::getConfig().getServiceProvider()->getApplication(in["application_id"].string());
\r
1041 throw ListenerException("Application not found, check configuration?");
\r
1045 DDFJanitor jan(ret);
\r
1048 else if (!strcmp(in.name(),"getAssertion::"REMOTED_SESSION_CACHE"::SessionCache")) {
\r
1049 const char* key=in["key"].string();
\r
1050 const char* id=in["id"].string();
\r
1052 throw ListenerException("Required parameters missing for assertion retrieval.");
\r
1054 if (!m_storage->readText(key, id, &token, NULL))
\r
1055 throw FatalProfileException("Assertion not found in cache.");
\r