Path resolution for error templates.
[shibboleth/sp.git] / shibsp / ServiceProvider.cpp
1 /*
2  *  Copyright 2001-2007 Internet2
3  * 
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 /**
18  * ServiceProvider.cpp
19  * 
20  * Interface to a Shibboleth ServiceProvider instance.
21  */
22
23 #include "internal.h"
24 #include "exceptions.h"
25 #include "AccessControl.h"
26 #include "Application.h"
27 #include "ServiceProvider.h"
28 #include "SessionCache.h"
29 #include "SPRequest.h"
30 #include "attribute/Attribute.h"
31 #include "handler/SessionInitiator.h"
32 #include "util/TemplateParameters.h"
33
34 #include <fstream>
35 #include <sstream>
36 #include <xmltooling/XMLToolingConfig.h>
37 #include <xmltooling/util/NDC.h>
38 #include <xmltooling/util/PathResolver.h>
39 #include <xmltooling/util/URLEncoder.h>
40 #include <xmltooling/util/XMLHelper.h>
41
42 using namespace shibsp;
43 using namespace xmltooling::logging;
44 using namespace xmltooling;
45 using namespace std;
46
47 namespace shibsp {
48     SHIBSP_DLLLOCAL PluginManager<ServiceProvider,string,const DOMElement*>::Factory XMLServiceProviderFactory;
49
50     long SHIBSP_DLLLOCAL sendError(
51         Category& log, SPRequest& request, const Application* app, const char* page, TemplateParameters& tp, bool mayRedirect=true
52         )
53     {
54         // The properties we need can be set in the RequestMap, or the Errors element.
55         bool mderror = dynamic_cast<const opensaml::saml2md::MetadataException*>(tp.getRichException())!=NULL;
56         pair<bool,const char*> redirectErrors = pair<bool,const char*>(false,NULL);
57         pair<bool,const char*> pathname = pair<bool,const char*>(false,NULL);
58         const PropertySet* props=app ? app->getPropertySet("Errors") : NULL;
59
60         try {
61             RequestMapper::Settings settings = request.getRequestSettings();
62             if (mderror)
63                 pathname = settings.first->getString("metadataError");
64             if (!pathname.first) {
65                 string pagename(page);
66                 pagename += "Error";
67                 pathname = settings.first->getString(pagename.c_str());
68             }
69             if (mayRedirect)
70                 redirectErrors = settings.first->getString("redirectErrors");
71         }
72         catch (exception& ex) {
73             log.error(ex.what());
74         }
75
76         if (mayRedirect) {
77             // Check for redirection on errors instead of template.
78             if (!redirectErrors.first && props)
79                 redirectErrors = props->getString("redirectErrors");
80             if (redirectErrors.first) {
81                 string loc(redirectErrors.second);
82                 loc = loc + '?' + tp.toQueryString();
83                 return request.sendRedirect(loc.c_str());
84             }
85         }
86
87         request.setContentType("text/html");
88         request.setResponseHeader("Expires","01-Jan-1997 12:00:00 GMT");
89         request.setResponseHeader("Cache-Control","private,no-store,no-cache");
90     
91         if (!pathname.first && props) {
92             if (mderror)
93                 pathname=props->getString("metadata");
94             if (!pathname.first)
95                 pathname=props->getString(page);
96         }
97         if (pathname.first) {
98             string fname(pathname.second);
99             ifstream infile(XMLToolingConfig::getConfig().getPathResolver()->resolve(fname, PathResolver::XMLTOOLING_CFG_FILE).c_str());
100             if (infile) {
101                 tp.setPropertySet(props);
102                 stringstream str;
103                 XMLToolingConfig::getConfig().getTemplateEngine()->run(infile, str, tp, tp.getRichException());
104                 return request.sendResponse(str);
105             }
106         }
107         
108         if (!strcmp(page,"access")) {
109             istringstream msg("Access Denied");
110             return request.sendResponse(msg, HTTPResponse::XMLTOOLING_HTTP_STATUS_UNAUTHORIZED);
111         }
112     
113         log.error("sendError could not process error template (%s)", page);
114         istringstream msg("Internal Server Error. Please contact the site administrator.");
115         return request.sendError(msg);
116     }
117     
118     void SHIBSP_DLLLOCAL clearHeaders(SPRequest& request) {
119         request.clearHeader("Shib-Session-ID", "HTTP_SHIB_SESSION_ID");
120         request.clearHeader("Shib-Identity-Provider", "HTTP_SHIB_IDENTITY_PROVIDER");
121         request.clearHeader("Shib-Authentication-Method", "HTTP_SHIB_AUTHENTICATION_METHOD");
122         request.clearHeader("Shib-Authentication-Instant", "HTTP_SHIB_AUTHENTICATION_INSTANT");
123         request.clearHeader("Shib-AuthnContext-Class", "HTTP_SHIB_AUTHNCONTEXT_CLASS");
124         request.clearHeader("Shib-AuthnContext-Decl", "HTTP_SHIB_AUTHNCONTEXT_DECL");
125         request.clearHeader("Shib-Assertion-Count", "HTTP_SHIB_ASSERTION_COUNT");
126         request.clearHeader("REMOTE_USER", "HTTP_REMOTE_USER");
127         //request.clearHeader("Shib-Application-ID");   handle inside app method
128         request.getApplication().clearAttributeHeaders(request);
129     }
130 };
131
132 void SHIBSP_API shibsp::registerServiceProviders()
133 {
134     SPConfig::getConfig().ServiceProviderManager.registerFactory(XML_SERVICE_PROVIDER, XMLServiceProviderFactory);
135 }
136
137 pair<bool,long> ServiceProvider::doAuthentication(SPRequest& request, bool handler) const
138 {
139 #ifdef _DEBUG
140     xmltooling::NDC ndc("doAuthentication");
141 #endif
142     Category& log = Category::getInstance(SHIBSP_LOGCAT".ServiceProvider");
143
144     const Application* app=NULL;
145     string targetURL = request.getRequestURL();
146
147     try {
148         RequestMapper::Settings settings = request.getRequestSettings();
149         app = &(request.getApplication());
150
151         // If not SSL, check to see if we should block or redirect it.
152         if (!request.isSecure()) {
153             pair<bool,const char*> redirectToSSL = settings.first->getString("redirectToSSL");
154             if (redirectToSSL.first) {
155 #ifdef HAVE_STRCASECMP
156                 if (!strcasecmp("GET",request.getMethod()) || !strcasecmp("HEAD",request.getMethod())) {
157 #else
158                 if (!stricmp("GET",request.getMethod()) || !stricmp("HEAD",request.getMethod())) {
159 #endif
160                     // Compute the new target URL
161                     string redirectURL = string("https://") + request.getHostname();
162                     if (strcmp(redirectToSSL.second,"443")) {
163                         redirectURL = redirectURL + ':' + redirectToSSL.second;
164                     }
165                     redirectURL += request.getRequestURI();
166                     return make_pair(true, request.sendRedirect(redirectURL.c_str()));
167                 }
168                 else {
169                     TemplateParameters tp;
170                     tp.m_map["requestURL"] = targetURL.substr(0,targetURL.find('?'));
171                     return make_pair(true,sendError(log, request, app, "ssl", tp, false));
172                 }
173             }
174         }
175         
176         const char* handlerURL=request.getHandlerURL(targetURL.c_str());
177         if (!handlerURL)
178             throw ConfigurationException("Cannot determine handler from resource URL, check configuration.");
179
180         // If the request URL contains the handler base URL for this application, either dispatch
181         // directly (mainly Apache 2.0) or just pass back control.
182         if (strstr(targetURL.c_str(),handlerURL)) {
183             if (handler)
184                 return doHandler(request);
185             else
186                 return make_pair(true, request.returnOK());
187         }
188
189         // Three settings dictate how to proceed.
190         pair<bool,const char*> authType = settings.first->getString("authType");
191         pair<bool,bool> requireSession = settings.first->getBool("requireSession");
192         pair<bool,const char*> requireSessionWith = settings.first->getString("requireSessionWith");
193
194         // If no session is required AND the AuthType (an Apache-derived concept) isn't shibboleth,
195         // then we ignore this request and consider it unprotected. Apache might lie to us if
196         // ShibBasicHijack is on, but that's up to it.
197         if ((!requireSession.first || !requireSession.second) && !requireSessionWith.first &&
198 #ifdef HAVE_STRCASECMP
199                 (!authType.first || strcasecmp(authType.second,"shibboleth")))
200 #else
201                 (!authType.first || _stricmp(authType.second,"shibboleth")))
202 #endif
203             return make_pair(true,request.returnDecline());
204
205         // Fix for secadv 20050901
206         clearHeaders(request);
207
208         Session* session = NULL;
209         try {
210             session = request.getSession();
211         }
212         catch (exception& e) {
213             log.warn("error during session lookup: %s", e.what());
214             // If it's not a retryable session failure, we throw to the outer handler for reporting.
215             if (dynamic_cast<opensaml::RetryableProfileException*>(&e)==NULL)
216                 throw;
217         }
218
219         if (!session) {
220             // No session.  Maybe that's acceptable?
221             if ((!requireSession.first || !requireSession.second) && !requireSessionWith.first)
222                 return make_pair(true,request.returnOK());
223
224             // No session, but we require one. Initiate a new session using the indicated method.
225             const Handler* initiator=NULL;
226             if (requireSessionWith.first) {
227                 initiator=app->getSessionInitiatorById(requireSessionWith.second);
228                 if (!initiator) {
229                     throw ConfigurationException(
230                         "No session initiator found with id ($1), check requireSessionWith command.", params(1,requireSessionWith.second)
231                         );
232                 }
233             }
234             else {
235                 initiator=app->getDefaultSessionInitiator();
236                 if (!initiator)
237                     throw ConfigurationException("No default session initiator found, check configuration.");
238             }
239
240             return initiator->run(request,false);
241         }
242
243         // We're done.  Everything is okay.  Nothing to report.  Nothing to do..
244         // Let the caller decide how to proceed.
245         log.debug("doAuthentication succeeded");
246         return make_pair(false,0L);
247     }
248     catch (exception& e) {
249         TemplateParameters tp(&e);
250         tp.m_map["requestURL"] = targetURL.substr(0,targetURL.find('?'));
251         return make_pair(true,sendError(log, request, app, "session", tp));
252     }
253 }
254
255 pair<bool,long> ServiceProvider::doAuthorization(SPRequest& request) const
256 {
257 #ifdef _DEBUG
258     xmltooling::NDC ndc("doAuthorization");
259 #endif
260     Category& log = Category::getInstance(SHIBSP_LOGCAT".ServiceProvider");
261
262     const Application* app=NULL;
263     string targetURL = request.getRequestURL();
264
265     try {
266         RequestMapper::Settings settings = request.getRequestSettings();
267         app = &(request.getApplication());
268
269         // Three settings dictate how to proceed.
270         pair<bool,const char*> authType = settings.first->getString("authType");
271         pair<bool,bool> requireSession = settings.first->getBool("requireSession");
272         pair<bool,const char*> requireSessionWith = settings.first->getString("requireSessionWith");
273
274         // If no session is required AND the AuthType (an Apache-derived concept) isn't shibboleth,
275         // then we ignore this request and consider it unprotected. Apache might lie to us if
276         // ShibBasicHijack is on, but that's up to it.
277         if ((!requireSession.first || !requireSession.second) && !requireSessionWith.first &&
278 #ifdef HAVE_STRCASECMP
279                 (!authType.first || strcasecmp(authType.second,"shibboleth")))
280 #else
281                 (!authType.first || _stricmp(authType.second,"shibboleth")))
282 #endif
283             return make_pair(true,request.returnDecline());
284
285         // Do we have an access control plugin?
286         if (settings.second) {
287             const Session* session = NULL;
288             try {
289                 session = request.getSession(false);
290             }
291             catch (exception& e) {
292                 log.warn("unable to obtain session to pass to access control provider: %s", e.what());
293             }
294         
295             Locker acllock(settings.second);
296             switch (settings.second->authorized(request,session)) {
297                 case AccessControl::shib_acl_true:
298                     log.debug("access control provider granted access");
299                     return make_pair(true,request.returnOK());
300
301                 case AccessControl::shib_acl_false:
302                 {
303                     log.warn("access control provider denied access");
304                     TemplateParameters tp;
305                     tp.m_map["requestURL"] = targetURL;
306                     return make_pair(true,sendError(log, request, app, "access", tp, false));
307                 }
308
309                 default:
310                     // Use the "DECLINE" interface to signal we don't know what to do.
311                     return make_pair(true,request.returnDecline());
312             }
313         }
314         else {
315             return make_pair(true,request.returnDecline());
316         }
317     }
318     catch (exception& e) {
319         TemplateParameters tp(&e);
320         tp.m_map["requestURL"] = targetURL.substr(0,targetURL.find('?'));
321         return make_pair(true,sendError(log, request, app, "access", tp));
322     }
323 }
324
325 pair<bool,long> ServiceProvider::doExport(SPRequest& request, bool requireSession) const
326 {
327 #ifdef _DEBUG
328     xmltooling::NDC ndc("doExport");
329 #endif
330     Category& log = Category::getInstance(SHIBSP_LOGCAT".ServiceProvider");
331
332     const Application* app=NULL;
333     string targetURL = request.getRequestURL();
334
335     try {
336         RequestMapper::Settings settings = request.getRequestSettings();
337         app = &(request.getApplication());
338
339         const Session* session = NULL;
340         try {
341             session = request.getSession(false);
342         }
343         catch (exception& e) {
344             log.warn("unable to obtain session to export to request: %s", e.what());
345                 // If we have to have a session, then this is a fatal error.
346                 if (requireSession)
347                         throw;
348         }
349
350                 // Still no data?
351         if (!session) {
352                 if (requireSession)
353                 throw opensaml::RetryableProfileException("Unable to obtain session to export to request.");
354                 else
355                         return make_pair(false,0L);     // just bail silently
356         }
357         
358         request.setHeader("Shib-Application-ID", app->getId());
359         request.setHeader("Shib-Session-ID", session->getID());
360
361         // Export the IdP name and Authn method/context info.
362         const char* hval = session->getEntityID();
363         if (hval)
364             request.setHeader("Shib-Identity-Provider", hval);
365         hval = session->getAuthnInstant();
366         if (hval)
367             request.setHeader("Shib-Authentication-Instant", hval);
368         hval = session->getAuthnContextClassRef();
369         if (hval) {
370             request.setHeader("Shib-Authentication-Method", hval);
371             request.setHeader("Shib-AuthnContext-Class", hval);
372         }
373         hval = session->getAuthnContextDeclRef();
374         if (hval)
375             request.setHeader("Shib-AuthnContext-Decl", hval);
376         
377         // Maybe export the assertion keys.
378         pair<bool,bool> exp=settings.first->getBool("exportAssertion");
379         if (exp.first && exp.second) {
380             const PropertySet* sessions=app->getPropertySet("Sessions");
381             pair<bool,const char*> exportLocation = sessions ? sessions->getString("exportLocation") : pair<bool,const char*>(false,NULL);
382             if (!exportLocation.first)
383                 log.warn("can't export assertions without an exportLocation Sessions property");
384             else {
385                 const URLEncoder* encoder = XMLToolingConfig::getConfig().getURLEncoder();
386                 string exportName = "Shib-Assertion-00";
387                 string baseURL;
388                 if (!strncmp(exportLocation.second, "http", 4))
389                     baseURL = exportLocation.second;
390                 else
391                     baseURL = string(request.getHandlerURL(targetURL.c_str())) + exportLocation.second;
392                 baseURL = baseURL + "?key=" + session->getID() + "&ID=";
393                 const vector<const char*>& tokens = session->getAssertionIDs();
394                 vector<const char*>::size_type count = 0;
395                 for (vector<const char*>::const_iterator tokenids = tokens.begin(); tokenids!=tokens.end(); ++tokenids) {
396                     count++;
397                     *(exportName.rbegin()) = '0' + (count%10);
398                     *(++exportName.rbegin()) = '0' + (count/10);
399                     string fullURL = baseURL + encoder->encode(*tokenids);
400                     request.setHeader(exportName.c_str(), fullURL.c_str());
401                 }
402                 request.setHeader("Shib-Assertion-Count", exportName.c_str() + 15);
403             }
404         }
405
406         // Export the attributes.
407         const multimap<string,const Attribute*>& attributes = session->getIndexedAttributes();
408         for (multimap<string,const Attribute*>::const_iterator a = attributes.begin(); a!=attributes.end(); ++a) {
409             string header(request.getSecureHeader(a->first.c_str()));
410             const vector<string>& vals = a->second->getSerializedValues();
411             for (vector<string>::const_iterator v = vals.begin(); v!=vals.end(); ++v) {
412                 if (!header.empty())
413                     header += ";";
414                 string::size_type pos = v->find_first_of(';',string::size_type(0));
415                 if (pos!=string::npos) {
416                     string value(*v);
417                     for (; pos != string::npos; pos = value.find_first_of(';',pos)) {
418                         value.insert(pos, "\\");
419                         pos += 2;
420                     }
421                     header += value;
422                 }
423                 else {
424                     header += (*v);
425                 }
426             }
427             request.setHeader(a->first.c_str(), header.c_str());
428         }
429
430         // Check for REMOTE_USER.
431         bool remoteUserSet = false;
432         const vector<string>& rmids = app->getRemoteUserAttributeIds();
433         for (vector<string>::const_iterator rmid = rmids.begin(); !remoteUserSet && rmid != rmids.end(); ++rmid) {
434             pair<multimap<string,const Attribute*>::const_iterator,multimap<string,const Attribute*>::const_iterator> matches =
435                 attributes.equal_range(*rmid);
436             while (matches.first != matches.second) {
437                 const vector<string>& vals = matches.first->second->getSerializedValues();
438                 if (!vals.empty()) {
439                     request.setRemoteUser(vals.front().c_str());
440                     remoteUserSet = true;
441                     break;
442                 }
443             }
444         }
445
446         return make_pair(false,0L);
447     }
448     catch (exception& e) {
449         TemplateParameters tp(&e);
450         tp.m_map["requestURL"] = targetURL.substr(0,targetURL.find('?'));
451         return make_pair(true,sendError(log, request, app, "session", tp));
452     }
453 }
454
455 pair<bool,long> ServiceProvider::doHandler(SPRequest& request) const
456 {
457 #ifdef _DEBUG
458     xmltooling::NDC ndc("doHandler");
459 #endif
460     Category& log = Category::getInstance(SHIBSP_LOGCAT".ServiceProvider");
461
462     const Application* app=NULL;
463     string targetURL = request.getRequestURL();
464
465     try {
466         RequestMapper::Settings settings = request.getRequestSettings();
467         app = &(request.getApplication());
468
469         // If not SSL, check to see if we should block or redirect it.
470         if (!request.isSecure()) {
471             pair<bool,const char*> redirectToSSL = settings.first->getString("redirectToSSL");
472             if (redirectToSSL.first) {
473 #ifdef HAVE_STRCASECMP
474                 if (!strcasecmp("GET",request.getMethod()) || !strcasecmp("HEAD",request.getMethod())) {
475 #else
476                 if (!stricmp("GET",request.getMethod()) || !stricmp("HEAD",request.getMethod())) {
477 #endif
478                     // Compute the new target URL
479                     string redirectURL = string("https://") + request.getHostname();
480                     if (strcmp(redirectToSSL.second,"443")) {
481                         redirectURL = redirectURL + ':' + redirectToSSL.second;
482                     }
483                     redirectURL += request.getRequestURI();
484                     return make_pair(true, request.sendRedirect(redirectURL.c_str()));
485                 }
486                 else {
487                     TemplateParameters tp;
488                     tp.m_map["requestURL"] = targetURL.substr(0,targetURL.find('?'));
489                     return make_pair(true,sendError(log, request, app, "ssl", tp, false));
490                 }
491             }
492         }
493
494         const char* handlerURL=request.getHandlerURL(targetURL.c_str());
495         if (!handlerURL)
496             throw ConfigurationException("Cannot determine handler from resource URL, check configuration.");
497
498         // Make sure we only process handler requests.
499         if (!strstr(targetURL.c_str(),handlerURL))
500             return make_pair(true, request.returnDecline());
501
502         const PropertySet* sessionProps=app->getPropertySet("Sessions");
503         if (!sessionProps)
504             throw ConfigurationException("Unable to map request to application session settings, check configuration.");
505
506         // Process incoming request.
507         pair<bool,bool> handlerSSL=sessionProps->getBool("handlerSSL");
508       
509         // Make sure this is SSL, if it should be
510         if ((!handlerSSL.first || handlerSSL.second) && !request.isSecure())
511             throw opensaml::FatalProfileException("Blocked non-SSL access to Shibboleth handler.");
512
513         // We dispatch based on our path info. We know the request URL begins with or equals the handler URL,
514         // so the path info is the next character (or null).
515         const Handler* handler=app->getHandler(targetURL.c_str() + strlen(handlerURL));
516         if (!handler)
517             throw ConfigurationException("Shibboleth handler invoked at an unconfigured location.");
518
519         pair<bool,long> hret=handler->run(request);
520
521         // Did the handler run successfully?
522         if (hret.first)
523             return hret;
524        
525         throw ConfigurationException("Configured Shibboleth handler failed to process the request.");
526     }
527     catch (exception& e) {
528         TemplateParameters tp(&e);
529         tp.m_map["requestURL"] = targetURL.substr(0,targetURL.find('?'));
530         tp.m_request = &request;
531         return make_pair(true,sendError(log, request, app, "session", tp));
532     }
533 }