Path resolution for error templates.
[shibboleth/sp.git] / shibsp / ServiceProvider.cpp
index 5af4e4b..df7cf81 100644 (file)
 #include <sstream>
 #include <xmltooling/XMLToolingConfig.h>
 #include <xmltooling/util/NDC.h>
+#include <xmltooling/util/PathResolver.h>
 #include <xmltooling/util/URLEncoder.h>
 #include <xmltooling/util/XMLHelper.h>
 
 using namespace shibsp;
+using namespace xmltooling::logging;
 using namespace xmltooling;
 using namespace std;
 
 namespace shibsp {
     SHIBSP_DLLLOCAL PluginManager<ServiceProvider,string,const DOMElement*>::Factory XMLServiceProviderFactory;
 
-    long SHIBSP_DLLLOCAL sendError(SPRequest& request, const Application* app, const char* page, TemplateParameters& tp, bool mayRedirect=false)
+    long SHIBSP_DLLLOCAL sendError(
+        Category& log, SPRequest& request, const Application* app, const char* page, TemplateParameters& tp, bool mayRedirect=true
+        )
     {
+        // The properties we need can be set in the RequestMap, or the Errors element.
+        bool mderror = dynamic_cast<const opensaml::saml2md::MetadataException*>(tp.getRichException())!=NULL;
+        pair<bool,const char*> redirectErrors = pair<bool,const char*>(false,NULL);
+        pair<bool,const char*> pathname = pair<bool,const char*>(false,NULL);
+        const PropertySet* props=app ? app->getPropertySet("Errors") : NULL;
+
+        try {
+            RequestMapper::Settings settings = request.getRequestSettings();
+            if (mderror)
+                pathname = settings.first->getString("metadataError");
+            if (!pathname.first) {
+                string pagename(page);
+                pagename += "Error";
+                pathname = settings.first->getString(pagename.c_str());
+            }
+            if (mayRedirect)
+                redirectErrors = settings.first->getString("redirectErrors");
+        }
+        catch (exception& ex) {
+            log.error(ex.what());
+        }
+
         if (mayRedirect) {
             // Check for redirection on errors instead of template.
-            pair<bool,const char*> redirectErrors = app ? app->getString("redirectErrors") : pair<bool,const char*>(false,NULL);
+            if (!redirectErrors.first && props)
+                redirectErrors = props->getString("redirectErrors");
             if (redirectErrors.first) {
                 string loc(redirectErrors.second);
                 loc = loc + '?' + tp.toQueryString();
@@ -61,26 +88,29 @@ namespace shibsp {
         request.setResponseHeader("Expires","01-Jan-1997 12:00:00 GMT");
         request.setResponseHeader("Cache-Control","private,no-store,no-cache");
     
-        const PropertySet* props=app ? app->getPropertySet("Errors") : NULL;
-        if (props) {
-            pair<bool,const char*> p=props->getString(page);
-            if (p.first) {
-                ifstream infile(p.second);
-                if (infile) {
-                    tp.setPropertySet(props);
-                    stringstream str;
-                    XMLToolingConfig::getConfig().getTemplateEngine()->run(infile, str, tp, tp.getRichException());
-                    return request.sendResponse(str);
-                }
-            }
-            else if (!strcmp(page,"access")) {
-                istringstream msg("Access Denied");
-                return request.sendResponse(msg, HTTPResponse::XMLTOOLING_HTTP_STATUS_FORBIDDEN);
+        if (!pathname.first && props) {
+            if (mderror)
+                pathname=props->getString("metadata");
+            if (!pathname.first)
+                pathname=props->getString(page);
+        }
+        if (pathname.first) {
+            string fname(pathname.second);
+            ifstream infile(XMLToolingConfig::getConfig().getPathResolver()->resolve(fname, PathResolver::XMLTOOLING_CFG_FILE).c_str());
+            if (infile) {
+                tp.setPropertySet(props);
+                stringstream str;
+                XMLToolingConfig::getConfig().getTemplateEngine()->run(infile, str, tp, tp.getRichException());
+                return request.sendResponse(str);
             }
         }
+        
+        if (!strcmp(page,"access")) {
+            istringstream msg("Access Denied");
+            return request.sendResponse(msg, HTTPResponse::XMLTOOLING_HTTP_STATUS_UNAUTHORIZED);
+        }
     
-        string errstr = string("sendError could not process error template (") + page + ")";
-        request.log(SPRequest::SPError, errstr);
+        log.error("sendError could not process error template (%s)", page);
         istringstream msg("Internal Server Error. Please contact the site administrator.");
         return request.sendError(msg);
     }
@@ -89,6 +119,7 @@ namespace shibsp {
         request.clearHeader("Shib-Session-ID", "HTTP_SHIB_SESSION_ID");
         request.clearHeader("Shib-Identity-Provider", "HTTP_SHIB_IDENTITY_PROVIDER");
         request.clearHeader("Shib-Authentication-Method", "HTTP_SHIB_AUTHENTICATION_METHOD");
+        request.clearHeader("Shib-Authentication-Instant", "HTTP_SHIB_AUTHENTICATION_INSTANT");
         request.clearHeader("Shib-AuthnContext-Class", "HTTP_SHIB_AUTHNCONTEXT_CLASS");
         request.clearHeader("Shib-AuthnContext-Decl", "HTTP_SHIB_AUTHNCONTEXT_DECL");
         request.clearHeader("Shib-Assertion-Count", "HTTP_SHIB_ASSERTION_COUNT");
@@ -108,6 +139,7 @@ pair<bool,long> ServiceProvider::doAuthentication(SPRequest& request, bool handl
 #ifdef _DEBUG
     xmltooling::NDC ndc("doAuthentication");
 #endif
+    Category& log = Category::getInstance(SHIBSP_LOGCAT".ServiceProvider");
 
     const Application* app=NULL;
     string targetURL = request.getRequestURL();
@@ -136,7 +168,7 @@ pair<bool,long> ServiceProvider::doAuthentication(SPRequest& request, bool handl
                 else {
                     TemplateParameters tp;
                     tp.m_map["requestURL"] = targetURL.substr(0,targetURL.find('?'));
-                    return make_pair(true,sendError(request, app, "ssl", tp));
+                    return make_pair(true,sendError(log, request, app, "ssl", tp, false));
                 }
             }
         }
@@ -178,7 +210,7 @@ pair<bool,long> ServiceProvider::doAuthentication(SPRequest& request, bool handl
             session = request.getSession();
         }
         catch (exception& e) {
-            request.log(SPRequest::SPWarn, string("error during session lookup: ") + e.what());
+            log.warn("error during session lookup: %s", e.what());
             // If it's not a retryable session failure, we throw to the outer handler for reporting.
             if (dynamic_cast<opensaml::RetryableProfileException*>(&e)==NULL)
                 throw;
@@ -193,11 +225,11 @@ pair<bool,long> ServiceProvider::doAuthentication(SPRequest& request, bool handl
             const Handler* initiator=NULL;
             if (requireSessionWith.first) {
                 initiator=app->getSessionInitiatorById(requireSessionWith.second);
-                if (!initiator)
+                if (!initiator) {
                     throw ConfigurationException(
-                        "No session initiator found with id ($1), check requireSessionWith command.",
-                        params(1,requireSessionWith.second)
+                        "No session initiator found with id ($1), check requireSessionWith command.", params(1,requireSessionWith.second)
                         );
+                }
             }
             else {
                 initiator=app->getDefaultSessionInitiator();
@@ -210,23 +242,14 @@ pair<bool,long> ServiceProvider::doAuthentication(SPRequest& request, bool handl
 
         // We're done.  Everything is okay.  Nothing to report.  Nothing to do..
         // Let the caller decide how to proceed.
-        request.log(SPRequest::SPDebug, "doAuthentication succeeded");
-        return make_pair(false,0);
+        log.debug("doAuthentication succeeded");
+        return make_pair(false,0L);
     }
     catch (exception& e) {
         TemplateParameters tp(&e);
         tp.m_map["requestURL"] = targetURL.substr(0,targetURL.find('?'));
-        return make_pair(true,sendError(request, app, "session", tp));
+        return make_pair(true,sendError(log, request, app, "session", tp));
     }
-#ifndef _DEBUG
-    catch (...) {
-        TemplateParameters tp;
-        tp.m_map["errorType"] = "Unexpected Error";
-        tp.m_map["errorText"] = "Caught an unknown exception.";
-        tp.m_map["requestURL"] = targetURL.substr(0,targetURL.find('?'));
-        return make_pair(true,sendError(request, app, "session", tp));
-    }
-#endif
 }
 
 pair<bool,long> ServiceProvider::doAuthorization(SPRequest& request) const
@@ -234,6 +257,7 @@ pair<bool,long> ServiceProvider::doAuthorization(SPRequest& request) const
 #ifdef _DEBUG
     xmltooling::NDC ndc("doAuthorization");
 #endif
+    Category& log = Category::getInstance(SHIBSP_LOGCAT".ServiceProvider");
 
     const Application* app=NULL;
     string targetURL = request.getRequestURL();
@@ -265,40 +289,37 @@ pair<bool,long> ServiceProvider::doAuthorization(SPRequest& request) const
                 session = request.getSession(false);
             }
             catch (exception& e) {
-                request.log(SPRequest::SPWarn, string("unable to obtain session to pass to access control provider: ") + e.what());
+                log.warn("unable to obtain session to pass to access control provider: %s", e.what());
             }
        
             Locker acllock(settings.second);
-            if (settings.second->authorized(request,session)) {
-                // Let the caller decide how to proceed.
-                request.log(SPRequest::SPDebug, "access control provider granted access");
-                return make_pair(false,0);
-            }
-            else {
-                request.log(SPRequest::SPWarn, "access control provider denied access");
-                TemplateParameters tp;
-                tp.m_map["requestURL"] = targetURL;
-                return make_pair(true,sendError(request, app, "access", tp));
+            switch (settings.second->authorized(request,session)) {
+                case AccessControl::shib_acl_true:
+                    log.debug("access control provider granted access");
+                    return make_pair(true,request.returnOK());
+
+                case AccessControl::shib_acl_false:
+                {
+                    log.warn("access control provider denied access");
+                    TemplateParameters tp;
+                    tp.m_map["requestURL"] = targetURL;
+                    return make_pair(true,sendError(log, request, app, "access", tp, false));
+                }
+
+                default:
+                    // Use the "DECLINE" interface to signal we don't know what to do.
+                    return make_pair(true,request.returnDecline());
             }
-            return make_pair(false,0);
         }
-        else
+        else {
             return make_pair(true,request.returnDecline());
+        }
     }
     catch (exception& e) {
         TemplateParameters tp(&e);
         tp.m_map["requestURL"] = targetURL.substr(0,targetURL.find('?'));
-        return make_pair(true,sendError(request, app, "access", tp));
+        return make_pair(true,sendError(log, request, app, "access", tp));
     }
-#ifndef _DEBUG
-    catch (...) {
-        TemplateParameters tp;
-        tp.m_map["errorType"] = "Unexpected Error";
-        tp.m_map["errorText"] = "Caught an unknown exception.";
-        tp.m_map["requestURL"] = targetURL.substr(0,targetURL.find('?'));
-        return make_pair(true,sendError(request, app, "access", tp));
-    }
-#endif
 }
 
 pair<bool,long> ServiceProvider::doExport(SPRequest& request, bool requireSession) const
@@ -306,6 +327,7 @@ pair<bool,long> ServiceProvider::doExport(SPRequest& request, bool requireSessio
 #ifdef _DEBUG
     xmltooling::NDC ndc("doExport");
 #endif
+    Category& log = Category::getInstance(SHIBSP_LOGCAT".ServiceProvider");
 
     const Application* app=NULL;
     string targetURL = request.getRequestURL();
@@ -319,7 +341,7 @@ pair<bool,long> ServiceProvider::doExport(SPRequest& request, bool requireSessio
             session = request.getSession(false);
         }
         catch (exception& e) {
-            request.log(SPRequest::SPWarn, string("unable to obtain session to export to request: ") +  e.what());
+            log.warn("unable to obtain session to export to request: %s", e.what());
                // If we have to have a session, then this is a fatal error.
                if (requireSession)
                        throw;
@@ -330,7 +352,7 @@ pair<bool,long> ServiceProvider::doExport(SPRequest& request, bool requireSessio
                if (requireSession)
                 throw opensaml::RetryableProfileException("Unable to obtain session to export to request.");
                else
-                       return make_pair(false,0);      // just bail silently
+                       return make_pair(false,0L);     // just bail silently
         }
         
         request.setHeader("Shib-Application-ID", app->getId());
@@ -340,6 +362,9 @@ pair<bool,long> ServiceProvider::doExport(SPRequest& request, bool requireSessio
         const char* hval = session->getEntityID();
         if (hval)
             request.setHeader("Shib-Identity-Provider", hval);
+        hval = session->getAuthnInstant();
+        if (hval)
+            request.setHeader("Shib-Authentication-Instant", hval);
         hval = session->getAuthnContextClassRef();
         if (hval) {
             request.setHeader("Shib-Authentication-Method", hval);
@@ -355,7 +380,7 @@ pair<bool,long> ServiceProvider::doExport(SPRequest& request, bool requireSessio
             const PropertySet* sessions=app->getPropertySet("Sessions");
             pair<bool,const char*> exportLocation = sessions ? sessions->getString("exportLocation") : pair<bool,const char*>(false,NULL);
             if (!exportLocation.first)
-                request.log(SPRequest::SPWarn, "can't export assertions without an exportLocation Sessions property");
+                log.warn("can't export assertions without an exportLocation Sessions property");
             else {
                 const URLEncoder* encoder = XMLToolingConfig::getConfig().getURLEncoder();
                 string exportName = "Shib-Assertion-00";
@@ -379,19 +404,10 @@ pair<bool,long> ServiceProvider::doExport(SPRequest& request, bool requireSessio
         }
 
         // Export the attributes.
-        bool remoteUserSet = false;
         const multimap<string,const Attribute*>& attributes = session->getIndexedAttributes();
         for (multimap<string,const Attribute*>::const_iterator a = attributes.begin(); a!=attributes.end(); ++a) {
-            const vector<string>& vals = a->second->getSerializedValues();
-
-            // See if this needs to be set as the REMOTE_USER value.
-            if (!remoteUserSet && !vals.empty() && app->getRemoteUserAttributeIds().count(a->first)) {
-                request.setRemoteUser(vals.front().c_str());
-                remoteUserSet = true;
-            }
-
-            // Handle the normal export case.
             string header(request.getSecureHeader(a->first.c_str()));
+            const vector<string>& vals = a->second->getSerializedValues();
             for (vector<string>::const_iterator v = vals.begin(); v!=vals.end(); ++v) {
                 if (!header.empty())
                     header += ";";
@@ -410,23 +426,30 @@ pair<bool,long> ServiceProvider::doExport(SPRequest& request, bool requireSessio
             }
             request.setHeader(a->first.c_str(), header.c_str());
         }
-    
-        return make_pair(false,0);
+
+        // Check for REMOTE_USER.
+        bool remoteUserSet = false;
+        const vector<string>& rmids = app->getRemoteUserAttributeIds();
+        for (vector<string>::const_iterator rmid = rmids.begin(); !remoteUserSet && rmid != rmids.end(); ++rmid) {
+            pair<multimap<string,const Attribute*>::const_iterator,multimap<string,const Attribute*>::const_iterator> matches =
+                attributes.equal_range(*rmid);
+            while (matches.first != matches.second) {
+                const vector<string>& vals = matches.first->second->getSerializedValues();
+                if (!vals.empty()) {
+                    request.setRemoteUser(vals.front().c_str());
+                    remoteUserSet = true;
+                    break;
+                }
+            }
+        }
+
+        return make_pair(false,0L);
     }
     catch (exception& e) {
         TemplateParameters tp(&e);
         tp.m_map["requestURL"] = targetURL.substr(0,targetURL.find('?'));
-        return make_pair(true,sendError(request, app, "session", tp));
-    }
-#ifndef _DEBUG
-    catch (...) {
-        TemplateParameters tp;
-        tp.m_map["errorType"] = "Unexpected Error";
-        tp.m_map["errorText"] = "Caught an unknown exception.";
-        tp.m_map["requestURL"] = targetURL.substr(0,targetURL.find('?'));
-        return make_pair(true,sendError(request, app, "session", tp));
+        return make_pair(true,sendError(log, request, app, "session", tp));
     }
-#endif
 }
 
 pair<bool,long> ServiceProvider::doHandler(SPRequest& request) const
@@ -434,6 +457,7 @@ pair<bool,long> ServiceProvider::doHandler(SPRequest& request) const
 #ifdef _DEBUG
     xmltooling::NDC ndc("doHandler");
 #endif
+    Category& log = Category::getInstance(SHIBSP_LOGCAT".ServiceProvider");
 
     const Application* app=NULL;
     string targetURL = request.getRequestURL();
@@ -442,6 +466,31 @@ pair<bool,long> ServiceProvider::doHandler(SPRequest& request) const
         RequestMapper::Settings settings = request.getRequestSettings();
         app = &(request.getApplication());
 
+        // If not SSL, check to see if we should block or redirect it.
+        if (!request.isSecure()) {
+            pair<bool,const char*> redirectToSSL = settings.first->getString("redirectToSSL");
+            if (redirectToSSL.first) {
+#ifdef HAVE_STRCASECMP
+                if (!strcasecmp("GET",request.getMethod()) || !strcasecmp("HEAD",request.getMethod())) {
+#else
+                if (!stricmp("GET",request.getMethod()) || !stricmp("HEAD",request.getMethod())) {
+#endif
+                    // Compute the new target URL
+                    string redirectURL = string("https://") + request.getHostname();
+                    if (strcmp(redirectToSSL.second,"443")) {
+                        redirectURL = redirectURL + ':' + redirectToSSL.second;
+                    }
+                    redirectURL += request.getRequestURI();
+                    return make_pair(true, request.sendRedirect(redirectURL.c_str()));
+                }
+                else {
+                    TemplateParameters tp;
+                    tp.m_map["requestURL"] = targetURL.substr(0,targetURL.find('?'));
+                    return make_pair(true,sendError(log, request, app, "ssl", tp, false));
+                }
+            }
+        }
+
         const char* handlerURL=request.getHandlerURL(targetURL.c_str());
         if (!handlerURL)
             throw ConfigurationException("Cannot determine handler from resource URL, check configuration.");
@@ -475,30 +524,10 @@ pair<bool,long> ServiceProvider::doHandler(SPRequest& request) const
        
         throw ConfigurationException("Configured Shibboleth handler failed to process the request.");
     }
-    catch (opensaml::saml2md::MetadataException& e) {
-        TemplateParameters tp(&e);
-        tp.m_map["requestURL"] = targetURL.substr(0,targetURL.find('?'));
-        // See if a metadata error page is installed.
-        const PropertySet* props=app ? app->getPropertySet("Errors") : NULL;
-        if (props) {
-            pair<bool,const char*> p=props->getString("metadata");
-            if (p.first)
-                return make_pair(true,sendError(request, app, "metadata", tp, true));
-        }
-        return make_pair(true,sendError(request, app, "session", tp, true));
-    }
     catch (exception& e) {
         TemplateParameters tp(&e);
         tp.m_map["requestURL"] = targetURL.substr(0,targetURL.find('?'));
-        return make_pair(true,sendError(request, app, "session", tp, true));
-    }
-#ifndef _DEBUG
-    catch (...) {
-        TemplateParameters tp;
-        tp.m_map["errorType"] = "Unexpected Error";
-        tp.m_map["errorText"] = "Caught an unknown exception.";
-        tp.m_map["requestURL"] = targetURL.substr(0,targetURL.find('?'));
-        return make_pair(true,sendError(request, app, "session", tp, true));
+        tp.m_request = &request;
+        return make_pair(true,sendError(log, request, app, "session", tp));
     }
-#endif
 }