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/XMLHelper.h>
40 using namespace shibsp;
41 using namespace xmltooling;
45 SHIBSP_DLLLOCAL PluginManager<ServiceProvider,string,const DOMElement*>::Factory XMLServiceProviderFactory;
47 long SHIBSP_DLLLOCAL sendError(SPRequest& request, const Application* app, const char* page, TemplateParameters& tp, bool mayRedirect=false)
50 // Check for redirection on errors instead of template.
51 const PropertySet* sessions=app ? app->getPropertySet("Sessions") : NULL;
52 pair<bool,const char*> redirectErrors = sessions ? sessions->getString("redirectErrors") : pair<bool,const char*>(false,NULL);
53 if (redirectErrors.first) {
54 string loc(redirectErrors.second);
55 loc = loc + '?' + tp.toQueryString();
56 return request.sendRedirect(loc.c_str());
60 request.setContentType("text/html");
61 request.setResponseHeader("Expires","01-Jan-1997 12:00:00 GMT");
62 request.setResponseHeader("Cache-Control","private,no-store,no-cache");
64 const PropertySet* props=app ? app->getPropertySet("Errors") : NULL;
66 pair<bool,const char*> p=props->getString(page);
68 ifstream infile(p.second);
70 tp.setPropertySet(props);
72 XMLToolingConfig::getConfig().getTemplateEngine()->run(infile, str, tp, tp.getRichException());
73 return request.sendResponse(str);
76 else if (!strcmp(page,"access")) {
77 istringstream msg("Access Denied");
78 return request.sendResponse(msg, HTTPResponse::XMLTOOLING_HTTP_STATUS_FORBIDDEN);
82 string errstr = string("sendError could not process error template (") + page + ")";
83 request.log(SPRequest::SPError, errstr);
84 istringstream msg("Internal Server Error. Please contact the site administrator.");
85 return request.sendError(msg);
88 void SHIBSP_DLLLOCAL clearHeaders(SPRequest& request) {
89 request.clearHeader("Shib-Identity-Provider");
90 request.clearHeader("Shib-Authentication-Method");
91 request.clearHeader("Shib-AuthnContext-Class");
92 request.clearHeader("Shib-AuthnContext-Decl");
93 request.clearHeader("Shib-Attributes");
94 //request.clearHeader("Shib-Application-ID"); handle inside app method
95 request.getApplication().clearAttributeHeaders(request);
99 void SHIBSP_API shibsp::registerServiceProviders()
101 SPConfig::getConfig().ServiceProviderManager.registerFactory(XML_SERVICE_PROVIDER, XMLServiceProviderFactory);
104 pair<bool,long> ServiceProvider::doAuthentication(SPRequest& request, bool handler) const
107 xmltooling::NDC ndc("doAuthentication");
110 const Application* app=NULL;
111 string targetURL = request.getRequestURL();
114 RequestMapper::Settings settings = request.getRequestSettings();
115 app = &(request.getApplication());
117 // If not SSL, check to see if we should block or redirect it.
118 if (!request.isSecure()) {
119 pair<bool,const char*> redirectToSSL = settings.first->getString("redirectToSSL");
120 if (redirectToSSL.first) {
121 #ifdef HAVE_STRCASECMP
122 if (!strcasecmp("GET",request.getMethod()) || !strcasecmp("HEAD",request.getMethod())) {
124 if (!stricmp("GET",request.getMethod()) || !stricmp("HEAD",request.getMethod())) {
126 // Compute the new target URL
127 string redirectURL = string("https://") + request.getHostname();
128 if (strcmp(redirectToSSL.second,"443")) {
129 redirectURL = redirectURL + ':' + redirectToSSL.second;
131 redirectURL += request.getRequestURI();
132 return make_pair(true, request.sendRedirect(redirectURL.c_str()));
135 TemplateParameters tp;
136 tp.m_map["requestURL"] = targetURL.substr(0,targetURL.find('?'));
137 return make_pair(true,sendError(request, app, "ssl", tp));
142 const char* handlerURL=request.getHandlerURL(targetURL.c_str());
144 throw ConfigurationException("Cannot determine handler from resource URL, check configuration.");
146 // If the request URL contains the handler base URL for this application, either dispatch
147 // directly (mainly Apache 2.0) or just pass back control.
148 if (strstr(targetURL.c_str(),handlerURL)) {
150 return doHandler(request);
152 return make_pair(true, request.returnOK());
155 // Three settings dictate how to proceed.
156 pair<bool,const char*> authType = settings.first->getString("authType");
157 pair<bool,bool> requireSession = settings.first->getBool("requireSession");
158 pair<bool,const char*> requireSessionWith = settings.first->getString("requireSessionWith");
160 // If no session is required AND the AuthType (an Apache-derived concept) isn't shibboleth,
161 // then we ignore this request and consider it unprotected. Apache might lie to us if
162 // ShibBasicHijack is on, but that's up to it.
163 if ((!requireSession.first || !requireSession.second) && !requireSessionWith.first &&
164 #ifdef HAVE_STRCASECMP
165 (!authType.first || strcasecmp(authType.second,"shibboleth")))
167 (!authType.first || _stricmp(authType.second,"shibboleth")))
169 return make_pair(true,request.returnDecline());
171 // Fix for secadv 20050901
172 clearHeaders(request);
174 Session* session = NULL;
176 session = request.getSession();
178 catch (exception& e) {
179 request.log(SPRequest::SPWarn, string("error during session lookup: ") + e.what());
180 // If it's not a retryable session failure, we throw to the outer handler for reporting.
181 if (dynamic_cast<opensaml::RetryableProfileException*>(&e)==NULL)
186 // No session. Maybe that's acceptable?
187 if ((!requireSession.first || !requireSession.second) && !requireSessionWith.first)
188 return make_pair(true,request.returnOK());
190 // No session, but we require one. Initiate a new session using the indicated method.
191 const Handler* initiator=NULL;
192 if (requireSessionWith.first) {
193 initiator=app->getSessionInitiatorById(requireSessionWith.second);
195 throw ConfigurationException(
196 "No session initiator found with id ($1), check requireSessionWith command.",
197 params(1,requireSessionWith.second)
201 initiator=app->getDefaultSessionInitiator();
203 throw ConfigurationException("No default session initiator found, check configuration.");
206 return initiator->run(request,false);
209 // We're done. Everything is okay. Nothing to report. Nothing to do..
210 // Let the caller decide how to proceed.
211 request.log(SPRequest::SPDebug, "doAuthentication succeeded");
212 return make_pair(false,0);
214 catch (exception& e) {
215 TemplateParameters tp(&e);
216 tp.m_map["requestURL"] = targetURL.substr(0,targetURL.find('?'));
217 return make_pair(true,sendError(request, app, "session", tp));
221 TemplateParameters tp;
222 tp.m_map["errorType"] = "Unexpected Error";
223 tp.m_map["errorText"] = "Caught an unknown exception.";
224 tp.m_map["requestURL"] = targetURL.substr(0,targetURL.find('?'));
225 return make_pair(true,sendError(request, app, "session", tp));
230 pair<bool,long> ServiceProvider::doAuthorization(SPRequest& request) const
233 xmltooling::NDC ndc("doAuthorization");
236 const Application* app=NULL;
237 string targetURL = request.getRequestURL();
240 RequestMapper::Settings settings = request.getRequestSettings();
241 app = &(request.getApplication());
243 // Three settings dictate how to proceed.
244 pair<bool,const char*> authType = settings.first->getString("authType");
245 pair<bool,bool> requireSession = settings.first->getBool("requireSession");
246 pair<bool,const char*> requireSessionWith = settings.first->getString("requireSessionWith");
248 // If no session is required AND the AuthType (an Apache-derived concept) isn't shibboleth,
249 // then we ignore this request and consider it unprotected. Apache might lie to us if
250 // ShibBasicHijack is on, but that's up to it.
251 if ((!requireSession.first || !requireSession.second) && !requireSessionWith.first &&
252 #ifdef HAVE_STRCASECMP
253 (!authType.first || strcasecmp(authType.second,"shibboleth")))
255 (!authType.first || _stricmp(authType.second,"shibboleth")))
257 return make_pair(true,request.returnDecline());
259 // Do we have an access control plugin?
260 if (settings.second) {
261 const Session* session = NULL;
263 session = request.getSession();
265 catch (exception& e) {
266 request.log(SPRequest::SPWarn, string("unable to obtain session to pass to access control provider: ") + e.what());
269 Locker acllock(settings.second);
270 if (settings.second->authorized(request,session)) {
271 // Let the caller decide how to proceed.
272 request.log(SPRequest::SPDebug, "access control provider granted access");
273 return make_pair(false,0);
276 request.log(SPRequest::SPWarn, "access control provider denied access");
277 TemplateParameters tp;
278 tp.m_map["requestURL"] = targetURL;
279 return make_pair(true,sendError(request, app, "access", tp));
281 return make_pair(false,0);
284 return make_pair(true,request.returnDecline());
286 catch (exception& e) {
287 TemplateParameters tp(&e);
288 tp.m_map["requestURL"] = targetURL.substr(0,targetURL.find('?'));
289 return make_pair(true,sendError(request, app, "access", tp));
293 TemplateParameters tp;
294 tp.m_map["errorType"] = "Unexpected Error";
295 tp.m_map["errorText"] = "Caught an unknown exception.";
296 tp.m_map["requestURL"] = targetURL.substr(0,targetURL.find('?'));
297 return make_pair(true,sendError(request, app, "access", tp));
302 pair<bool,long> ServiceProvider::doExport(SPRequest& request, bool requireSession) const
305 xmltooling::NDC ndc("doExport");
308 const Application* app=NULL;
309 string targetURL = request.getRequestURL();
312 RequestMapper::Settings settings = request.getRequestSettings();
313 app = &(request.getApplication());
315 const Session* session = NULL;
317 session = request.getSession();
319 catch (exception& e) {
320 request.log(SPRequest::SPWarn, string("unable to obtain session to export to request: ") + e.what());
321 // If we have to have a session, then this is a fatal error.
329 throw opensaml::RetryableProfileException("Unable to obtain session to export to request.");
331 return make_pair(false,0); // just bail silently
334 request.setHeader("Shib-Application-ID", app->getId());
336 // Export the IdP name and Authn method/context info.
337 const char* hval = session->getEntityID();
339 request.setHeader("Shib-Identity-Provider", hval);
340 hval = session->getAuthnContextClassRef();
342 request.setHeader("Shib-Authentication-Method", hval);
343 request.setHeader("Shib-AuthnContext-Class", hval);
345 hval = session->getAuthnContextDeclRef();
347 request.setHeader("Shib-AuthnContext-Decl", hval);
349 // Maybe export the assertion keys.
350 pair<bool,bool> exp=settings.first->getBool("exportAssertion");
351 if (exp.first && exp.second) {
352 //setHeader("Shib-Attributes", reinterpret_cast<char*>(serialized));
353 // TODO: export lookup URLs to access assertions by ID
354 const vector<const char*>& tokens = session->getAssertionIDs();
357 // Export the attributes.
358 bool remoteUserSet = false;
359 const multimap<string,Attribute*>& attributes = session->getAttributes();
360 for (multimap<string,Attribute*>::const_iterator a = attributes.begin(); a!=attributes.end(); ++a) {
361 const vector<string>& vals = a->second->getSerializedValues();
363 // See if this needs to be set as the REMOTE_USER value.
364 if (!remoteUserSet && !vals.empty() && app->getRemoteUserAttributeIds().count(a->first)) {
365 request.setRemoteUser(vals.front().c_str());
366 remoteUserSet = true;
369 // Handle the normal export case.
370 string header(request.getSecureHeader(a->first.c_str()));
371 for (vector<string>::const_iterator v = vals.begin(); v!=vals.end(); ++v) {
374 string::size_type pos = v->find_first_of(';',string::size_type(0));
375 if (pos!=string::npos) {
377 for (; pos != string::npos; pos = value.find_first_of(';',pos)) {
378 value.insert(pos, "\\");
387 request.setHeader(a->first.c_str(), header.c_str());
390 return make_pair(false,0);
392 catch (exception& e) {
393 TemplateParameters tp(&e);
394 tp.m_map["requestURL"] = targetURL.substr(0,targetURL.find('?'));
395 return make_pair(true,sendError(request, app, "rm", tp));
399 TemplateParameters tp;
400 tp.m_map["errorType"] = "Unexpected Error";
401 tp.m_map["errorText"] = "Caught an unknown exception.";
402 tp.m_map["requestURL"] = targetURL.substr(0,targetURL.find('?'));
403 return make_pair(true,sendError(request, app, "rm", tp));
408 pair<bool,long> ServiceProvider::doHandler(SPRequest& request) const
411 xmltooling::NDC ndc("doHandler");
414 const Application* app=NULL;
415 string targetURL = request.getRequestURL();
418 RequestMapper::Settings settings = request.getRequestSettings();
419 app = &(request.getApplication());
421 const char* handlerURL=request.getHandlerURL(targetURL.c_str());
423 throw ConfigurationException("Cannot determine handler from resource URL, check configuration.");
425 // Make sure we only process handler requests.
426 if (!strstr(targetURL.c_str(),handlerURL))
427 return make_pair(true, request.returnDecline());
429 const PropertySet* sessionProps=app->getPropertySet("Sessions");
431 throw ConfigurationException("Unable to map request to application session settings, check configuration.");
433 // Process incoming request.
434 pair<bool,bool> handlerSSL=sessionProps->getBool("handlerSSL");
436 // Make sure this is SSL, if it should be
437 if ((!handlerSSL.first || handlerSSL.second) && !request.isSecure())
438 throw opensaml::FatalProfileException("Blocked non-SSL access to Shibboleth handler.");
440 // We dispatch based on our path info. We know the request URL begins with or equals the handler URL,
441 // so the path info is the next character (or null).
442 const Handler* handler=app->getHandler(targetURL.c_str() + strlen(handlerURL));
444 throw ConfigurationException("Shibboleth handler invoked at an unconfigured location.");
446 pair<bool,long> hret=handler->run(request);
448 // Did the handler run successfully?
452 throw ConfigurationException("Configured Shibboleth handler failed to process the request.");
454 catch (opensaml::saml2md::MetadataException& e) {
455 TemplateParameters tp(&e);
456 tp.m_map["requestURL"] = targetURL.substr(0,targetURL.find('?'));
457 // See if a metadata error page is installed.
458 const PropertySet* props=app ? app->getPropertySet("Errors") : NULL;
460 pair<bool,const char*> p=props->getString("metadata");
462 return make_pair(true,sendError(request, app, "metadata", tp, true));
464 return make_pair(true,sendError(request, app, "session", tp, true));
466 catch (exception& e) {
467 TemplateParameters tp(&e);
468 tp.m_map["requestURL"] = targetURL.substr(0,targetURL.find('?'));
469 return make_pair(true,sendError(request, app, "session", tp, true));
473 TemplateParameters tp;
474 tp.m_map["errorType"] = "Unexpected Error";
475 tp.m_map["errorText"] = "Caught an unknown exception.";
476 tp.m_map["requestURL"] = targetURL.substr(0,targetURL.find('?'));
477 return make_pair(true,sendError(request, app, "session", tp, true));