Make shared libraries for libshibsp5 not libshibsp4
[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(nullptr);
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-Session-Index", "HTTP_SHIB_SESSION_INDEX");
148         app.clearHeader(request, "Shib-Identity-Provider", "HTTP_SHIB_IDENTITY_PROVIDER");
149         app.clearHeader(request, "Shib-Authentication-Method", "HTTP_SHIB_AUTHENTICATION_METHOD");
150         app.clearHeader(request, "Shib-Authentication-Instant", "HTTP_SHIB_AUTHENTICATION_INSTANT");
151         app.clearHeader(request, "Shib-AuthnContext-Class", "HTTP_SHIB_AUTHNCONTEXT_CLASS");
152         app.clearHeader(request, "Shib-AuthnContext-Decl", "HTTP_SHIB_AUTHNCONTEXT_DECL");
153         app.clearHeader(request, "Shib-Assertion-Count", "HTTP_SHIB_ASSERTION_COUNT");
154         app.clearAttributeHeaders(request);
155         request.clearHeader("REMOTE_USER", "HTTP_REMOTE_USER");
156     }
157 };
158
159 void SHIBSP_API shibsp::registerServiceProviders()
160 {
161     SPConfig::getConfig().ServiceProviderManager.registerFactory(XML_SERVICE_PROVIDER, XMLServiceProviderFactory);
162 }
163
164 ServiceProvider::ServiceProvider()
165 {
166 }
167
168 ServiceProvider::~ServiceProvider()
169 {
170 }
171
172 #ifndef SHIBSP_LITE
173 SecurityPolicyProvider* ServiceProvider::getSecurityPolicyProvider(bool required) const
174 {
175     if (required)
176         throw ConfigurationException("No SecurityPolicyProvider available.");
177     return NULL;
178 }
179 #endif
180
181 pair<bool,long> ServiceProvider::doAuthentication(SPRequest& request, bool handler) const
182 {
183 #ifdef _DEBUG
184     xmltooling::NDC ndc("doAuthentication");
185 #endif
186     Category& log = Category::getInstance(SHIBSP_LOGCAT".ServiceProvider");
187
188     const Application* app=nullptr;
189     string targetURL = request.getRequestURL();
190
191     try {
192         RequestMapper::Settings settings = request.getRequestSettings();
193         app = &(request.getApplication());
194
195         // If not SSL, check to see if we should block or redirect it.
196         if (!request.isSecure()) {
197             pair<bool,const char*> redirectToSSL = settings.first->getString("redirectToSSL");
198             if (redirectToSSL.first) {
199 #ifdef HAVE_STRCASECMP
200                 if (!strcasecmp("GET",request.getMethod()) || !strcasecmp("HEAD",request.getMethod())) {
201 #else
202                 if (!stricmp("GET",request.getMethod()) || !stricmp("HEAD",request.getMethod())) {
203 #endif
204                     // Compute the new target URL
205                     string redirectURL = string("https://") + request.getHostname();
206                     if (strcmp(redirectToSSL.second,"443")) {
207                         redirectURL = redirectURL + ':' + redirectToSSL.second;
208                     }
209                     redirectURL += request.getRequestURI();
210                     return make_pair(true, request.sendRedirect(redirectURL.c_str()));
211                 }
212                 else {
213                     TemplateParameters tp;
214                     tp.m_map["requestURL"] = targetURL.substr(0,targetURL.find('?'));
215                     return make_pair(true,sendError(log, request, app, "ssl", tp, false));
216                 }
217             }
218         }
219
220         const char* handlerURL=request.getHandlerURL(targetURL.c_str());
221         if (!handlerURL)
222             throw ConfigurationException("Cannot determine handler from resource URL, check configuration.");
223
224         // If the request URL contains the handler base URL for this application, either dispatch
225         // directly (mainly Apache 2.0) or just pass back control.
226         if (strstr(targetURL.c_str(),handlerURL)) {
227             if (handler)
228                 return doHandler(request);
229             else
230                 return make_pair(true, request.returnOK());
231         }
232
233         // Three settings dictate how to proceed.
234         pair<bool,const char*> authType = settings.first->getString("authType");
235         pair<bool,bool> requireSession = settings.first->getBool("requireSession");
236         pair<bool,const char*> requireSessionWith = settings.first->getString("requireSessionWith");
237
238         // If no session is required AND the AuthType (an Apache-derived concept) isn't shibboleth,
239         // then we ignore this request and consider it unprotected. Apache might lie to us if
240         // ShibBasicHijack is on, but that's up to it.
241         if ((!requireSession.first || !requireSession.second) && !requireSessionWith.first &&
242 #ifdef HAVE_STRCASECMP
243                 (!authType.first || strcasecmp(authType.second,"shibboleth")))
244 #else
245                 (!authType.first || _stricmp(authType.second,"shibboleth")))
246 #endif
247             return make_pair(true,request.returnDecline());
248
249         // Fix for secadv 20050901
250         clearHeaders(request);
251
252         Session* session = nullptr;
253         try {
254             session = request.getSession();
255         }
256         catch (exception& e) {
257             log.warn("error during session lookup: %s", e.what());
258             // If it's not a retryable session failure, we throw to the outer handler for reporting.
259             if (dynamic_cast<opensaml::RetryableProfileException*>(&e)==nullptr)
260                 throw;
261         }
262
263         if (!session) {
264             // No session.  Maybe that's acceptable?
265             if ((!requireSession.first || !requireSession.second) && !requireSessionWith.first)
266                 return make_pair(true,request.returnOK());
267
268             // No session, but we require one. Initiate a new session using the indicated method.
269             const SessionInitiator* initiator=nullptr;
270             if (requireSessionWith.first) {
271                 initiator=app->getSessionInitiatorById(requireSessionWith.second);
272                 if (!initiator) {
273                     throw ConfigurationException(
274                         "No session initiator found with id ($1), check requireSessionWith command.", params(1,requireSessionWith.second)
275                         );
276                 }
277             }
278             else {
279                 initiator=app->getDefaultSessionInitiator();
280                 if (!initiator)
281                     throw ConfigurationException("No default session initiator found, check configuration.");
282             }
283
284             return initiator->run(request,false);
285         }
286
287         request.setAuthType("shibboleth");
288
289         // We're done.  Everything is okay.  Nothing to report.  Nothing to do..
290         // Let the caller decide how to proceed.
291         log.debug("doAuthentication succeeded");
292         return make_pair(false,0L);
293     }
294     catch (exception& e) {
295         request.log(SPRequest::SPError, e.what());
296         TemplateParameters tp(&e);
297         tp.m_map["requestURL"] = targetURL.substr(0,targetURL.find('?'));
298         return make_pair(true,sendError(log, request, app, "session", tp));
299     }
300 }
301
302 pair<bool,long> ServiceProvider::doAuthorization(SPRequest& request) const
303 {
304 #ifdef _DEBUG
305     xmltooling::NDC ndc("doAuthorization");
306 #endif
307     Category& log = Category::getInstance(SHIBSP_LOGCAT".ServiceProvider");
308
309     const Application* app=nullptr;
310     string targetURL = request.getRequestURL();
311
312     try {
313         RequestMapper::Settings settings = request.getRequestSettings();
314         app = &(request.getApplication());
315
316         // Three settings dictate how to proceed.
317         pair<bool,const char*> authType = settings.first->getString("authType");
318         pair<bool,bool> requireSession = settings.first->getBool("requireSession");
319         pair<bool,const char*> requireSessionWith = settings.first->getString("requireSessionWith");
320
321         // If no session is required AND the AuthType (an Apache-derived concept) isn't shibboleth,
322         // then we ignore this request and consider it unprotected. Apache might lie to us if
323         // ShibBasicHijack is on, but that's up to it.
324         if ((!requireSession.first || !requireSession.second) && !requireSessionWith.first &&
325 #ifdef HAVE_STRCASECMP
326                 (!authType.first || strcasecmp(authType.second,"shibboleth")))
327 #else
328                 (!authType.first || _stricmp(authType.second,"shibboleth")))
329 #endif
330             return make_pair(true,request.returnDecline());
331
332         // Do we have an access control plugin?
333         if (settings.second) {
334             const Session* session = nullptr;
335             try {
336                 session = request.getSession(false);
337             }
338             catch (exception& e) {
339                 log.warn("unable to obtain session to pass to access control provider: %s", e.what());
340             }
341
342             Locker acllock(settings.second);
343             switch (settings.second->authorized(request,session)) {
344                 case AccessControl::shib_acl_true:
345                     log.debug("access control provider granted access");
346                     return make_pair(true,request.returnOK());
347
348                 case AccessControl::shib_acl_false:
349                 {
350                     log.warn("access control provider denied access");
351                     TemplateParameters tp;
352                     tp.m_map["requestURL"] = targetURL;
353                     return make_pair(true,sendError(log, request, app, "access", tp, false));
354                 }
355
356                 default:
357                     // Use the "DECLINE" interface to signal we don't know what to do.
358                     return make_pair(true,request.returnDecline());
359             }
360         }
361         else {
362             return make_pair(true,request.returnDecline());
363         }
364     }
365     catch (exception& e) {
366         request.log(SPRequest::SPError, e.what());
367         TemplateParameters tp(&e);
368         tp.m_map["requestURL"] = targetURL.substr(0,targetURL.find('?'));
369         return make_pair(true,sendError(log, request, app, "access", tp));
370     }
371 }
372
373 pair<bool,long> ServiceProvider::doExport(SPRequest& request, bool requireSession) const
374 {
375 #ifdef _DEBUG
376     xmltooling::NDC ndc("doExport");
377 #endif
378     Category& log = Category::getInstance(SHIBSP_LOGCAT".ServiceProvider");
379
380     const Application* app=nullptr;
381     string targetURL = request.getRequestURL();
382
383     try {
384         RequestMapper::Settings settings = request.getRequestSettings();
385         app = &(request.getApplication());
386
387         const Session* session = nullptr;
388         try {
389             session = request.getSession(false);
390         }
391         catch (exception& e) {
392             log.warn("unable to obtain session to export to request: %s", e.what());
393                 // If we have to have a session, then this is a fatal error.
394                 if (requireSession)
395                         throw;
396         }
397
398                 // Still no data?
399         if (!session) {
400                 if (requireSession)
401                 throw opensaml::RetryableProfileException("Unable to obtain session to export to request.");
402                 else
403                         return make_pair(false,0L);     // just bail silently
404         }
405
406         app->setHeader(request, "Shib-Application-ID", app->getId());
407         app->setHeader(request, "Shib-Session-ID", session->getID());
408
409         // Export the IdP name and Authn method/context info.
410         const char* hval = session->getEntityID();
411         if (hval)
412             app->setHeader(request, "Shib-Identity-Provider", hval);
413         hval = session->getAuthnInstant();
414         if (hval)
415             app->setHeader(request, "Shib-Authentication-Instant", hval);
416         hval = session->getAuthnContextClassRef();
417         if (hval) {
418             app->setHeader(request, "Shib-Authentication-Method", hval);
419             app->setHeader(request, "Shib-AuthnContext-Class", hval);
420         }
421         hval = session->getAuthnContextDeclRef();
422         if (hval)
423             app->setHeader(request, "Shib-AuthnContext-Decl", hval);
424         hval = session->getSessionIndex();
425         if (hval)
426             app->setHeader(request, "Shib-Session-Index", hval);
427
428         // Maybe export the assertion keys.
429         pair<bool,bool> exp=settings.first->getBool("exportAssertion");
430         if (exp.first && exp.second) {
431             const PropertySet* sessions=app->getPropertySet("Sessions");
432             pair<bool,const char*> exportLocation = sessions ? sessions->getString("exportLocation") : pair<bool,const char*>(false,nullptr);
433             if (!exportLocation.first)
434                 log.warn("can't export assertions without an exportLocation Sessions property");
435             else {
436                 const URLEncoder* encoder = XMLToolingConfig::getConfig().getURLEncoder();
437                 string exportName = "Shib-Assertion-00";
438                 string baseURL;
439                 if (!strncmp(exportLocation.second, "http", 4))
440                     baseURL = exportLocation.second;
441                 else
442                     baseURL = string(request.getHandlerURL(targetURL.c_str())) + exportLocation.second;
443                 baseURL = baseURL + "?key=" + session->getID() + "&ID=";
444                 const vector<const char*>& tokens = session->getAssertionIDs();
445                 vector<const char*>::size_type count = 0;
446                 for (vector<const char*>::const_iterator tokenids = tokens.begin(); tokenids!=tokens.end(); ++tokenids) {
447                     count++;
448                     *(exportName.rbegin()) = '0' + (count%10);
449                     *(++exportName.rbegin()) = '0' + (count/10);
450                     string fullURL = baseURL + encoder->encode(*tokenids);
451                     app->setHeader(request, exportName.c_str(), fullURL.c_str());
452                 }
453                 app->setHeader(request, "Shib-Assertion-Count", exportName.c_str() + 15);
454             }
455         }
456
457         // Export the attributes.
458         const multimap<string,const Attribute*>& attributes = session->getIndexedAttributes();
459         for (multimap<string,const Attribute*>::const_iterator a = attributes.begin(); a!=attributes.end(); ++a) {
460             if (a->second->isInternal())
461                 continue;
462             string header(app->getSecureHeader(request, a->first.c_str()));
463             const vector<string>& vals = a->second->getSerializedValues();
464             for (vector<string>::const_iterator v = vals.begin(); v!=vals.end(); ++v) {
465                 if (!header.empty())
466                     header += ";";
467                 string::size_type pos = v->find_first_of(';',string::size_type(0));
468                 if (pos!=string::npos) {
469                     string value(*v);
470                     for (; pos != string::npos; pos = value.find_first_of(';',pos)) {
471                         value.insert(pos, "\\");
472                         pos += 2;
473                     }
474                     header += value;
475                 }
476                 else {
477                     header += (*v);
478                 }
479             }
480             app->setHeader(request, a->first.c_str(), header.c_str());
481         }
482
483         // Check for REMOTE_USER.
484         bool remoteUserSet = false;
485         const vector<string>& rmids = app->getRemoteUserAttributeIds();
486         for (vector<string>::const_iterator rmid = rmids.begin(); !remoteUserSet && rmid != rmids.end(); ++rmid) {
487             pair<multimap<string,const Attribute*>::const_iterator,multimap<string,const Attribute*>::const_iterator> matches =
488                 attributes.equal_range(*rmid);
489             for (; matches.first != matches.second; ++matches.first) {
490                 const vector<string>& vals = matches.first->second->getSerializedValues();
491                 if (!vals.empty()) {
492                     request.setRemoteUser(vals.front().c_str());
493                     remoteUserSet = true;
494                     break;
495                 }
496             }
497         }
498
499         return make_pair(false,0L);
500     }
501     catch (exception& e) {
502         request.log(SPRequest::SPError, e.what());
503         TemplateParameters tp(&e);
504         tp.m_map["requestURL"] = targetURL.substr(0,targetURL.find('?'));
505         return make_pair(true,sendError(log, request, app, "session", tp));
506     }
507 }
508
509 pair<bool,long> ServiceProvider::doHandler(SPRequest& request) const
510 {
511 #ifdef _DEBUG
512     xmltooling::NDC ndc("doHandler");
513 #endif
514     Category& log = Category::getInstance(SHIBSP_LOGCAT".ServiceProvider");
515
516     const Application* app=nullptr;
517     string targetURL = request.getRequestURL();
518
519     try {
520         RequestMapper::Settings settings = request.getRequestSettings();
521         app = &(request.getApplication());
522
523         // If not SSL, check to see if we should block or redirect it.
524         if (!request.isSecure()) {
525             pair<bool,const char*> redirectToSSL = settings.first->getString("redirectToSSL");
526             if (redirectToSSL.first) {
527 #ifdef HAVE_STRCASECMP
528                 if (!strcasecmp("GET",request.getMethod()) || !strcasecmp("HEAD",request.getMethod())) {
529 #else
530                 if (!stricmp("GET",request.getMethod()) || !stricmp("HEAD",request.getMethod())) {
531 #endif
532                     // Compute the new target URL
533                     string redirectURL = string("https://") + request.getHostname();
534                     if (strcmp(redirectToSSL.second,"443")) {
535                         redirectURL = redirectURL + ':' + redirectToSSL.second;
536                     }
537                     redirectURL += request.getRequestURI();
538                     return make_pair(true, request.sendRedirect(redirectURL.c_str()));
539                 }
540                 else {
541                     TemplateParameters tp;
542                     tp.m_map["requestURL"] = targetURL.substr(0,targetURL.find('?'));
543                     return make_pair(true,sendError(log, request, app, "ssl", tp, false));
544                 }
545             }
546         }
547
548         const char* handlerURL=request.getHandlerURL(targetURL.c_str());
549         if (!handlerURL)
550             throw ConfigurationException("Cannot determine handler from resource URL, check configuration.");
551
552         // Make sure we only process handler requests.
553         if (!strstr(targetURL.c_str(),handlerURL))
554             return make_pair(true, request.returnDecline());
555
556         const PropertySet* sessionProps=app->getPropertySet("Sessions");
557         if (!sessionProps)
558             throw ConfigurationException("Unable to map request to application session settings, check configuration.");
559
560         // Process incoming request.
561         pair<bool,bool> handlerSSL=sessionProps->getBool("handlerSSL");
562
563         // Make sure this is SSL, if it should be
564         if ((!handlerSSL.first || handlerSSL.second) && !request.isSecure())
565             throw opensaml::FatalProfileException("Blocked non-SSL access to Shibboleth handler.");
566
567         // We dispatch based on our path info. We know the request URL begins with or equals the handler URL,
568         // so the path info is the next character (or null).
569         const Handler* handler=app->getHandler(targetURL.c_str() + strlen(handlerURL));
570         if (!handler)
571             throw ConfigurationException("Shibboleth handler invoked at an unconfigured location.");
572
573         pair<bool,long> hret=handler->run(request);
574
575         // Did the handler run successfully?
576         if (hret.first)
577             return hret;
578
579         throw ConfigurationException("Configured Shibboleth handler failed to process the request.");
580     }
581     catch (exception& e) {
582         request.log(SPRequest::SPError, e.what());
583         TemplateParameters tp(&e);
584         tp.m_map["requestURL"] = targetURL.substr(0,targetURL.find('?'));
585         tp.m_request = &request;
586         return make_pair(true,sendError(log, request, app, "session", tp));
587     }
588 }