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