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/Handler.h"
32 #include "util/TemplateParameters.h"
36 #include <saml/saml2/metadata/Metadata.h>
37 #include <saml/util/SAMLConstants.h>
38 #include <xmltooling/XMLToolingConfig.h>
39 #include <xmltooling/util/NDC.h>
40 #include <xmltooling/util/XMLHelper.h>
42 using namespace shibsp;
43 using namespace opensaml::saml2md;
44 using namespace opensaml;
45 using namespace xmltooling;
49 SHIBSP_DLLLOCAL PluginManager<ServiceProvider,const DOMElement*>::Factory XMLServiceProviderFactory;
51 long SHIBSP_DLLLOCAL sendError(SPRequest& request, const Application* app, const char* page, TemplateParameters& tp, bool mayRedirect=false)
54 // Check for redirection on errors instead of template.
55 const PropertySet* sessions=app ? app->getPropertySet("Sessions") : NULL;
56 pair<bool,const char*> redirectErrors = sessions ? sessions->getString("redirectErrors") : pair<bool,const char*>(false,NULL);
57 if (redirectErrors.first) {
58 string loc(redirectErrors.second);
59 loc = loc + '?' + tp.toQueryString();
60 return request.sendRedirect(loc.c_str());
64 request.setContentType("text/html");
65 request.setResponseHeader("Expires","01-Jan-1997 12:00:00 GMT");
66 request.setResponseHeader("Cache-Control","private,no-store,no-cache");
68 const PropertySet* props=app ? app->getPropertySet("Errors") : NULL;
70 pair<bool,const char*> p=props->getString(page);
72 ifstream infile(p.second);
74 tp.setPropertySet(props);
76 XMLToolingConfig::getConfig().getTemplateEngine()->run(infile, str, tp, tp.getRichException());
77 return request.sendResponse(str);
80 else if (!strcmp(page,"access")) {
81 istringstream msg("Access Denied");
82 return static_cast<opensaml::GenericResponse&>(request).sendResponse(msg, HTTPResponse::SAML_HTTP_STATUS_FORBIDDEN);
86 string errstr = string("sendError could not process error template (") + page + ")";
87 request.log(SPRequest::SPError, errstr);
88 istringstream msg("Internal Server Error. Please contact the site administrator.");
89 return request.sendError(msg);
92 void SHIBSP_DLLLOCAL clearHeaders(SPRequest& request) {
93 // Clear invariant stuff.
94 request.clearHeader("Shib-Identity-Provider");
95 request.clearHeader("Shib-Authentication-Method");
96 request.clearHeader("Shib-AuthnContext-Class");
97 request.clearHeader("Shib-AuthnContext-Decl");
98 request.clearHeader("Shib-Attributes");
99 request.clearHeader("Shib-Application-ID");
101 // Clear out the list of mapped attributes
102 /* TODO: need some kind of master attribute list via the new resolver
103 Iterator<IAAP*> provs=dynamic_cast<const IApplication&>(getApplication()).getAAPProviders();
104 while (provs.hasNext()) {
105 IAAP* aap=provs.next();
106 xmltooling::Locker locker(aap);
107 Iterator<const IAttributeRule*> rules=aap->getAttributeRules();
108 while (rules.hasNext()) {
109 const char* header=rules.next()->getHeader();
111 request.clearHeader(header);
117 static const XMLCh SessionInitiator[] = UNICODE_LITERAL_16(S,e,s,s,i,o,n,I,n,i,t,i,a,t,o,r);
120 void SHIBSP_API shibsp::registerServiceProviders()
122 SPConfig::getConfig().ServiceProviderManager.registerFactory(XML_SERVICE_PROVIDER, XMLServiceProviderFactory);
125 pair<bool,long> ServiceProvider::doAuthentication(SPRequest& request, bool handler) const
128 xmltooling::NDC ndc("doAuthentication");
131 const Application* app=NULL;
132 string targetURL = request.getRequestURL();
135 RequestMapper::Settings settings = request.getRequestSettings();
136 app = &(request.getApplication());
138 // If not SSL, check to see if we should block or redirect it.
139 if (!request.isSecure()) {
140 pair<bool,const char*> redirectToSSL = settings.first->getString("redirectToSSL");
141 if (redirectToSSL.first) {
142 #ifdef HAVE_STRCASECMP
143 if (!strcasecmp("GET",request.getMethod()) || !strcasecmp("HEAD",request.getMethod())) {
145 if (!stricmp("GET",request.getMethod()) || !stricmp("HEAD",request.getMethod())) {
147 // Compute the new target URL
148 string redirectURL = string("https://") + request.getHostname();
149 if (strcmp(redirectToSSL.second,"443")) {
150 redirectURL = redirectURL + ':' + redirectToSSL.second;
152 redirectURL += request.getRequestURI();
153 return make_pair(true, request.sendRedirect(redirectURL.c_str()));
156 TemplateParameters tp;
157 tp.m_map["requestURL"] = targetURL.substr(0,targetURL.find('?'));
158 return make_pair(true,sendError(request, app, "ssl", tp));
163 const char* handlerURL=request.getHandlerURL(targetURL.c_str());
165 throw ConfigurationException("Cannot determine handler from resource URL, check configuration.");
167 // If the request URL contains the handler base URL for this application, either dispatch
168 // directly (mainly Apache 2.0) or just pass back control.
169 if (strstr(targetURL.c_str(),handlerURL)) {
171 return doHandler(request);
173 return make_pair(true, request.returnOK());
176 // Three settings dictate how to proceed.
177 pair<bool,const char*> authType = settings.first->getString("authType");
178 pair<bool,bool> requireSession = settings.first->getBool("requireSession");
179 pair<bool,const char*> requireSessionWith = settings.first->getString("requireSessionWith");
181 // If no session is required AND the AuthType (an Apache-derived concept) isn't shibboleth,
182 // then we ignore this request and consider it unprotected. Apache might lie to us if
183 // ShibBasicHijack is on, but that's up to it.
184 if ((!requireSession.first || !requireSession.second) && !requireSessionWith.first &&
185 #ifdef HAVE_STRCASECMP
186 (!authType.first || strcasecmp(authType.second,"shibboleth")))
188 (!authType.first || _stricmp(authType.second,"shibboleth")))
190 return make_pair(true,request.returnDecline());
192 // Fix for secadv 20050901
193 clearHeaders(request);
195 Session* session = NULL;
197 session = request.getSession();
199 catch (exception& e) {
200 request.log(SPRequest::SPWarn, string("error during session lookup: ") + e.what());
201 // If it's not a retryable session failure, we throw to the outer handler for reporting.
202 if (dynamic_cast<RetryableProfileException*>(&e)==NULL)
207 // No session. Maybe that's acceptable?
208 if ((!requireSession.first || !requireSession.second) && !requireSessionWith.first)
209 return make_pair(true,request.returnOK());
211 // No session, but we require one. Initiate a new session using the indicated method.
212 const Handler* initiator=NULL;
213 if (requireSessionWith.first) {
214 initiator=app->getSessionInitiatorById(requireSessionWith.second);
216 throw ConfigurationException(
217 "No session initiator found with id ($1), check requireSessionWith command.",
218 params(1,requireSessionWith.second)
222 initiator=app->getDefaultSessionInitiator();
224 throw ConfigurationException("No default session initiator found, check configuration.");
227 return initiator->run(request,false);
230 // We're done. Everything is okay. Nothing to report. Nothing to do..
231 // Let the caller decide how to proceed.
232 request.log(SPRequest::SPDebug, "doAuthentication succeeded");
233 return make_pair(false,0);
235 catch (exception& e) {
236 TemplateParameters tp(&e);
237 tp.m_map["requestURL"] = targetURL.substr(0,targetURL.find('?'));
238 return make_pair(true,sendError(request, app, "session", tp));
242 TemplateParameters tp;
243 tp.m_map["errorType"] = "Unexpected Error";
244 tp.m_map["errorText"] = "Caught an unknown exception.";
245 tp.m_map["requestURL"] = targetURL.substr(0,targetURL.find('?'));
246 return make_pair(true,sendError(request, app, "session", tp));
251 pair<bool,long> ServiceProvider::doAuthorization(SPRequest& request) const
254 xmltooling::NDC ndc("doAuthorization");
257 const Application* app=NULL;
258 string targetURL = request.getRequestURL();
261 RequestMapper::Settings settings = request.getRequestSettings();
262 app = &(request.getApplication());
264 // Three settings dictate how to proceed.
265 pair<bool,const char*> authType = settings.first->getString("authType");
266 pair<bool,bool> requireSession = settings.first->getBool("requireSession");
267 pair<bool,const char*> requireSessionWith = settings.first->getString("requireSessionWith");
269 // If no session is required AND the AuthType (an Apache-derived concept) isn't shibboleth,
270 // then we ignore this request and consider it unprotected. Apache might lie to us if
271 // ShibBasicHijack is on, but that's up to it.
272 if ((!requireSession.first || !requireSession.second) && !requireSessionWith.first &&
273 #ifdef HAVE_STRCASECMP
274 (!authType.first || strcasecmp(authType.second,"shibboleth")))
276 (!authType.first || _stricmp(authType.second,"shibboleth")))
278 return make_pair(true,request.returnDecline());
280 // Do we have an access control plugin?
281 if (settings.second) {
282 const Session* session = NULL;
284 session = request.getSession();
286 catch (exception& e) {
287 request.log(SPRequest::SPWarn, string("unable to obtain session to pass to access control provider: ") + e.what());
290 Locker acllock(settings.second);
291 if (settings.second->authorized(request,session)) {
292 // Let the caller decide how to proceed.
293 request.log(SPRequest::SPDebug, "access control provider granted access");
294 return make_pair(false,0);
297 request.log(SPRequest::SPWarn, "access control provider denied access");
298 TemplateParameters tp;
299 tp.m_map["requestURL"] = targetURL;
300 return make_pair(true,sendError(request, app, "access", tp));
302 return make_pair(false,0);
305 return make_pair(true,request.returnDecline());
307 catch (exception& e) {
308 TemplateParameters tp(&e);
309 tp.m_map["requestURL"] = targetURL.substr(0,targetURL.find('?'));
310 return make_pair(true,sendError(request, app, "access", tp));
314 TemplateParameters tp;
315 tp.m_map["errorType"] = "Unexpected Error";
316 tp.m_map["errorText"] = "Caught an unknown exception.";
317 tp.m_map["requestURL"] = targetURL.substr(0,targetURL.find('?'));
318 return make_pair(true,sendError(request, app, "access", tp));
323 pair<bool,long> ServiceProvider::doExport(SPRequest& request, bool requireSession) const
326 xmltooling::NDC ndc("doExport");
329 const Application* app=NULL;
330 string targetURL = request.getRequestURL();
333 RequestMapper::Settings settings = request.getRequestSettings();
334 app = &(request.getApplication());
336 const Session* session = NULL;
338 session = request.getSession();
340 catch (exception& e) {
341 request.log(SPRequest::SPWarn, string("unable to obtain session to export to request: ") + e.what());
342 // If we have to have a session, then this is a fatal error.
350 throw RetryableProfileException("Unable to obtain session to export to request.");
352 return make_pair(false,0); // just bail silently
355 request.setHeader("Shib-Application-ID", app->getId());
357 // Export the IdP name and Authn method/context info.
358 const char* hval = session->getEntityID();
360 request.setHeader("Shib-Identity-Provider", hval);
361 hval = session->getAuthnContextClassRef();
363 request.setHeader("Shib-Authentication-Method", hval);
364 request.setHeader("Shib-AuthnContext-Class", hval);
366 hval = session->getAuthnContextDeclRef();
368 request.setHeader("Shib-AuthnContext-Decl", hval);
370 // Maybe export the assertion keys.
371 pair<bool,bool> exp=settings.first->getBool("exportAssertion");
372 if (exp.first && exp.second) {
373 //setHeader("Shib-Attributes", reinterpret_cast<char*>(serialized));
374 // TODO: export lookup URLs to access assertions by ID
375 const vector<const char*>& tokens = session->getAssertionIDs();
378 // Export the attributes.
379 const map<string,const Attribute*>& attributes = session->getAttributes();
380 for (map<string,const Attribute*>::const_iterator a = attributes.begin(); a!=attributes.end(); ++a) {
381 const vector<string>& vals = a->second->getSerializedValues();
382 if (!strcmp(a->second->getId(), "REMOTE_USER") && !vals.empty())
383 request.setRemoteUser(vals.front().c_str());
385 string header(request.getSecureHeader(a->second->getId()));
386 for (vector<string>::const_iterator v = vals.begin(); v!=vals.end(); ++v) {
389 string::size_type pos = v->find_first_of(';',string::size_type(0));
390 if (pos!=string::npos) {
392 for (; pos != string::npos; pos = value.find_first_of(';',pos)) {
393 value.insert(pos, "\\");
402 request.setHeader(a->second->getId(), header.c_str());
406 return make_pair(false,0);
408 catch (exception& e) {
409 TemplateParameters tp(&e);
410 tp.m_map["requestURL"] = targetURL.substr(0,targetURL.find('?'));
411 return make_pair(true,sendError(request, app, "rm", tp));
415 TemplateParameters tp;
416 tp.m_map["errorType"] = "Unexpected Error";
417 tp.m_map["errorText"] = "Caught an unknown exception.";
418 tp.m_map["requestURL"] = targetURL.substr(0,targetURL.find('?'));
419 return make_pair(true,sendError(request, app, "rm", tp));
424 pair<bool,long> ServiceProvider::doHandler(SPRequest& request) const
427 xmltooling::NDC ndc("doHandler");
430 const Application* app=NULL;
431 string targetURL = request.getRequestURL();
434 RequestMapper::Settings settings = request.getRequestSettings();
435 app = &(request.getApplication());
437 const char* handlerURL=request.getHandlerURL(targetURL.c_str());
439 throw ConfigurationException("Cannot determine handler from resource URL, check configuration.");
441 // Make sure we only process handler requests.
442 if (!strstr(targetURL.c_str(),handlerURL))
443 return make_pair(true, request.returnDecline());
445 const PropertySet* sessionProps=app->getPropertySet("Sessions");
447 throw ConfigurationException("Unable to map request to application session settings, check configuration.");
449 // Process incoming request.
450 pair<bool,bool> handlerSSL=sessionProps->getBool("handlerSSL");
452 // Make sure this is SSL, if it should be
453 if ((!handlerSSL.first || handlerSSL.second) && !request.isSecure())
454 throw SecurityPolicyException("Blocked non-SSL access to Shibboleth handler.");
456 // We dispatch based on our path info. We know the request URL begins with or equals the handler URL,
457 // so the path info is the next character (or null).
458 const Handler* handler=app->getHandler(targetURL.c_str() + strlen(handlerURL));
460 throw ConfigurationException("Shibboleth handler invoked at an unconfigured location.");
462 pair<bool,long> hret=handler->run(request);
464 // Did the handler run successfully?
468 throw ConfigurationException("Configured Shibboleth handler failed to process the request.");
470 catch (MetadataException& e) {
471 TemplateParameters tp(&e);
472 tp.m_map["requestURL"] = targetURL.substr(0,targetURL.find('?'));
473 // See if a metadata error page is installed.
474 const PropertySet* props=app ? app->getPropertySet("Errors") : NULL;
476 pair<bool,const char*> p=props->getString("metadata");
478 return make_pair(true,sendError(request, app, "metadata", tp, true));
480 return make_pair(true,sendError(request, app, "session", tp, true));
482 catch (exception& e) {
483 TemplateParameters tp(&e);
484 tp.m_map["requestURL"] = targetURL.substr(0,targetURL.find('?'));
485 return make_pair(true,sendError(request, app, "session", tp, true));
489 TemplateParameters tp;
490 tp.m_map["errorType"] = "Unexpected Error";
491 tp.m_map["errorText"] = "Caught an unknown exception.";
492 tp.m_map["requestURL"] = targetURL.substr(0,targetURL.find('?'));
493 return make_pair(true,sendError(request, app, "session", tp, true));