2 * Licensed to the University Corporation for Advanced Internet
3 * Development, Inc. (UCAID) under one or more contributor license
4 * agreements. See the NOTICE file distributed with this work for
5 * additional information regarding copyright ownership.
7 * UCAID licenses this file to you under the Apache License,
8 * Version 2.0 (the "License"); you may not use this file except
9 * in compliance with the License. You may obtain a copy of the
12 * http://www.apache.org/licenses/LICENSE-2.0
14 * Unless required by applicable law or agreed to in writing,
15 * software distributed under the License is distributed on an
16 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
17 * either express or implied. See the License for the specific
18 * language governing permissions and limitations under the License.
24 * Interface to a Shibboleth ServiceProvider instance.
28 #include "exceptions.h"
29 #include "AccessControl.h"
30 #include "Application.h"
31 #include "ServiceProvider.h"
32 #include "SessionCache.h"
33 #include "SPRequest.h"
34 #include "attribute/Attribute.h"
35 #include "handler/SessionInitiator.h"
36 #include "util/TemplateParameters.h"
40 #include <boost/algorithm/string.hpp>
42 # include <saml/exceptions.h>
43 # include <saml/saml2/metadata/MetadataProvider.h>
45 #include <xmltooling/XMLToolingConfig.h>
46 #include <xmltooling/util/NDC.h>
47 #include <xmltooling/util/PathResolver.h>
48 #include <xmltooling/util/URLEncoder.h>
49 #include <xmltooling/util/XMLHelper.h>
51 using namespace shibsp;
52 using namespace xmltooling::logging;
53 using namespace xmltooling;
57 SHIBSP_DLLLOCAL PluginManager<ServiceProvider,string,const DOMElement*>::Factory XMLServiceProviderFactory;
59 long SHIBSP_DLLLOCAL sendError(
60 Category& log, SPRequest& request, const Application* app, const char* page, TemplateParameters& tp, bool mayRedirect=true
63 // The properties we need can be set in the RequestMap, or the Errors element.
64 bool mderror = dynamic_cast<const opensaml::saml2md::MetadataException*>(tp.getRichException())!=nullptr;
65 bool accesserror = (strcmp(page, "access")==0);
66 pair<bool,const char*> redirectErrors = pair<bool,const char*>(false,nullptr);
67 pair<bool,const char*> pathname = pair<bool,const char*>(false,nullptr);
69 // Strictly for error handling, detect a nullptr application and point at the default.
71 app = request.getServiceProvider().getApplication(nullptr);
73 const PropertySet* props=app->getPropertySet("Errors");
75 // First look for settings in the request map of the form pageError.
77 RequestMapper::Settings settings = request.getRequestSettings();
79 pathname = settings.first->getString("metadataError");
80 if (!pathname.first) {
81 string pagename(page);
83 pathname = settings.first->getString(pagename.c_str());
86 redirectErrors = settings.first->getString("redirectErrors");
88 catch (exception& ex) {
92 // Check for redirection on errors instead of template.
94 if (!redirectErrors.first && props)
95 redirectErrors = props->getString("redirectErrors");
96 if (redirectErrors.first) {
97 string loc(redirectErrors.second);
98 request.absolutize(loc);
99 loc = loc + '?' + tp.toQueryString();
100 return request.sendRedirect(loc.c_str());
104 request.setContentType("text/html");
105 request.setResponseHeader("Expires","Wed, 01 Jan 1997 12:00:00 GMT");
106 request.setResponseHeader("Cache-Control","private,no-store,no-cache,max-age=0");
108 // Nothing in the request map, so check for a property named "page" in the Errors property set.
109 if (!pathname.first && props) {
111 pathname=props->getString("metadata");
113 pathname=props->getString(page);
116 // If there's still no template to use, just use pageError.html unless it's an access issue.
118 if (!pathname.first) {
120 fname = string(page) + "Error.html";
121 pathname.second = fname.c_str();
125 fname = pathname.second;
128 // If we have a template to use, use it.
129 if (!fname.empty()) {
130 ifstream infile(XMLToolingConfig::getConfig().getPathResolver()->resolve(fname, PathResolver::XMLTOOLING_CFG_FILE).c_str());
132 tp.setPropertySet(props);
134 XMLToolingConfig::getConfig().getTemplateEngine()->run(infile, str, tp, tp.getRichException());
135 return request.sendError(str);
139 // If we got here, then either it's an access error or a template failed.
141 istringstream msg("Access Denied");
142 return request.sendResponse(msg, HTTPResponse::XMLTOOLING_HTTP_STATUS_FORBIDDEN);
145 log.error("sendError could not process error template (%s)", pathname.second);
146 istringstream msg("Internal Server Error. Please contact the site administrator.");
147 return request.sendError(msg);
150 void SHIBSP_DLLLOCAL clearHeaders(SPRequest& request) {
151 const Application& app = request.getApplication();
152 app.clearHeader(request, "Shib-Session-ID", "HTTP_SHIB_SESSION_ID");
153 app.clearHeader(request, "Shib-Session-Index", "HTTP_SHIB_SESSION_INDEX");
154 app.clearHeader(request, "Shib-Identity-Provider", "HTTP_SHIB_IDENTITY_PROVIDER");
155 app.clearHeader(request, "Shib-Authentication-Method", "HTTP_SHIB_AUTHENTICATION_METHOD");
156 app.clearHeader(request, "Shib-Authentication-Instant", "HTTP_SHIB_AUTHENTICATION_INSTANT");
157 app.clearHeader(request, "Shib-AuthnContext-Class", "HTTP_SHIB_AUTHNCONTEXT_CLASS");
158 app.clearHeader(request, "Shib-AuthnContext-Decl", "HTTP_SHIB_AUTHNCONTEXT_DECL");
159 app.clearHeader(request, "Shib-Assertion-Count", "HTTP_SHIB_ASSERTION_COUNT");
160 app.clearAttributeHeaders(request);
161 request.clearHeader("REMOTE_USER", "HTTP_REMOTE_USER");
165 void SHIBSP_API shibsp::registerServiceProviders()
167 SPConfig::getConfig().ServiceProviderManager.registerFactory(XML_SERVICE_PROVIDER, XMLServiceProviderFactory);
170 ServiceProvider::ServiceProvider()
172 m_authTypes.insert("shibboleth");
175 ServiceProvider::~ServiceProvider()
180 SecurityPolicyProvider* ServiceProvider::getSecurityPolicyProvider(bool required) const
183 throw ConfigurationException("No SecurityPolicyProvider available.");
188 Remoted* ServiceProvider::regListener(const char* address, Remoted* listener)
190 Remoted* ret = nullptr;
191 map<string,Remoted*>::const_iterator i = m_listenerMap.find(address);
192 if (i != m_listenerMap.end())
194 m_listenerMap[address] = listener;
195 Category::getInstance(SHIBSP_LOGCAT".ServiceProvider").info("registered remoted message endpoint (%s)",address);
199 bool ServiceProvider::unregListener(const char* address, Remoted* current, Remoted* restore)
201 map<string,Remoted*>::const_iterator i = m_listenerMap.find(address);
202 if (i != m_listenerMap.end() && i->second == current) {
204 m_listenerMap[address] = restore;
206 m_listenerMap.erase(address);
207 Category::getInstance(SHIBSP_LOGCAT".ServiceProvider").info("unregistered remoted message endpoint (%s)",address);
213 Remoted* ServiceProvider::lookupListener(const char *address) const
215 map<string,Remoted*>::const_iterator i = m_listenerMap.find(address);
216 return (i == m_listenerMap.end()) ? nullptr : i->second;
219 pair<bool,long> ServiceProvider::doAuthentication(SPRequest& request, bool handler) const
222 xmltooling::NDC ndc("doAuthentication");
224 Category& log = Category::getInstance(SHIBSP_LOGCAT".ServiceProvider");
226 const Application* app = nullptr;
227 string targetURL = request.getRequestURL();
230 RequestMapper::Settings settings = request.getRequestSettings();
231 app = &(request.getApplication());
233 // If not SSL, check to see if we should block or redirect it.
234 if (!request.isSecure()) {
235 pair<bool,const char*> redirectToSSL = settings.first->getString("redirectToSSL");
236 if (redirectToSSL.first) {
237 #ifdef HAVE_STRCASECMP
238 if (!strcasecmp("GET",request.getMethod()) || !strcasecmp("HEAD",request.getMethod())) {
240 if (!stricmp("GET",request.getMethod()) || !stricmp("HEAD",request.getMethod())) {
242 // Compute the new target URL
243 string redirectURL = string("https://") + request.getHostname();
244 if (strcmp(redirectToSSL.second,"443")) {
245 redirectURL = redirectURL + ':' + redirectToSSL.second;
247 redirectURL += request.getRequestURI();
248 return make_pair(true, request.sendRedirect(redirectURL.c_str()));
251 TemplateParameters tp;
252 tp.m_map["requestURL"] = targetURL.substr(0,targetURL.find('?'));
253 return make_pair(true, sendError(log, request, app, "ssl", tp, false));
258 const char* handlerURL=request.getHandlerURL(targetURL.c_str());
260 throw ConfigurationException("Cannot determine handler from resource URL, check configuration.");
262 // If the request URL contains the handler base URL for this application, either dispatch
263 // directly (mainly Apache 2.0) or just pass back control.
264 if (boost::contains(targetURL, handlerURL)) {
266 return doHandler(request);
268 return make_pair(true, request.returnOK());
271 // Three settings dictate how to proceed.
272 pair<bool,const char*> authType = settings.first->getString("authType");
273 pair<bool,bool> requireSession = settings.first->getBool("requireSession");
274 pair<bool,const char*> requireSessionWith = settings.first->getString("requireSessionWith");
276 // If no session is required AND the AuthType (an Apache-derived concept) isn't recognized,
277 // then we ignore this request and consider it unprotected. Apache might lie to us if
278 // ShibBasicHijack is on, but that's up to it.
279 if ((!requireSession.first || !requireSession.second) && !requireSessionWith.first &&
280 (!authType.first || m_authTypes.find(boost::to_lower_copy(string(authType.second))) == m_authTypes.end()))
281 return make_pair(true, request.returnDecline());
283 // Fix for secadv 20050901
284 clearHeaders(request);
286 Session* session = nullptr;
288 session = request.getSession();
290 catch (exception& e) {
291 log.warn("error during session lookup: %s", e.what());
292 // If it's not a retryable session failure, we throw to the outer handler for reporting.
293 if (dynamic_cast<opensaml::RetryableProfileException*>(&e) == nullptr)
298 // No session. Maybe that's acceptable?
299 if ((!requireSession.first || !requireSession.second) && !requireSessionWith.first)
300 return make_pair(true, request.returnOK());
302 // No session, but we require one. Initiate a new session using the indicated method.
303 const SessionInitiator* initiator=nullptr;
304 if (requireSessionWith.first) {
305 initiator=app->getSessionInitiatorById(requireSessionWith.second);
307 throw ConfigurationException(
308 "No session initiator found with id ($1), check requireSessionWith command.", params(1,requireSessionWith.second)
313 initiator=app->getDefaultSessionInitiator();
315 throw ConfigurationException("No default session initiator found, check configuration.");
318 return initiator->run(request, false);
321 request.setAuthType(authType.second);
323 // We're done. Everything is okay. Nothing to report. Nothing to do..
324 // Let the caller decide how to proceed.
325 log.debug("doAuthentication succeeded");
326 return make_pair(false,0L);
328 catch (exception& e) {
329 request.log(SPRequest::SPError, e.what());
330 TemplateParameters tp(&e);
331 tp.m_map["requestURL"] = targetURL.substr(0,targetURL.find('?'));
332 return make_pair(true,sendError(log, request, app, "session", tp));
336 pair<bool,long> ServiceProvider::doAuthorization(SPRequest& request) const
339 xmltooling::NDC ndc("doAuthorization");
341 Category& log = Category::getInstance(SHIBSP_LOGCAT".ServiceProvider");
343 const Application* app = nullptr;
344 const Session* session = nullptr;
345 string targetURL = request.getRequestURL();
348 RequestMapper::Settings settings = request.getRequestSettings();
349 app = &(request.getApplication());
351 // Three settings dictate how to proceed.
352 pair<bool,const char*> authType = settings.first->getString("authType");
353 pair<bool,bool> requireSession = settings.first->getBool("requireSession");
354 pair<bool,const char*> requireSessionWith = settings.first->getString("requireSessionWith");
356 // If no session is required AND the AuthType (an Apache-derived concept) isn't recognized,
357 // then we ignore this request and consider it unprotected. Apache might lie to us if
358 // ShibBasicHijack is on, but that's up to it.
359 if ((!requireSession.first || !requireSession.second) && !requireSessionWith.first &&
360 (!authType.first || m_authTypes.find(boost::to_lower_copy(string(authType.second))) == m_authTypes.end()))
361 return make_pair(true, request.returnDecline());
363 // Do we have an access control plugin?
364 if (settings.second) {
366 session = request.getSession(false);
368 catch (exception& e) {
369 log.warn("unable to obtain session to pass to access control provider: %s", e.what());
372 Locker acllock(settings.second);
373 switch (settings.second->authorized(request, session)) {
374 case AccessControl::shib_acl_true:
375 log.debug("access control provider granted access");
376 return make_pair(true, request.returnOK());
378 case AccessControl::shib_acl_false:
380 log.warn("access control provider denied access");
381 TemplateParameters tp(nullptr, nullptr, session);
382 tp.m_map["requestURL"] = targetURL;
383 return make_pair(true, sendError(log, request, app, "access", tp, false));
387 // Use the "DECLINE" interface to signal we don't know what to do.
388 return make_pair(true, request.returnDecline());
392 return make_pair(true, request.returnDecline());
395 catch (exception& e) {
396 request.log(SPRequest::SPError, e.what());
397 TemplateParameters tp(&e, nullptr, session);
398 tp.m_map["requestURL"] = targetURL.substr(0,targetURL.find('?'));
399 return make_pair(true,sendError(log, request, app, "access", tp));
403 pair<bool,long> ServiceProvider::doExport(SPRequest& request, bool requireSession) const
406 xmltooling::NDC ndc("doExport");
408 Category& log = Category::getInstance(SHIBSP_LOGCAT".ServiceProvider");
410 const Application* app = nullptr;
411 const Session* session = nullptr;
412 string targetURL = request.getRequestURL();
415 RequestMapper::Settings settings = request.getRequestSettings();
416 app = &(request.getApplication());
419 session = request.getSession(false);
421 catch (exception& e) {
422 log.warn("unable to obtain session to export to request: %s", e.what());
423 // If we have to have a session, then this is a fatal error.
431 throw opensaml::RetryableProfileException("Unable to obtain session to export to request.");
433 return make_pair(false, 0L); // just bail silently
436 pair<bool,const char*> enc = settings.first->getString("encoding");
437 if (enc.first && strcmp(enc.second, "URL"))
438 throw ConfigurationException("Unsupported value for 'encoding' content setting ($1).", params(1,enc.second));
440 const URLEncoder* encoder = XMLToolingConfig::getConfig().getURLEncoder();
442 app->setHeader(request, "Shib-Application-ID", app->getId());
443 app->setHeader(request, "Shib-Session-ID", session->getID());
445 // Check for export of "standard" variables.
446 // A 3.0 release would switch this default to false and rely solely on the
447 // Assertion extractor plugin and ship out of the box with the same defaults.
448 pair<bool,bool> stdvars = settings.first->getBool("exportStdVars");
449 if (!stdvars.first || stdvars.second) {
450 const char* hval = session->getEntityID();
452 app->setHeader(request, "Shib-Identity-Provider", hval);
453 hval = session->getAuthnInstant();
455 app->setHeader(request, "Shib-Authentication-Instant", hval);
456 hval = session->getAuthnContextClassRef();
458 app->setHeader(request, "Shib-Authentication-Method", hval);
459 app->setHeader(request, "Shib-AuthnContext-Class", hval);
461 hval = session->getAuthnContextDeclRef();
463 app->setHeader(request, "Shib-AuthnContext-Decl", hval);
464 hval = session->getSessionIndex();
466 app->setHeader(request, "Shib-Session-Index", hval);
469 // Maybe export the assertion keys.
470 pair<bool,bool> exp = settings.first->getBool("exportAssertion");
471 if (exp.first && exp.second) {
472 const PropertySet* sessions = app->getPropertySet("Sessions");
473 pair<bool,const char*> exportLocation = sessions ? sessions->getString("exportLocation") : pair<bool,const char*>(false,nullptr);
474 if (!exportLocation.first)
475 log.warn("can't export assertions without an exportLocation Sessions property");
477 string exportName = "Shib-Assertion-00";
479 if (!strncmp(exportLocation.second, "http", 4))
480 baseURL = exportLocation.second;
482 baseURL = string(request.getHandlerURL(targetURL.c_str())) + exportLocation.second;
483 baseURL = baseURL + "?key=" + session->getID() + "&ID=";
484 const vector<const char*>& tokens = session->getAssertionIDs();
485 vector<const char*>::size_type count = 0;
486 for (vector<const char*>::const_iterator tokenids = tokens.begin(); tokenids!=tokens.end(); ++tokenids) {
488 *(exportName.rbegin()) = '0' + (count%10);
489 *(++exportName.rbegin()) = '0' + (count/10);
490 string fullURL = baseURL + encoder->encode(*tokenids);
491 app->setHeader(request, exportName.c_str(), fullURL.c_str());
493 app->setHeader(request, "Shib-Assertion-Count", exportName.c_str() + 15);
497 // Export the attributes.
498 const multimap<string,const Attribute*>& attributes = session->getIndexedAttributes();
499 for (multimap<string,const Attribute*>::const_iterator a = attributes.begin(); a != attributes.end(); ++a) {
500 if (a->second->isInternal())
502 string header(app->getSecureHeader(request, a->first.c_str()));
503 const vector<string>& vals = a->second->getSerializedValues();
504 for (vector<string>::const_iterator v = vals.begin(); v != vals.end(); ++v) {
508 // If URL-encoding, any semicolons will get escaped anyway.
509 header += encoder->encode(v->c_str());
512 string::size_type pos = v->find_first_of(';', string::size_type(0));
513 if (pos != string::npos) {
515 for (; pos != string::npos; pos = value.find_first_of(';', pos)) {
516 value.insert(pos, "\\");
526 app->setHeader(request, a->first.c_str(), header.c_str());
529 // Check for REMOTE_USER.
530 bool remoteUserSet = false;
531 const vector<string>& rmids = app->getRemoteUserAttributeIds();
532 for (vector<string>::const_iterator rmid = rmids.begin(); !remoteUserSet && rmid != rmids.end(); ++rmid) {
533 pair<multimap<string,const Attribute*>::const_iterator,multimap<string,const Attribute*>::const_iterator> matches =
534 attributes.equal_range(*rmid);
535 for (; matches.first != matches.second; ++matches.first) {
536 const vector<string>& vals = matches.first->second->getSerializedValues();
539 request.setRemoteUser(encoder->encode(vals.front().c_str()).c_str());
541 request.setRemoteUser(vals.front().c_str());
542 remoteUserSet = true;
548 return make_pair(false,0L);
550 catch (exception& e) {
551 request.log(SPRequest::SPError, e.what());
552 TemplateParameters tp(&e, nullptr, session);
553 tp.m_map["requestURL"] = targetURL.substr(0,targetURL.find('?'));
554 return make_pair(true,sendError(log, request, app, "session", tp));
558 pair<bool,long> ServiceProvider::doHandler(SPRequest& request) const
561 xmltooling::NDC ndc("doHandler");
563 Category& log = Category::getInstance(SHIBSP_LOGCAT".ServiceProvider");
565 const Application* app = nullptr;
566 string targetURL = request.getRequestURL();
569 RequestMapper::Settings settings = request.getRequestSettings();
570 app = &(request.getApplication());
572 // If not SSL, check to see if we should block or redirect it.
573 if (!request.isSecure()) {
574 pair<bool,const char*> redirectToSSL = settings.first->getString("redirectToSSL");
575 if (redirectToSSL.first) {
576 #ifdef HAVE_STRCASECMP
577 if (!strcasecmp("GET",request.getMethod()) || !strcasecmp("HEAD",request.getMethod())) {
579 if (!stricmp("GET",request.getMethod()) || !stricmp("HEAD",request.getMethod())) {
581 // Compute the new target URL
582 string redirectURL = string("https://") + request.getHostname();
583 if (strcmp(redirectToSSL.second,"443")) {
584 redirectURL = redirectURL + ':' + redirectToSSL.second;
586 redirectURL += request.getRequestURI();
587 return make_pair(true, request.sendRedirect(redirectURL.c_str()));
590 TemplateParameters tp;
591 tp.m_map["requestURL"] = targetURL.substr(0,targetURL.find('?'));
592 return make_pair(true,sendError(log, request, app, "ssl", tp, false));
597 const char* handlerURL = request.getHandlerURL(targetURL.c_str());
599 throw ConfigurationException("Cannot determine handler from resource URL, check configuration.");
601 // Make sure we only process handler requests.
602 if (!boost::contains(targetURL, handlerURL))
603 return make_pair(true, request.returnDecline());
605 const PropertySet* sessionProps = app->getPropertySet("Sessions");
607 throw ConfigurationException("Unable to map request to application session settings, check configuration.");
609 // Process incoming request.
610 pair<bool,bool> handlerSSL = sessionProps->getBool("handlerSSL");
612 // Make sure this is SSL, if it should be
613 if ((!handlerSSL.first || handlerSSL.second) && !request.isSecure())
614 throw opensaml::FatalProfileException("Blocked non-SSL access to Shibboleth handler.");
616 // We dispatch based on our path info. We know the request URL begins with or equals the handler URL,
617 // so the path info is the next character (or null).
618 const Handler* handler = app->getHandler(targetURL.c_str() + strlen(handlerURL));
620 throw ConfigurationException("Shibboleth handler invoked at an unconfigured location.");
622 pair<bool,long> hret = handler->run(request);
624 // Did the handler run successfully?
628 throw ConfigurationException("Configured Shibboleth handler failed to process the request.");
630 catch (exception& e) {
631 request.log(SPRequest::SPError, e.what());
632 const Session* session = nullptr;
634 session = request.getSession(false, true);
638 TemplateParameters tp(&e, nullptr, session);
639 tp.m_map["requestURL"] = targetURL.substr(0, targetURL.find('?'));
640 tp.m_request = &request;
641 return make_pair(true, sendError(log, request, app, "session", tp));