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 * RemotedSessionCache.cpp
\r
20 * SessionCache implementation that delegates to a remoted version.
\r
23 #include "internal.h"
\r
24 #include "Application.h"
\r
25 #include "exceptions.h"
\r
26 #include "ServiceProvider.h"
\r
27 #include "SessionCache.h"
\r
28 #include "TransactionLog.h"
\r
29 #include "attribute/Attribute.h"
\r
30 #include "remoting/ListenerService.h"
\r
31 #include "util/SPConstants.h"
\r
34 #include <log4cpp/Category.hh>
\r
35 #include <xmltooling/XMLToolingConfig.h>
\r
36 #include <xmltooling/util/NDC.h>
\r
37 #include <xmltooling/util/XMLHelper.h>
\r
39 using namespace shibsp;
\r
40 using namespace opensaml::saml2md;
\r
41 using namespace opensaml;
\r
42 using namespace xmltooling;
\r
43 using namespace log4cpp;
\r
44 using namespace std;
\r
49 class RemotedSession : public virtual Session
\r
52 RemotedSession(RemotedCache* cache, DDF& obj) : m_version(obj["version"].integer()), m_obj(obj),
\r
53 m_nameid(NULL), m_expires(0), m_lastAccess(time(NULL)), m_cache(cache), m_lock(NULL) {
\r
54 const char* nameid = obj["nameid"].string();
\r
56 // Parse and bind the NameID into an XMLObject.
\r
57 istringstream instr(nameid);
\r
58 DOMDocument* doc = XMLToolingConfig::getConfig().getParser().parse(instr);
\r
59 XercesJanitor<DOMDocument> janitor(doc);
\r
60 auto_ptr<saml2::NameID> n(saml2::NameIDBuilder::buildNameID());
\r
61 n->unmarshall(doc->getDocumentElement(), true);
\r
63 m_nameid = n.release();
\r
66 auto_ptr_XMLCh exp(m_obj["expires"].string());
\r
68 DateTime iso(exp.get());
\r
69 iso.parseDateTime();
\r
70 m_expires = iso.getEpoch();
\r
73 m_lock = Mutex::create();
\r
80 for_each(m_attributes.begin(), m_attributes.end(), cleanup_const_pair<string,Attribute>());
\r
81 for_each(m_tokens.begin(), m_tokens.end(), cleanup_pair<string,Assertion>());
\r
92 const char* getApplicationID() const {
\r
93 return m_obj["application_id"].string();
\r
95 const char* getClientAddress() const {
\r
96 return m_obj["client_addr"].string();
\r
98 const char* getEntityID() const {
\r
99 return m_obj["entity_id"].string();
\r
101 const char* getAuthnInstant() const {
\r
102 return m_obj["authn_instant"].string();
\r
104 const opensaml::saml2::NameID* getNameID() const {
\r
107 const char* getSessionIndex() const {
\r
108 return m_obj["session_index"].string();
\r
110 const char* getAuthnContextClassRef() const {
\r
111 return m_obj["authncontext_class"].string();
\r
113 const char* getAuthnContextDeclRef() const {
\r
114 return m_obj["authncontext_decl"].string();
\r
116 const map<string,const Attribute*>& getAttributes() const {
\r
117 if (m_attributes.empty())
\r
118 unmarshallAttributes();
\r
119 return m_attributes;
\r
121 const vector<const char*>& getAssertionIDs() const {
\r
122 if (m_ids.empty()) {
\r
123 DDF ids = m_obj["assertions"];
\r
124 DDF id = ids.first();
\r
125 while (id.isstring()) {
\r
126 m_ids.push_back(id.string());
\r
133 const Assertion* getAssertion(const char* id) const;
\r
135 void addAttributes(const vector<Attribute*>& attributes) {
\r
136 throw ConfigurationException("addAttributes method not implemented by this session cache plugin.");
\r
138 void addAssertion(Assertion* assertion) {
\r
139 throw ConfigurationException("addAssertion method not implemented by this session cache plugin.");
\r
142 time_t expires() const { return m_expires; }
\r
143 time_t lastAccess() const { return m_lastAccess; }
\r
144 void validate(const Application& application, const char* client_addr, time_t timeout, bool local=true);
\r
147 void unmarshallAttributes() const;
\r
151 saml2::NameID* m_nameid;
\r
152 mutable map<string,const Attribute*> m_attributes;
\r
153 mutable vector<const char*> m_ids;
\r
154 mutable map<string,Assertion*> m_tokens;
\r
155 time_t m_expires,m_lastAccess;
\r
156 RemotedCache* m_cache;
\r
160 class RemotedCache : public SessionCache
\r
163 RemotedCache(const DOMElement* e);
\r
168 const Application& application,
\r
169 const char* client_addr=NULL,
\r
170 const saml2md::EntityDescriptor* issuer=NULL,
\r
171 const saml2::NameID* nameid=NULL,
\r
172 const char* authn_instant=NULL,
\r
173 const char* session_index=NULL,
\r
174 const char* authncontext_class=NULL,
\r
175 const char* authncontext_decl=NULL,
\r
176 const vector<const Assertion*>* tokens=NULL,
\r
177 const vector<Attribute*>* attributes=NULL
\r
179 Session* find(const char* key, const Application& application, const char* client_addr=NULL, time_t timeout=0);
\r
180 void remove(const char* key, const Application& application, const char* client_addr);
\r
186 const DOMElement* m_root; // Only valid during initialization
\r
188 map<string,RemotedSession*> m_hashtable;
\r
190 void dormant(const char* key);
\r
191 static void* cleanup_fn(void*);
\r
193 CondWait* shutdown_wait;
\r
194 Thread* cleanup_thread;
\r
197 SessionCache* SHIBSP_DLLLOCAL RemotedCacheFactory(const DOMElement* const & e)
\r
199 return new RemotedCache(e);
\r
203 void RemotedSession::unmarshallAttributes() const
\r
205 Attribute* attribute;
\r
206 DDF attrs = m_obj["attributes"];
\r
207 DDF attr = attrs.first();
\r
208 while (!attr.isnull()) {
\r
210 attribute = Attribute::unmarshall(attr);
\r
211 m_attributes[attribute->getId()] = attribute;
\r
212 if (m_cache->m_log.isDebugEnabled())
\r
213 m_cache->m_log.debug("unmarshalled attribute (ID: %s) with %d value%s",
\r
214 attribute->getId(), attr.first().integer(), attr.first().integer()!=1 ? "s" : "");
\r
216 catch (AttributeException& ex) {
\r
217 const char* id = attr.first().name();
\r
218 m_cache->m_log.error("error unmarshalling attribute (ID: %s): %s", id ? id : "none", ex.what());
\r
220 attr = attrs.next();
\r
224 const Assertion* RemotedSession::getAssertion(const char* id) const
\r
226 map<string,Assertion*>::const_iterator i = m_tokens.find(id);
\r
227 if (i!=m_tokens.end())
\r
230 // Fetch from remoted cache.
\r
231 DDF in("getAssertion::"REMOTED_SESSION_CACHE"::SessionCache");
\r
232 DDFJanitor jin(in);
\r
234 in.addmember("key").string(m_obj.name());
\r
235 in.addmember("id").string(id);
\r
237 DDF out=SPConfig::getConfig().getServiceProvider()->getListenerService()->send(in);
\r
238 DDFJanitor jout(out);
\r
240 // Parse and bind the document into an XMLObject.
\r
241 istringstream instr(out.string());
\r
242 DOMDocument* doc = XMLToolingConfig::getConfig().getParser().parse(instr);
\r
243 XercesJanitor<DOMDocument> janitor(doc);
\r
244 auto_ptr<XMLObject> xmlObject(XMLObjectBuilder::buildOneFromElement(doc->getDocumentElement(), true));
\r
247 Assertion* token = dynamic_cast<Assertion*>(xmlObject.get());
\r
249 throw FatalProfileException("Cached assertion was of an unknown object type.");
\r
251 // Transfer ownership to us.
\r
252 xmlObject.release();
\r
253 m_tokens[id]=token;
\r
257 void RemotedSession::validate(const Application& application, const char* client_addr, time_t timeout, bool local)
\r
259 // Basic expiration?
\r
260 time_t now = time(NULL);
\r
261 if (now > m_expires) {
\r
262 m_cache->m_log.info("session expired (ID: %s)", m_obj.name());
\r
263 throw RetryableProfileException("Your session has expired, and you must re-authenticate.");
\r
268 if (m_cache->m_log.isDebugEnabled())
\r
269 m_cache->m_log.debug("comparing client address %s against %s", client_addr, getClientAddress());
\r
270 if (strcmp(getClientAddress(),client_addr)) {
\r
271 m_cache->m_log.warn("client address mismatch");
\r
272 throw RetryableProfileException(
\r
273 "Your IP address ($1) does not match the address recorded at the time the session was established.",
\r
274 params(1,client_addr)
\r
282 DDF in("touch::"REMOTED_SESSION_CACHE"::SessionCache"), out;
\r
283 DDFJanitor jin(in);
\r
285 in.addmember("key").string(m_obj.name());
\r
286 in.addmember("version").integer(m_obj["version"].integer());
\r
288 // On 64-bit Windows, time_t doesn't fit in a long, so I'm using ISO timestamps.
\r
289 #ifndef HAVE_GMTIME_R
\r
290 struct tm* ptime=gmtime(&timeout);
\r
293 struct tm* ptime=gmtime_r(&timeout,&res);
\r
296 strftime(timebuf,32,"%Y-%m-%dT%H:%M:%SZ",ptime);
\r
297 in.addmember("timeout").string(timebuf);
\r
301 out=application.getServiceProvider().getListenerService()->send(in);
\r
308 if (out.isstruct()) {
\r
309 // We got an updated record back.
\r
311 for_each(m_attributes.begin(), m_attributes.end(), cleanup_const_pair<string,Attribute>());
\r
312 m_attributes.clear();
\r
317 m_lastAccess = now;
\r
320 RemotedCache::RemotedCache(const DOMElement* e)
\r
321 : SessionCache(e), m_log(Category::getInstance(SHIBSP_LOGCAT".SessionCache")), m_root(e), m_lock(NULL), shutdown(false)
\r
323 if (!SPConfig::getConfig().getServiceProvider()->getListenerService())
\r
324 throw ConfigurationException("RemotedCacheService requires a ListenerService, but none available.");
\r
326 m_lock = RWLock::create();
\r
327 shutdown_wait = CondWait::create();
\r
328 cleanup_thread = Thread::create(&cleanup_fn, (void*)this);
\r
331 RemotedCache::~RemotedCache()
\r
333 // Shut down the cleanup thread and let it know...
\r
335 shutdown_wait->signal();
\r
336 cleanup_thread->join(NULL);
\r
338 for_each(m_hashtable.begin(),m_hashtable.end(),xmltooling::cleanup_pair<string,RemotedSession>());
\r
340 delete shutdown_wait;
\r
343 string RemotedCache::insert(
\r
345 const Application& application,
\r
346 const char* client_addr,
\r
347 const saml2md::EntityDescriptor* issuer,
\r
348 const saml2::NameID* nameid,
\r
349 const char* authn_instant,
\r
350 const char* session_index,
\r
351 const char* authncontext_class,
\r
352 const char* authncontext_decl,
\r
353 const vector<const Assertion*>* tokens,
\r
354 const vector<Attribute*>* attributes
\r
357 DDF in("insert::"REMOTED_SESSION_CACHE"::SessionCache");
\r
358 DDFJanitor jin(in);
\r
361 #ifndef HAVE_GMTIME_R
\r
362 struct tm* ptime=gmtime(&expires);
\r
365 struct tm* ptime=gmtime_r(&expires,&res);
\r
368 strftime(timebuf,32,"%Y-%m-%dT%H:%M:%SZ",ptime);
\r
369 in.addmember("expires").string(timebuf);
\r
371 in.addmember("application_id").string(application.getId());
\r
373 in.addmember("client_addr").string(client_addr);
\r
375 auto_ptr_char provid(issuer->getEntityID());
\r
376 in.addmember("entity_id").string(provid.get());
\r
379 in.addmember("authn_instant").string(authn_instant);
\r
381 in.addmember("session_index").string(session_index);
\r
382 if (authncontext_class)
\r
383 in.addmember("authncontext_class").string(authncontext_class);
\r
384 if (authncontext_decl)
\r
385 in.addmember("authncontext_decl").string(authncontext_decl);
\r
388 ostringstream namestr;
\r
389 namestr << *nameid;
\r
390 in.addmember("nameid").string(namestr.str().c_str());
\r
394 in.addmember("assertions").list();
\r
395 in.addmember("tokens").list();
\r
396 for (vector<const Assertion*>::const_iterator t = tokens->begin(); t!=tokens->end(); ++t) {
\r
397 ostringstream tokenstr;
\r
399 auto_ptr_char tokenid((*t)->getID());
\r
400 DDF tokid = DDF(NULL).string(tokenid.get());
\r
401 in["assertions"].add(tokid);
\r
402 DDF tok = DDF(tokenid.get()).string(tokenstr.str().c_str());
\r
403 in["tokens"].add(tok);
\r
409 DDF attrs = in.addmember("attributes").list();
\r
410 for (vector<Attribute*>::const_iterator a=attributes->begin(); a!=attributes->end(); ++a) {
\r
411 attr = (*a)->marshall();
\r
416 DDF out=application.getServiceProvider().getListenerService()->send(in);
\r
417 DDFJanitor jout(out);
\r
418 if (out["key"].isstring()) {
\r
419 // Transaction Logging
\r
420 auto_ptr_char name(nameid ? nameid->getName() : NULL);
\r
421 const char* pid = in["entity_id"].string();
\r
422 TransactionLog* xlog = application.getServiceProvider().getTransactionLog();
\r
423 Locker locker(xlog);
\r
424 xlog->log.infoStream() <<
\r
425 "New session (ID: " <<
\r
426 out["key"].string() <<
\r
427 ") with (applicationId: " <<
\r
428 application.getId() <<
\r
429 ") for principal from (IdP: " <<
\r
430 (pid ? pid : "none") <<
\r
431 ") at (ClientAddress: " <<
\r
432 (client_addr ? client_addr : "none") <<
\r
433 ") with (NameIdentifier: " <<
\r
434 (name.get() ? name.get() : "none") <<
\r
438 xlog->log.infoStream() <<
\r
439 "Cached the following attributes with session (ID: " <<
\r
440 out["key"].string() <<
\r
441 ") for (applicationId: " <<
\r
442 application.getId() <<
\r
444 for (vector<Attribute*>::const_iterator a=attributes->begin(); a!=attributes->end(); ++a)
\r
445 xlog->log.infoStream() << "\t" << (*a)->getId() << " (" << (*a)->valueCount() << " values)";
\r
446 xlog->log.info("}");
\r
447 for_each(attributes->begin(), attributes->end(), xmltooling::cleanup<Attribute>());
\r
450 return out["key"].string();
\r
452 throw RetryableProfileException("A remoted cache insertion operation did not return a usable session key.");
\r
455 Session* RemotedCache::find(const char* key, const Application& application, const char* client_addr, time_t timeout)
\r
458 xmltooling::NDC ndc("find");
\r
461 bool localValidation = false;
\r
462 RemotedSession* session=NULL;
\r
463 m_log.debug("searching local cache for session (%s)", key);
\r
465 map<string,RemotedSession*>::const_iterator i=m_hashtable.find(key);
\r
466 if (i==m_hashtable.end()) {
\r
468 m_log.debug("session not found locally, searching remote cache");
\r
470 DDF in("find::"REMOTED_SESSION_CACHE"::SessionCache"), out;
\r
471 DDFJanitor jin(in);
\r
473 in.addmember("key").string(key);
\r
475 // On 64-bit Windows, time_t doesn't fit in a long, so I'm using ISO timestamps.
\r
476 #ifndef HAVE_GMTIME_R
\r
477 struct tm* ptime=gmtime(&timeout);
\r
480 struct tm* ptime=gmtime_r(&timeout,&res);
\r
483 strftime(timebuf,32,"%Y-%m-%dT%H:%M:%SZ",ptime);
\r
484 in.addmember("timeout").string(timebuf);
\r
488 out=application.getServiceProvider().getListenerService()->send(in);
\r
489 if (!out.isstruct()) {
\r
491 m_log.debug("session not found in remote cache");
\r
495 // Wrap the results in a local entry and save it.
\r
496 session = new RemotedSession(this, out);
\r
497 // The remote end has handled timeout issues, we handle address and expiration checks.
\r
498 localValidation = true;
\r
505 // Lock for writing and repeat the search to avoid duplication.
\r
507 SharedLock shared(m_lock, false);
\r
508 if (m_hashtable.count(key)) {
\r
510 // We're using an existing session entry, so we have to switch back to full validation.
\r
511 localValidation = false;
\r
512 session = m_hashtable[key];
\r
516 m_hashtable[key]=session;
\r
521 // Save off and lock the session.
\r
522 session = i->second;
\r
526 m_log.debug("session found locally, validating it for use");
\r
529 if (!XMLString::equals(session->getApplicationID(), application.getId())) {
\r
530 m_log.error("an application (%s) tried to access another application's session", application.getId());
\r
535 // Verify currency and update the timestamp.
\r
536 // If the local switch is false, we also update the access time.
\r
538 session->validate(application, client_addr, timeout, localValidation);
\r
542 remove(key, application, client_addr);
\r
549 void RemotedCache::remove(const char* key, const Application& application, const char* client_addr)
\r
551 // Take care of local copy.
\r
555 DDF in("remove::"REMOTED_SESSION_CACHE"::SessionCache");
\r
556 DDFJanitor jin(in);
\r
558 in.addmember("key").string(key);
\r
559 in.addmember("application_id").string(application.getId());
\r
560 in.addmember("client_addr").string(client_addr);
\r
562 DDF out = application.getServiceProvider().getListenerService()->send(in);
\r
566 void RemotedCache::dormant(const char* key)
\r
569 xmltooling::NDC ndc("dormant");
\r
572 m_log.debug("deleting local copy of session (%s)", key);
\r
574 // lock the cache for writing, which means we know nobody is sitting in find()
\r
577 // grab the entry from the table
\r
578 map<string,RemotedSession*>::const_iterator i=m_hashtable.find(key);
\r
579 if (i==m_hashtable.end()) {
\r
584 // ok, remove the entry and lock it
\r
585 RemotedSession* entry=i->second;
\r
586 m_hashtable.erase(key);
\r
589 // unlock the cache
\r
592 // we can release the cache entry lock because we know we're not in the cache anymore
\r
598 void RemotedCache::cleanup()
\r
601 xmltooling::NDC ndc("cleanup");
\r
604 Mutex* mutex = Mutex::create();
\r
606 // Load our configuration details...
\r
607 static const XMLCh cleanupInterval[] = UNICODE_LITERAL_15(c,l,e,a,n,u,p,I,n,t,e,r,v,a,l);
\r
608 const XMLCh* tag=m_root ? m_root->getAttributeNS(NULL,cleanupInterval) : NULL;
\r
609 int rerun_timer = 900;
\r
611 rerun_timer = XMLString::parseInt(tag);
\r
612 if (rerun_timer <= 0)
\r
617 m_log.info("cleanup thread started...run every %d secs; timeout after %d secs", rerun_timer, m_cacheTimeout);
\r
619 while (!shutdown) {
\r
620 shutdown_wait->timedwait(mutex,rerun_timer);
\r
624 // Ok, let's run through the cleanup process and clean out
\r
625 // really old sessions. This is a two-pass process. The
\r
626 // first pass is done holding a read-lock while we iterate over
\r
627 // the cache. The second pass doesn't need a lock because
\r
628 // the 'deletes' will lock the cache.
\r
630 // Pass 1: iterate over the map and find all entries that have not been
\r
632 vector<string> stale_keys;
\r
633 time_t stale = time(NULL) - m_cacheTimeout;
\r
636 for (map<string,RemotedSession*>::const_iterator i=m_hashtable.begin(); i!=m_hashtable.end(); ++i) {
\r
637 // If the last access was BEFORE the stale timeout...
\r
639 time_t last=i->second->lastAccess();
\r
640 i->second->unlock();
\r
642 stale_keys.push_back(i->first);
\r
646 if (!stale_keys.empty()) {
\r
647 m_log.info("purging %d old sessions", stale_keys.size());
\r
649 // Pass 2: walk through the list of stale entries and remove them from the cache
\r
650 for (vector<string>::const_iterator j = stale_keys.begin(); j != stale_keys.end(); ++j)
\r
651 dormant(j->c_str());
\r
655 m_log.info("cleanup thread exiting");
\r
659 Thread::exit(NULL);
\r
662 void* RemotedCache::cleanup_fn(void* cache_p)
\r
664 RemotedCache* cache = reinterpret_cast<RemotedCache*>(cache_p);
\r
667 // First, let's block all signals
\r
668 Thread::mask_all_signals();
\r
671 // Now run the cleanup process.
\r
676 /* These are currently unimplemented.
\r
678 void RemotedSession::addAttributes(const vector<Attribute*>& attributes)
\r
680 DDF in("addAttributes::"REMOTED_SESSION_CACHE);
\r
681 DDFJanitor jin(in);
\r
683 in.addmember("key").string(m_key.c_str());
\r
684 in.addmember("application_id").string(m_appId.c_str());
\r
687 DDF attrs = in.addmember("attributes").list();
\r
688 for (vector<Attribute*>::const_iterator a=attributes.begin(); a!=attributes.end(); ++a) {
\r
689 attr = (*a)->marshall();
\r
693 attr=SPConfig::getConfig().getServiceProvider()->getListenerService()->send(in);
\r
694 DDFJanitor jout(attr);
\r
696 // Transfer ownership to us.
\r
697 m_attributes.insert(m_attributes.end(), attributes.begin(), attributes.end());
\r
700 void RemotedSession::addAssertion(Assertion* assertion)
\r
703 throw FatalProfileException("Unknown object type passed to session cache for storage.");
\r
705 DDF in("addAssertion::"REMOTED_SESSION_CACHE);
\r
706 DDFJanitor jin(in);
\r
708 in.addmember("key").string(m_key.c_str());
\r
709 in.addmember("application_id").string(m_appId.c_str());
\r
713 string token(os.str());
\r
714 auto_ptr_char tokenid(assertion->getID());
\r
715 in.addmember("assertion_id").string(tokenid.get());
\r
716 in.addmember("assertion").string(token.c_str());
\r
718 DDF out = SPConfig::getConfig().getServiceProvider()->getListenerService()->send(in);
\r
721 // Add to local record and token map.
\r
722 // Next attempt to find and lock session will refresh from remote store anyway.
\r
723 m_obj["assertions"].addmember(tokenid.get()).string(token.c_str());
\r
725 m_tokens[tokenid.get()] = assertion;
\r