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