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);
58 const PropertySet* props=app ? app->getPropertySet("Errors") : NULL;
61 RequestMapper::Settings settings = request.getRequestSettings();
63 pathname = settings.first->getString("metadataError");
64 if (!pathname.first) {
65 string pagename(page);
67 pathname = settings.first->getString(pagename.c_str());
70 redirectErrors = settings.first->getString("redirectErrors");
72 catch (exception& ex) {
77 // Check for redirection on errors instead of template.
78 if (!redirectErrors.first && props)
79 redirectErrors = props->getString("redirectErrors");
80 if (redirectErrors.first) {
81 string loc(redirectErrors.second);
82 loc = loc + '?' + tp.toQueryString();
83 return request.sendRedirect(loc.c_str());
87 request.setContentType("text/html");
88 request.setResponseHeader("Expires","01-Jan-1997 12:00:00 GMT");
89 request.setResponseHeader("Cache-Control","private,no-store,no-cache");
91 if (!pathname.first && props) {
93 pathname=props->getString("metadata");
95 pathname=props->getString(page);
98 string fname(pathname.second);
99 ifstream infile(XMLToolingConfig::getConfig().getPathResolver()->resolve(fname, PathResolver::XMLTOOLING_CFG_FILE).c_str());
101 tp.setPropertySet(props);
103 XMLToolingConfig::getConfig().getTemplateEngine()->run(infile, str, tp, tp.getRichException());
104 return request.sendResponse(str);
108 if (!strcmp(page,"access")) {
109 istringstream msg("Access Denied");
110 return request.sendResponse(msg, HTTPResponse::XMLTOOLING_HTTP_STATUS_UNAUTHORIZED);
113 log.error("sendError could not process error template (%s)", page);
114 istringstream msg("Internal Server Error. Please contact the site administrator.");
115 return request.sendError(msg);
118 void SHIBSP_DLLLOCAL clearHeaders(SPRequest& request) {
119 request.clearHeader("Shib-Session-ID", "HTTP_SHIB_SESSION_ID");
120 request.clearHeader("Shib-Identity-Provider", "HTTP_SHIB_IDENTITY_PROVIDER");
121 request.clearHeader("Shib-Authentication-Method", "HTTP_SHIB_AUTHENTICATION_METHOD");
122 request.clearHeader("Shib-Authentication-Instant", "HTTP_SHIB_AUTHENTICATION_INSTANT");
123 request.clearHeader("Shib-AuthnContext-Class", "HTTP_SHIB_AUTHNCONTEXT_CLASS");
124 request.clearHeader("Shib-AuthnContext-Decl", "HTTP_SHIB_AUTHNCONTEXT_DECL");
125 request.clearHeader("Shib-Assertion-Count", "HTTP_SHIB_ASSERTION_COUNT");
126 request.clearHeader("REMOTE_USER", "HTTP_REMOTE_USER");
127 //request.clearHeader("Shib-Application-ID"); handle inside app method
128 request.getApplication().clearAttributeHeaders(request);
132 void SHIBSP_API shibsp::registerServiceProviders()
134 SPConfig::getConfig().ServiceProviderManager.registerFactory(XML_SERVICE_PROVIDER, XMLServiceProviderFactory);
137 pair<bool,long> ServiceProvider::doAuthentication(SPRequest& request, bool handler) const
140 xmltooling::NDC ndc("doAuthentication");
142 Category& log = Category::getInstance(SHIBSP_LOGCAT".ServiceProvider");
144 const Application* app=NULL;
145 string targetURL = request.getRequestURL();
148 RequestMapper::Settings settings = request.getRequestSettings();
149 app = &(request.getApplication());
151 // If not SSL, check to see if we should block or redirect it.
152 if (!request.isSecure()) {
153 pair<bool,const char*> redirectToSSL = settings.first->getString("redirectToSSL");
154 if (redirectToSSL.first) {
155 #ifdef HAVE_STRCASECMP
156 if (!strcasecmp("GET",request.getMethod()) || !strcasecmp("HEAD",request.getMethod())) {
158 if (!stricmp("GET",request.getMethod()) || !stricmp("HEAD",request.getMethod())) {
160 // Compute the new target URL
161 string redirectURL = string("https://") + request.getHostname();
162 if (strcmp(redirectToSSL.second,"443")) {
163 redirectURL = redirectURL + ':' + redirectToSSL.second;
165 redirectURL += request.getRequestURI();
166 return make_pair(true, request.sendRedirect(redirectURL.c_str()));
169 TemplateParameters tp;
170 tp.m_map["requestURL"] = targetURL.substr(0,targetURL.find('?'));
171 return make_pair(true,sendError(log, request, app, "ssl", tp, false));
176 const char* handlerURL=request.getHandlerURL(targetURL.c_str());
178 throw ConfigurationException("Cannot determine handler from resource URL, check configuration.");
180 // If the request URL contains the handler base URL for this application, either dispatch
181 // directly (mainly Apache 2.0) or just pass back control.
182 if (strstr(targetURL.c_str(),handlerURL)) {
184 return doHandler(request);
186 return make_pair(true, request.returnOK());
189 // Three settings dictate how to proceed.
190 pair<bool,const char*> authType = settings.first->getString("authType");
191 pair<bool,bool> requireSession = settings.first->getBool("requireSession");
192 pair<bool,const char*> requireSessionWith = settings.first->getString("requireSessionWith");
194 // If no session is required AND the AuthType (an Apache-derived concept) isn't shibboleth,
195 // then we ignore this request and consider it unprotected. Apache might lie to us if
196 // ShibBasicHijack is on, but that's up to it.
197 if ((!requireSession.first || !requireSession.second) && !requireSessionWith.first &&
198 #ifdef HAVE_STRCASECMP
199 (!authType.first || strcasecmp(authType.second,"shibboleth")))
201 (!authType.first || _stricmp(authType.second,"shibboleth")))
203 return make_pair(true,request.returnDecline());
205 // Fix for secadv 20050901
206 clearHeaders(request);
208 Session* session = NULL;
210 session = request.getSession();
212 catch (exception& e) {
213 log.warn("error during session lookup: %s", e.what());
214 // If it's not a retryable session failure, we throw to the outer handler for reporting.
215 if (dynamic_cast<opensaml::RetryableProfileException*>(&e)==NULL)
220 // No session. Maybe that's acceptable?
221 if ((!requireSession.first || !requireSession.second) && !requireSessionWith.first)
222 return make_pair(true,request.returnOK());
224 // No session, but we require one. Initiate a new session using the indicated method.
225 const Handler* initiator=NULL;
226 if (requireSessionWith.first) {
227 initiator=app->getSessionInitiatorById(requireSessionWith.second);
229 throw ConfigurationException(
230 "No session initiator found with id ($1), check requireSessionWith command.", params(1,requireSessionWith.second)
235 initiator=app->getDefaultSessionInitiator();
237 throw ConfigurationException("No default session initiator found, check configuration.");
240 return initiator->run(request,false);
243 // We're done. Everything is okay. Nothing to report. Nothing to do..
244 // Let the caller decide how to proceed.
245 log.debug("doAuthentication succeeded");
246 return make_pair(false,0L);
248 catch (exception& e) {
249 TemplateParameters tp(&e);
250 tp.m_map["requestURL"] = targetURL.substr(0,targetURL.find('?'));
251 return make_pair(true,sendError(log, request, app, "session", tp));
255 pair<bool,long> ServiceProvider::doAuthorization(SPRequest& request) const
258 xmltooling::NDC ndc("doAuthorization");
260 Category& log = Category::getInstance(SHIBSP_LOGCAT".ServiceProvider");
262 const Application* app=NULL;
263 string targetURL = request.getRequestURL();
266 RequestMapper::Settings settings = request.getRequestSettings();
267 app = &(request.getApplication());
269 // Three settings dictate how to proceed.
270 pair<bool,const char*> authType = settings.first->getString("authType");
271 pair<bool,bool> requireSession = settings.first->getBool("requireSession");
272 pair<bool,const char*> requireSessionWith = settings.first->getString("requireSessionWith");
274 // If no session is required AND the AuthType (an Apache-derived concept) isn't shibboleth,
275 // then we ignore this request and consider it unprotected. Apache might lie to us if
276 // ShibBasicHijack is on, but that's up to it.
277 if ((!requireSession.first || !requireSession.second) && !requireSessionWith.first &&
278 #ifdef HAVE_STRCASECMP
279 (!authType.first || strcasecmp(authType.second,"shibboleth")))
281 (!authType.first || _stricmp(authType.second,"shibboleth")))
283 return make_pair(true,request.returnDecline());
285 // Do we have an access control plugin?
286 if (settings.second) {
287 const Session* session = NULL;
289 session = request.getSession(false);
291 catch (exception& e) {
292 log.warn("unable to obtain session to pass to access control provider: %s", e.what());
295 Locker acllock(settings.second);
296 switch (settings.second->authorized(request,session)) {
297 case AccessControl::shib_acl_true:
298 log.debug("access control provider granted access");
299 return make_pair(true,request.returnOK());
301 case AccessControl::shib_acl_false:
303 log.warn("access control provider denied access");
304 TemplateParameters tp;
305 tp.m_map["requestURL"] = targetURL;
306 return make_pair(true,sendError(log, request, app, "access", tp, false));
310 // Use the "DECLINE" interface to signal we don't know what to do.
311 return make_pair(true,request.returnDecline());
315 return make_pair(true,request.returnDecline());
318 catch (exception& e) {
319 TemplateParameters tp(&e);
320 tp.m_map["requestURL"] = targetURL.substr(0,targetURL.find('?'));
321 return make_pair(true,sendError(log, request, app, "access", tp));
325 pair<bool,long> ServiceProvider::doExport(SPRequest& request, bool requireSession) const
328 xmltooling::NDC ndc("doExport");
330 Category& log = Category::getInstance(SHIBSP_LOGCAT".ServiceProvider");
332 const Application* app=NULL;
333 string targetURL = request.getRequestURL();
336 RequestMapper::Settings settings = request.getRequestSettings();
337 app = &(request.getApplication());
339 const Session* session = NULL;
341 session = request.getSession(false);
343 catch (exception& e) {
344 log.warn("unable to obtain session to export to request: %s", e.what());
345 // If we have to have a session, then this is a fatal error.
353 throw opensaml::RetryableProfileException("Unable to obtain session to export to request.");
355 return make_pair(false,0L); // just bail silently
358 request.setHeader("Shib-Application-ID", app->getId());
359 request.setHeader("Shib-Session-ID", session->getID());
361 // Export the IdP name and Authn method/context info.
362 const char* hval = session->getEntityID();
364 request.setHeader("Shib-Identity-Provider", hval);
365 hval = session->getAuthnInstant();
367 request.setHeader("Shib-Authentication-Instant", hval);
368 hval = session->getAuthnContextClassRef();
370 request.setHeader("Shib-Authentication-Method", hval);
371 request.setHeader("Shib-AuthnContext-Class", hval);
373 hval = session->getAuthnContextDeclRef();
375 request.setHeader("Shib-AuthnContext-Decl", hval);
377 // Maybe export the assertion keys.
378 pair<bool,bool> exp=settings.first->getBool("exportAssertion");
379 if (exp.first && exp.second) {
380 const PropertySet* sessions=app->getPropertySet("Sessions");
381 pair<bool,const char*> exportLocation = sessions ? sessions->getString("exportLocation") : pair<bool,const char*>(false,NULL);
382 if (!exportLocation.first)
383 log.warn("can't export assertions without an exportLocation Sessions property");
385 const URLEncoder* encoder = XMLToolingConfig::getConfig().getURLEncoder();
386 string exportName = "Shib-Assertion-00";
388 if (!strncmp(exportLocation.second, "http", 4))
389 baseURL = exportLocation.second;
391 baseURL = string(request.getHandlerURL(targetURL.c_str())) + exportLocation.second;
392 baseURL = baseURL + "?key=" + session->getID() + "&ID=";
393 const vector<const char*>& tokens = session->getAssertionIDs();
394 vector<const char*>::size_type count = 0;
395 for (vector<const char*>::const_iterator tokenids = tokens.begin(); tokenids!=tokens.end(); ++tokenids) {
397 *(exportName.rbegin()) = '0' + (count%10);
398 *(++exportName.rbegin()) = '0' + (count/10);
399 string fullURL = baseURL + encoder->encode(*tokenids);
400 request.setHeader(exportName.c_str(), fullURL.c_str());
402 request.setHeader("Shib-Assertion-Count", exportName.c_str() + 15);
406 // Export the attributes.
407 const multimap<string,const Attribute*>& attributes = session->getIndexedAttributes();
408 for (multimap<string,const Attribute*>::const_iterator a = attributes.begin(); a!=attributes.end(); ++a) {
409 string header(request.getSecureHeader(a->first.c_str()));
410 const vector<string>& vals = a->second->getSerializedValues();
411 for (vector<string>::const_iterator v = vals.begin(); v!=vals.end(); ++v) {
414 string::size_type pos = v->find_first_of(';',string::size_type(0));
415 if (pos!=string::npos) {
417 for (; pos != string::npos; pos = value.find_first_of(';',pos)) {
418 value.insert(pos, "\\");
427 request.setHeader(a->first.c_str(), header.c_str());
430 // Check for REMOTE_USER.
431 bool remoteUserSet = false;
432 const vector<string>& rmids = app->getRemoteUserAttributeIds();
433 for (vector<string>::const_iterator rmid = rmids.begin(); !remoteUserSet && rmid != rmids.end(); ++rmid) {
434 pair<multimap<string,const Attribute*>::const_iterator,multimap<string,const Attribute*>::const_iterator> matches =
435 attributes.equal_range(*rmid);
436 while (matches.first != matches.second) {
437 const vector<string>& vals = matches.first->second->getSerializedValues();
439 request.setRemoteUser(vals.front().c_str());
440 remoteUserSet = true;
446 return make_pair(false,0L);
448 catch (exception& e) {
449 TemplateParameters tp(&e);
450 tp.m_map["requestURL"] = targetURL.substr(0,targetURL.find('?'));
451 return make_pair(true,sendError(log, request, app, "session", tp));
455 pair<bool,long> ServiceProvider::doHandler(SPRequest& request) const
458 xmltooling::NDC ndc("doHandler");
460 Category& log = Category::getInstance(SHIBSP_LOGCAT".ServiceProvider");
462 const Application* app=NULL;
463 string targetURL = request.getRequestURL();
466 RequestMapper::Settings settings = request.getRequestSettings();
467 app = &(request.getApplication());
469 // If not SSL, check to see if we should block or redirect it.
470 if (!request.isSecure()) {
471 pair<bool,const char*> redirectToSSL = settings.first->getString("redirectToSSL");
472 if (redirectToSSL.first) {
473 #ifdef HAVE_STRCASECMP
474 if (!strcasecmp("GET",request.getMethod()) || !strcasecmp("HEAD",request.getMethod())) {
476 if (!stricmp("GET",request.getMethod()) || !stricmp("HEAD",request.getMethod())) {
478 // Compute the new target URL
479 string redirectURL = string("https://") + request.getHostname();
480 if (strcmp(redirectToSSL.second,"443")) {
481 redirectURL = redirectURL + ':' + redirectToSSL.second;
483 redirectURL += request.getRequestURI();
484 return make_pair(true, request.sendRedirect(redirectURL.c_str()));
487 TemplateParameters tp;
488 tp.m_map["requestURL"] = targetURL.substr(0,targetURL.find('?'));
489 return make_pair(true,sendError(log, request, app, "ssl", tp, false));
494 const char* handlerURL=request.getHandlerURL(targetURL.c_str());
496 throw ConfigurationException("Cannot determine handler from resource URL, check configuration.");
498 // Make sure we only process handler requests.
499 if (!strstr(targetURL.c_str(),handlerURL))
500 return make_pair(true, request.returnDecline());
502 const PropertySet* sessionProps=app->getPropertySet("Sessions");
504 throw ConfigurationException("Unable to map request to application session settings, check configuration.");
506 // Process incoming request.
507 pair<bool,bool> handlerSSL=sessionProps->getBool("handlerSSL");
509 // Make sure this is SSL, if it should be
510 if ((!handlerSSL.first || handlerSSL.second) && !request.isSecure())
511 throw opensaml::FatalProfileException("Blocked non-SSL access to Shibboleth handler.");
513 // We dispatch based on our path info. We know the request URL begins with or equals the handler URL,
514 // so the path info is the next character (or null).
515 const Handler* handler=app->getHandler(targetURL.c_str() + strlen(handlerURL));
517 throw ConfigurationException("Shibboleth handler invoked at an unconfigured location.");
519 pair<bool,long> hret=handler->run(request);
521 // Did the handler run successfully?
525 throw ConfigurationException("Configured Shibboleth handler failed to process the request.");
527 catch (exception& e) {
528 TemplateParameters tp(&e);
529 tp.m_map["requestURL"] = targetURL.substr(0,targetURL.find('?'));
530 tp.m_request = &request;
531 return make_pair(true,sendError(log, request, app, "session", tp));