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