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