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