2 * Copyright 2001-2007 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"
36 #include <xmltooling/XMLToolingConfig.h>
37 #include <xmltooling/util/NDC.h>
38 #include <xmltooling/util/PathResolver.h>
39 #include <xmltooling/util/URLEncoder.h>
40 #include <xmltooling/util/XMLHelper.h>
42 using namespace shibsp;
43 using namespace xmltooling::logging;
44 using namespace xmltooling;
48 SHIBSP_DLLLOCAL PluginManager<ServiceProvider,string,const DOMElement*>::Factory XMLServiceProviderFactory;
50 long SHIBSP_DLLLOCAL sendError(
51 Category& log, SPRequest& request, const Application* app, const char* page, TemplateParameters& tp, bool mayRedirect=true
54 // The properties we need can be set in the RequestMap, or the Errors element.
55 bool mderror = dynamic_cast<const opensaml::saml2md::MetadataException*>(tp.getRichException())!=NULL;
56 pair<bool,const char*> redirectErrors = pair<bool,const char*>(false,NULL);
57 pair<bool,const char*> pathname = pair<bool,const char*>(false,NULL);
59 // Strictly for error handling, detect a NULL application and point at the default.
61 app = request.getServiceProvider().getApplication("default");
63 const PropertySet* props=app->getPropertySet("Errors");
66 RequestMapper::Settings settings = request.getRequestSettings();
68 pathname = settings.first->getString("metadataError");
69 if (!pathname.first) {
70 string pagename(page);
72 pathname = settings.first->getString(pagename.c_str());
75 redirectErrors = settings.first->getString("redirectErrors");
77 catch (exception& ex) {
82 // Check for redirection on errors instead of template.
83 if (!redirectErrors.first && props)
84 redirectErrors = props->getString("redirectErrors");
85 if (redirectErrors.first) {
86 string loc(redirectErrors.second);
87 loc = loc + '?' + tp.toQueryString();
88 return request.sendRedirect(loc.c_str());
92 request.setContentType("text/html");
93 request.setResponseHeader("Expires","01-Jan-1997 12:00:00 GMT");
94 request.setResponseHeader("Cache-Control","private,no-store,no-cache");
96 if (!pathname.first && props) {
98 pathname=props->getString("metadata");
100 pathname=props->getString(page);
102 if (pathname.first) {
103 string fname(pathname.second);
104 ifstream infile(XMLToolingConfig::getConfig().getPathResolver()->resolve(fname, PathResolver::XMLTOOLING_CFG_FILE).c_str());
106 tp.setPropertySet(props);
108 XMLToolingConfig::getConfig().getTemplateEngine()->run(infile, str, tp, tp.getRichException());
109 return request.sendResponse(str);
113 if (!strcmp(page,"access")) {
114 istringstream msg("Access Denied");
115 return request.sendResponse(msg, HTTPResponse::XMLTOOLING_HTTP_STATUS_FORBIDDEN);
118 log.error("sendError could not process error template (%s)", page);
119 istringstream msg("Internal Server Error. Please contact the site administrator.");
120 return request.sendError(msg);
123 void SHIBSP_DLLLOCAL clearHeaders(SPRequest& request) {
124 const Application& app = request.getApplication();
125 app.clearHeader(request, "Shib-Session-ID", "HTTP_SHIB_SESSION_ID");
126 app.clearHeader(request, "Shib-Identity-Provider", "HTTP_SHIB_IDENTITY_PROVIDER");
127 app.clearHeader(request, "Shib-Authentication-Method", "HTTP_SHIB_AUTHENTICATION_METHOD");
128 app.clearHeader(request, "Shib-Authentication-Instant", "HTTP_SHIB_AUTHENTICATION_INSTANT");
129 app.clearHeader(request, "Shib-AuthnContext-Class", "HTTP_SHIB_AUTHNCONTEXT_CLASS");
130 app.clearHeader(request, "Shib-AuthnContext-Decl", "HTTP_SHIB_AUTHNCONTEXT_DECL");
131 app.clearHeader(request, "Shib-Assertion-Count", "HTTP_SHIB_ASSERTION_COUNT");
132 app.clearAttributeHeaders(request);
133 request.clearHeader("REMOTE_USER", "HTTP_REMOTE_USER");
137 void SHIBSP_API shibsp::registerServiceProviders()
139 SPConfig::getConfig().ServiceProviderManager.registerFactory(XML_SERVICE_PROVIDER, XMLServiceProviderFactory);
142 pair<bool,long> ServiceProvider::doAuthentication(SPRequest& request, bool handler) const
145 xmltooling::NDC ndc("doAuthentication");
147 Category& log = Category::getInstance(SHIBSP_LOGCAT".ServiceProvider");
149 const Application* app=NULL;
150 string targetURL = request.getRequestURL();
153 RequestMapper::Settings settings = request.getRequestSettings();
154 app = &(request.getApplication());
156 // If not SSL, check to see if we should block or redirect it.
157 if (!request.isSecure()) {
158 pair<bool,const char*> redirectToSSL = settings.first->getString("redirectToSSL");
159 if (redirectToSSL.first) {
160 #ifdef HAVE_STRCASECMP
161 if (!strcasecmp("GET",request.getMethod()) || !strcasecmp("HEAD",request.getMethod())) {
163 if (!stricmp("GET",request.getMethod()) || !stricmp("HEAD",request.getMethod())) {
165 // Compute the new target URL
166 string redirectURL = string("https://") + request.getHostname();
167 if (strcmp(redirectToSSL.second,"443")) {
168 redirectURL = redirectURL + ':' + redirectToSSL.second;
170 redirectURL += request.getRequestURI();
171 return make_pair(true, request.sendRedirect(redirectURL.c_str()));
174 TemplateParameters tp;
175 tp.m_map["requestURL"] = targetURL.substr(0,targetURL.find('?'));
176 return make_pair(true,sendError(log, request, app, "ssl", tp, false));
181 const char* handlerURL=request.getHandlerURL(targetURL.c_str());
183 throw ConfigurationException("Cannot determine handler from resource URL, check configuration.");
185 // If the request URL contains the handler base URL for this application, either dispatch
186 // directly (mainly Apache 2.0) or just pass back control.
187 if (strstr(targetURL.c_str(),handlerURL)) {
189 return doHandler(request);
191 return make_pair(true, request.returnOK());
194 // Three settings dictate how to proceed.
195 pair<bool,const char*> authType = settings.first->getString("authType");
196 pair<bool,bool> requireSession = settings.first->getBool("requireSession");
197 pair<bool,const char*> requireSessionWith = settings.first->getString("requireSessionWith");
199 // If no session is required AND the AuthType (an Apache-derived concept) isn't shibboleth,
200 // then we ignore this request and consider it unprotected. Apache might lie to us if
201 // ShibBasicHijack is on, but that's up to it.
202 if ((!requireSession.first || !requireSession.second) && !requireSessionWith.first &&
203 #ifdef HAVE_STRCASECMP
204 (!authType.first || strcasecmp(authType.second,"shibboleth")))
206 (!authType.first || _stricmp(authType.second,"shibboleth")))
208 return make_pair(true,request.returnDecline());
210 // Fix for secadv 20050901
211 clearHeaders(request);
213 Session* session = NULL;
215 session = request.getSession();
217 catch (exception& e) {
218 log.warn("error during session lookup: %s", e.what());
219 // If it's not a retryable session failure, we throw to the outer handler for reporting.
220 if (dynamic_cast<opensaml::RetryableProfileException*>(&e)==NULL)
225 // No session. Maybe that's acceptable?
226 if ((!requireSession.first || !requireSession.second) && !requireSessionWith.first)
227 return make_pair(true,request.returnOK());
229 // No session, but we require one. Initiate a new session using the indicated method.
230 const SessionInitiator* initiator=NULL;
231 if (requireSessionWith.first) {
232 initiator=app->getSessionInitiatorById(requireSessionWith.second);
234 throw ConfigurationException(
235 "No session initiator found with id ($1), check requireSessionWith command.", params(1,requireSessionWith.second)
240 initiator=app->getDefaultSessionInitiator();
242 throw ConfigurationException("No default session initiator found, check configuration.");
245 return initiator->run(request,false);
248 // We're done. Everything is okay. Nothing to report. Nothing to do..
249 // Let the caller decide how to proceed.
250 log.debug("doAuthentication succeeded");
251 return make_pair(false,0L);
253 catch (exception& e) {
254 TemplateParameters tp(&e);
255 tp.m_map["requestURL"] = targetURL.substr(0,targetURL.find('?'));
256 return make_pair(true,sendError(log, request, app, "session", tp));
260 pair<bool,long> ServiceProvider::doAuthorization(SPRequest& request) const
263 xmltooling::NDC ndc("doAuthorization");
265 Category& log = Category::getInstance(SHIBSP_LOGCAT".ServiceProvider");
267 const Application* app=NULL;
268 string targetURL = request.getRequestURL();
271 RequestMapper::Settings settings = request.getRequestSettings();
272 app = &(request.getApplication());
274 // Three settings dictate how to proceed.
275 pair<bool,const char*> authType = settings.first->getString("authType");
276 pair<bool,bool> requireSession = settings.first->getBool("requireSession");
277 pair<bool,const char*> requireSessionWith = settings.first->getString("requireSessionWith");
279 // If no session is required AND the AuthType (an Apache-derived concept) isn't shibboleth,
280 // then we ignore this request and consider it unprotected. Apache might lie to us if
281 // ShibBasicHijack is on, but that's up to it.
282 if ((!requireSession.first || !requireSession.second) && !requireSessionWith.first &&
283 #ifdef HAVE_STRCASECMP
284 (!authType.first || strcasecmp(authType.second,"shibboleth")))
286 (!authType.first || _stricmp(authType.second,"shibboleth")))
288 return make_pair(true,request.returnDecline());
290 // Do we have an access control plugin?
291 if (settings.second) {
292 const Session* session = NULL;
294 session = request.getSession(false);
296 catch (exception& e) {
297 log.warn("unable to obtain session to pass to access control provider: %s", e.what());
300 Locker acllock(settings.second);
301 switch (settings.second->authorized(request,session)) {
302 case AccessControl::shib_acl_true:
303 log.debug("access control provider granted access");
304 return make_pair(true,request.returnOK());
306 case AccessControl::shib_acl_false:
308 log.warn("access control provider denied access");
309 TemplateParameters tp;
310 tp.m_map["requestURL"] = targetURL;
311 return make_pair(true,sendError(log, request, app, "access", tp, false));
315 // Use the "DECLINE" interface to signal we don't know what to do.
316 return make_pair(true,request.returnDecline());
320 return make_pair(true,request.returnDecline());
323 catch (exception& e) {
324 TemplateParameters tp(&e);
325 tp.m_map["requestURL"] = targetURL.substr(0,targetURL.find('?'));
326 return make_pair(true,sendError(log, request, app, "access", tp));
330 pair<bool,long> ServiceProvider::doExport(SPRequest& request, bool requireSession) const
333 xmltooling::NDC ndc("doExport");
335 Category& log = Category::getInstance(SHIBSP_LOGCAT".ServiceProvider");
337 const Application* app=NULL;
338 string targetURL = request.getRequestURL();
341 RequestMapper::Settings settings = request.getRequestSettings();
342 app = &(request.getApplication());
344 const Session* session = NULL;
346 session = request.getSession(false);
348 catch (exception& e) {
349 log.warn("unable to obtain session to export to request: %s", e.what());
350 // If we have to have a session, then this is a fatal error.
358 throw opensaml::RetryableProfileException("Unable to obtain session to export to request.");
360 return make_pair(false,0L); // just bail silently
363 app->setHeader(request, "Shib-Application-ID", app->getId());
364 app->setHeader(request, "Shib-Session-ID", session->getID());
366 // Export the IdP name and Authn method/context info.
367 const char* hval = session->getEntityID();
369 app->setHeader(request, "Shib-Identity-Provider", hval);
370 hval = session->getAuthnInstant();
372 app->setHeader(request, "Shib-Authentication-Instant", hval);
373 hval = session->getAuthnContextClassRef();
375 app->setHeader(request, "Shib-Authentication-Method", hval);
376 app->setHeader(request, "Shib-AuthnContext-Class", hval);
378 hval = session->getAuthnContextDeclRef();
380 app->setHeader(request, "Shib-AuthnContext-Decl", hval);
382 // Maybe export the assertion keys.
383 pair<bool,bool> exp=settings.first->getBool("exportAssertion");
384 if (exp.first && exp.second) {
385 const PropertySet* sessions=app->getPropertySet("Sessions");
386 pair<bool,const char*> exportLocation = sessions ? sessions->getString("exportLocation") : pair<bool,const char*>(false,NULL);
387 if (!exportLocation.first)
388 log.warn("can't export assertions without an exportLocation Sessions property");
390 const URLEncoder* encoder = XMLToolingConfig::getConfig().getURLEncoder();
391 string exportName = "Shib-Assertion-00";
393 if (!strncmp(exportLocation.second, "http", 4))
394 baseURL = exportLocation.second;
396 baseURL = string(request.getHandlerURL(targetURL.c_str())) + exportLocation.second;
397 baseURL = baseURL + "?key=" + session->getID() + "&ID=";
398 const vector<const char*>& tokens = session->getAssertionIDs();
399 vector<const char*>::size_type count = 0;
400 for (vector<const char*>::const_iterator tokenids = tokens.begin(); tokenids!=tokens.end(); ++tokenids) {
402 *(exportName.rbegin()) = '0' + (count%10);
403 *(++exportName.rbegin()) = '0' + (count/10);
404 string fullURL = baseURL + encoder->encode(*tokenids);
405 app->setHeader(request, exportName.c_str(), fullURL.c_str());
407 app->setHeader(request, "Shib-Assertion-Count", exportName.c_str() + 15);
411 // Export the attributes.
412 const multimap<string,const Attribute*>& attributes = session->getIndexedAttributes();
413 for (multimap<string,const Attribute*>::const_iterator a = attributes.begin(); a!=attributes.end(); ++a) {
414 string header(app->getSecureHeader(request, a->first.c_str()));
415 const vector<string>& vals = a->second->getSerializedValues();
416 for (vector<string>::const_iterator v = vals.begin(); v!=vals.end(); ++v) {
419 string::size_type pos = v->find_first_of(';',string::size_type(0));
420 if (pos!=string::npos) {
422 for (; pos != string::npos; pos = value.find_first_of(';',pos)) {
423 value.insert(pos, "\\");
432 app->setHeader(request, a->first.c_str(), header.c_str());
435 // Check for REMOTE_USER.
436 bool remoteUserSet = false;
437 const vector<string>& rmids = app->getRemoteUserAttributeIds();
438 for (vector<string>::const_iterator rmid = rmids.begin(); !remoteUserSet && rmid != rmids.end(); ++rmid) {
439 pair<multimap<string,const Attribute*>::const_iterator,multimap<string,const Attribute*>::const_iterator> matches =
440 attributes.equal_range(*rmid);
441 while (matches.first != matches.second) {
442 const vector<string>& vals = matches.first->second->getSerializedValues();
444 request.setRemoteUser(vals.front().c_str());
445 remoteUserSet = true;
451 return make_pair(false,0L);
453 catch (exception& e) {
454 TemplateParameters tp(&e);
455 tp.m_map["requestURL"] = targetURL.substr(0,targetURL.find('?'));
456 return make_pair(true,sendError(log, request, app, "session", tp));
460 pair<bool,long> ServiceProvider::doHandler(SPRequest& request) const
463 xmltooling::NDC ndc("doHandler");
465 Category& log = Category::getInstance(SHIBSP_LOGCAT".ServiceProvider");
467 const Application* app=NULL;
468 string targetURL = request.getRequestURL();
471 RequestMapper::Settings settings = request.getRequestSettings();
472 app = &(request.getApplication());
474 // If not SSL, check to see if we should block or redirect it.
475 if (!request.isSecure()) {
476 pair<bool,const char*> redirectToSSL = settings.first->getString("redirectToSSL");
477 if (redirectToSSL.first) {
478 #ifdef HAVE_STRCASECMP
479 if (!strcasecmp("GET",request.getMethod()) || !strcasecmp("HEAD",request.getMethod())) {
481 if (!stricmp("GET",request.getMethod()) || !stricmp("HEAD",request.getMethod())) {
483 // Compute the new target URL
484 string redirectURL = string("https://") + request.getHostname();
485 if (strcmp(redirectToSSL.second,"443")) {
486 redirectURL = redirectURL + ':' + redirectToSSL.second;
488 redirectURL += request.getRequestURI();
489 return make_pair(true, request.sendRedirect(redirectURL.c_str()));
492 TemplateParameters tp;
493 tp.m_map["requestURL"] = targetURL.substr(0,targetURL.find('?'));
494 return make_pair(true,sendError(log, request, app, "ssl", tp, false));
499 const char* handlerURL=request.getHandlerURL(targetURL.c_str());
501 throw ConfigurationException("Cannot determine handler from resource URL, check configuration.");
503 // Make sure we only process handler requests.
504 if (!strstr(targetURL.c_str(),handlerURL))
505 return make_pair(true, request.returnDecline());
507 const PropertySet* sessionProps=app->getPropertySet("Sessions");
509 throw ConfigurationException("Unable to map request to application session settings, check configuration.");
511 // Process incoming request.
512 pair<bool,bool> handlerSSL=sessionProps->getBool("handlerSSL");
514 // Make sure this is SSL, if it should be
515 if ((!handlerSSL.first || handlerSSL.second) && !request.isSecure())
516 throw opensaml::FatalProfileException("Blocked non-SSL access to Shibboleth handler.");
518 // We dispatch based on our path info. We know the request URL begins with or equals the handler URL,
519 // so the path info is the next character (or null).
520 const Handler* handler=app->getHandler(targetURL.c_str() + strlen(handlerURL));
522 throw ConfigurationException("Shibboleth handler invoked at an unconfigured location.");
524 pair<bool,long> hret=handler->run(request);
526 // Did the handler run successfully?
530 throw ConfigurationException("Configured Shibboleth handler failed to process the request.");
532 catch (exception& e) {
533 TemplateParameters tp(&e);
534 tp.m_map["requestURL"] = targetURL.substr(0,targetURL.find('?'));
535 tp.m_request = &request;
536 return make_pair(true,sendError(log, request, app, "session", tp));