--- /dev/null
+/*
+ * Copyright 2001-2007 Internet2
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/**
+ * SAML2Logout.cpp
+ *
+ * Handles SAML 2.0 single logout protocol messages.
+ */
+
+#include "internal.h"
+#include "exceptions.h"
+#include "Application.h"
+#include "ServiceProvider.h"
+#include "handler/AbstractHandler.h"
+#include "handler/LogoutHandler.h"
+#include "util/SPConstants.h"
+
+#ifndef SHIBSP_LITE
+# include "SessionCache.h"
+# include "security/SecurityPolicy.h"
+# include "util/TemplateParameters.h"
+# include <fstream>
+# include <saml/SAMLConfig.h>
+# include <saml/saml2/core/Protocols.h>
+# include <saml/saml2/metadata/EndpointManager.h>
+# include <saml/saml2/metadata/MetadataCredentialCriteria.h>
+# include <xmltooling/util/URLEncoder.h>
+using namespace opensaml::saml2;
+using namespace opensaml::saml2p;
+using namespace opensaml::saml2md;
+using namespace opensaml;
+#endif
+
+using namespace shibsp;
+using namespace xmltooling;
+using namespace log4cpp;
+using namespace std;
+
+namespace shibsp {
+
+#if defined (_MSC_VER)
+ #pragma warning( push )
+ #pragma warning( disable : 4250 )
+#endif
+
+ class SHIBSP_DLLLOCAL SAML2Logout : public AbstractHandler, public LogoutHandler
+ {
+ public:
+ SAML2Logout(const DOMElement* e, const char* appId);
+ virtual ~SAML2Logout() {
+#ifndef SHIBSP_LITE
+ if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess)) {
+ delete m_decoder;
+ XMLString::release(&m_outgoing);
+ for_each(m_encoders.begin(), m_encoders.end(), cleanup_pair<const XMLCh*,MessageEncoder>());
+ }
+#endif
+ }
+
+ void receive(DDF& in, ostream& out);
+ pair<bool,long> run(SPRequest& request, bool isHandler=true) const;
+
+ private:
+ pair<bool,long> doRequest(
+ const Application& application, const char* session_id, const HTTPRequest& httpRequest, HTTPResponse& httpResponse
+ ) const;
+
+#ifndef SHIBSP_LITE
+ bool stronglyMatches(const XMLCh* idp, const XMLCh* sp, const saml2::NameID& n1, const saml2::NameID& n2) const;
+
+ pair<bool,long> sendResponse(
+ const XMLCh* requestID,
+ const XMLCh* code,
+ const XMLCh* subcode,
+ const char* msg,
+ const char* relayState,
+ const RoleDescriptor* role,
+ const Application& application,
+ HTTPResponse& httpResponse,
+ bool front
+ ) const;
+
+ QName m_role;
+ MessageDecoder* m_decoder;
+ XMLCh* m_outgoing;
+ vector<const XMLCh*> m_bindings;
+ map<const XMLCh*,MessageEncoder*> m_encoders;
+#endif
+ };
+
+#if defined (_MSC_VER)
+ #pragma warning( pop )
+#endif
+
+ Handler* SHIBSP_DLLLOCAL SAML2LogoutFactory(const pair<const DOMElement*,const char*>& p)
+ {
+ return new SAML2Logout(p.first, p.second);
+ }
+};
+
+SAML2Logout::SAML2Logout(const DOMElement* e, const char* appId)
+ : AbstractHandler(e, Category::getInstance(SHIBSP_LOGCAT".SAML2Logout"))
+#ifndef SHIBSP_LITE
+ ,m_role(samlconstants::SAML20MD_NS, IDPSSODescriptor::LOCAL_NAME), m_decoder(NULL), m_outgoing(NULL)
+#endif
+{
+#ifndef SHIBSP_LITE
+ m_initiator = false;
+ m_preserve.push_back("ID");
+ m_preserve.push_back("entityID");
+ m_preserve.push_back("RelayState");
+
+ if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess)) {
+ SAMLConfig& conf = SAMLConfig::getConfig();
+
+ // Handle incoming binding.
+ m_decoder = conf.MessageDecoderManager.newPlugin(getString("Binding").second,make_pair(e,shibspconstants::SHIB2SPCONFIG_NS));
+ m_decoder->setArtifactResolver(SPConfig::getConfig().getArtifactResolver());
+
+ if (m_decoder->isUserAgentPresent()) {
+ // Handle front-channel binding setup.
+ pair<bool,const XMLCh*> outgoing = getXMLString("outgoingBindings", m_configNS.get());
+ if (outgoing.first) {
+ m_outgoing = XMLString::replicate(outgoing.second);
+ XMLString::trim(m_outgoing);
+ }
+ else {
+ // No override, so we'll install a default binding precedence.
+ string prec = string(samlconstants::SAML20_BINDING_HTTP_REDIRECT) + ' ' + samlconstants::SAML20_BINDING_HTTP_POST + ' ' +
+ samlconstants::SAML20_BINDING_HTTP_POST_SIMPLESIGN + ' ' + samlconstants::SAML20_BINDING_HTTP_ARTIFACT;
+ m_outgoing = XMLString::transcode(prec.c_str());
+ }
+
+ int pos;
+ XMLCh* start = m_outgoing;
+ while (start && *start) {
+ pos = XMLString::indexOf(start,chSpace);
+ if (pos != -1)
+ *(start + pos)=chNull;
+ m_bindings.push_back(start);
+ try {
+ auto_ptr_char b(start);
+ MessageEncoder * encoder = conf.MessageEncoderManager.newPlugin(b.get(),make_pair(e,shibspconstants::SHIB2SPCONFIG_NS));
+ m_encoders[start] = encoder;
+ m_log.debug("supporting outgoing front-channel binding (%s)", b.get());
+ }
+ catch (exception& ex) {
+ m_log.error("error building MessageEncoder: %s", ex.what());
+ }
+ if (pos != -1)
+ start = start + pos + 1;
+ else
+ break;
+ }
+ }
+ else {
+ MessageEncoder* encoder = conf.MessageEncoderManager.newPlugin(
+ getString("Binding").second,make_pair(e,shibspconstants::SHIB2SPCONFIG_NS)
+ );
+ m_encoders.insert(pair<const XMLCh*,MessageEncoder*>(NULL, encoder));
+ }
+ }
+#endif
+
+ string address(appId);
+ address += getString("Location").second;
+ setAddress(address.c_str());
+}
+
+pair<bool,long> SAML2Logout::run(SPRequest& request, bool isHandler) const
+{
+ // Defer to base class for front-channel loop first.
+ // This won't initiate the loop, only continue/end it.
+ pair<bool,long> ret = LogoutHandler::run(request, isHandler);
+ if (ret.first)
+ return ret;
+
+ // Get the session_id in case this is a front-channel LogoutRequest.
+ pair<string,const char*> shib_cookie = request.getApplication().getCookieNameProps("_shibsession_");
+ const char* session_id = request.getCookie(shib_cookie.first.c_str());
+
+ SPConfig& conf = SPConfig::getConfig();
+ if (conf.isEnabled(SPConfig::OutOfProcess)) {
+ // When out of process, we run natively and directly process the message.
+ return doRequest(request.getApplication(), session_id, request, request);
+ }
+ else {
+ // When not out of process, we remote all the message processing.
+ DDF out,in = wrap(request, NULL, true);
+ DDFJanitor jin(in), jout(out);
+ if (session_id)
+ in.addmember("session_id").string(session_id);
+ out=request.getServiceProvider().getListenerService()->send(in);
+ return unwrap(request, out);
+ }
+}
+
+void SAML2Logout::receive(DDF& in, ostream& out)
+{
+ // Find application.
+ const char* aid=in["application_id"].string();
+ const Application* app=aid ? SPConfig::getConfig().getServiceProvider()->getApplication(aid) : NULL;
+ if (!app) {
+ // Something's horribly wrong.
+ m_log.error("couldn't find application (%s) for logout", aid ? aid : "(missing)");
+ throw ConfigurationException("Unable to locate application for logout, deleted?");
+ }
+
+ // Unpack the request.
+ DDF ret(NULL);
+ DDFJanitor jout(ret);
+ auto_ptr<HTTPRequest> req(getRequest(in));
+ auto_ptr<HTTPResponse> resp(getResponse(ret));
+
+ // Since we're remoted, the result should either be a throw, which we pass on,
+ // a false/0 return, which we just return as an empty structure, or a response/redirect,
+ // which we capture in the facade and send back.
+ doRequest(*app, in["session_id"].string(), *req.get(), *resp.get());
+ out << ret;
+}
+
+pair<bool,long> SAML2Logout::doRequest(
+ const Application& application, const char* session_id, const HTTPRequest& request, HTTPResponse& response
+ ) const
+{
+#ifndef SHIBSP_LITE
+ SessionCache* cache = application.getServiceProvider().getSessionCache();
+ if (!strcmp(request.getMethod(),"GET") && request.getParameter("notifying")) {
+
+ // This is returning from a front-channel notification, so we have to do the back-channel and then
+ // respond. To do that, we need state from the original request.
+ if (!request.getParameter("entityID")) {
+ if (session_id)
+ cache->remove(session_id, application);
+ throw FatalProfileException("Application notification loop did not return entityID for LogoutResponse.");
+ }
+
+ // Best effort on back channel and to remove the user agent's session.
+ bool worked1 = false,worked2 = false;
+ if (session_id) {
+ vector<string> sessions(1,session_id);
+ worked1 = notifyBackChannel(application, sessions);
+ try {
+ cache->remove(session_id, application);
+ worked2 = true;
+ }
+ catch (exception& ex) {
+ m_log.error("error removing session (%s): %s", session_id, ex.what());
+ }
+ }
+ else {
+ worked1 = worked2 = true;
+ }
+
+ // We need metadata to issue a response.
+ Locker metadataLocker(application.getMetadataProvider());
+ const EntityDescriptor* entity = application.getMetadataProvider()->getEntityDescriptor(request.getParameter("entityID"));
+ if (!entity) {
+ throw MetadataException(
+ "Unable to locate metadata for identity provider ($entityID)", namedparams(1, "entityID", request.getParameter("entityID"))
+ );
+ }
+ const IDPSSODescriptor* idp = entity->getIDPSSODescriptor(samlconstants::SAML20P_NS);
+ if (!idp) {
+ throw MetadataException(
+ "Unable to locate SAML 2.0 IdP role for identity provider ($entityID).",
+ namedparams(1, "entityID", request.getParameter("entityID"))
+ );
+ }
+
+ auto_ptr_XMLCh reqid(request.getParameter("ID"));
+ if (worked1 && worked2) {
+ // Successful LogoutResponse. Has to be front-channel or we couldn't be here.
+ return sendResponse(
+ reqid.get(), StatusCode::SUCCESS, NULL, NULL, request.getParameter("RelayState"), idp, application, response, true
+ );
+ }
+
+ return sendResponse(
+ reqid.get(),
+ StatusCode::RESPONDER, NULL, "Unable to fully destroy principal's session.",
+ request.getParameter("RelayState"),
+ idp,
+ application,
+ response,
+ true
+ );
+ }
+
+ // If we get here, it's an external protocol message to decode.
+
+ // Locate policy key.
+ pair<bool,const char*> policyId = getString("policyId", m_configNS.get()); // namespace-qualified if inside handler element
+ if (!policyId.first)
+ policyId = application.getString("policyId"); // unqualified in Application(s) element
+
+ // Access policy properties.
+ const PropertySet* settings = application.getServiceProvider().getPolicySettings(policyId.second);
+ pair<bool,bool> validate = settings->getBool("validate");
+
+ // Lock metadata for use by policy.
+ Locker metadataLocker(application.getMetadataProvider());
+
+ // Create the policy.
+ shibsp::SecurityPolicy policy(application, &m_role, validate.first && validate.second);
+
+ // Decode the message.
+ string relayState;
+ auto_ptr<XMLObject> msg(m_decoder->decode(relayState, request, policy));
+ const LogoutRequest* logoutRequest = dynamic_cast<LogoutRequest*>(msg.get());
+ if (logoutRequest) {
+ if (!policy.isSecure())
+ throw SecurityPolicyException("Security of LogoutRequest not established.");
+
+ // Message from IdP to logout one or more sessions.
+
+ // If this is front-channel, we have to have a session_id to use already.
+ if (m_decoder->isUserAgentPresent() && !session_id) {
+ m_log.error("no active session");
+ return sendResponse(
+ logoutRequest->getID(),
+ StatusCode::REQUESTER, StatusCode::UNKNOWN_PRINCIPAL, "No active session found in request.",
+ relayState.c_str(),
+ policy.getIssuerMetadata(),
+ application,
+ response,
+ true
+ );
+ }
+
+ bool ownedName = false;
+ NameID* nameid = logoutRequest->getNameID();
+ if (!nameid) {
+ // Check for EncryptedID.
+ EncryptedID* encname = logoutRequest->getEncryptedID();
+ if (encname) {
+ CredentialResolver* cr=application.getCredentialResolver();
+ if (!cr)
+ m_log.warn("found encrypted NameID, but no decryption credential was available");
+ else {
+ Locker credlocker(cr);
+ auto_ptr<MetadataCredentialCriteria> mcc(
+ policy.getIssuerMetadata() ? new MetadataCredentialCriteria(*policy.getIssuerMetadata()) : NULL
+ );
+ try {
+ auto_ptr<XMLObject> decryptedID(encname->decrypt(*cr,application.getXMLString("entityID").second,mcc.get()));
+ nameid = dynamic_cast<NameID*>(decryptedID.get());
+ if (nameid) {
+ ownedName = true;
+ decryptedID.release();
+ }
+ }
+ catch (exception& ex) {
+ m_log.error(ex.what());
+ }
+ }
+ }
+ }
+ if (!nameid) {
+ // No NameID, so must respond with an error.
+ m_log.error("NameID not found in request");
+ return sendResponse(
+ logoutRequest->getID(),
+ StatusCode::REQUESTER, StatusCode::UNKNOWN_PRINCIPAL, "NameID not found in request.",
+ relayState.c_str(),
+ policy.getIssuerMetadata(),
+ application,
+ response,
+ m_decoder->isUserAgentPresent()
+ );
+ }
+
+ // Suck indexes out of the request for next steps.
+ set<string> indexes;
+ EntityDescriptor* entity = policy.getIssuerMetadata() ? dynamic_cast<EntityDescriptor*>(policy.getIssuerMetadata()->getParent()) : NULL;
+ const vector<SessionIndex*> sindexes = logoutRequest->getSessionIndexs();
+ for (vector<SessionIndex*>::const_iterator i = sindexes.begin(); i != sindexes.end(); ++i) {
+ auto_ptr_char sindex((*i)->getSessionIndex());
+ indexes.insert(sindex.get());
+ }
+
+ // For a front-channel LogoutRequest, we have to match the information in the request
+ // against the current session.
+ if (session_id) {
+ if (!cache->matches(session_id, entity, *nameid, &indexes, application)) {
+ return sendResponse(
+ logoutRequest->getID(),
+ StatusCode::REQUESTER, StatusCode::REQUEST_DENIED, "Active sessions did not match logout request.",
+ relayState.c_str(),
+ policy.getIssuerMetadata(),
+ application,
+ response,
+ true
+ );
+ }
+
+ }
+
+ // Now we perform "logout" by finding the matching sessions.
+ vector<string> sessions;
+ try {
+ time_t expires = logoutRequest->getNotOnOrAfter() ? logoutRequest->getNotOnOrAfterEpoch() : 0;
+ cache->logout(entity, *nameid, &indexes, expires, application, sessions);
+
+ // Now we actually terminate everything except for the active session,
+ // if this is front-channel, for notification purposes.
+ for (vector<string>::const_iterator sit = sessions.begin(); sit != sessions.end(); ++sit)
+ if (session_id && strcmp(sit->c_str(), session_id))
+ cache->remove(sit->c_str(), application);
+ }
+ catch (exception& ex) {
+ m_log.error("error while logging out matching sessions: %s", ex.what());
+ return sendResponse(
+ logoutRequest->getID(),
+ StatusCode::RESPONDER, NULL, ex.what(),
+ relayState.c_str(),
+ policy.getIssuerMetadata(),
+ application,
+ response,
+ m_decoder->isUserAgentPresent()
+ );
+ }
+
+ if (m_decoder->isUserAgentPresent()) {
+ // Pass control to the first front channel notification point, if any.
+ map<string,string> parammap;
+ if (!relayState.empty())
+ parammap["RelayState"] = relayState;
+ auto_ptr_char entityID(entity ? entity->getEntityID() : NULL);
+ if (entityID.get())
+ parammap["entityID"] = entityID.get();
+ auto_ptr_char reqID(logoutRequest->getID());
+ if (reqID.get())
+ parammap["ID"] = reqID.get();
+ pair<bool,long> result = notifyFrontChannel(application, request, response, ¶mmap);
+ if (result.first)
+ return result;
+ }
+
+ // For back-channel requests, or if no front-channel notification is needed...
+ bool worked1 = false,worked2 = false;
+ worked1 = notifyBackChannel(application, sessions);
+ if (session_id) {
+ // One last session to yoink...
+ try {
+ cache->remove(session_id, application);
+ worked2 = true;
+ }
+ catch (exception& ex) {
+ m_log.error("error removing active session (%s): %s", session_id, ex.what());
+ }
+ }
+
+ return sendResponse(
+ logoutRequest->getID(),
+ (worked1 && worked2) ? StatusCode::SUCCESS : StatusCode::RESPONDER,
+ (worked1 && worked2) ? NULL : StatusCode::PARTIAL_LOGOUT,
+ NULL,
+ relayState.c_str(),
+ policy.getIssuerMetadata(),
+ application,
+ response,
+ m_decoder->isUserAgentPresent()
+ );
+ }
+
+ // A LogoutResponse completes an SP-initiated logout sequence.
+ const LogoutResponse* logoutResponse = dynamic_cast<LogoutResponse*>(msg.get());
+ if (logoutResponse) {
+ if (!policy.isSecure()) {
+ SecurityPolicyException ex("Security of LogoutResponse not established.");
+ if (policy.getIssuerMetadata())
+ annotateException(&ex, policy.getIssuerMetadata()); // throws it
+ ex.raise();
+ }
+ checkError(logoutResponse, policy.getIssuerMetadata()); // throws if Status doesn't look good...
+
+ // Return template for completion of global logout, or redirect to homeURL.
+ return sendLogoutPage(application, response, false, "Global logout completed.");
+ }
+
+ FatalProfileException ex("Incoming message was not a samlp:LogoutRequest or samlp:LogoutResponse.");
+ if (policy.getIssuerMetadata())
+ annotateException(&ex, policy.getIssuerMetadata()); // throws it
+ ex.raise();
+ return make_pair(false,0); // never happen, satisfies compiler
+#else
+ throw ConfigurationException("Cannot process logout message using lite version of shibsp library.");
+#endif
+}
+
+#ifndef SHIBSP_LITE
+
+bool SAML2Logout::stronglyMatches(const XMLCh* idp, const XMLCh* sp, const saml2::NameID& n1, const saml2::NameID& n2) const
+{
+ if (!XMLString::equals(n1.getName(), n2.getName()))
+ return false;
+
+ const XMLCh* s1 = n1.getFormat();
+ const XMLCh* s2 = n2.getFormat();
+ if (!s1 || !*s1)
+ s1 = saml2::NameID::UNSPECIFIED;
+ if (!s2 || !*s2)
+ s2 = saml2::NameID::UNSPECIFIED;
+ if (!XMLString::equals(s1,s2))
+ return false;
+
+ s1 = n1.getNameQualifier();
+ s2 = n2.getNameQualifier();
+ if (!s1 || !*s1)
+ s1 = idp;
+ if (!s2 || !*s2)
+ s2 = idp;
+ if (!XMLString::equals(s1,s2))
+ return false;
+
+ s1 = n1.getSPNameQualifier();
+ s2 = n2.getSPNameQualifier();
+ if (!s1 || !*s1)
+ s1 = sp;
+ if (!s2 || !*s2)
+ s2 = sp;
+ if (!XMLString::equals(s1,s2))
+ return false;
+
+ return true;
+}
+
+pair<bool,long> SAML2Logout::sendResponse(
+ const XMLCh* requestID,
+ const XMLCh* code,
+ const XMLCh* subcode,
+ const char* msg,
+ const char* relayState,
+ const RoleDescriptor* role,
+ const Application& application,
+ HTTPResponse& httpResponse,
+ bool front
+ ) const
+{
+ // Get endpoint and encoder to use.
+ const EndpointType* ep = NULL;
+ const MessageEncoder* encoder = NULL;
+ if (front) {
+ const IDPSSODescriptor* idp = dynamic_cast<const IDPSSODescriptor*>(role);
+ for (vector<const XMLCh*>::const_iterator b = m_bindings.begin(); idp && b!=m_bindings.end(); ++b) {
+ if (ep=EndpointManager<SingleLogoutService>(idp->getSingleLogoutServices()).getByBinding(*b)) {
+ map<const XMLCh*,MessageEncoder*>::const_iterator enc = m_encoders.find(*b);
+ if (enc!=m_encoders.end())
+ encoder = enc->second;
+ break;
+ }
+ }
+ if (!ep || !encoder) {
+ auto_ptr_char id(dynamic_cast<EntityDescriptor*>(role->getParent())->getEntityID());
+ m_log.error("unable to locate compatible SLO service for provider (%s)", id.get());
+ MetadataException ex("Unable to locate endpoint at IdP ($entityID) to send LogoutResponse.");
+ annotateException(&ex, role); // throws it
+ }
+ }
+ else {
+ encoder = m_encoders.begin()->second;
+ }
+
+ // Prepare response.
+ auto_ptr<LogoutResponse> logout(LogoutResponseBuilder::buildLogoutResponse());
+ logout->setInResponseTo(requestID);
+ if (ep)
+ logout->setDestination(ep->getLocation());
+ Issuer* issuer = IssuerBuilder::buildIssuer();
+ logout->setIssuer(issuer);
+ issuer->setName(application.getXMLString("entityID").second);
+ fillStatus(*logout.get(), code, subcode, msg);
+
+ auto_ptr_char dest(ep ? ep->getLocation() : NULL);
+
+ long ret = sendMessage(*encoder, logout.get(), relayState, dest.get(), role, application, httpResponse, "signResponses");
+ logout.release(); // freed by encoder
+ return make_pair(true,ret);
+}
+
+#endif
-/*\r
- * Copyright 2001-2007 Internet2\r
- * \r
- * Licensed under the Apache License, Version 2.0 (the "License");\r
- * you may not use this file except in compliance with the License.\r
- * You may obtain a copy of the License at\r
- *\r
- * http://www.apache.org/licenses/LICENSE-2.0\r
- *\r
- * Unless required by applicable law or agreed to in writing, software\r
- * distributed under the License is distributed on an "AS IS" BASIS,\r
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
- * See the License for the specific language governing permissions and\r
- * limitations under the License.\r
- */\r
-\r
-/**\r
- * StorageServiceSessionCache.cpp\r
- * \r
- * StorageService-based SessionCache implementation.\r
- * \r
- * Instead of optimizing this plugin with a buffering scheme that keeps objects around\r
- * and avoids extra parsing steps, I'm assuming that systems that require such can\r
- * layer their own cache plugin on top of this version either by delegating to it\r
- * or using the remoting support. So this version will load sessions directly\r
- * from the StorageService, instantiate enough to expose the Session API,\r
- * and then delete everything when they're unlocked. All data in memory is always\r
- * kept in sync with the StorageService (no lazy updates).\r
- */\r
-\r
-#include "internal.h"\r
-#include "Application.h"\r
-#include "exceptions.h"\r
-#include "ServiceProvider.h"\r
-#include "SessionCache.h"\r
-#include "TransactionLog.h"\r
-#include "attribute/Attribute.h"\r
-#include "remoting/ListenerService.h"\r
-#include "util/SPConstants.h"\r
-\r
-#include <log4cpp/Category.hh>\r
-#include <saml/SAMLConfig.h>\r
-#include <xmltooling/util/NDC.h>\r
-#include <xmltooling/util/StorageService.h>\r
-#include <xmltooling/util/XMLHelper.h>\r
-#include <xercesc/util/XMLUniDefs.hpp>\r
-\r
-using namespace shibsp;\r
-using namespace opensaml::saml2md;\r
-using namespace opensaml;\r
-using namespace xmltooling;\r
-using namespace log4cpp;\r
-using namespace std;\r
-\r
-namespace shibsp {\r
-\r
- class SSCache;\r
- class StoredSession : public virtual Session\r
- {\r
- public:\r
- StoredSession(SSCache* cache, DDF& obj) : m_obj(obj), m_nameid(NULL), m_cache(cache) {\r
- const char* nameid = obj["nameid"].string();\r
- if (nameid) {\r
- // Parse and bind the document into an XMLObject.\r
- istringstream instr(nameid);\r
- DOMDocument* doc = XMLToolingConfig::getConfig().getParser().parse(instr); \r
- XercesJanitor<DOMDocument> janitor(doc);\r
- auto_ptr<saml2::NameID> n(saml2::NameIDBuilder::buildNameID());\r
- n->unmarshall(doc->getDocumentElement(), true);\r
- janitor.release();\r
- m_nameid = n.release();\r
- }\r
- }\r
- \r
- ~StoredSession();\r
- \r
- Lockable* lock() {\r
- return this;\r
- }\r
- void unlock() {\r
- delete this;\r
- }\r
- \r
- const char* getID() const {\r
- return m_obj.name();\r
- }\r
- const char* getClientAddress() const {\r
- return m_obj["client_addr"].string();\r
- }\r
- const char* getEntityID() const {\r
- return m_obj["entity_id"].string();\r
- }\r
- const char* getProtocol() const {\r
- return m_obj["protocol"].string();\r
- }\r
- const char* getAuthnInstant() const {\r
- return m_obj["authn_instant"].string();\r
- }\r
- const opensaml::saml2::NameID* getNameID() const {\r
- return m_nameid;\r
- }\r
- const char* getSessionIndex() const {\r
- return m_obj["session_index"].string();\r
- }\r
- const char* getAuthnContextClassRef() const {\r
- return m_obj["authncontext_class"].string();\r
- }\r
- const char* getAuthnContextDeclRef() const {\r
- return m_obj["authncontext_decl"].string();\r
- }\r
- const multimap<string,Attribute*>& getAttributes() const {\r
- if (m_attributes.empty())\r
- unmarshallAttributes();\r
- return m_attributes;\r
- }\r
- const vector<const char*>& getAssertionIDs() const {\r
- if (m_ids.empty()) {\r
- DDF ids = m_obj["assertions"];\r
- DDF id = ids.first();\r
- while (id.isstring()) {\r
- m_ids.push_back(id.string());\r
- id = ids.next();\r
- }\r
- }\r
- return m_ids;\r
- }\r
- \r
- void addAttributes(const vector<Attribute*>& attributes);\r
- const Assertion* getAssertion(const char* id) const;\r
- void addAssertion(Assertion* assertion);\r
-\r
- private:\r
- void unmarshallAttributes() const;\r
-\r
- DDF m_obj;\r
- saml2::NameID* m_nameid;\r
- mutable multimap<string,Attribute*> m_attributes;\r
- mutable vector<const char*> m_ids;\r
- mutable map<string,Assertion*> m_tokens;\r
- SSCache* m_cache;\r
- };\r
- \r
- class SSCache : public SessionCache, public virtual Remoted\r
- {\r
- public:\r
- SSCache(const DOMElement* e);\r
- ~SSCache();\r
- \r
- void receive(DDF& in, ostream& out);\r
- \r
- string insert(\r
- time_t expires,\r
- const Application& application,\r
- const char* client_addr=NULL,\r
- const saml2md::EntityDescriptor* issuer=NULL,\r
- const XMLCh* protocol=NULL,\r
- const saml2::NameID* nameid=NULL,\r
- const XMLCh* authn_instant=NULL,\r
- const XMLCh* session_index=NULL,\r
- const XMLCh* authncontext_class=NULL,\r
- const XMLCh* authncontext_decl=NULL,\r
- const vector<const Assertion*>* tokens=NULL,\r
- const multimap<string,Attribute*>* attributes=NULL\r
- );\r
- Session* find(const char* key, const Application& application, const char* client_addr=NULL, time_t* timeout=NULL);\r
- void remove(const char* key, const Application& application);\r
- void remove(\r
- const saml2md::EntityDescriptor* issuer,\r
- const saml2::NameID& nameid,\r
- const char* index,\r
- const Application& application,\r
- vector<string>& sessions\r
- );\r
-\r
- Category& m_log;\r
- StorageService* m_storage;\r
-\r
- private:\r
- // maintain back-mappings of NameID/SessionIndex -> session key\r
- void insert(const char* key, time_t expires, const char* name, const char* index);\r
-\r
- bool stronglyMatches(const XMLCh* idp, const XMLCh* sp, const saml2::NameID& n1, const saml2::NameID& n2) const;\r
- };\r
-\r
- SessionCache* SHIBSP_DLLLOCAL StorageServiceCacheFactory(const DOMElement* const & e)\r
- {\r
- return new SSCache(e);\r
- }\r
-\r
- static const XMLCh _StorageService[] = UNICODE_LITERAL_14(S,t,o,r,a,g,e,S,e,r,v,i,c,e);\r
-}\r
-\r
-StoredSession::~StoredSession()\r
-{\r
- m_obj.destroy();\r
- delete m_nameid;\r
- for_each(m_attributes.begin(), m_attributes.end(), cleanup_pair<string,Attribute>());\r
- for_each(m_tokens.begin(), m_tokens.end(), cleanup_pair<string,Assertion>());\r
-}\r
-\r
-void StoredSession::unmarshallAttributes() const\r
-{\r
- Attribute* attribute;\r
- DDF attrs = m_obj["attributes"];\r
- DDF attr = attrs.first();\r
- while (!attr.isnull()) {\r
- try {\r
- attribute = Attribute::unmarshall(attr);\r
- m_attributes.insert(make_pair(attribute->getId(), attribute));\r
- if (m_cache->m_log.isDebugEnabled())\r
- m_cache->m_log.debug("unmarshalled attribute (ID: %s) with %d value%s",\r
- attribute->getId(), attr.first().integer(), attr.first().integer()!=1 ? "s" : "");\r
- }\r
- catch (AttributeException& ex) {\r
- const char* id = attr.first().name();\r
- m_cache->m_log.error("error unmarshalling attribute (ID: %s): %s", id ? id : "none", ex.what());\r
- }\r
- attr = attrs.next();\r
- }\r
-}\r
-\r
-void StoredSession::addAttributes(const vector<Attribute*>& attributes)\r
-{\r
-#ifdef _DEBUG\r
- xmltooling::NDC ndc("addAttributes");\r
-#endif\r
-\r
- m_cache->m_log.debug("adding attributes to session (%s)", getID());\r
- \r
- int ver;\r
- do {\r
- DDF attr;\r
- DDF attrs = m_obj["attributes"];\r
- if (!attrs.islist())\r
- attrs = m_obj.addmember("attributes").list();\r
- for (vector<Attribute*>::const_iterator a=attributes.begin(); a!=attributes.end(); ++a) {\r
- attr = (*a)->marshall();\r
- attrs.add(attr);\r
- }\r
- \r
- // Tentatively increment the version.\r
- m_obj["version"].integer(m_obj["version"].integer()+1);\r
- \r
- ostringstream str;\r
- str << m_obj;\r
- string record(str.str()); \r
-\r
- try {\r
- ver = m_cache->m_storage->updateText(getID(), "session", record.c_str(), 0, m_obj["version"].integer()-1);\r
- }\r
- catch (exception&) {\r
- // Roll back modification to record.\r
- m_obj["version"].integer(m_obj["version"].integer()-1);\r
- vector<Attribute*>::size_type count = attributes.size();\r
- while (count--)\r
- attrs.last().destroy(); \r
- throw;\r
- }\r
-\r
- if (ver <= 0) {\r
- // Roll back modification to record.\r
- m_obj["version"].integer(m_obj["version"].integer()-1);\r
- vector<Attribute*>::size_type count = attributes.size();\r
- while (count--)\r
- attrs.last().destroy(); \r
- }\r
- if (!ver) {\r
- // Fatal problem with update.\r
- throw IOException("Unable to update stored session.");\r
- }\r
- else if (ver < 0) {\r
- // Out of sync.\r
- m_cache->m_log.warn("storage service indicates the record is out of sync, updating with a fresh copy...");\r
- ver = m_cache->m_storage->readText(getID(), "session", &record, NULL);\r
- if (!ver) {\r
- m_cache->m_log.error("readText failed on StorageService for session (%s)", getID());\r
- throw IOException("Unable to read back stored session.");\r
- }\r
- \r
- // Reset object.\r
- DDF newobj;\r
- istringstream in(record);\r
- in >> newobj;\r
-\r
- m_ids.clear();\r
- for_each(m_attributes.begin(), m_attributes.end(), cleanup_const_pair<string,Attribute>());\r
- m_attributes.clear();\r
- newobj["version"].integer(ver);\r
- m_obj.destroy();\r
- m_obj = newobj;\r
-\r
- ver = -1;\r
- }\r
- } while (ver < 0); // negative indicates a sync issue so we retry\r
-\r
- TransactionLog* xlog = SPConfig::getConfig().getServiceProvider()->getTransactionLog();\r
- Locker locker(xlog);\r
- xlog->log.infoStream() <<\r
- "Added the following attributes to session (ID: " <<\r
- getID() <<\r
- ") for (applicationId: " <<\r
- m_obj["application_id"].string() <<\r
- ") {";\r
- for (vector<Attribute*>::const_iterator a=attributes.begin(); a!=attributes.end(); ++a)\r
- xlog->log.infoStream() << "\t" << (*a)->getId() << " (" << (*a)->valueCount() << " values)";\r
- xlog->log.info("}");\r
-\r
- // We own them now, so clean them up.\r
- for_each(attributes.begin(), attributes.end(), xmltooling::cleanup<Attribute>());\r
-}\r
-\r
-const Assertion* StoredSession::getAssertion(const char* id) const\r
-{\r
- map<string,Assertion*>::const_iterator i = m_tokens.find(id);\r
- if (i!=m_tokens.end())\r
- return i->second;\r
- \r
- string tokenstr;\r
- if (!m_cache->m_storage->readText(getID(), id, &tokenstr, NULL))\r
- throw FatalProfileException("Assertion not found in cache.");\r
-\r
- // Parse and bind the document into an XMLObject.\r
- istringstream instr(tokenstr);\r
- DOMDocument* doc = XMLToolingConfig::getConfig().getParser().parse(instr); \r
- XercesJanitor<DOMDocument> janitor(doc);\r
- auto_ptr<XMLObject> xmlObject(XMLObjectBuilder::buildOneFromElement(doc->getDocumentElement(), true));\r
- janitor.release();\r
- \r
- Assertion* token = dynamic_cast<Assertion*>(xmlObject.get());\r
- if (!token)\r
- throw FatalProfileException("Request for cached assertion returned an unknown object type.");\r
-\r
- // Transfer ownership to us.\r
- xmlObject.release();\r
- m_tokens[id]=token;\r
- return token;\r
-}\r
-\r
-void StoredSession::addAssertion(Assertion* assertion)\r
-{\r
-#ifdef _DEBUG\r
- xmltooling::NDC ndc("addAssertion");\r
-#endif\r
- \r
- if (!assertion)\r
- throw FatalProfileException("Unknown object type passed to session for storage.");\r
-\r
- auto_ptr_char id(assertion->getID());\r
-\r
- m_cache->m_log.debug("adding assertion (%s) to session (%s)", id.get(), getID());\r
-\r
- time_t exp;\r
- if (!m_cache->m_storage->readText(getID(), "session", NULL, &exp))\r
- throw IOException("Unable to load expiration time for stored session.");\r
-\r
- ostringstream tokenstr;\r
- tokenstr << *assertion;\r
- if (!m_cache->m_storage->createText(getID(), id.get(), tokenstr.str().c_str(), exp))\r
- throw IOException("Attempted to insert duplicate assertion ID into session.");\r
- \r
- int ver;\r
- do {\r
- DDF token = DDF(NULL).string(id.get());\r
- m_obj["assertions"].add(token);\r
-\r
- // Tentatively increment the version.\r
- m_obj["version"].integer(m_obj["version"].integer()+1);\r
- \r
- ostringstream str;\r
- str << m_obj;\r
- string record(str.str()); \r
-\r
- try {\r
- ver = m_cache->m_storage->updateText(getID(), "session", record.c_str(), 0, m_obj["version"].integer()-1);\r
- }\r
- catch (exception&) {\r
- token.destroy();\r
- m_obj["version"].integer(m_obj["version"].integer()-1);\r
- m_cache->m_storage->deleteText(getID(), id.get());\r
- throw;\r
- }\r
-\r
- if (ver <= 0) {\r
- token.destroy();\r
- m_obj["version"].integer(m_obj["version"].integer()-1);\r
- } \r
- if (!ver) {\r
- // Fatal problem with update.\r
- m_cache->m_log.error("updateText failed on StorageService for session (%s)", getID());\r
- m_cache->m_storage->deleteText(getID(), id.get());\r
- throw IOException("Unable to update stored session.");\r
- }\r
- else if (ver < 0) {\r
- // Out of sync.\r
- m_cache->m_log.warn("storage service indicates the record is out of sync, updating with a fresh copy...");\r
- ver = m_cache->m_storage->readText(getID(), "session", &record, NULL);\r
- if (!ver) {\r
- m_cache->m_log.error("readText failed on StorageService for session (%s)", getID());\r
- m_cache->m_storage->deleteText(getID(), id.get());\r
- throw IOException("Unable to read back stored session.");\r
- }\r
- \r
- // Reset object.\r
- DDF newobj;\r
- istringstream in(record);\r
- in >> newobj;\r
-\r
- m_ids.clear();\r
- for_each(m_attributes.begin(), m_attributes.end(), cleanup_const_pair<string,Attribute>());\r
- m_attributes.clear();\r
- newobj["version"].integer(ver);\r
- m_obj.destroy();\r
- m_obj = newobj;\r
- \r
- ver = -1;\r
- }\r
- } while (ver < 0); // negative indicates a sync issue so we retry\r
-\r
- m_ids.clear();\r
- delete assertion;\r
-\r
- TransactionLog* xlog = SPConfig::getConfig().getServiceProvider()->getTransactionLog();\r
- Locker locker(xlog);\r
- xlog->log.info(\r
- "Added assertion (ID: %s) to session for (applicationId: %s) with (ID: %s)",\r
- id.get(), m_obj["application_id"].string(), getID()\r
- );\r
-}\r
-\r
-SSCache::SSCache(const DOMElement* e)\r
- : SessionCache(e), m_log(Category::getInstance(SHIBSP_LOGCAT".SessionCache")), m_storage(NULL)\r
-{\r
- SPConfig& conf = SPConfig::getConfig();\r
- const XMLCh* tag = e ? e->getAttributeNS(NULL,_StorageService) : NULL;\r
- if (tag && *tag) {\r
- auto_ptr_char ssid(tag);\r
- m_storage = conf.getServiceProvider()->getStorageService(ssid.get());\r
- if (m_storage)\r
- m_log.info("bound to StorageService (%s)", ssid.get());\r
- else\r
- throw ConfigurationException("SessionCache unable to locate StorageService, check configuration.");\r
- }\r
-\r
- ListenerService* listener=conf.getServiceProvider()->getListenerService(false);\r
- if (listener && conf.isEnabled(SPConfig::OutOfProcess)) {\r
- listener->regListener("find::"REMOTED_SESSION_CACHE"::SessionCache",this);\r
- listener->regListener("remove::"REMOTED_SESSION_CACHE"::SessionCache",this);\r
- listener->regListener("touch::"REMOTED_SESSION_CACHE"::SessionCache",this);\r
- listener->regListener("getAssertion::"REMOTED_SESSION_CACHE"::SessionCache",this);\r
- }\r
- else {\r
- m_log.info("no ListenerService available, cache remoting disabled");\r
- }\r
-}\r
-\r
-SSCache::~SSCache()\r
-{\r
- SPConfig& conf = SPConfig::getConfig();\r
- ListenerService* listener=conf.getServiceProvider()->getListenerService(false);\r
- if (listener && conf.isEnabled(SPConfig::OutOfProcess)) {\r
- listener->unregListener("find::"REMOTED_SESSION_CACHE"::SessionCache",this);\r
- listener->unregListener("remove::"REMOTED_SESSION_CACHE"::SessionCache",this);\r
- listener->unregListener("touch::"REMOTED_SESSION_CACHE"::SessionCache",this);\r
- listener->unregListener("getAssertion::"REMOTED_SESSION_CACHE"::SessionCache",this);\r
- }\r
-}\r
-\r
-void SSCache::insert(const char* key, time_t expires, const char* name, const char* index)\r
-{\r
- string dup;\r
- if (strlen(name) > 255) {\r
- dup = string(name).substr(0,255);\r
- name = dup.c_str();\r
- }\r
-\r
- DDF obj;\r
- DDFJanitor jobj(obj);\r
-\r
- // Since we can't guarantee uniqueness, check for an existing record.\r
- string record;\r
- time_t recordexp;\r
- int ver = m_storage->readText("NameID", name, &record, &recordexp);\r
- if (ver > 0) {\r
- // Existing record, so we need to unmarshall it.\r
- istringstream in(record);\r
- in >> obj;\r
- }\r
- else {\r
- // New record.\r
- obj.structure();\r
- }\r
-\r
- if (!index || !*index)\r
- index = "_shibnull";\r
- DDF sessions = obj.addmember(index);\r
- if (!sessions.islist())\r
- sessions.list();\r
- DDF session = DDF(NULL).string(key);\r
- sessions.add(session);\r
-\r
- // Remarshall the record.\r
- ostringstream out;\r
- out << obj;\r
-\r
- // Try and store it back...\r
- if (ver > 0) {\r
- ver = m_storage->updateText("NameID", name, out.str().c_str(), max(expires, recordexp), ver);\r
- if (ver <= 0) {\r
- // Out of sync, or went missing, so retry.\r
- return insert(key, expires, name, index);\r
- }\r
- }\r
- else if (!m_storage->createText("NameID", name, out.str().c_str(), expires)) {\r
- // Hit a dup, so just retry, hopefully hitting the other branch.\r
- return insert(key, expires, name, index);\r
- }\r
-}\r
-\r
-string SSCache::insert(\r
- time_t expires,\r
- const Application& application,\r
- const char* client_addr,\r
- const saml2md::EntityDescriptor* issuer,\r
- const XMLCh* protocol,\r
- const saml2::NameID* nameid,\r
- const XMLCh* authn_instant,\r
- const XMLCh* session_index,\r
- const XMLCh* authncontext_class,\r
- const XMLCh* authncontext_decl,\r
- const vector<const Assertion*>* tokens,\r
- const multimap<string,Attribute*>* attributes\r
- )\r
-{\r
-#ifdef _DEBUG\r
- xmltooling::NDC ndc("insert");\r
-#endif\r
-\r
- m_log.debug("creating new session");\r
-\r
- auto_ptr_char key(SAMLConfig::getConfig().generateIdentifier());\r
-\r
- // Store session properties in DDF.\r
- DDF obj = DDF(key.get()).structure();\r
- obj.addmember("version").integer(1);\r
- obj.addmember("application_id").string(application.getId());\r
-\r
- // On 64-bit Windows, time_t doesn't fit in a long, so I'm using ISO timestamps. \r
-#ifndef HAVE_GMTIME_R\r
- struct tm* ptime=gmtime(&expires);\r
-#else\r
- struct tm res;\r
- struct tm* ptime=gmtime_r(&expires,&res);\r
-#endif\r
- char timebuf[32];\r
- strftime(timebuf,32,"%Y-%m-%dT%H:%M:%SZ",ptime);\r
- obj.addmember("expires").string(timebuf);\r
-\r
- if (client_addr)\r
- obj.addmember("client_addr").string(client_addr);\r
- if (issuer) {\r
- auto_ptr_char entity_id(issuer->getEntityID());\r
- obj.addmember("entity_id").string(entity_id.get());\r
- }\r
- if (protocol) {\r
- auto_ptr_char prot(protocol);\r
- obj.addmember("protocol").string(prot.get());\r
- }\r
- if (authn_instant) {\r
- auto_ptr_char instant(authn_instant);\r
- obj.addmember("authn_instant").string(instant.get());\r
- }\r
- auto_ptr_char index(session_index);\r
- if (session_index)\r
- obj.addmember("session_index").string(index.get());\r
- if (authncontext_class) {\r
- auto_ptr_char ac(authncontext_class);\r
- obj.addmember("authncontext_class").string(ac.get());\r
- }\r
- if (authncontext_decl) {\r
- auto_ptr_char ad(authncontext_decl);\r
- obj.addmember("authncontext_decl").string(ad.get());\r
- }\r
-\r
- if (nameid) {\r
- ostringstream namestr;\r
- namestr << *nameid;\r
- obj.addmember("nameid").string(namestr.str().c_str());\r
- }\r
-\r
- if (tokens) {\r
- obj.addmember("assertions").list();\r
- for (vector<const Assertion*>::const_iterator t = tokens->begin(); t!=tokens->end(); ++t) {\r
- auto_ptr_char tokenid((*t)->getID());\r
- DDF tokid = DDF(NULL).string(tokenid.get());\r
- obj["assertions"].add(tokid);\r
- }\r
- }\r
- \r
- if (attributes) {\r
- DDF attr;\r
- DDF attrlist = obj.addmember("attributes").list();\r
- for (multimap<string,Attribute*>::const_iterator a=attributes->begin(); a!=attributes->end(); ++a) {\r
- attr = a->second->marshall();\r
- attrlist.add(attr);\r
- }\r
- }\r
- \r
- ostringstream record;\r
- record << obj;\r
- \r
- m_log.debug("storing new session...");\r
- time_t now = time(NULL);\r
- if (!m_storage->createText(key.get(), "session", record.str().c_str(), now + m_cacheTimeout))\r
- throw FatalProfileException("Attempted to create a session with a duplicate key.");\r
- \r
- // Store the reverse mapping for logout.\r
- auto_ptr_char name(nameid ? nameid->getName() : NULL);\r
- try {\r
- if (name.get())\r
- insert(key.get(), expires, name.get(), index.get());\r
- }\r
- catch (exception& ex) {\r
- m_log.error("error storing back mapping of NameID for logout: %s", ex.what());\r
- }\r
-\r
- if (tokens) {\r
- try {\r
- for (vector<const Assertion*>::const_iterator t = tokens->begin(); t!=tokens->end(); ++t) {\r
- ostringstream tokenstr;\r
- tokenstr << *(*t);\r
- auto_ptr_char tokenid((*t)->getID());\r
- if (!m_storage->createText(key.get(), tokenid.get(), tokenstr.str().c_str(), now + m_cacheTimeout))\r
- throw IOException("duplicate assertion ID ($1)", params(1, tokenid.get()));\r
- }\r
- }\r
- catch (exception& ex) {\r
- m_log.error("error storing assertion along with session: %s", ex.what());\r
- }\r
- }\r
-\r
- const char* pid = obj["entity_id"].string();\r
- m_log.info("new session created: SessionID (%s) IdP (%s) Address (%s)", key.get(), pid ? pid : "none", client_addr);\r
-\r
- // Transaction Logging\r
- TransactionLog* xlog = application.getServiceProvider().getTransactionLog();\r
- Locker locker(xlog);\r
- xlog->log.infoStream() <<\r
- "New session (ID: " <<\r
- key.get() <<\r
- ") with (applicationId: " <<\r
- application.getId() <<\r
- ") for principal from (IdP: " <<\r
- (pid ? pid : "none") <<\r
- ") at (ClientAddress: " <<\r
- (client_addr ? client_addr : "none") <<\r
- ") with (NameIdentifier: " <<\r
- (name.get() ? name.get() : "none") <<\r
- ")";\r
- \r
- if (attributes) {\r
- xlog->log.infoStream() <<\r
- "Cached the following attributes with session (ID: " <<\r
- key.get() <<\r
- ") for (applicationId: " <<\r
- application.getId() <<\r
- ") {";\r
- for (multimap<string,Attribute*>::const_iterator a=attributes->begin(); a!=attributes->end(); ++a)\r
- xlog->log.infoStream() << "\t" << a->second->getId() << " (" << a->second->valueCount() << " values)";\r
- xlog->log.info("}");\r
- }\r
-\r
- return key.get();\r
-}\r
-\r
-Session* SSCache::find(const char* key, const Application& application, const char* client_addr, time_t* timeout)\r
-{\r
-#ifdef _DEBUG\r
- xmltooling::NDC ndc("find");\r
-#endif\r
-\r
- m_log.debug("searching for session (%s)", key);\r
- \r
- time_t lastAccess;\r
- string record;\r
- int ver = m_storage->readText(key, "session", &record, &lastAccess);\r
- if (!ver)\r
- return NULL;\r
- \r
- m_log.debug("reconstituting session and checking validity");\r
- \r
- DDF obj;\r
- istringstream in(record);\r
- in >> obj;\r
- \r
- if (!XMLString::equals(obj["application_id"].string(), application.getId())) {\r
- m_log.error("an application (%s) tried to access another application's session", application.getId());\r
- obj.destroy();\r
- return NULL;\r
- }\r
-\r
- if (client_addr) {\r
- if (m_log.isDebugEnabled())\r
- m_log.debug("comparing client address %s against %s", client_addr, obj["client_addr"].string());\r
- if (strcmp(obj["client_addr"].string(),client_addr)) {\r
- m_log.warn("client address mismatch");\r
- remove(key, application);\r
- RetryableProfileException ex(\r
- "Your IP address ($1) does not match the address recorded at the time the session was established.",\r
- params(1,client_addr)\r
- );\r
- string eid(obj["entity_id"].string());\r
- obj.destroy();\r
- if (eid.empty())\r
- throw ex;\r
- MetadataProvider* m=application.getMetadataProvider();\r
- Locker locker(m);\r
- annotateException(&ex,m->getEntityDescriptor(eid.c_str(),false)); // throws it\r
- }\r
- }\r
-\r
- lastAccess -= m_cacheTimeout; // adjusts it back to the last time the record's timestamp was touched\r
- time_t now=time(NULL);\r
- \r
- if (timeout && *timeout > 0 && now - lastAccess >= *timeout) {\r
- m_log.info("session timed out (ID: %s)", key);\r
- remove(key, application);\r
- RetryableProfileException ex("Your session has expired, and you must re-authenticate.");\r
- string eid(obj["entity_id"].string());\r
- obj.destroy();\r
- if (eid.empty())\r
- throw ex;\r
- MetadataProvider* m=application.getMetadataProvider();\r
- Locker locker(m);\r
- annotateException(&ex,m->getEntityDescriptor(eid.c_str(),false)); // throws it\r
- }\r
- \r
- auto_ptr_XMLCh exp(obj["expires"].string());\r
- if (exp.get()) {\r
- DateTime iso(exp.get());\r
- iso.parseDateTime();\r
- if (now > iso.getEpoch()) {\r
- m_log.info("session expired (ID: %s)", key);\r
- remove(key, application);\r
- RetryableProfileException ex("Your session has expired, and you must re-authenticate.");\r
- string eid(obj["entity_id"].string());\r
- obj.destroy();\r
- if (eid.empty())\r
- throw ex;\r
- MetadataProvider* m=application.getMetadataProvider();\r
- Locker locker(m);\r
- annotateException(&ex,m->getEntityDescriptor(eid.c_str(),false)); // throws it\r
- }\r
- }\r
- \r
- if (timeout) {\r
- // Update storage expiration, if possible.\r
- try {\r
- m_storage->updateContext(key, now + m_cacheTimeout);\r
- }\r
- catch (exception& ex) {\r
- m_log.error("failed to update session expiration: %s", ex.what());\r
- }\r
- }\r
-\r
- // Finally build the Session object.\r
- try {\r
- return new StoredSession(this, obj);\r
- }\r
- catch (exception&) {\r
- obj.destroy();\r
- throw;\r
- }\r
-}\r
-\r
-void SSCache::remove(const char* key, const Application& application)\r
-{\r
-#ifdef _DEBUG\r
- xmltooling::NDC ndc("remove");\r
-#endif\r
-\r
- m_storage->deleteContext(key);\r
- m_log.info("removed session (%s)", key);\r
-\r
- TransactionLog* xlog = application.getServiceProvider().getTransactionLog();\r
- Locker locker(xlog);\r
- xlog->log.info("Destroyed session (applicationId: %s) (ID: %s)", application.getId(), key);\r
-}\r
-\r
-void SSCache::remove(\r
- const saml2md::EntityDescriptor* issuer,\r
- const saml2::NameID& nameid,\r
- const char* index,\r
- const Application& application,\r
- vector<string>& sessionsKilled\r
- )\r
-{\r
-#ifdef _DEBUG\r
- xmltooling::NDC ndc("remove");\r
-#endif\r
-\r
- auto_ptr_char entityID(issuer ? issuer->getEntityID() : NULL);\r
- auto_ptr_char name(nameid.getName());\r
-\r
- m_log.info(\r
- "request to logout sessions from (%s) for (%s) for session index (%s)",\r
- entityID.get() ? entityID.get() : "unknown", name.get(), index ? index : "all"\r
- );\r
-\r
- if (strlen(name.get()) > 255)\r
- const_cast<char*>(name.get())[255] = 0;\r
-\r
- // Read in potentially matching sessions.\r
- string record;\r
- int ver = m_storage->readText("NameID", name.get(), &record);\r
- if (ver == 0) {\r
- m_log.debug("no active sessions to remove for supplied issuer and name identifier");\r
- return;\r
- }\r
-\r
- DDF obj;\r
- DDFJanitor jobj(obj);\r
- istringstream in(record);\r
- in >> obj;\r
-\r
- // The record contains child lists for each known session index.\r
- DDF key;\r
- DDF sessions = obj.first();\r
- while (sessions.islist()) {\r
- if (!index || !strcmp(sessions.name(), index)) {\r
- key = sessions.first();\r
- while (key.isstring()) {\r
- // Fetch the session for comparison and possible removal.\r
- Session* session = find(key.string(), application);\r
- Locker locker(session);\r
- if (session) {\r
- // Same issuer?\r
- if (XMLString::equals(session->getEntityID(), entityID.get())) {\r
- // Same NameID?\r
- if (stronglyMatches(issuer->getEntityID(), application.getXMLString("entityID").second, nameid, *session->getNameID())) {\r
- sessionsKilled.push_back(key.string());\r
- remove(key.string(), application); // let this throw to detect errors in case the full logout fails?\r
- key.destroy();\r
- }\r
- else {\r
- m_log.debug("session (%s) contained a non-matching NameID, leaving it alone", key.string());\r
- }\r
- }\r
- else {\r
- m_log.debug("session (%s) established by different IdP, leaving it alone", key.string());\r
- }\r
- }\r
- else {\r
- // Session's gone, so...\r
- sessionsKilled.push_back(key.string());\r
- key.destroy();\r
- }\r
- key = sessions.next();\r
- }\r
-\r
- // No sessions left for this index?\r
- if (sessions.first().isnull())\r
- sessions.destroy();\r
- }\r
- sessions = obj.next();\r
- }\r
- \r
- if (obj.first().isnull())\r
- obj.destroy();\r
-\r
- // If possible, write back the mapping record (this isn't crucial).\r
- try {\r
- if (obj.isnull()) {\r
- m_storage->deleteText("NameID", name.get());\r
- }\r
- else if (!sessionsKilled.empty()) {\r
- ostringstream out;\r
- out << obj;\r
- if (m_storage->updateText("NameID", name.get(), out.str().c_str(), 0, ver) <= 0)\r
- m_log.warn("logout mapping record changed behind us, leaving it alone");\r
- }\r
- }\r
- catch (exception& ex) {\r
- m_log.error("error updating logout mapping record: %s", ex.what());\r
- }\r
-}\r
-\r
-bool SSCache::stronglyMatches(const XMLCh* idp, const XMLCh* sp, const saml2::NameID& n1, const saml2::NameID& n2) const\r
-{\r
- if (!XMLString::equals(n1.getName(), n2.getName()))\r
- return false;\r
- \r
- const XMLCh* s1 = n1.getFormat();\r
- const XMLCh* s2 = n2.getFormat();\r
- if (!s1 || !*s1)\r
- s1 = saml2::NameID::UNSPECIFIED;\r
- if (!s2 || !*s2)\r
- s2 = saml2::NameID::UNSPECIFIED;\r
- if (!XMLString::equals(s1,s2))\r
- return false;\r
- \r
- s1 = n1.getNameQualifier();\r
- s2 = n2.getNameQualifier();\r
- if (!s1 || !*s1)\r
- s1 = idp;\r
- if (!s2 || !*s2)\r
- s2 = idp;\r
- if (!XMLString::equals(s1,s2))\r
- return false;\r
-\r
- s1 = n1.getSPNameQualifier();\r
- s2 = n2.getSPNameQualifier();\r
- if (!s1 || !*s1)\r
- s1 = sp;\r
- if (!s2 || !*s2)\r
- s2 = sp;\r
- if (!XMLString::equals(s1,s2))\r
- return false;\r
-\r
- return true;\r
-}\r
-\r
-void SSCache::receive(DDF& in, ostream& out)\r
-{\r
-#ifdef _DEBUG\r
- xmltooling::NDC ndc("receive");\r
-#endif\r
-\r
- if (!strcmp(in.name(),"find::"REMOTED_SESSION_CACHE"::SessionCache")) {\r
- const char* key=in["key"].string();\r
- if (!key)\r
- throw ListenerException("Required parameters missing for session removal.");\r
-\r
- const Application* app = SPConfig::getConfig().getServiceProvider()->getApplication(in["application_id"].string());\r
- if (!app)\r
- throw ListenerException("Application not found, check configuration?");\r
-\r
- // Do an unversioned read.\r
- string record;\r
- time_t lastAccess;\r
- if (!m_storage->readText(key, "session", &record, &lastAccess)) {\r
- DDF ret(NULL);\r
- DDFJanitor jan(ret);\r
- out << ret;\r
- return;\r
- }\r
-\r
- // Adjust for expiration to recover last access time and check timeout.\r
- lastAccess -= m_cacheTimeout;\r
- time_t now=time(NULL);\r
-\r
- // See if we need to check for a timeout.\r
- if (in["timeout"].string()) {\r
- time_t timeout = 0;\r
- auto_ptr_XMLCh dt(in["timeout"].string());\r
- DateTime dtobj(dt.get());\r
- dtobj.parseDateTime();\r
- timeout = dtobj.getEpoch();\r
- \r
- if (timeout > 0 && now - lastAccess >= timeout) {\r
- m_log.info("session timed out (ID: %s)", key);\r
- remove(key,*app);\r
- throw RetryableProfileException("Your session has expired, and you must re-authenticate.");\r
- } \r
-\r
- // Update storage expiration, if possible.\r
- try {\r
- m_storage->updateContext(key, now + m_cacheTimeout);\r
- }\r
- catch (exception& ex) {\r
- m_log.error("failed to update session expiration: %s", ex.what());\r
- }\r
- }\r
- \r
- // Send the record back.\r
- out << record;\r
- }\r
- else if (!strcmp(in.name(),"touch::"REMOTED_SESSION_CACHE"::SessionCache")) {\r
- const char* key=in["key"].string();\r
- if (!key)\r
- throw ListenerException("Required parameters missing for session check.");\r
-\r
- // Do a versioned read.\r
- string record;\r
- time_t lastAccess;\r
- int curver = in["version"].integer();\r
- int ver = m_storage->readText(key, "session", &record, &lastAccess, curver);\r
- if (ver == 0) {\r
- m_log.warn("unsuccessful versioned read of session (ID: %s), caches out of sync?", key);\r
- throw RetryableProfileException("Your session has expired, and you must re-authenticate.");\r
- }\r
-\r
- // Adjust for expiration to recover last access time and check timeout.\r
- lastAccess -= m_cacheTimeout;\r
- time_t now=time(NULL);\r
-\r
- // See if we need to check for a timeout.\r
- time_t timeout = 0;\r
- auto_ptr_XMLCh dt(in["timeout"].string());\r
- if (dt.get()) {\r
- DateTime dtobj(dt.get());\r
- dtobj.parseDateTime();\r
- timeout = dtobj.getEpoch();\r
- }\r
- \r
- if (timeout > 0 && now - lastAccess >= timeout) {\r
- m_log.info("session timed out (ID: %s)", key);\r
- throw RetryableProfileException("Your session has expired, and you must re-authenticate.");\r
- } \r
-\r
- // Update storage expiration, if possible.\r
- try {\r
- m_storage->updateContext(key, now + m_cacheTimeout);\r
- }\r
- catch (exception& ex) {\r
- m_log.error("failed to update session expiration: %s", ex.what());\r
- }\r
- \r
- if (ver > curver) {\r
- // Send the record back.\r
- out << record;\r
- }\r
- else {\r
- DDF ret(NULL);\r
- DDFJanitor jan(ret);\r
- out << ret;\r
- }\r
- }\r
- else if (!strcmp(in.name(),"remove::"REMOTED_SESSION_CACHE"::SessionCache")) {\r
- const char* key=in["key"].string();\r
- if (!key)\r
- throw ListenerException("Required parameter missing for session removal.");\r
-\r
- const Application* app = SPConfig::getConfig().getServiceProvider()->getApplication(in["application_id"].string());\r
- if (!app)\r
- throw ListenerException("Application not found, check configuration?");\r
-\r
- remove(key,*app);\r
- DDF ret(NULL);\r
- DDFJanitor jan(ret);\r
- out << ret;\r
- }\r
- else if (!strcmp(in.name(),"getAssertion::"REMOTED_SESSION_CACHE"::SessionCache")) {\r
- const char* key=in["key"].string();\r
- const char* id=in["id"].string();\r
- if (!key || !id)\r
- throw ListenerException("Required parameters missing for assertion retrieval.");\r
- string token;\r
- if (!m_storage->readText(key, id, &token, NULL))\r
- throw FatalProfileException("Assertion not found in cache.");\r
- out << token;\r
- }\r
-}\r
+/*
+ * Copyright 2001-2007 Internet2
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/**
+ * StorageServiceSessionCache.cpp
+ *
+ * StorageService-based SessionCache implementation.
+ *
+ * Instead of optimizing this plugin with a buffering scheme that keeps objects around
+ * and avoids extra parsing steps, I'm assuming that systems that require such can
+ * layer their own cache plugin on top of this version either by delegating to it
+ * or using the remoting support. So this version will load sessions directly
+ * from the StorageService, instantiate enough to expose the Session API,
+ * and then delete everything when they're unlocked. All data in memory is always
+ * kept in sync with the StorageService (no lazy updates).
+ */
+
+#include "internal.h"
+#include "Application.h"
+#include "exceptions.h"
+#include "ServiceProvider.h"
+#include "SessionCache.h"
+#include "TransactionLog.h"
+#include "attribute/Attribute.h"
+#include "remoting/ListenerService.h"
+#include "util/SPConstants.h"
+
+#include <log4cpp/Category.hh>
+#include <saml/SAMLConfig.h>
+#include <xmltooling/util/NDC.h>
+#include <xmltooling/util/StorageService.h>
+#include <xmltooling/util/XMLHelper.h>
+#include <xercesc/util/XMLUniDefs.hpp>
+
+using namespace shibsp;
+using namespace opensaml::saml2md;
+using namespace opensaml;
+using namespace xmltooling;
+using namespace log4cpp;
+using namespace std;
+
+namespace shibsp {
+
+ class SSCache;
+ class StoredSession : public virtual Session
+ {
+ public:
+ StoredSession(SSCache* cache, DDF& obj) : m_obj(obj), m_nameid(NULL), m_cache(cache) {
+ const char* nameid = obj["nameid"].string();
+ if (nameid) {
+ // Parse and bind the document into an XMLObject.
+ istringstream instr(nameid);
+ DOMDocument* doc = XMLToolingConfig::getConfig().getParser().parse(instr);
+ XercesJanitor<DOMDocument> janitor(doc);
+ auto_ptr<saml2::NameID> n(saml2::NameIDBuilder::buildNameID());
+ n->unmarshall(doc->getDocumentElement(), true);
+ janitor.release();
+ m_nameid = n.release();
+ }
+ }
+
+ ~StoredSession();
+
+ Lockable* lock() {
+ return this;
+ }
+ void unlock() {
+ delete this;
+ }
+
+ const char* getID() const {
+ return m_obj.name();
+ }
+ const char* getClientAddress() const {
+ return m_obj["client_addr"].string();
+ }
+ const char* getEntityID() const {
+ return m_obj["entity_id"].string();
+ }
+ const char* getProtocol() const {
+ return m_obj["protocol"].string();
+ }
+ const char* getAuthnInstant() const {
+ return m_obj["authn_instant"].string();
+ }
+ const opensaml::saml2::NameID* getNameID() const {
+ return m_nameid;
+ }
+ const char* getSessionIndex() const {
+ return m_obj["session_index"].string();
+ }
+ const char* getAuthnContextClassRef() const {
+ return m_obj["authncontext_class"].string();
+ }
+ const char* getAuthnContextDeclRef() const {
+ return m_obj["authncontext_decl"].string();
+ }
+ const multimap<string,Attribute*>& getAttributes() const {
+ if (m_attributes.empty())
+ unmarshallAttributes();
+ return m_attributes;
+ }
+ const vector<const char*>& getAssertionIDs() const {
+ if (m_ids.empty()) {
+ DDF ids = m_obj["assertions"];
+ DDF id = ids.first();
+ while (id.isstring()) {
+ m_ids.push_back(id.string());
+ id = ids.next();
+ }
+ }
+ return m_ids;
+ }
+
+ void addAttributes(const vector<Attribute*>& attributes);
+ const Assertion* getAssertion(const char* id) const;
+ void addAssertion(Assertion* assertion);
+
+ private:
+ void unmarshallAttributes() const;
+
+ DDF m_obj;
+ saml2::NameID* m_nameid;
+ mutable multimap<string,Attribute*> m_attributes;
+ mutable vector<const char*> m_ids;
+ mutable map<string,Assertion*> m_tokens;
+ SSCache* m_cache;
+ };
+
+ class SSCache : public SessionCache, public virtual Remoted
+ {
+ public:
+ SSCache(const DOMElement* e);
+ ~SSCache();
+
+ void receive(DDF& in, ostream& out);
+
+ string insert(
+ time_t expires,
+ const Application& application,
+ const char* client_addr=NULL,
+ const saml2md::EntityDescriptor* issuer=NULL,
+ const XMLCh* protocol=NULL,
+ const saml2::NameID* nameid=NULL,
+ const XMLCh* authn_instant=NULL,
+ const XMLCh* session_index=NULL,
+ const XMLCh* authncontext_class=NULL,
+ const XMLCh* authncontext_decl=NULL,
+ const vector<const Assertion*>* tokens=NULL,
+ const multimap<string,Attribute*>* attributes=NULL
+ );
+ Session* find(const char* key, const Application& application, const char* client_addr=NULL, time_t* timeout=NULL);
+ void remove(const char* key, const Application& application);
+ bool matches(
+ const char* key,
+ const saml2md::EntityDescriptor* issuer,
+ const saml2::NameID& nameid,
+ const set<string>* indexes,
+ const Application& application
+ );
+ vector<string>::size_type logout(
+ const saml2md::EntityDescriptor* issuer,
+ const saml2::NameID& nameid,
+ const set<string>* indexes,
+ time_t expires,
+ const Application& application,
+ vector<string>& sessions
+ );
+
+ Category& m_log;
+ StorageService* m_storage;
+
+ private:
+ // maintain back-mappings of NameID/SessionIndex -> session key
+ void insert(const char* key, time_t expires, const char* name, const char* index);
+
+ bool stronglyMatches(const XMLCh* idp, const XMLCh* sp, const saml2::NameID& n1, const saml2::NameID& n2) const;
+ };
+
+ SessionCache* SHIBSP_DLLLOCAL StorageServiceCacheFactory(const DOMElement* const & e)
+ {
+ return new SSCache(e);
+ }
+
+ static const XMLCh _StorageService[] = UNICODE_LITERAL_14(S,t,o,r,a,g,e,S,e,r,v,i,c,e);
+}
+
+StoredSession::~StoredSession()
+{
+ m_obj.destroy();
+ delete m_nameid;
+ for_each(m_attributes.begin(), m_attributes.end(), cleanup_pair<string,Attribute>());
+ for_each(m_tokens.begin(), m_tokens.end(), cleanup_pair<string,Assertion>());
+}
+
+void StoredSession::unmarshallAttributes() const
+{
+ Attribute* attribute;
+ DDF attrs = m_obj["attributes"];
+ DDF attr = attrs.first();
+ while (!attr.isnull()) {
+ try {
+ attribute = Attribute::unmarshall(attr);
+ m_attributes.insert(make_pair(attribute->getId(), attribute));
+ if (m_cache->m_log.isDebugEnabled())
+ m_cache->m_log.debug("unmarshalled attribute (ID: %s) with %d value%s",
+ attribute->getId(), attr.first().integer(), attr.first().integer()!=1 ? "s" : "");
+ }
+ catch (AttributeException& ex) {
+ const char* id = attr.first().name();
+ m_cache->m_log.error("error unmarshalling attribute (ID: %s): %s", id ? id : "none", ex.what());
+ }
+ attr = attrs.next();
+ }
+}
+
+void StoredSession::addAttributes(const vector<Attribute*>& attributes)
+{
+#ifdef _DEBUG
+ xmltooling::NDC ndc("addAttributes");
+#endif
+
+ m_cache->m_log.debug("adding attributes to session (%s)", getID());
+
+ int ver;
+ do {
+ DDF attr;
+ DDF attrs = m_obj["attributes"];
+ if (!attrs.islist())
+ attrs = m_obj.addmember("attributes").list();
+ for (vector<Attribute*>::const_iterator a=attributes.begin(); a!=attributes.end(); ++a) {
+ attr = (*a)->marshall();
+ attrs.add(attr);
+ }
+
+ // Tentatively increment the version.
+ m_obj["version"].integer(m_obj["version"].integer()+1);
+
+ ostringstream str;
+ str << m_obj;
+ string record(str.str());
+
+ try {
+ ver = m_cache->m_storage->updateText(getID(), "session", record.c_str(), 0, m_obj["version"].integer()-1);
+ }
+ catch (exception&) {
+ // Roll back modification to record.
+ m_obj["version"].integer(m_obj["version"].integer()-1);
+ vector<Attribute*>::size_type count = attributes.size();
+ while (count--)
+ attrs.last().destroy();
+ throw;
+ }
+
+ if (ver <= 0) {
+ // Roll back modification to record.
+ m_obj["version"].integer(m_obj["version"].integer()-1);
+ vector<Attribute*>::size_type count = attributes.size();
+ while (count--)
+ attrs.last().destroy();
+ }
+ if (!ver) {
+ // Fatal problem with update.
+ throw IOException("Unable to update stored session.");
+ }
+ else if (ver < 0) {
+ // Out of sync.
+ m_cache->m_log.warn("storage service indicates the record is out of sync, updating with a fresh copy...");
+ ver = m_cache->m_storage->readText(getID(), "session", &record, NULL);
+ if (!ver) {
+ m_cache->m_log.error("readText failed on StorageService for session (%s)", getID());
+ throw IOException("Unable to read back stored session.");
+ }
+
+ // Reset object.
+ DDF newobj;
+ istringstream in(record);
+ in >> newobj;
+
+ m_ids.clear();
+ for_each(m_attributes.begin(), m_attributes.end(), cleanup_const_pair<string,Attribute>());
+ m_attributes.clear();
+ newobj["version"].integer(ver);
+ m_obj.destroy();
+ m_obj = newobj;
+
+ ver = -1;
+ }
+ } while (ver < 0); // negative indicates a sync issue so we retry
+
+ TransactionLog* xlog = SPConfig::getConfig().getServiceProvider()->getTransactionLog();
+ Locker locker(xlog);
+ xlog->log.infoStream() <<
+ "Added the following attributes to session (ID: " <<
+ getID() <<
+ ") for (applicationId: " <<
+ m_obj["application_id"].string() <<
+ ") {";
+ for (vector<Attribute*>::const_iterator a=attributes.begin(); a!=attributes.end(); ++a)
+ xlog->log.infoStream() << "\t" << (*a)->getId() << " (" << (*a)->valueCount() << " values)";
+ xlog->log.info("}");
+
+ // We own them now, so clean them up.
+ for_each(attributes.begin(), attributes.end(), xmltooling::cleanup<Attribute>());
+}
+
+const Assertion* StoredSession::getAssertion(const char* id) const
+{
+ map<string,Assertion*>::const_iterator i = m_tokens.find(id);
+ if (i!=m_tokens.end())
+ return i->second;
+
+ string tokenstr;
+ if (!m_cache->m_storage->readText(getID(), id, &tokenstr, NULL))
+ throw FatalProfileException("Assertion not found in cache.");
+
+ // Parse and bind the document into an XMLObject.
+ istringstream instr(tokenstr);
+ DOMDocument* doc = XMLToolingConfig::getConfig().getParser().parse(instr);
+ XercesJanitor<DOMDocument> janitor(doc);
+ auto_ptr<XMLObject> xmlObject(XMLObjectBuilder::buildOneFromElement(doc->getDocumentElement(), true));
+ janitor.release();
+
+ Assertion* token = dynamic_cast<Assertion*>(xmlObject.get());
+ if (!token)
+ throw FatalProfileException("Request for cached assertion returned an unknown object type.");
+
+ // Transfer ownership to us.
+ xmlObject.release();
+ m_tokens[id]=token;
+ return token;
+}
+
+void StoredSession::addAssertion(Assertion* assertion)
+{
+#ifdef _DEBUG
+ xmltooling::NDC ndc("addAssertion");
+#endif
+
+ if (!assertion)
+ throw FatalProfileException("Unknown object type passed to session for storage.");
+
+ auto_ptr_char id(assertion->getID());
+
+ m_cache->m_log.debug("adding assertion (%s) to session (%s)", id.get(), getID());
+
+ time_t exp;
+ if (!m_cache->m_storage->readText(getID(), "session", NULL, &exp))
+ throw IOException("Unable to load expiration time for stored session.");
+
+ ostringstream tokenstr;
+ tokenstr << *assertion;
+ if (!m_cache->m_storage->createText(getID(), id.get(), tokenstr.str().c_str(), exp))
+ throw IOException("Attempted to insert duplicate assertion ID into session.");
+
+ int ver;
+ do {
+ DDF token = DDF(NULL).string(id.get());
+ m_obj["assertions"].add(token);
+
+ // Tentatively increment the version.
+ m_obj["version"].integer(m_obj["version"].integer()+1);
+
+ ostringstream str;
+ str << m_obj;
+ string record(str.str());
+
+ try {
+ ver = m_cache->m_storage->updateText(getID(), "session", record.c_str(), 0, m_obj["version"].integer()-1);
+ }
+ catch (exception&) {
+ token.destroy();
+ m_obj["version"].integer(m_obj["version"].integer()-1);
+ m_cache->m_storage->deleteText(getID(), id.get());
+ throw;
+ }
+
+ if (ver <= 0) {
+ token.destroy();
+ m_obj["version"].integer(m_obj["version"].integer()-1);
+ }
+ if (!ver) {
+ // Fatal problem with update.
+ m_cache->m_log.error("updateText failed on StorageService for session (%s)", getID());
+ m_cache->m_storage->deleteText(getID(), id.get());
+ throw IOException("Unable to update stored session.");
+ }
+ else if (ver < 0) {
+ // Out of sync.
+ m_cache->m_log.warn("storage service indicates the record is out of sync, updating with a fresh copy...");
+ ver = m_cache->m_storage->readText(getID(), "session", &record, NULL);
+ if (!ver) {
+ m_cache->m_log.error("readText failed on StorageService for session (%s)", getID());
+ m_cache->m_storage->deleteText(getID(), id.get());
+ throw IOException("Unable to read back stored session.");
+ }
+
+ // Reset object.
+ DDF newobj;
+ istringstream in(record);
+ in >> newobj;
+
+ m_ids.clear();
+ for_each(m_attributes.begin(), m_attributes.end(), cleanup_const_pair<string,Attribute>());
+ m_attributes.clear();
+ newobj["version"].integer(ver);
+ m_obj.destroy();
+ m_obj = newobj;
+
+ ver = -1;
+ }
+ } while (ver < 0); // negative indicates a sync issue so we retry
+
+ m_ids.clear();
+ delete assertion;
+
+ TransactionLog* xlog = SPConfig::getConfig().getServiceProvider()->getTransactionLog();
+ Locker locker(xlog);
+ xlog->log.info(
+ "Added assertion (ID: %s) to session for (applicationId: %s) with (ID: %s)",
+ id.get(), m_obj["application_id"].string(), getID()
+ );
+}
+
+SSCache::SSCache(const DOMElement* e)
+ : SessionCache(e), m_log(Category::getInstance(SHIBSP_LOGCAT".SessionCache")), m_storage(NULL)
+{
+ SPConfig& conf = SPConfig::getConfig();
+ const XMLCh* tag = e ? e->getAttributeNS(NULL,_StorageService) : NULL;
+ if (tag && *tag) {
+ auto_ptr_char ssid(tag);
+ m_storage = conf.getServiceProvider()->getStorageService(ssid.get());
+ if (m_storage)
+ m_log.info("bound to StorageService (%s)", ssid.get());
+ else
+ throw ConfigurationException("SessionCache unable to locate StorageService, check configuration.");
+ }
+
+ ListenerService* listener=conf.getServiceProvider()->getListenerService(false);
+ if (listener && conf.isEnabled(SPConfig::OutOfProcess)) {
+ listener->regListener("find::"REMOTED_SESSION_CACHE"::SessionCache",this);
+ listener->regListener("remove::"REMOTED_SESSION_CACHE"::SessionCache",this);
+ listener->regListener("touch::"REMOTED_SESSION_CACHE"::SessionCache",this);
+ listener->regListener("getAssertion::"REMOTED_SESSION_CACHE"::SessionCache",this);
+ }
+ else {
+ m_log.info("no ListenerService available, cache remoting disabled");
+ }
+}
+
+SSCache::~SSCache()
+{
+ SPConfig& conf = SPConfig::getConfig();
+ ListenerService* listener=conf.getServiceProvider()->getListenerService(false);
+ if (listener && conf.isEnabled(SPConfig::OutOfProcess)) {
+ listener->unregListener("find::"REMOTED_SESSION_CACHE"::SessionCache",this);
+ listener->unregListener("remove::"REMOTED_SESSION_CACHE"::SessionCache",this);
+ listener->unregListener("touch::"REMOTED_SESSION_CACHE"::SessionCache",this);
+ listener->unregListener("getAssertion::"REMOTED_SESSION_CACHE"::SessionCache",this);
+ }
+}
+
+void SSCache::insert(const char* key, time_t expires, const char* name, const char* index)
+{
+ string dup;
+ if (strlen(name) > 255) {
+ dup = string(name).substr(0,255);
+ name = dup.c_str();
+ }
+
+ DDF obj;
+ DDFJanitor jobj(obj);
+
+ // Since we can't guarantee uniqueness, check for an existing record.
+ string record;
+ time_t recordexp;
+ int ver = m_storage->readText("Logout", name, &record, &recordexp);
+ if (ver > 0) {
+ // Existing record, so we need to unmarshall it.
+ istringstream in(record);
+ in >> obj;
+ }
+ else {
+ // New record.
+ obj.structure();
+ }
+
+ if (!index || !*index)
+ index = "_shibnull";
+ DDF sessions = obj.addmember(index);
+ if (!sessions.islist())
+ sessions.list();
+ DDF session = DDF(NULL).string(key);
+ sessions.add(session);
+
+ // Remarshall the record.
+ ostringstream out;
+ out << obj;
+
+ // Try and store it back...
+ if (ver > 0) {
+ ver = m_storage->updateText("Logout", name, out.str().c_str(), max(expires, recordexp), ver);
+ if (ver <= 0) {
+ // Out of sync, or went missing, so retry.
+ return insert(key, expires, name, index);
+ }
+ }
+ else if (!m_storage->createText("Logout", name, out.str().c_str(), expires)) {
+ // Hit a dup, so just retry, hopefully hitting the other branch.
+ return insert(key, expires, name, index);
+ }
+}
+
+string SSCache::insert(
+ time_t expires,
+ const Application& application,
+ const char* client_addr,
+ const saml2md::EntityDescriptor* issuer,
+ const XMLCh* protocol,
+ const saml2::NameID* nameid,
+ const XMLCh* authn_instant,
+ const XMLCh* session_index,
+ const XMLCh* authncontext_class,
+ const XMLCh* authncontext_decl,
+ const vector<const Assertion*>* tokens,
+ const multimap<string,Attribute*>* attributes
+ )
+{
+#ifdef _DEBUG
+ xmltooling::NDC ndc("insert");
+#endif
+
+ m_log.debug("creating new session");
+
+ auto_ptr_char key(SAMLConfig::getConfig().generateIdentifier());
+
+ // Store session properties in DDF.
+ DDF obj = DDF(key.get()).structure();
+ obj.addmember("version").integer(1);
+ obj.addmember("application_id").string(application.getId());
+
+ // On 64-bit Windows, time_t doesn't fit in a long, so I'm using ISO timestamps.
+#ifndef HAVE_GMTIME_R
+ struct tm* ptime=gmtime(&expires);
+#else
+ struct tm res;
+ struct tm* ptime=gmtime_r(&expires,&res);
+#endif
+ char timebuf[32];
+ strftime(timebuf,32,"%Y-%m-%dT%H:%M:%SZ",ptime);
+ obj.addmember("expires").string(timebuf);
+
+ if (client_addr)
+ obj.addmember("client_addr").string(client_addr);
+ if (issuer) {
+ auto_ptr_char entity_id(issuer->getEntityID());
+ obj.addmember("entity_id").string(entity_id.get());
+ }
+ if (protocol) {
+ auto_ptr_char prot(protocol);
+ obj.addmember("protocol").string(prot.get());
+ }
+ if (authn_instant) {
+ auto_ptr_char instant(authn_instant);
+ obj.addmember("authn_instant").string(instant.get());
+ }
+ auto_ptr_char index(session_index);
+ if (session_index)
+ obj.addmember("session_index").string(index.get());
+ if (authncontext_class) {
+ auto_ptr_char ac(authncontext_class);
+ obj.addmember("authncontext_class").string(ac.get());
+ }
+ if (authncontext_decl) {
+ auto_ptr_char ad(authncontext_decl);
+ obj.addmember("authncontext_decl").string(ad.get());
+ }
+
+ if (nameid) {
+ ostringstream namestr;
+ namestr << *nameid;
+ obj.addmember("nameid").string(namestr.str().c_str());
+ }
+
+ if (tokens) {
+ obj.addmember("assertions").list();
+ for (vector<const Assertion*>::const_iterator t = tokens->begin(); t!=tokens->end(); ++t) {
+ auto_ptr_char tokenid((*t)->getID());
+ DDF tokid = DDF(NULL).string(tokenid.get());
+ obj["assertions"].add(tokid);
+ }
+ }
+
+ if (attributes) {
+ DDF attr;
+ DDF attrlist = obj.addmember("attributes").list();
+ for (multimap<string,Attribute*>::const_iterator a=attributes->begin(); a!=attributes->end(); ++a) {
+ attr = a->second->marshall();
+ attrlist.add(attr);
+ }
+ }
+
+ ostringstream record;
+ record << obj;
+
+ m_log.debug("storing new session...");
+ time_t now = time(NULL);
+ if (!m_storage->createText(key.get(), "session", record.str().c_str(), now + m_cacheTimeout))
+ throw FatalProfileException("Attempted to create a session with a duplicate key.");
+
+ // Store the reverse mapping for logout.
+ auto_ptr_char name(nameid ? nameid->getName() : NULL);
+ try {
+ if (name.get())
+ insert(key.get(), expires, name.get(), index.get());
+ }
+ catch (exception& ex) {
+ m_log.error("error storing back mapping of NameID for logout: %s", ex.what());
+ }
+
+ if (tokens) {
+ try {
+ for (vector<const Assertion*>::const_iterator t = tokens->begin(); t!=tokens->end(); ++t) {
+ ostringstream tokenstr;
+ tokenstr << *(*t);
+ auto_ptr_char tokenid((*t)->getID());
+ if (!m_storage->createText(key.get(), tokenid.get(), tokenstr.str().c_str(), now + m_cacheTimeout))
+ throw IOException("duplicate assertion ID ($1)", params(1, tokenid.get()));
+ }
+ }
+ catch (exception& ex) {
+ m_log.error("error storing assertion along with session: %s", ex.what());
+ }
+ }
+
+ const char* pid = obj["entity_id"].string();
+ m_log.info("new session created: SessionID (%s) IdP (%s) Address (%s)", key.get(), pid ? pid : "none", client_addr);
+
+ // Transaction Logging
+ TransactionLog* xlog = application.getServiceProvider().getTransactionLog();
+ Locker locker(xlog);
+ xlog->log.infoStream() <<
+ "New session (ID: " <<
+ key.get() <<
+ ") with (applicationId: " <<
+ application.getId() <<
+ ") for principal from (IdP: " <<
+ (pid ? pid : "none") <<
+ ") at (ClientAddress: " <<
+ (client_addr ? client_addr : "none") <<
+ ") with (NameIdentifier: " <<
+ (name.get() ? name.get() : "none") <<
+ ")";
+
+ if (attributes) {
+ xlog->log.infoStream() <<
+ "Cached the following attributes with session (ID: " <<
+ key.get() <<
+ ") for (applicationId: " <<
+ application.getId() <<
+ ") {";
+ for (multimap<string,Attribute*>::const_iterator a=attributes->begin(); a!=attributes->end(); ++a)
+ xlog->log.infoStream() << "\t" << a->second->getId() << " (" << a->second->valueCount() << " values)";
+ xlog->log.info("}");
+ }
+
+ return key.get();
+}
+
+Session* SSCache::find(const char* key, const Application& application, const char* client_addr, time_t* timeout)
+{
+#ifdef _DEBUG
+ xmltooling::NDC ndc("find");
+#endif
+
+ m_log.debug("searching for session (%s)", key);
+
+ time_t lastAccess;
+ string record;
+ int ver = m_storage->readText(key, "session", &record, &lastAccess);
+ if (!ver)
+ return NULL;
+
+ m_log.debug("reconstituting session and checking validity");
+
+ DDF obj;
+ istringstream in(record);
+ in >> obj;
+
+ if (!XMLString::equals(obj["application_id"].string(), application.getId())) {
+ m_log.error("an application (%s) tried to access another application's session", application.getId());
+ obj.destroy();
+ return NULL;
+ }
+
+ if (client_addr) {
+ if (m_log.isDebugEnabled())
+ m_log.debug("comparing client address %s against %s", client_addr, obj["client_addr"].string());
+ if (strcmp(obj["client_addr"].string(),client_addr)) {
+ m_log.warn("client address mismatch");
+ remove(key, application);
+ RetryableProfileException ex(
+ "Your IP address ($1) does not match the address recorded at the time the session was established.",
+ params(1,client_addr)
+ );
+ string eid(obj["entity_id"].string());
+ obj.destroy();
+ if (eid.empty())
+ throw ex;
+ MetadataProvider* m=application.getMetadataProvider();
+ Locker locker(m);
+ annotateException(&ex,m->getEntityDescriptor(eid.c_str(),false)); // throws it
+ }
+ }
+
+ lastAccess -= m_cacheTimeout; // adjusts it back to the last time the record's timestamp was touched
+ time_t now=time(NULL);
+
+ if (timeout && *timeout > 0 && now - lastAccess >= *timeout) {
+ m_log.info("session timed out (ID: %s)", key);
+ remove(key, application);
+ RetryableProfileException ex("Your session has expired, and you must re-authenticate.");
+ string eid(obj["entity_id"].string());
+ obj.destroy();
+ if (eid.empty())
+ throw ex;
+ MetadataProvider* m=application.getMetadataProvider();
+ Locker locker(m);
+ annotateException(&ex,m->getEntityDescriptor(eid.c_str(),false)); // throws it
+ }
+
+ auto_ptr_XMLCh exp(obj["expires"].string());
+ if (exp.get()) {
+ DateTime iso(exp.get());
+ iso.parseDateTime();
+ if (now > iso.getEpoch()) {
+ m_log.info("session expired (ID: %s)", key);
+ remove(key, application);
+ RetryableProfileException ex("Your session has expired, and you must re-authenticate.");
+ string eid(obj["entity_id"].string());
+ obj.destroy();
+ if (eid.empty())
+ throw ex;
+ MetadataProvider* m=application.getMetadataProvider();
+ Locker locker(m);
+ annotateException(&ex,m->getEntityDescriptor(eid.c_str(),false)); // throws it
+ }
+ }
+
+ if (timeout) {
+ // Update storage expiration, if possible.
+ try {
+ m_storage->updateContext(key, now + m_cacheTimeout);
+ }
+ catch (exception& ex) {
+ m_log.error("failed to update session expiration: %s", ex.what());
+ }
+ }
+
+ // Finally build the Session object.
+ try {
+ return new StoredSession(this, obj);
+ }
+ catch (exception&) {
+ obj.destroy();
+ throw;
+ }
+}
+
+void SSCache::remove(const char* key, const Application& application)
+{
+#ifdef _DEBUG
+ xmltooling::NDC ndc("remove");
+#endif
+
+ m_storage->deleteContext(key);
+ m_log.info("removed session (%s)", key);
+
+ TransactionLog* xlog = application.getServiceProvider().getTransactionLog();
+ Locker locker(xlog);
+ xlog->log.info("Destroyed session (applicationId: %s) (ID: %s)", application.getId(), key);
+}
+
+bool SSCache::matches(
+ const char* key,
+ const saml2md::EntityDescriptor* issuer,
+ const saml2::NameID& nameid,
+ const set<string>* indexes,
+ const Application& application
+ )
+{
+ auto_ptr_char entityID(issuer ? issuer->getEntityID() : NULL);
+ try {
+ Session* session = find(key, application);
+ if (session) {
+ Locker locker(session);
+ if (XMLString::equals(session->getEntityID(), entityID.get()) && session->getNameID() &&
+ stronglyMatches(issuer->getEntityID(), application.getXMLString("entityID").second, nameid, *session->getNameID())) {
+ return (!indexes || indexes->empty() || (session->getSessionIndex() ? (indexes->count(session->getSessionIndex())>0) : false));
+ }
+ }
+ }
+ catch (exception& ex) {
+ m_log.error("error while matching session (%s): %s", key, ex.what());
+ }
+ return false;
+}
+
+vector<string>::size_type SSCache::logout(
+ const saml2md::EntityDescriptor* issuer,
+ const saml2::NameID& nameid,
+ const set<string>* indexes,
+ time_t expires,
+ const Application& application,
+ vector<string>& sessionsKilled
+ )
+{
+#ifdef _DEBUG
+ xmltooling::NDC ndc("logout");
+#endif
+
+ auto_ptr_char entityID(issuer ? issuer->getEntityID() : NULL);
+ auto_ptr_char name(nameid.getName());
+
+ m_log.info("request to logout sessions from (%s) for (%s)", entityID.get() ? entityID.get() : "unknown", name.get());
+
+ if (strlen(name.get()) > 255)
+ const_cast<char*>(name.get())[255] = 0;
+
+ // Read in potentially matching sessions.
+ string record;
+ int ver = m_storage->readText("Logout", name.get(), &record);
+ if (ver == 0) {
+ m_log.debug("no active sessions to logout for supplied issuer and subject");
+ return 0;
+ }
+
+ DDF obj;
+ DDFJanitor jobj(obj);
+ istringstream in(record);
+ in >> obj;
+
+ // The record contains child lists for each known session index.
+ DDF key;
+ DDF sessions = obj.first();
+ while (sessions.islist()) {
+ if (!indexes || indexes->empty() || indexes->count(sessions.name())) {
+ key = sessions.first();
+ while (key.isstring()) {
+ // Fetch the session for comparison.
+ Session* session = NULL;
+ try {
+ session = find(key.string(), application);
+ }
+ catch (exception& ex) {
+ m_log.error("error locating session (%s): %s", key.string(), ex.what());
+ }
+
+ if (session) {
+ Locker locker(session);
+ // Same issuer?
+ if (XMLString::equals(session->getEntityID(), entityID.get())) {
+ // Same NameID?
+ if (stronglyMatches(issuer->getEntityID(), application.getXMLString("entityID").second, nameid, *session->getNameID())) {
+ sessionsKilled.push_back(key.string());
+ key.destroy();
+ }
+ else {
+ m_log.debug("session (%s) contained a non-matching NameID, leaving it alone", key.string());
+ }
+ }
+ else {
+ m_log.debug("session (%s) established by different IdP, leaving it alone", key.string());
+ }
+ }
+ else {
+ // Session's gone, so...
+ sessionsKilled.push_back(key.string());
+ key.destroy();
+ }
+ key = sessions.next();
+ }
+
+ // No sessions left for this index?
+ if (sessions.first().isnull())
+ sessions.destroy();
+ }
+ sessions = obj.next();
+ }
+
+ if (obj.first().isnull())
+ obj.destroy();
+
+ // If possible, write back the mapping record (this isn't crucial).
+ try {
+ if (obj.isnull()) {
+ m_storage->deleteText("Logout", name.get());
+ }
+ else if (!sessionsKilled.empty()) {
+ ostringstream out;
+ out << obj;
+ if (m_storage->updateText("Logout", name.get(), out.str().c_str(), 0, ver) <= 0)
+ m_log.warn("logout mapping record changed behind us, leaving it alone");
+ }
+ }
+ catch (exception& ex) {
+ m_log.error("error updating logout mapping record: %s", ex.what());
+ }
+
+ return sessionsKilled.size();
+}
+
+bool SSCache::stronglyMatches(const XMLCh* idp, const XMLCh* sp, const saml2::NameID& n1, const saml2::NameID& n2) const
+{
+ if (!XMLString::equals(n1.getName(), n2.getName()))
+ return false;
+
+ const XMLCh* s1 = n1.getFormat();
+ const XMLCh* s2 = n2.getFormat();
+ if (!s1 || !*s1)
+ s1 = saml2::NameID::UNSPECIFIED;
+ if (!s2 || !*s2)
+ s2 = saml2::NameID::UNSPECIFIED;
+ if (!XMLString::equals(s1,s2))
+ return false;
+
+ s1 = n1.getNameQualifier();
+ s2 = n2.getNameQualifier();
+ if (!s1 || !*s1)
+ s1 = idp;
+ if (!s2 || !*s2)
+ s2 = idp;
+ if (!XMLString::equals(s1,s2))
+ return false;
+
+ s1 = n1.getSPNameQualifier();
+ s2 = n2.getSPNameQualifier();
+ if (!s1 || !*s1)
+ s1 = sp;
+ if (!s2 || !*s2)
+ s2 = sp;
+ if (!XMLString::equals(s1,s2))
+ return false;
+
+ return true;
+}
+
+void SSCache::receive(DDF& in, ostream& out)
+{
+#ifdef _DEBUG
+ xmltooling::NDC ndc("receive");
+#endif
+
+ if (!strcmp(in.name(),"find::"REMOTED_SESSION_CACHE"::SessionCache")) {
+ const char* key=in["key"].string();
+ if (!key)
+ throw ListenerException("Required parameters missing for session removal.");
+
+ const Application* app = SPConfig::getConfig().getServiceProvider()->getApplication(in["application_id"].string());
+ if (!app)
+ throw ListenerException("Application not found, check configuration?");
+
+ // Do an unversioned read.
+ string record;
+ time_t lastAccess;
+ if (!m_storage->readText(key, "session", &record, &lastAccess)) {
+ DDF ret(NULL);
+ DDFJanitor jan(ret);
+ out << ret;
+ return;
+ }
+
+ // Adjust for expiration to recover last access time and check timeout.
+ lastAccess -= m_cacheTimeout;
+ time_t now=time(NULL);
+
+ // See if we need to check for a timeout.
+ if (in["timeout"].string()) {
+ time_t timeout = 0;
+ auto_ptr_XMLCh dt(in["timeout"].string());
+ DateTime dtobj(dt.get());
+ dtobj.parseDateTime();
+ timeout = dtobj.getEpoch();
+
+ if (timeout > 0 && now - lastAccess >= timeout) {
+ m_log.info("session timed out (ID: %s)", key);
+ remove(key,*app);
+ throw RetryableProfileException("Your session has expired, and you must re-authenticate.");
+ }
+
+ // Update storage expiration, if possible.
+ try {
+ m_storage->updateContext(key, now + m_cacheTimeout);
+ }
+ catch (exception& ex) {
+ m_log.error("failed to update session expiration: %s", ex.what());
+ }
+ }
+
+ // Send the record back.
+ out << record;
+ }
+ else if (!strcmp(in.name(),"touch::"REMOTED_SESSION_CACHE"::SessionCache")) {
+ const char* key=in["key"].string();
+ if (!key)
+ throw ListenerException("Required parameters missing for session check.");
+
+ // Do a versioned read.
+ string record;
+ time_t lastAccess;
+ int curver = in["version"].integer();
+ int ver = m_storage->readText(key, "session", &record, &lastAccess, curver);
+ if (ver == 0) {
+ m_log.warn("unsuccessful versioned read of session (ID: %s), caches out of sync?", key);
+ throw RetryableProfileException("Your session has expired, and you must re-authenticate.");
+ }
+
+ // Adjust for expiration to recover last access time and check timeout.
+ lastAccess -= m_cacheTimeout;
+ time_t now=time(NULL);
+
+ // See if we need to check for a timeout.
+ time_t timeout = 0;
+ auto_ptr_XMLCh dt(in["timeout"].string());
+ if (dt.get()) {
+ DateTime dtobj(dt.get());
+ dtobj.parseDateTime();
+ timeout = dtobj.getEpoch();
+ }
+
+ if (timeout > 0 && now - lastAccess >= timeout) {
+ m_log.info("session timed out (ID: %s)", key);
+ throw RetryableProfileException("Your session has expired, and you must re-authenticate.");
+ }
+
+ // Update storage expiration, if possible.
+ try {
+ m_storage->updateContext(key, now + m_cacheTimeout);
+ }
+ catch (exception& ex) {
+ m_log.error("failed to update session expiration: %s", ex.what());
+ }
+
+ if (ver > curver) {
+ // Send the record back.
+ out << record;
+ }
+ else {
+ DDF ret(NULL);
+ DDFJanitor jan(ret);
+ out << ret;
+ }
+ }
+ else if (!strcmp(in.name(),"remove::"REMOTED_SESSION_CACHE"::SessionCache")) {
+ const char* key=in["key"].string();
+ if (!key)
+ throw ListenerException("Required parameter missing for session removal.");
+
+ const Application* app = SPConfig::getConfig().getServiceProvider()->getApplication(in["application_id"].string());
+ if (!app)
+ throw ListenerException("Application not found, check configuration?");
+
+ remove(key,*app);
+ DDF ret(NULL);
+ DDFJanitor jan(ret);
+ out << ret;
+ }
+ else if (!strcmp(in.name(),"getAssertion::"REMOTED_SESSION_CACHE"::SessionCache")) {
+ const char* key=in["key"].string();
+ const char* id=in["id"].string();
+ if (!key || !id)
+ throw ListenerException("Required parameters missing for assertion retrieval.");
+ string token;
+ if (!m_storage->readText(key, id, &token, NULL))
+ throw FatalProfileException("Assertion not found in cache.");
+ out << token;
+ }
+}