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