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