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