2 * Copyright 2001-2009 Internet2
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
20 * Interface to a Shibboleth ServiceProvider instance.
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"
37 # include <saml/exceptions.h>
38 # include <saml/saml2/metadata/MetadataProvider.h>
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>
46 using namespace shibsp;
47 using namespace xmltooling::logging;
48 using namespace xmltooling;
52 SHIBSP_DLLLOCAL PluginManager<ServiceProvider,string,const DOMElement*>::Factory XMLServiceProviderFactory;
54 long SHIBSP_DLLLOCAL sendError(
55 Category& log, SPRequest& request, const Application* app, const char* page, TemplateParameters& tp, bool mayRedirect=true
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())!=NULL;
60 pair<bool,const char*> redirectErrors = pair<bool,const char*>(false,NULL);
61 pair<bool,const char*> pathname = pair<bool,const char*>(false,NULL);
63 // Strictly for error handling, detect a NULL application and point at the default.
65 app = request.getServiceProvider().getApplication("default");
67 const PropertySet* props=app->getPropertySet("Errors");
70 RequestMapper::Settings settings = request.getRequestSettings();
72 pathname = settings.first->getString("metadataError");
73 if (!pathname.first) {
74 string pagename(page);
76 pathname = settings.first->getString(pagename.c_str());
79 redirectErrors = settings.first->getString("redirectErrors");
81 catch (exception& ex) {
86 // Check for redirection on errors instead of template.
87 if (!redirectErrors.first && props)
88 redirectErrors = props->getString("redirectErrors");
89 if (redirectErrors.first) {
90 string loc(redirectErrors.second);
91 loc = loc + '?' + tp.toQueryString();
92 return request.sendRedirect(loc.c_str());
96 request.setContentType("text/html");
97 request.setResponseHeader("Expires","01-Jan-1997 12:00:00 GMT");
98 request.setResponseHeader("Cache-Control","private,no-store,no-cache");
100 if (!pathname.first && props) {
102 pathname=props->getString("metadata");
104 pathname=props->getString(page);
108 if (!pathname.first) {
109 fname = string(page) + "Error.html";
110 pathname.second = fname.c_str();
113 fname = pathname.second;
116 ifstream infile(XMLToolingConfig::getConfig().getPathResolver()->resolve(fname, PathResolver::XMLTOOLING_CFG_FILE).c_str());
118 tp.setPropertySet(props);
120 XMLToolingConfig::getConfig().getTemplateEngine()->run(infile, str, tp, tp.getRichException());
121 return request.sendError(str);
124 if (!strcmp(page, "access")) {
125 istringstream msg("Access Denied");
126 return request.sendResponse(msg, HTTPResponse::XMLTOOLING_HTTP_STATUS_FORBIDDEN);
129 log.error("sendError could not process error template (%s)", pathname.second);
130 istringstream msg("Internal Server Error. Please contact the site administrator.");
131 return request.sendError(msg);
134 void SHIBSP_DLLLOCAL clearHeaders(SPRequest& request) {
135 const Application& app = request.getApplication();
136 app.clearHeader(request, "Shib-Session-ID", "HTTP_SHIB_SESSION_ID");
137 app.clearHeader(request, "Shib-Identity-Provider", "HTTP_SHIB_IDENTITY_PROVIDER");
138 app.clearHeader(request, "Shib-Authentication-Method", "HTTP_SHIB_AUTHENTICATION_METHOD");
139 app.clearHeader(request, "Shib-Authentication-Instant", "HTTP_SHIB_AUTHENTICATION_INSTANT");
140 app.clearHeader(request, "Shib-AuthnContext-Class", "HTTP_SHIB_AUTHNCONTEXT_CLASS");
141 app.clearHeader(request, "Shib-AuthnContext-Decl", "HTTP_SHIB_AUTHNCONTEXT_DECL");
142 app.clearHeader(request, "Shib-Assertion-Count", "HTTP_SHIB_ASSERTION_COUNT");
143 app.clearAttributeHeaders(request);
144 request.clearHeader("REMOTE_USER", "HTTP_REMOTE_USER");
148 void SHIBSP_API shibsp::registerServiceProviders()
150 SPConfig::getConfig().ServiceProviderManager.registerFactory(XML_SERVICE_PROVIDER, XMLServiceProviderFactory);
153 ServiceProvider::ServiceProvider()
157 ServiceProvider::~ServiceProvider()
161 pair<bool,long> ServiceProvider::doAuthentication(SPRequest& request, bool handler) const
164 xmltooling::NDC ndc("doAuthentication");
166 Category& log = Category::getInstance(SHIBSP_LOGCAT".ServiceProvider");
168 const Application* app=NULL;
169 string targetURL = request.getRequestURL();
172 RequestMapper::Settings settings = request.getRequestSettings();
173 app = &(request.getApplication());
175 // If not SSL, check to see if we should block or redirect it.
176 if (!request.isSecure()) {
177 pair<bool,const char*> redirectToSSL = settings.first->getString("redirectToSSL");
178 if (redirectToSSL.first) {
179 #ifdef HAVE_STRCASECMP
180 if (!strcasecmp("GET",request.getMethod()) || !strcasecmp("HEAD",request.getMethod())) {
182 if (!stricmp("GET",request.getMethod()) || !stricmp("HEAD",request.getMethod())) {
184 // Compute the new target URL
185 string redirectURL = string("https://") + request.getHostname();
186 if (strcmp(redirectToSSL.second,"443")) {
187 redirectURL = redirectURL + ':' + redirectToSSL.second;
189 redirectURL += request.getRequestURI();
190 return make_pair(true, request.sendRedirect(redirectURL.c_str()));
193 TemplateParameters tp;
194 tp.m_map["requestURL"] = targetURL.substr(0,targetURL.find('?'));
195 return make_pair(true,sendError(log, request, app, "ssl", tp, false));
200 const char* handlerURL=request.getHandlerURL(targetURL.c_str());
202 throw ConfigurationException("Cannot determine handler from resource URL, check configuration.");
204 // If the request URL contains the handler base URL for this application, either dispatch
205 // directly (mainly Apache 2.0) or just pass back control.
206 if (strstr(targetURL.c_str(),handlerURL)) {
208 return doHandler(request);
210 return make_pair(true, request.returnOK());
213 // Three settings dictate how to proceed.
214 pair<bool,const char*> authType = settings.first->getString("authType");
215 pair<bool,bool> requireSession = settings.first->getBool("requireSession");
216 pair<bool,const char*> requireSessionWith = settings.first->getString("requireSessionWith");
218 // If no session is required AND the AuthType (an Apache-derived concept) isn't shibboleth,
219 // then we ignore this request and consider it unprotected. Apache might lie to us if
220 // ShibBasicHijack is on, but that's up to it.
221 if ((!requireSession.first || !requireSession.second) && !requireSessionWith.first &&
222 #ifdef HAVE_STRCASECMP
223 (!authType.first || strcasecmp(authType.second,"shibboleth")))
225 (!authType.first || _stricmp(authType.second,"shibboleth")))
227 return make_pair(true,request.returnDecline());
229 // Fix for secadv 20050901
230 clearHeaders(request);
232 Session* session = NULL;
234 session = request.getSession();
236 catch (exception& e) {
237 log.warn("error during session lookup: %s", e.what());
238 // If it's not a retryable session failure, we throw to the outer handler for reporting.
239 if (dynamic_cast<opensaml::RetryableProfileException*>(&e)==NULL)
244 // No session. Maybe that's acceptable?
245 if ((!requireSession.first || !requireSession.second) && !requireSessionWith.first)
246 return make_pair(true,request.returnOK());
248 // No session, but we require one. Initiate a new session using the indicated method.
249 const SessionInitiator* initiator=NULL;
250 if (requireSessionWith.first) {
251 initiator=app->getSessionInitiatorById(requireSessionWith.second);
253 throw ConfigurationException(
254 "No session initiator found with id ($1), check requireSessionWith command.", params(1,requireSessionWith.second)
259 initiator=app->getDefaultSessionInitiator();
261 throw ConfigurationException("No default session initiator found, check configuration.");
264 return initiator->run(request,false);
267 request.setAuthType("shibboleth");
269 // We're done. Everything is okay. Nothing to report. Nothing to do..
270 // Let the caller decide how to proceed.
271 log.debug("doAuthentication succeeded");
272 return make_pair(false,0L);
274 catch (exception& e) {
275 request.log(SPRequest::SPError, e.what());
276 TemplateParameters tp(&e);
277 tp.m_map["requestURL"] = targetURL.substr(0,targetURL.find('?'));
278 return make_pair(true,sendError(log, request, app, "session", tp));
282 pair<bool,long> ServiceProvider::doAuthorization(SPRequest& request) const
285 xmltooling::NDC ndc("doAuthorization");
287 Category& log = Category::getInstance(SHIBSP_LOGCAT".ServiceProvider");
289 const Application* app=NULL;
290 string targetURL = request.getRequestURL();
293 RequestMapper::Settings settings = request.getRequestSettings();
294 app = &(request.getApplication());
296 // Three settings dictate how to proceed.
297 pair<bool,const char*> authType = settings.first->getString("authType");
298 pair<bool,bool> requireSession = settings.first->getBool("requireSession");
299 pair<bool,const char*> requireSessionWith = settings.first->getString("requireSessionWith");
301 // If no session is required AND the AuthType (an Apache-derived concept) isn't shibboleth,
302 // then we ignore this request and consider it unprotected. Apache might lie to us if
303 // ShibBasicHijack is on, but that's up to it.
304 if ((!requireSession.first || !requireSession.second) && !requireSessionWith.first &&
305 #ifdef HAVE_STRCASECMP
306 (!authType.first || strcasecmp(authType.second,"shibboleth")))
308 (!authType.first || _stricmp(authType.second,"shibboleth")))
310 return make_pair(true,request.returnDecline());
312 // Do we have an access control plugin?
313 if (settings.second) {
314 const Session* session = NULL;
316 session = request.getSession(false);
318 catch (exception& e) {
319 log.warn("unable to obtain session to pass to access control provider: %s", e.what());
322 Locker acllock(settings.second);
323 switch (settings.second->authorized(request,session)) {
324 case AccessControl::shib_acl_true:
325 log.debug("access control provider granted access");
326 return make_pair(true,request.returnOK());
328 case AccessControl::shib_acl_false:
330 log.warn("access control provider denied access");
331 TemplateParameters tp;
332 tp.m_map["requestURL"] = targetURL;
333 return make_pair(true,sendError(log, request, app, "access", tp, false));
337 // Use the "DECLINE" interface to signal we don't know what to do.
338 return make_pair(true,request.returnDecline());
342 return make_pair(true,request.returnDecline());
345 catch (exception& e) {
346 request.log(SPRequest::SPError, e.what());
347 TemplateParameters tp(&e);
348 tp.m_map["requestURL"] = targetURL.substr(0,targetURL.find('?'));
349 return make_pair(true,sendError(log, request, app, "access", tp));
353 pair<bool,long> ServiceProvider::doExport(SPRequest& request, bool requireSession) const
356 xmltooling::NDC ndc("doExport");
358 Category& log = Category::getInstance(SHIBSP_LOGCAT".ServiceProvider");
360 const Application* app=NULL;
361 string targetURL = request.getRequestURL();
364 RequestMapper::Settings settings = request.getRequestSettings();
365 app = &(request.getApplication());
367 const Session* session = NULL;
369 session = request.getSession(false);
371 catch (exception& e) {
372 log.warn("unable to obtain session to export to request: %s", e.what());
373 // If we have to have a session, then this is a fatal error.
381 throw opensaml::RetryableProfileException("Unable to obtain session to export to request.");
383 return make_pair(false,0L); // just bail silently
386 app->setHeader(request, "Shib-Application-ID", app->getId());
387 app->setHeader(request, "Shib-Session-ID", session->getID());
389 // Export the IdP name and Authn method/context info.
390 const char* hval = session->getEntityID();
392 app->setHeader(request, "Shib-Identity-Provider", hval);
393 hval = session->getAuthnInstant();
395 app->setHeader(request, "Shib-Authentication-Instant", hval);
396 hval = session->getAuthnContextClassRef();
398 app->setHeader(request, "Shib-Authentication-Method", hval);
399 app->setHeader(request, "Shib-AuthnContext-Class", hval);
401 hval = session->getAuthnContextDeclRef();
403 app->setHeader(request, "Shib-AuthnContext-Decl", hval);
405 // Maybe export the assertion keys.
406 pair<bool,bool> exp=settings.first->getBool("exportAssertion");
407 if (exp.first && exp.second) {
408 const PropertySet* sessions=app->getPropertySet("Sessions");
409 pair<bool,const char*> exportLocation = sessions ? sessions->getString("exportLocation") : pair<bool,const char*>(false,NULL);
410 if (!exportLocation.first)
411 log.warn("can't export assertions without an exportLocation Sessions property");
413 const URLEncoder* encoder = XMLToolingConfig::getConfig().getURLEncoder();
414 string exportName = "Shib-Assertion-00";
416 if (!strncmp(exportLocation.second, "http", 4))
417 baseURL = exportLocation.second;
419 baseURL = string(request.getHandlerURL(targetURL.c_str())) + exportLocation.second;
420 baseURL = baseURL + "?key=" + session->getID() + "&ID=";
421 const vector<const char*>& tokens = session->getAssertionIDs();
422 vector<const char*>::size_type count = 0;
423 for (vector<const char*>::const_iterator tokenids = tokens.begin(); tokenids!=tokens.end(); ++tokenids) {
425 *(exportName.rbegin()) = '0' + (count%10);
426 *(++exportName.rbegin()) = '0' + (count/10);
427 string fullURL = baseURL + encoder->encode(*tokenids);
428 app->setHeader(request, exportName.c_str(), fullURL.c_str());
430 app->setHeader(request, "Shib-Assertion-Count", exportName.c_str() + 15);
434 // Export the attributes.
435 const multimap<string,const Attribute*>& attributes = session->getIndexedAttributes();
436 for (multimap<string,const Attribute*>::const_iterator a = attributes.begin(); a!=attributes.end(); ++a) {
437 if (a->second->isInternal())
439 string header(app->getSecureHeader(request, a->first.c_str()));
440 const vector<string>& vals = a->second->getSerializedValues();
441 for (vector<string>::const_iterator v = vals.begin(); v!=vals.end(); ++v) {
444 string::size_type pos = v->find_first_of(';',string::size_type(0));
445 if (pos!=string::npos) {
447 for (; pos != string::npos; pos = value.find_first_of(';',pos)) {
448 value.insert(pos, "\\");
457 app->setHeader(request, a->first.c_str(), header.c_str());
460 // Check for REMOTE_USER.
461 bool remoteUserSet = false;
462 const vector<string>& rmids = app->getRemoteUserAttributeIds();
463 for (vector<string>::const_iterator rmid = rmids.begin(); !remoteUserSet && rmid != rmids.end(); ++rmid) {
464 pair<multimap<string,const Attribute*>::const_iterator,multimap<string,const Attribute*>::const_iterator> matches =
465 attributes.equal_range(*rmid);
466 for (; matches.first != matches.second; ++matches.first) {
467 const vector<string>& vals = matches.first->second->getSerializedValues();
469 request.setRemoteUser(vals.front().c_str());
470 remoteUserSet = true;
476 return make_pair(false,0L);
478 catch (exception& e) {
479 request.log(SPRequest::SPError, e.what());
480 TemplateParameters tp(&e);
481 tp.m_map["requestURL"] = targetURL.substr(0,targetURL.find('?'));
482 return make_pair(true,sendError(log, request, app, "session", tp));
486 pair<bool,long> ServiceProvider::doHandler(SPRequest& request) const
489 xmltooling::NDC ndc("doHandler");
491 Category& log = Category::getInstance(SHIBSP_LOGCAT".ServiceProvider");
493 const Application* app=NULL;
494 string targetURL = request.getRequestURL();
497 RequestMapper::Settings settings = request.getRequestSettings();
498 app = &(request.getApplication());
500 // If not SSL, check to see if we should block or redirect it.
501 if (!request.isSecure()) {
502 pair<bool,const char*> redirectToSSL = settings.first->getString("redirectToSSL");
503 if (redirectToSSL.first) {
504 #ifdef HAVE_STRCASECMP
505 if (!strcasecmp("GET",request.getMethod()) || !strcasecmp("HEAD",request.getMethod())) {
507 if (!stricmp("GET",request.getMethod()) || !stricmp("HEAD",request.getMethod())) {
509 // Compute the new target URL
510 string redirectURL = string("https://") + request.getHostname();
511 if (strcmp(redirectToSSL.second,"443")) {
512 redirectURL = redirectURL + ':' + redirectToSSL.second;
514 redirectURL += request.getRequestURI();
515 return make_pair(true, request.sendRedirect(redirectURL.c_str()));
518 TemplateParameters tp;
519 tp.m_map["requestURL"] = targetURL.substr(0,targetURL.find('?'));
520 return make_pair(true,sendError(log, request, app, "ssl", tp, false));
525 const char* handlerURL=request.getHandlerURL(targetURL.c_str());
527 throw ConfigurationException("Cannot determine handler from resource URL, check configuration.");
529 // Make sure we only process handler requests.
530 if (!strstr(targetURL.c_str(),handlerURL))
531 return make_pair(true, request.returnDecline());
533 const PropertySet* sessionProps=app->getPropertySet("Sessions");
535 throw ConfigurationException("Unable to map request to application session settings, check configuration.");
537 // Process incoming request.
538 pair<bool,bool> handlerSSL=sessionProps->getBool("handlerSSL");
540 // Make sure this is SSL, if it should be
541 if ((!handlerSSL.first || handlerSSL.second) && !request.isSecure())
542 throw opensaml::FatalProfileException("Blocked non-SSL access to Shibboleth handler.");
544 // We dispatch based on our path info. We know the request URL begins with or equals the handler URL,
545 // so the path info is the next character (or null).
546 const Handler* handler=app->getHandler(targetURL.c_str() + strlen(handlerURL));
548 throw ConfigurationException("Shibboleth handler invoked at an unconfigured location.");
550 pair<bool,long> hret=handler->run(request);
552 // Did the handler run successfully?
556 throw ConfigurationException("Configured Shibboleth handler failed to process the request.");
558 catch (exception& e) {
559 request.log(SPRequest::SPError, e.what());
560 TemplateParameters tp(&e);
561 tp.m_map["requestURL"] = targetURL.substr(0,targetURL.find('?'));
562 tp.m_request = &request;
563 return make_pair(true,sendError(log, request, app, "session", tp));