SSPCPP-616 - clean up concatenated string literals
[shibboleth/cpp-sp.git] / shibsp / handler / impl / AbstractHandler.cpp
index 38c7d92..d7adee0 100644 (file)
@@ -1,17 +1,21 @@
-/*
- *  Copyright 2001-2010 Internet2
+/**
+ * Licensed to the University Corporation for Advanced Internet
+ * Development, Inc. (UCAID) under one or more contributor license
+ * agreements. See the NOTICE file distributed with this work for
+ * additional information regarding copyright ownership.
  *
- * 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
+ * UCAID licenses this file to you 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
+ * 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.
+ * 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.
  */
 
 /**
@@ -34,6 +38,9 @@
 
 #include <vector>
 #include <fstream>
+#include <boost/bind.hpp>
+#include <boost/lexical_cast.hpp>
+#include <boost/algorithm/string.hpp>
 #include <xmltooling/XMLToolingConfig.h>
 #include <xmltooling/util/PathResolver.h>
 #include <xmltooling/util/URLEncoder.h>
@@ -64,37 +71,23 @@ using namespace shibsp;
 using namespace samlconstants;
 using namespace xmltooling;
 using namespace xercesc;
+using namespace boost;
 using namespace std;
 
 namespace shibsp {
-
     SHIBSP_DLLLOCAL PluginManager< Handler,string,pair<const DOMElement*,const char*> >::Factory SAML1ConsumerFactory;
     SHIBSP_DLLLOCAL PluginManager< Handler,string,pair<const DOMElement*,const char*> >::Factory SAML2ConsumerFactory;
     SHIBSP_DLLLOCAL PluginManager< Handler,string,pair<const DOMElement*,const char*> >::Factory SAML2ArtifactResolutionFactory;
     SHIBSP_DLLLOCAL PluginManager< Handler,string,pair<const DOMElement*,const char*> >::Factory SAML2LogoutFactory;
     SHIBSP_DLLLOCAL PluginManager< Handler,string,pair<const DOMElement*,const char*> >::Factory SAML2NameIDMgmtFactory;
     SHIBSP_DLLLOCAL PluginManager< Handler,string,pair<const DOMElement*,const char*> >::Factory AssertionLookupFactory;
+    SHIBSP_DLLLOCAL PluginManager< Handler,string,pair<const DOMElement*,const char*> >::Factory AttributeCheckerFactory;
     SHIBSP_DLLLOCAL PluginManager< Handler,string,pair<const DOMElement*,const char*> >::Factory DiscoveryFeedFactory;
+    SHIBSP_DLLLOCAL PluginManager< Handler,string,pair<const DOMElement*,const char*> >::Factory ExternalAuthFactory;
     SHIBSP_DLLLOCAL PluginManager< Handler,string,pair<const DOMElement*,const char*> >::Factory MetadataGeneratorFactory;
     SHIBSP_DLLLOCAL PluginManager< Handler,string,pair<const DOMElement*,const char*> >::Factory StatusHandlerFactory;
     SHIBSP_DLLLOCAL PluginManager< Handler,string,pair<const DOMElement*,const char*> >::Factory SessionHandlerFactory;
 
-    void SHIBSP_DLLLOCAL absolutize(const HTTPRequest& request, string& url) {
-        if (url.empty())
-            url = '/';
-        if (url[0] == '/') {
-            // Compute a URL to the root of the site.
-            int port = request.getPort();
-            const char* scheme = request.getScheme();
-            string root = string(scheme) + "://" + request.getHostname();
-            if ((!strcmp(scheme,"http") && port!=80) || (!strcmp(scheme,"https") && port!=443)) {
-                ostringstream portstr;
-                portstr << port;
-                root += ":" + portstr.str();
-            }
-            url = root + url;
-        }
-    }
 
     void SHIBSP_DLLLOCAL generateRandomHex(std::string& buf, unsigned int len) {
         static char DIGITS[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
@@ -111,8 +104,6 @@ namespace shibsp {
             buf += (DIGITS[0x0F & b2]);
         }
     }
-
-
 };
 
 void SHIBSP_API shibsp::registerHandlers()
@@ -132,7 +123,9 @@ void SHIBSP_API shibsp::registerHandlers()
     conf.ArtifactResolutionServiceManager.registerFactory(SAML20_BINDING_SOAP, SAML2ArtifactResolutionFactory);
 
     conf.HandlerManager.registerFactory(SAML20_BINDING_URI, AssertionLookupFactory);
+    conf.HandlerManager.registerFactory(ATTR_CHECKER_HANDLER, AttributeCheckerFactory);
     conf.HandlerManager.registerFactory(DISCOVERY_FEED_HANDLER, DiscoveryFeedFactory);
+    conf.HandlerManager.registerFactory(EXTERNAL_AUTH_HANDLER, ExternalAuthFactory);
     conf.HandlerManager.registerFactory(METADATA_GENERATOR_HANDLER, MetadataGeneratorFactory);
     conf.HandlerManager.registerFactory(STATUS_HANDLER, StatusHandlerFactory);
     conf.HandlerManager.registerFactory(SESSION_HANDLER, SessionHandlerFactory);
@@ -175,7 +168,7 @@ const XMLCh* Handler::getProtocolFamily() const
 
 void Handler::log(SPRequest::SPLogLevel level, const string& msg) const
 {
-    Category::getInstance(SHIBSP_LOGCAT".Handler").log(
+    Category::getInstance(SHIBSP_LOGCAT ".Handler").log(
         (level == SPRequest::SPDebug ? Priority::DEBUG :
         (level == SPRequest::SPInfo ? Priority::INFO :
         (level == SPRequest::SPWarn ? Priority::WARN :
@@ -184,6 +177,54 @@ void Handler::log(SPRequest::SPLogLevel level, const string& msg) const
         );
 }
 
+void Handler::cleanRelayState(
+    const Application& application, const xmltooling::HTTPRequest& request, xmltooling::HTTPResponse& response
+    ) const
+{
+    // Only cookie-based relay state requires cleaning.
+    pair<bool,const char*> mech = getString("relayState");
+    if (!mech.first) {
+        // Check for setting on Sessions element.
+        const PropertySet* sessionprop = application.getPropertySet("Sessions");
+        if (sessionprop)
+            mech = sessionprop->getString("relayState");
+    }
+    if (!mech.first || !mech.second || strncmp(mech.second, "cookie", 6))
+        return;
+    
+    int maxCookies = 25,purgedCookies = 0;
+    mech.second += 6;
+    if (*mech.second == ':' && isdigit(*(++mech.second))) {
+        maxCookies = atoi(mech.second);
+        if (maxCookies == 0)
+            maxCookies = 25;
+    }
+
+    string exp;
+
+    // Walk the list of cookies backwards by name.
+    const map<string,string>& cookies = request.getCookies();
+    for (map<string,string>::const_reverse_iterator i = cookies.rbegin(); i != cookies.rend(); ++i) {
+        // Process relay state cookies only.
+        if (starts_with(i->first, "_shibstate_")) {
+            if (maxCookies > 0) {
+                // Keep it, but count it against the limit.
+                --maxCookies;
+            }
+            else {
+                // We're over the limit, so everything here and older gets cleaned up.
+                if (exp.empty())
+                    exp = string(application.getCookieNameProps("_shibstate_").second) + "; expires=Mon, 01 Jan 2001 00:00:00 GMT";
+                response.setCookie(i->first.c_str(), exp.c_str());
+                ++purgedCookies;
+            }
+        }
+    }
+
+    if (purgedCookies > 0)
+        log(SPRequest::SPDebug, string("purged ") + lexical_cast<string>(purgedCookies) + " stale relay state cookie(s) from client");
+}
+
 void Handler::preserveRelayState(const Application& application, HTTPResponse& response, string& relayState) const
 {
     // The empty string implies no state to deal with.
@@ -201,33 +242,41 @@ void Handler::preserveRelayState(const Application& application, HTTPResponse& r
     if (!mech.first || !mech.second || !*mech.second)
         return;
 
-    if (!strcmp(mech.second, "cookie")) {
+    if (!strncmp(mech.second, "cookie", 6)) {
         // Here we store the state in a cookie and send a fixed
         // value so we can recognize it on the way back.
-        if (relayState.find("cookie:") != 0) {
-            const URLEncoder* urlenc = XMLToolingConfig::getConfig().getURLEncoder();
-            pair<string,const char*> shib_cookie=application.getCookieNameProps("_shibstate_");
-            string stateval = urlenc->encode(relayState.c_str()) + shib_cookie.second;
+        if (relayState.find("cookie:") != 0 && relayState.find("ss:") != 0) {
+            pair<string,const char*> shib_cookie = application.getCookieNameProps("_shibstate_");
+            string stateval = XMLToolingConfig::getConfig().getURLEncoder()->encode(relayState.c_str()) + shib_cookie.second;
             // Generate a random key for the cookie name instead of the fixed name.
             string rsKey;
-            generateRandomHex(rsKey,5);
+            generateRandomHex(rsKey, 4);
+            rsKey = lexical_cast<string>(time(nullptr)) + '_' + rsKey;
             shib_cookie.first = "_shibstate_" + rsKey;
-            response.setCookie(shib_cookie.first.c_str(),stateval.c_str());
+            response.setCookie(shib_cookie.first.c_str(), stateval.c_str());
             relayState = "cookie:" + rsKey;
         }
     }
-    else if (strstr(mech.second,"ss:")==mech.second) {
-        if (relayState.find("ss:") != 0) {
+    else if (!strncmp(mech.second, "ss:", 3)) {
+        if (relayState.find("cookie:") != 0 && relayState.find("ss:") != 0) {
             mech.second+=3;
             if (*mech.second) {
                 if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess)) {
 #ifndef SHIBSP_LITE
                     StorageService* storage = application.getServiceProvider().getStorageService(mech.second);
                     if (storage) {
+                        // Use a random key
                         string rsKey;
-                        generateRandomHex(rsKey,32);
-                        if (!storage->createString("RelayState", rsKey.c_str(), relayState.c_str(), time(nullptr) + 600))
-                            throw IOException("Attempted to insert duplicate storage key.");
+                        SAMLConfig::getConfig().generateRandomBytes(rsKey,32);
+                        rsKey = SAMLArtifact::toHex(rsKey);
+                        if (relayState.length() <= storage->getCapabilities().getStringSize()) {
+                            if (!storage->createString("RelayState", rsKey.c_str(), relayState.c_str(), time(nullptr) + 600))
+                                throw IOException("Collision generating in-memory relay state key.");
+                        }
+                        else {
+                            if (!storage->createText("RelayState", rsKey.c_str(), relayState.c_str(), time(nullptr) + 600))
+                                throw IOException("Collision generating in-memory relay state key.");
+                        }
                         relayState = string(mech.second-3) + ':' + rsKey;
                     }
                     else {
@@ -236,6 +285,8 @@ void Handler::preserveRelayState(const Application& application, HTTPResponse& r
                         log(SPRequest::SPError, msg);
                         relayState.erase();
                     }
+#else
+                    throw ConfigurationException("Lite version of library cannot be used out of process.");
 #endif
                 }
                 else if (SPConfig::getConfig().isEnabled(SPConfig::InProcess)) {
@@ -251,8 +302,9 @@ void Handler::preserveRelayState(const Application& application, HTTPResponse& r
             }
         }
     }
-    else
+    else {
         throw ConfigurationException("Unsupported relayState mechanism ($1).", params(1,mech.second));
+    }
 }
 
 void Handler::recoverRelayState(
@@ -263,7 +315,7 @@ void Handler::recoverRelayState(
 
     // Look for StorageService-backed state of the form "ss:SSID:key".
     const char* state = relayState.c_str();
-    if (strstr(state,"ss:")==state) {
+    if (strstr(state,"ss:") == state) {
         state += 3;
         const char* key = strchr(state,':');
         if (key) {
@@ -278,11 +330,18 @@ void Handler::recoverRelayState(
                         if (storage->readString("RelayState",ssid.c_str(),&relayState) > 0) {
                             if (clear)
                                 storage->deleteString("RelayState",ssid.c_str());
-                            absolutize(request, relayState);
+                            request.absolutize(relayState);
+                            return;
+                        }
+                        else if (storage->readText("RelayState",ssid.c_str(),&relayState) > 0) {
+                            if (clear)
+                                storage->deleteText("RelayState",ssid.c_str());
+                            request.absolutize(relayState);
                             return;
                         }
-                        else
+                        else {
                             relayState.erase();
+                        }
                     }
                     else {
                         string msg("Storage-backed RelayState with invalid StorageService ID (");
@@ -305,7 +364,7 @@ void Handler::recoverRelayState(
                     }
                     else {
                         relayState = out.string();
-                        absolutize(request, relayState);
+                        request.absolutize(relayState);
                         return;
                     }
                 }
@@ -313,8 +372,9 @@ void Handler::recoverRelayState(
         }
     }
 
-    // Look for cookie-backed state of the form "cookie:key".
-    if (strstr(state,"cookie:")==state) {
+    // Look for cookie-backed state of the form "cookie:timestamp_key".
+    state = relayState.c_str();
+    if (strstr(state,"cookie:") == state) {
         state += 7;
         if (*state) {
             // Pull the value from the "relay state" cookie.
@@ -323,17 +383,16 @@ void Handler::recoverRelayState(
             state = request.getCookie(relay_cookie.first.c_str());
             if (state && *state) {
                 // URL-decode the value.
-                char* rscopy=strdup(state);
+                char* rscopy = strdup(state);
                 XMLToolingConfig::getConfig().getURLEncoder()->decode(rscopy);
                 relayState = rscopy;
                 free(rscopy);
-
                 if (clear) {
                     string exp(relay_cookie.second);
                     exp += "; expires=Mon, 01 Jan 2001 00:00:00 GMT";
                     response.setCookie(relay_cookie.first.c_str(), exp.c_str());
                 }
-                absolutize(request, relayState);
+                request.absolutize(relayState);
                 return;
             }
         }
@@ -350,13 +409,13 @@ void Handler::recoverRelayState(
             relayState = '/';
     }
 
-    absolutize(request, relayState);
+    request.absolutize(relayState);
 }
 
 AbstractHandler::AbstractHandler(
     const DOMElement* e, Category& log, DOMNodeFilter* filter, const map<string,string>* remapper
     ) : m_log(log), m_configNS(shibspconstants::SHIB2SPCONFIG_NS) {
-    load(e,nullptr,filter,remapper);
+    load(e, nullptr, filter, remapper);
 }
 
 AbstractHandler::~AbstractHandler()
@@ -390,7 +449,7 @@ void AbstractHandler::checkError(const XMLObject* response, const saml2md::RoleD
             const saml2p::StatusCode* sc = status->getStatusCode();
             const XMLCh* code = sc ? sc->getValue() : nullptr;
             if (code && !XMLString::equals(code,saml2p::StatusCode::SUCCESS)) {
-                FatalProfileException ex("SAML response contained an error.");
+                FatalProfileException ex("SAML response reported an IdP error.");
                 annotateException(&ex, role, status);   // throws it
             }
         }
@@ -403,19 +462,8 @@ void AbstractHandler::checkError(const XMLObject* response, const saml2md::RoleD
             const saml1p::StatusCode* sc = status->getStatusCode();
             const xmltooling::QName* code = sc ? sc->getValue() : nullptr;
             if (code && *code != saml1p::StatusCode::SUCCESS) {
-                FatalProfileException ex("SAML response contained an error.");
-                ex.addProperty("statusCode", code->toString().c_str());
-                if (sc->getStatusCode()) {
-                    code = sc->getStatusCode()->getValue();
-                    if (code)
-                        ex.addProperty("statusCode2", code->toString().c_str());
-                }
-                if (status->getStatusMessage()) {
-                    auto_ptr_char msg(status->getStatusMessage()->getMessage());
-                    if (msg.get() && *msg.get())
-                        ex.addProperty("statusMessage", msg.get());
-                }
-                ex.raise();
+                FatalProfileException ex("SAML response reported an IdP error.");
+                annotateException(&ex, role, status);   // throws it
             }
         }
     }
@@ -456,11 +504,10 @@ long AbstractHandler::sendMessage(
     const EntityDescriptor* entity = role ? dynamic_cast<const EntityDescriptor*>(role->getParent()) : nullptr;
     const PropertySet* relyingParty = application.getRelyingParty(entity);
     pair<bool,const char*> flag = signIfPossible ? make_pair(true,(const char*)"true") : relyingParty->getString("signing");
-    if (role && flag.first &&
-        (!strcmp(flag.second, "true") ||
-            (encoder.isUserAgentPresent() && !strcmp(flag.second, "front")) ||
-            (!encoder.isUserAgentPresent() && !strcmp(flag.second, "back")))) {
-        CredentialResolver* credResolver=application.getCredentialResolver();
+    if (flag.first && (!strcmp(flag.second, "true") ||
+                        (encoder.isUserAgentPresent() && !strcmp(flag.second, "front")) ||
+                        (!encoder.isUserAgentPresent() && !strcmp(flag.second, "back")))) {
+        CredentialResolver* credResolver = application.getCredentialResolver();
         if (credResolver) {
             Locker credLocker(credResolver);
             const Credential* cred = nullptr;
@@ -566,17 +613,19 @@ void AbstractHandler::preservePostData(
             if (storage) {
                 // Use a random key
                 string rsKey;
-                SAMLConfig::getConfig().generateRandomBytes(rsKey,20);
+                SAMLConfig::getConfig().generateRandomBytes(rsKey, 32);
                 rsKey = SAMLArtifact::toHex(rsKey);
                 ostringstream out;
                 out << postData;
-                if (!storage->createString("PostData", rsKey.c_str(), out.str().c_str(), time(nullptr) + 600))
+                if (!storage->createText("PostData", rsKey.c_str(), out.str().c_str(), time(nullptr) + 600))
                     throw IOException("Attempted to insert duplicate storage key.");
                 postkey = string(mech.second-3) + ':' + rsKey;
             }
             else {
                 m_log.error("storage-backed PostData mechanism with invalid StorageService ID (%s)", mech.second);
             }
+#else
+            throw ConfigurationException("Lite version of library cannot be used out of process.");
 #endif
         }
         else if (SPConfig::getConfig().isEnabled(SPConfig::InProcess)) {
@@ -630,8 +679,8 @@ DDF AbstractHandler::recoverPostData(
 #ifndef SHIBSP_LITE
                     StorageService* storage = conf.getServiceProvider()->getStorageService(ssid.c_str());
                     if (storage) {
-                        if (storage->readString("PostData", key, &ssid) > 0) {
-                            storage->deleteString("PostData", key);
+                        if (storage->readText("PostData", key, &ssid) > 0) {
+                            storage->deleteText("PostData", key);
                             istringstream inret(ssid);
                             DDF ret;
                             inret >> ret;
@@ -696,8 +745,8 @@ long AbstractHandler::sendPostResponse(
 
     httpResponse.setContentType("text/html");
     if (!postExpire.first || postExpire.second) {
-        httpResponse.setResponseHeader("Expires", "01-Jan-1997 12:00:00 GMT");
-        httpResponse.setResponseHeader("Cache-Control", "no-cache, no-store, must-revalidate, private");
+        httpResponse.setResponseHeader("Expires", "Wed, 01 Jan 1997 12:00:00 GMT");
+        httpResponse.setResponseHeader("Cache-Control", "no-cache, no-store, must-revalidate, private, max-age=0");
         httpResponse.setResponseHeader("Pragma", "no-cache");
     }
     return httpResponse.sendResponse(str);
@@ -723,8 +772,8 @@ pair<string,const char*> AbstractHandler::getPostCookieNameProps(const Applicati
 DDF AbstractHandler::getPostData(const Application& application, const HTTPRequest& request) const
 {
     string contentType = request.getContentType();
-    if (contentType.compare("application/x-www-form-urlencoded") == 0) {
-        const PropertySet* props=application.getPropertySet("Sessions");
+    if (contentType.find("application/x-www-form-urlencoded") != string::npos) {
+        const PropertySet* props = application.getPropertySet("Sessions");
         pair<bool,unsigned int> plimit = props ? props->getUnsignedInt("postLimit") : pair<bool,unsigned int>(false,0);
         if (!plimit.first)
             plimit.second = 1024 * 1024;
@@ -799,8 +848,14 @@ pair<bool,unsigned int> AbstractHandler::getUnsignedInt(const char* name, const
 {
     if (type & HANDLER_PROPERTY_REQUEST) {
         const char* param = request.getParameter(name);
-        if (param && *param)
-            return pair<bool,unsigned int>(true, strtol(param,nullptr,10));
+        if (param && *param) {
+            try {
+                return pair<bool,unsigned int>(true, lexical_cast<unsigned int>(param));
+            }
+            catch (bad_lexical_cast&) {
+                return pair<bool,unsigned int>(false,0);
+            }
+        }
     }
     
     if (type & HANDLER_PROPERTY_MAP) {