2 * Copyright 2001-2005 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
17 /** StorageServiceSessionCache.cpp
\r
19 * StorageService-based SessionCache implementation.
\r
21 * Instead of optimizing this plugin with a buffering scheme that keeps objects around
\r
22 * and avoids extra parsing steps, I'm assuming that systems that require such can
\r
23 * layer their own cache plugin on top of this version either by delegating to it
\r
24 * or using the remoting support. So this version will load sessions directly
\r
25 * from the StorageService, instantiate enough to expose the Session API,
\r
26 * and then delete everything when they're unlocked. All data in memory is always
\r
27 * kept in sync with the StorageService (no lazy updates).
\r
30 #include "internal.h"
\r
31 #include "Application.h"
\r
32 #include "exceptions.h"
\r
33 #include "ServiceProvider.h"
\r
34 #include "SessionCache.h"
\r
35 #include "TransactionLog.h"
\r
36 #include "attribute/Attribute.h"
\r
37 #include "remoting/ListenerService.h"
\r
38 #include "util/SPConstants.h"
\r
40 #include <log4cpp/Category.hh>
\r
41 #include <saml/SAMLConfig.h>
\r
42 #include <xmltooling/util/NDC.h>
\r
43 #include <xmltooling/util/StorageService.h>
\r
44 #include <xmltooling/util/XMLHelper.h>
\r
45 #include <xercesc/util/XMLUniDefs.hpp>
\r
47 using namespace shibsp;
\r
48 using namespace opensaml::saml2md;
\r
49 using namespace opensaml;
\r
50 using namespace xmltooling;
\r
51 using namespace log4cpp;
\r
52 using namespace std;
\r
57 class StoredSession : public virtual Session
\r
60 StoredSession(SSCache* cache, const Application& app, DDF& obj, int version)
\r
61 : m_appId(app.getId()), m_version(version), m_obj(obj), m_cache(cache) {
\r
62 const char* nameid = obj["nameid"].string();
\r
64 throw FatalProfileException("NameID missing from cached session.");
\r
66 // Parse and bind the document into an XMLObject.
\r
67 istringstream instr(nameid);
\r
68 DOMDocument* doc = XMLToolingConfig::getConfig().getParser().parse(instr);
\r
69 XercesJanitor<DOMDocument> janitor(doc);
\r
70 auto_ptr<saml2::NameID> n(saml2::NameIDBuilder::buildNameID());
\r
71 n->unmarshall(doc->getDocumentElement(), true);
\r
74 // TODO: Process attributes...
\r
76 m_nameid = n.release();
\r
88 const char* getClientAddress() const {
\r
89 return m_obj["client_address"].string();
\r
91 const char* getEntityID() const {
\r
92 return m_obj["entity_id"].string();
\r
94 const char* getAuthnInstant() const {
\r
95 return m_obj["authn_instant"].string();
\r
97 const opensaml::saml2::NameID& getNameID() const {
\r
100 const char* getSessionIndex() const {
\r
101 return m_obj["session_index"].string();
\r
103 const char* getAuthnContextClassRef() const {
\r
104 return m_obj["authncontext_class"].string();
\r
106 const char* getAuthnContextDeclRef() const {
\r
107 return m_obj["authncontext_decl"].string();
\r
109 const vector<const Attribute*>& getAttributes() const {
\r
110 return m_attributes;
\r
112 const vector<const char*>& getAssertionIDs() const {
\r
113 if (m_ids.empty()) {
\r
114 DDF id = m_obj["assertions"].first();
\r
115 while (id.isstring()) {
\r
116 m_ids.push_back(id.name());
\r
123 void addAttributes(const vector<Attribute*>& attributes);
\r
124 const RootObject* getAssertion(const char* id) const;
\r
125 void addAssertion(RootObject* assertion);
\r
131 saml2::NameID* m_nameid;
\r
132 vector<const Attribute*> m_attributes;
\r
133 mutable vector<const char*> m_ids;
\r
134 mutable map<string,RootObject*> m_tokens;
\r
138 class SSCache : public SessionCache, public virtual Remoted
\r
141 SSCache(const DOMElement* e);
\r
144 void receive(const DDF& in, ostream& out);
\r
148 const Application& application,
\r
149 const char* client_addr,
\r
150 const saml2md::EntityDescriptor* issuer,
\r
151 const saml2::NameID& nameid,
\r
152 const char* authn_instant=NULL,
\r
153 const char* session_index=NULL,
\r
154 const char* authncontext_class=NULL,
\r
155 const char* authncontext_decl=NULL,
\r
156 const RootObject* ssoToken=NULL,
\r
157 const vector<Attribute*>* attributes=NULL
\r
159 Session* find(const char* key, const Application& application, const char* client_addr=NULL, time_t timeout=0);
\r
160 void remove(const char* key, const Application& application, const char* client_addr);
\r
163 StorageService* m_storage;
\r
166 SessionCache* SHIBSP_DLLLOCAL StorageServiceCacheFactory(const DOMElement* const & e)
\r
168 return new SSCache(e);
\r
171 static const XMLCh _StorageService[] = UNICODE_LITERAL_14(S,t,o,r,a,g,e,S,e,r,v,i,c,e);
\r
174 StoredSession::~StoredSession()
\r
178 for_each(m_attributes.begin(), m_attributes.end(), xmltooling::cleanup<Attribute>());
\r
179 for_each(m_tokens.begin(), m_tokens.end(), xmltooling::cleanup_pair<string,RootObject>());
\r
182 void StoredSession::addAttributes(const vector<Attribute*>& attributes)
\r
185 xmltooling::NDC ndc("addAttributes");
\r
188 m_cache->m_log.debug("adding attributes to session (%s)", m_obj.name());
\r
193 DDF attrs = m_obj["attributes"];
\r
194 if (!attrs.islist())
\r
195 attrs = m_obj.addmember("attributes").list();
\r
196 for (vector<Attribute*>::const_iterator a=attributes.begin(); a!=attributes.end(); ++a) {
\r
197 attr = (*a)->marshall();
\r
203 string record(str.str());
\r
205 ver = m_cache->m_storage->updateText(m_appId.c_str(), m_obj.name(), record.c_str(), 0, m_version);
\r
207 // Roll back modification to record.
\r
208 vector<Attribute*>::size_type count = attributes.size();
\r
210 attrs.last().destroy();
\r
213 // Fatal problem with update.
\r
214 m_cache->m_log.error("updateText failed on StorageService for session (%s)", m_obj.name());
\r
215 throw IOException("Unable to update stored session.");
\r
217 else if (ver < 0) {
\r
219 m_cache->m_log.warn("storage service indicates the record is out of sync, updating with a fresh copy...");
\r
220 ver = m_cache->m_storage->readText(m_appId.c_str(), m_obj.name(), &record, NULL);
\r
222 m_cache->m_log.error("updateText failed on StorageService for session (%s)", m_obj.name());
\r
223 throw IOException("Unable to update stored session.");
\r
228 istringstream in(record);
\r
233 for_each(m_attributes.begin(), m_attributes.end(), xmltooling::cleanup<Attribute>());
\r
234 m_attributes.clear();
\r
237 // TODO: handle attributes
\r
242 // Update with new version.
\r
245 } while (ver < 0); // negative indicates a sync issue so we retry
\r
247 // Transfer ownership to us.
\r
248 m_attributes.insert(m_attributes.end(), attributes.begin(), attributes.end());
\r
250 TransactionLog* xlog = SPConfig::getConfig().getServiceProvider()->getTransactionLog();
\r
251 Locker locker(xlog);
\r
252 xlog->log.infoStream() <<
\r
253 "Added the following attributes to session (ID: " <<
\r
255 ") for (applicationId: " <<
\r
258 for (vector<Attribute*>::const_iterator a=attributes.begin(); a!=attributes.end(); ++a)
\r
259 xlog->log.infoStream() << "\t" << (*a)->getId() << " (" << (*a)->valueCount() << " values)";
\r
260 xlog->log.info("}");
\r
263 const RootObject* StoredSession::getAssertion(const char* id) const
\r
265 map<string,RootObject*>::const_iterator i = m_tokens.find(id);
\r
266 if (i!=m_tokens.end())
\r
269 // Parse and bind the document into an XMLObject.
\r
270 const char* tokenstr = m_obj["assertions"][id].string();
\r
272 throw FatalProfileException("Assertion not found in cache.");
\r
273 istringstream instr(tokenstr);
\r
274 DOMDocument* doc = XMLToolingConfig::getConfig().getParser().parse(instr);
\r
275 XercesJanitor<DOMDocument> janitor(doc);
\r
276 auto_ptr<XMLObject> xmlObject(XMLObjectBuilder::buildOneFromElement(doc->getDocumentElement(), true));
\r
279 RootObject* token = dynamic_cast<RootObject*>(xmlObject.get());
\r
280 if (!token || !token->isAssertion())
\r
281 throw FatalProfileException("Request for cached assertion returned an unknown object type.");
\r
283 // Transfer ownership to us.
\r
284 xmlObject.release();
\r
285 m_tokens[id]=token;
\r
289 void StoredSession::addAssertion(RootObject* assertion)
\r
292 xmltooling::NDC ndc("addAssertion");
\r
295 if (!assertion || !assertion->isAssertion())
\r
296 throw FatalProfileException("Unknown object type passed to session for storage.");
\r
298 auto_ptr_char id(assertion->getID());
\r
300 m_cache->m_log.debug("adding assertion (%s) to session (%s)", id.get(), m_obj.name());
\r
307 DDF token = m_obj["assertions"];
\r
308 if (!token.isstruct())
\r
309 token = m_obj.addmember("assertions").structure();
\r
310 token = token.addmember(id.get()).string(os.str().c_str());
\r
314 string record(str.str());
\r
316 ver = m_cache->m_storage->updateText(m_appId.c_str(), m_obj.name(), record.c_str(), 0, m_version);
\r
320 // Fatal problem with update.
\r
321 m_cache->m_log.error("updateText failed on StorageService for session (%s)", m_obj.name());
\r
322 throw IOException("Unable to update stored session.");
\r
324 else if (ver < 0) {
\r
326 m_cache->m_log.warn("storage service indicates the record is out of sync, updating with a fresh copy...");
\r
327 ver = m_cache->m_storage->readText(m_appId.c_str(), m_obj.name(), &record, NULL);
\r
329 m_cache->m_log.error("updateText failed on StorageService for session (%s)", m_obj.name());
\r
330 throw IOException("Unable to update stored session.");
\r
335 istringstream in(record);
\r
340 for_each(m_attributes.begin(), m_attributes.end(), xmltooling::cleanup<Attribute>());
\r
341 m_attributes.clear();
\r
344 // TODO: handle attributes
\r
349 // Update with new version.
\r
352 } while (ver < 0); // negative indicates a sync issue so we retry
\r
356 TransactionLog* xlog = SPConfig::getConfig().getServiceProvider()->getTransactionLog();
\r
357 Locker locker(xlog);
\r
359 "Added assertion (ID: %s) to session for (applicationId: %s) with (ID: %s)",
\r
360 id.get(), m_appId.c_str(), m_obj.name()
\r
364 SSCache::SSCache(const DOMElement* e)
\r
365 : SessionCache(e), m_log(Category::getInstance(SHIBSP_LOGCAT".SessionCache")), m_storage(NULL)
\r
367 SPConfig& conf = SPConfig::getConfig();
\r
368 const XMLCh* tag = e ? e->getAttributeNS(NULL,_StorageService) : NULL;
\r
370 auto_ptr_char ssid(tag);
\r
371 m_storage = conf.getServiceProvider()->getStorageService(ssid.get());
\r
373 m_log.info("bound to StorageService (%s)", ssid.get());
\r
375 throw ConfigurationException("SessionCache unable to locate StorageService, check configuration.");
\r
378 ListenerService* listener=conf.getServiceProvider()->getListenerService(false);
\r
379 if (listener && conf.isEnabled(SPConfig::OutOfProcess)) {
\r
380 listener->regListener("insert::"REMOTED_SESSION_CACHE,this);
\r
381 listener->regListener("find::"REMOTED_SESSION_CACHE,this);
\r
382 listener->regListener("remove::"REMOTED_SESSION_CACHE,this);
\r
385 m_log.info("no ListenerService available, cache remoting is disabled");
\r
389 string SSCache::insert(
\r
391 const Application& application,
\r
392 const char* client_addr,
\r
393 const saml2md::EntityDescriptor* issuer,
\r
394 const saml2::NameID& nameid,
\r
395 const char* authn_instant,
\r
396 const char* session_index,
\r
397 const char* authncontext_class,
\r
398 const char* authncontext_decl,
\r
399 const RootObject* ssoToken,
\r
400 const vector<Attribute*>* attributes
\r
404 xmltooling::NDC ndc("insert");
\r
407 m_log.debug("creating new session");
\r
409 auto_ptr_char key(SAMLConfig::getConfig().generateIdentifier());
\r
411 // Store session properties in DDF.
\r
412 DDF obj = DDF(key.get()).structure();
\r
414 // On 64-bit Windows, time_t doesn't fit in a long, so I'm using ISO timestamps.
\r
415 #ifndef HAVE_GMTIME_R
\r
416 struct tm* ptime=gmtime(&expires);
\r
419 struct tm* ptime=gmtime_r(&expires,&res);
\r
422 strftime(timebuf,32,"%Y-%m-%dT%H:%M:%SZ",ptime);
\r
423 obj.addmember("expires").string(timebuf);
\r
425 obj.addmember("client_address").string(client_addr);
\r
427 auto_ptr_char entity_id(issuer->getEntityID());
\r
428 obj.addmember("entity_id").string(entity_id.get());
\r
431 obj.addmember("authn_instant").string(authn_instant);
\r
433 obj.addmember("session_index").string(session_index);
\r
434 if (authncontext_class)
\r
435 obj.addmember("authncontext_class").string(authncontext_class);
\r
436 if (authncontext_decl)
\r
437 obj.addmember("authncontext_decl").string(authncontext_decl);
\r
439 ostringstream namestr;
\r
441 obj.addmember("nameid").string(namestr.str().c_str());
\r
444 ostringstream tokenstr;
\r
445 tokenstr << *ssoToken;
\r
446 auto_ptr_char tokenid(ssoToken->getID());
\r
447 obj.addmember("assertions").structure().addmember(tokenid.get()).string(tokenstr.str().c_str());
\r
452 DDF attrlist = obj.addmember("attributes").list();
\r
453 for (vector<Attribute*>::const_iterator a=attributes->begin(); a!=attributes->end(); ++a) {
\r
454 attr = (*a)->marshall();
\r
455 attrlist.add(attr);
\r
459 ostringstream record;
\r
462 m_log.debug("storing new session...");
\r
463 m_storage->createText(application.getId(), key.get(), record.str().c_str(), time(NULL) + m_cacheTimeout);
\r
464 const char* pid = obj["entity_id"].string();
\r
465 m_log.debug("new session created: SessionID (%s) IdP (%s) Address (%s)", key.get(), pid ? pid : "none", client_addr);
\r
467 // Transaction Logging
\r
468 auto_ptr_char name(nameid.getName());
\r
469 TransactionLog* xlog = SPConfig::getConfig().getServiceProvider()->getTransactionLog();
\r
470 Locker locker(xlog);
\r
471 xlog->log.infoStream() <<
\r
472 "New session (ID: " <<
\r
474 ") with (applicationId: " <<
\r
475 application.getId() <<
\r
476 ") for principal from (IdP: " <<
\r
477 (pid ? pid : "none") <<
\r
478 ") at (ClientAddress: " <<
\r
480 ") with (NameIdentifier: " <<
\r
487 Session* SSCache::find(const char* key, const Application& application, const char* client_addr, time_t timeout)
\r
490 xmltooling::NDC ndc("find");
\r
493 m_log.debug("searching for session (%s)", key);
\r
497 int ver = m_storage->readText(application.getId(), key, &record, &lastAccess);
\r
501 m_log.debug("reconstituting session and checking for validity");
\r
504 istringstream in(record);
\r
507 lastAccess -= m_cacheTimeout; // adjusts it back to the last time the record's timestamp was touched
\r
510 if (m_log.isDebugEnabled())
\r
511 m_log.debug("comparing client address %s against %s", client_addr, obj["client_address"].string());
\r
512 if (strcmp(obj["client_address"].string(),client_addr)) {
\r
513 m_log.info("client address mismatch");
\r
514 RetryableProfileException ex(
\r
515 "Your IP address ($1) does not match the address recorded at the time the session was established.",
\r
516 params(1,client_addr)
\r
518 string eid(obj["entity_id"].string());
\r
520 MetadataProvider* m=application.getMetadataProvider();
\r
522 annotateException(&ex,m->getEntityDescriptor(eid.c_str(),false)); // throws it
\r
526 time_t now=time(NULL);
\r
528 if (timeout > 0 && now - lastAccess >= timeout) {
\r
529 m_log.info("session timed out (ID: %s)", key);
\r
530 RetryableProfileException ex("Your session has expired, and you must re-authenticate.");
\r
531 string eid(obj["entity_id"].string());
\r
533 MetadataProvider* m=application.getMetadataProvider();
\r
535 annotateException(&ex,m->getEntityDescriptor(eid.c_str(),false)); // throws it
\r
538 auto_ptr_XMLCh exp(obj["expires"].string());
\r
540 DateTime iso(exp.get());
\r
541 iso.parseDateTime();
\r
542 if (now > iso.getEpoch()) {
\r
543 m_log.info("session expired (ID: %s)", key);
\r
544 RetryableProfileException ex("Your session has expired, and you must re-authenticate.");
\r
545 string eid(obj["entity_id"].string());
\r
547 MetadataProvider* m=application.getMetadataProvider();
\r
549 annotateException(&ex,m->getEntityDescriptor(eid.c_str(),false)); // throws it
\r
553 // Update storage expiration, if possible.
\r
554 ver = m_storage->updateText(application.getId(), key, NULL, now + m_cacheTimeout);
\r
556 m_log.error("failed to update record expiration");
\r
558 // Finally build the Session object.
\r
560 return new StoredSession(this, application, obj, ver);
\r
562 catch (exception&) {
\r
568 void SSCache::remove(const char* key, const Application& application, const char* client_addr)
\r
571 xmltooling::NDC ndc("remove");
\r
574 m_log.debug("removing session (%s)", key);
\r
576 m_storage->deleteText(application.getId(), key);
\r
578 TransactionLog* xlog = SPConfig::getConfig().getServiceProvider()->getTransactionLog();
\r
579 Locker locker(xlog);
\r
580 xlog->log.info("Destroyed session (applicationId: %s) (ID: %s)", application.getId(), key);
\r
583 void SSCache::receive(const DDF& in, ostream& out)
\r