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-Cookie-Name", "HTTP_SHIB_COOKIE_NAME");
153 app.clearHeader(request, "Shib-Session-ID", "HTTP_SHIB_SESSION_ID");
154 app.clearHeader(request, "Shib-Session-Index", "HTTP_SHIB_SESSION_INDEX");
155 app.clearHeader(request, "Shib-Identity-Provider", "HTTP_SHIB_IDENTITY_PROVIDER");
156 app.clearHeader(request, "Shib-Authentication-Method", "HTTP_SHIB_AUTHENTICATION_METHOD");
157 app.clearHeader(request, "Shib-Authentication-Instant", "HTTP_SHIB_AUTHENTICATION_INSTANT");
158 app.clearHeader(request, "Shib-AuthnContext-Class", "HTTP_SHIB_AUTHNCONTEXT_CLASS");
159 app.clearHeader(request, "Shib-AuthnContext-Decl", "HTTP_SHIB_AUTHNCONTEXT_DECL");
160 app.clearHeader(request, "Shib-Assertion-Count", "HTTP_SHIB_ASSERTION_COUNT");
161 app.clearAttributeHeaders(request);
162 request.clearHeader("REMOTE_USER", "HTTP_REMOTE_USER");
166 void SHIBSP_API shibsp::registerServiceProviders()
168 SPConfig::getConfig().ServiceProviderManager.registerFactory(XML_SERVICE_PROVIDER, XMLServiceProviderFactory);
171 ServiceProvider::ServiceProvider()
173 m_authTypes.insert("shibboleth");
176 ServiceProvider::~ServiceProvider()
181 SecurityPolicyProvider* ServiceProvider::getSecurityPolicyProvider(bool required) const
184 throw ConfigurationException("No SecurityPolicyProvider available.");
189 Remoted* ServiceProvider::regListener(const char* address, Remoted* listener)
191 Remoted* ret = nullptr;
192 map<string,Remoted*>::const_iterator i = m_listenerMap.find(address);
193 if (i != m_listenerMap.end())
195 m_listenerMap[address] = listener;
196 Category::getInstance(SHIBSP_LOGCAT".ServiceProvider").info("registered remoted message endpoint (%s)",address);
200 bool ServiceProvider::unregListener(const char* address, Remoted* current, Remoted* restore)
202 map<string,Remoted*>::const_iterator i = m_listenerMap.find(address);
203 if (i != m_listenerMap.end() && i->second == current) {
205 m_listenerMap[address] = restore;
207 m_listenerMap.erase(address);
208 Category::getInstance(SHIBSP_LOGCAT".ServiceProvider").info("unregistered remoted message endpoint (%s)",address);
214 Remoted* ServiceProvider::lookupListener(const char *address) const
216 map<string,Remoted*>::const_iterator i = m_listenerMap.find(address);
217 return (i == m_listenerMap.end()) ? nullptr : i->second;
220 pair<bool,long> ServiceProvider::doAuthentication(SPRequest& request, bool handler) const
223 xmltooling::NDC ndc("doAuthentication");
225 Category& log = Category::getInstance(SHIBSP_LOGCAT".ServiceProvider");
227 const Application* app = nullptr;
228 string targetURL = request.getRequestURL();
231 RequestMapper::Settings settings = request.getRequestSettings();
232 app = &(request.getApplication());
234 // If not SSL, check to see if we should block or redirect it.
235 if (!request.isSecure()) {
236 pair<bool,const char*> redirectToSSL = settings.first->getString("redirectToSSL");
237 if (redirectToSSL.first) {
238 #ifdef HAVE_STRCASECMP
239 if (!strcasecmp("GET",request.getMethod()) || !strcasecmp("HEAD",request.getMethod())) {
241 if (!stricmp("GET",request.getMethod()) || !stricmp("HEAD",request.getMethod())) {
243 // Compute the new target URL
244 string redirectURL = string("https://") + request.getHostname();
245 if (strcmp(redirectToSSL.second,"443")) {
246 redirectURL = redirectURL + ':' + redirectToSSL.second;
248 redirectURL += request.getRequestURI();
249 return make_pair(true, request.sendRedirect(redirectURL.c_str()));
252 TemplateParameters tp;
253 tp.m_map["requestURL"] = targetURL.substr(0,targetURL.find('?'));
254 return make_pair(true, sendError(log, request, app, "ssl", tp, false));
259 const char* handlerURL=request.getHandlerURL(targetURL.c_str());
261 throw ConfigurationException("Cannot determine handler from resource URL, check configuration.");
263 // If the request URL contains the handler base URL for this application, either dispatch
264 // directly (mainly Apache 2.0) or just pass back control.
265 if (boost::contains(targetURL, handlerURL)) {
267 return doHandler(request);
269 return make_pair(true, request.returnOK());
272 // These settings dictate how to proceed.
273 pair<bool,const char*> authType = settings.first->getString("authType");
274 pair<bool,bool> requireSession = settings.first->getBool("requireSession");
275 pair<bool,const char*> requireSessionWith = settings.first->getString("requireSessionWith");
276 pair<bool,const char*> requireLogoutWith = settings.first->getString("requireLogoutWith");
278 // If no session is required AND the AuthType (an Apache-derived concept) isn't recognized,
279 // then we ignore this request and consider it unprotected. Apache might lie to us if
280 // ShibBasicHijack is on, but that's up to it.
281 if ((!requireSession.first || !requireSession.second) && !requireSessionWith.first &&
282 (!authType.first || m_authTypes.find(boost::to_lower_copy(string(authType.second))) == m_authTypes.end()))
283 return make_pair(true, request.returnDecline());
285 // Fix for secadv 20050901
286 clearHeaders(request);
288 Session* session = nullptr;
290 session = request.getSession(true, false, false); // don't cache it
292 catch (exception& e) {
293 log.warn("error during session lookup: %s", e.what());
294 // If it's not a retryable session failure, we throw to the outer handler for reporting.
295 if (dynamic_cast<opensaml::RetryableProfileException*>(&e) == nullptr)
299 Locker slocker(session, false); // pop existing lock on exit
301 // Check for logout interception.
302 if (requireLogoutWith.first) {
303 // Check for a completion parameter on the query string.
304 const char* qstr = request.getQueryString();
305 if (!qstr || !strstr(qstr, "shiblogoutdone=1")) {
306 // First leg of circuit, so we redirect to the logout endpoint specified with this URL as a return location.
307 string selfurl = request.getRequestURL();
312 selfurl += "shiblogoutdone=1";
313 string loc = requireLogoutWith.second;
314 request.absolutize(loc);
315 if (loc.find('?') != string::npos)
319 loc += "return=" + XMLToolingConfig::getConfig().getURLEncoder()->encode(selfurl.c_str());
320 return make_pair(true, request.sendRedirect(loc.c_str()));
325 // No session. Maybe that's acceptable?
326 if ((!requireSession.first || !requireSession.second) && !requireSessionWith.first)
327 return make_pair(true, request.returnOK());
329 // No session, but we require one. Initiate a new session using the indicated method.
330 const SessionInitiator* initiator=nullptr;
331 if (requireSessionWith.first) {
332 initiator=app->getSessionInitiatorById(requireSessionWith.second);
334 throw ConfigurationException(
335 "No session initiator found with id ($1), check requireSessionWith command.", params(1, requireSessionWith.second)
340 initiator=app->getDefaultSessionInitiator();
342 throw ConfigurationException("No default session initiator found, check configuration.");
345 // Dispatch to SessionInitiator. This MUST handle the request, or we want to fail here.
346 // Used to fall through into doExport, but this is a cleaner exit path.
347 pair<bool,long> ret = initiator->run(request, false);
350 throw ConfigurationException("Session initiator did not handle request for a new session, check configuration.");
353 request.setAuthType(authType.second);
355 // We're done. Everything is okay. Nothing to report. Nothing to do..
356 // Let the caller decide how to proceed.
357 log.debug("doAuthentication succeeded");
358 return make_pair(false,0L);
360 catch (exception& e) {
361 request.log(SPRequest::SPError, e.what());
362 TemplateParameters tp(&e);
363 tp.m_map["requestURL"] = targetURL.substr(0,targetURL.find('?'));
364 return make_pair(true, sendError(log, request, app, "session", tp));
368 pair<bool,long> ServiceProvider::doAuthorization(SPRequest& request) const
371 xmltooling::NDC ndc("doAuthorization");
373 Category& log = Category::getInstance(SHIBSP_LOGCAT".ServiceProvider");
375 const Application* app = nullptr;
376 Session* session = nullptr;
378 string targetURL = request.getRequestURL();
381 RequestMapper::Settings settings = request.getRequestSettings();
382 app = &(request.getApplication());
384 // Three settings dictate how to proceed.
385 pair<bool,const char*> authType = settings.first->getString("authType");
386 pair<bool,bool> requireSession = settings.first->getBool("requireSession");
387 pair<bool,const char*> requireSessionWith = settings.first->getString("requireSessionWith");
389 // If no session is required AND the AuthType (an Apache-derived concept) isn't recognized,
390 // then we ignore this request and consider it unprotected. Apache might lie to us if
391 // ShibBasicHijack is on, but that's up to it.
392 if ((!requireSession.first || !requireSession.second) && !requireSessionWith.first &&
393 (!authType.first || m_authTypes.find(boost::to_lower_copy(string(authType.second))) == m_authTypes.end()))
394 return make_pair(true, request.returnDecline());
396 // Do we have an access control plugin?
397 if (settings.second) {
399 session = request.getSession(false, false, false); // ignore timeout and do not cache
401 slocker.assign(session, false); // assign to lock popper
403 catch (exception& e) {
404 log.warn("unable to obtain session to pass to access control provider: %s", e.what());
407 Locker acllock(settings.second);
408 switch (settings.second->authorized(request, session)) {
409 case AccessControl::shib_acl_true:
410 log.debug("access control provider granted access");
411 return make_pair(true, request.returnOK());
413 case AccessControl::shib_acl_false:
415 log.warn("access control provider denied access");
416 TemplateParameters tp(nullptr, nullptr, session);
417 tp.m_map["requestURL"] = targetURL;
418 return make_pair(true, sendError(log, request, app, "access", tp, false));
422 // Use the "DECLINE" interface to signal we don't know what to do.
423 return make_pair(true, request.returnDecline());
427 return make_pair(true, request.returnDecline());
430 catch (exception& e) {
431 request.log(SPRequest::SPError, e.what());
432 TemplateParameters tp(&e, nullptr, session);
433 tp.m_map["requestURL"] = targetURL.substr(0,targetURL.find('?'));
434 return make_pair(true, sendError(log, request, app, "access", tp));
438 pair<bool,long> ServiceProvider::doExport(SPRequest& request, bool requireSession) const
441 xmltooling::NDC ndc("doExport");
443 Category& log = Category::getInstance(SHIBSP_LOGCAT".ServiceProvider");
445 const Application* app = nullptr;
446 Session* session = nullptr;
448 string targetURL = request.getRequestURL();
451 RequestMapper::Settings settings = request.getRequestSettings();
452 app = &(request.getApplication());
455 session = request.getSession(false, false, false); // ignore timeout and do not cache
457 slocker.assign(session, false); // assign to lock popper
459 catch (exception& e) {
460 log.warn("unable to obtain session to export to request: %s", e.what());
461 // If we have to have a session, then this is a fatal error.
469 throw opensaml::RetryableProfileException("Unable to obtain session to export to request.");
471 return make_pair(false, 0L); // just bail silently
474 pair<bool,const char*> enc = settings.first->getString("encoding");
475 if (enc.first && strcmp(enc.second, "URL"))
476 throw ConfigurationException("Unsupported value for 'encoding' content setting ($1).", params(1,enc.second));
478 const URLEncoder* encoder = XMLToolingConfig::getConfig().getURLEncoder();
480 app->setHeader(request, "Shib-Application-ID", app->getId());
481 app->setHeader(request, "Shib-Session-ID", session->getID());
483 // Check for export of "standard" variables.
484 // A 3.0 release would switch this default to false and rely solely on the
485 // Assertion extractor plugin and ship out of the box with the same defaults.
486 pair<bool,bool> stdvars = settings.first->getBool("exportStdVars");
487 if (!stdvars.first || stdvars.second) {
488 const char* hval = session->getEntityID();
490 app->setHeader(request, "Shib-Identity-Provider", hval);
491 hval = session->getAuthnInstant();
493 app->setHeader(request, "Shib-Authentication-Instant", hval);
494 hval = session->getAuthnContextClassRef();
496 app->setHeader(request, "Shib-Authentication-Method", hval);
497 app->setHeader(request, "Shib-AuthnContext-Class", hval);
499 hval = session->getAuthnContextDeclRef();
501 app->setHeader(request, "Shib-AuthnContext-Decl", hval);
502 hval = session->getSessionIndex();
504 app->setHeader(request, "Shib-Session-Index", hval);
507 // Check for export of algorithmically-derived portion of cookie names.
508 stdvars = settings.first->getBool("exportCookie");
509 if (stdvars.first && stdvars.second) {
510 pair<string,const char*> cookieprops = app->getCookieNameProps(nullptr);
511 app->setHeader(request, "Shib-Cookie-Name", cookieprops.first.c_str());
514 // Maybe export the assertion keys.
515 pair<bool,bool> exp = settings.first->getBool("exportAssertion");
516 if (exp.first && exp.second) {
517 const PropertySet* sessions = app->getPropertySet("Sessions");
518 pair<bool,const char*> exportLocation = sessions ? sessions->getString("exportLocation") : pair<bool,const char*>(false,nullptr);
519 if (!exportLocation.first)
520 log.warn("can't export assertions without an exportLocation Sessions property");
522 string exportName = "Shib-Assertion-00";
524 if (!strncmp(exportLocation.second, "http", 4))
525 baseURL = exportLocation.second;
527 baseURL = string(request.getHandlerURL(targetURL.c_str())) + exportLocation.second;
528 baseURL = baseURL + "?key=" + session->getID() + "&ID=";
529 const vector<const char*>& tokens = session->getAssertionIDs();
530 vector<const char*>::size_type count = 0;
531 for (vector<const char*>::const_iterator tokenids = tokens.begin(); tokenids!=tokens.end(); ++tokenids) {
533 *(exportName.rbegin()) = '0' + (count%10);
534 *(++exportName.rbegin()) = '0' + (count/10);
535 string fullURL = baseURL + encoder->encode(*tokenids);
536 app->setHeader(request, exportName.c_str(), fullURL.c_str());
538 app->setHeader(request, "Shib-Assertion-Count", exportName.c_str() + 15);
542 // Export the attributes.
543 const multimap<string,const Attribute*>& attributes = session->getIndexedAttributes();
544 for (multimap<string,const Attribute*>::const_iterator a = attributes.begin(); a != attributes.end(); ++a) {
545 if (a->second->isInternal())
547 string header(app->getSecureHeader(request, a->first.c_str()));
548 const vector<string>& vals = a->second->getSerializedValues();
549 for (vector<string>::const_iterator v = vals.begin(); v != vals.end(); ++v) {
553 // If URL-encoding, any semicolons will get escaped anyway.
554 header += encoder->encode(v->c_str());
557 string::size_type pos = v->find_first_of(';', string::size_type(0));
558 if (pos != string::npos) {
560 for (; pos != string::npos; pos = value.find_first_of(';', pos)) {
561 value.insert(pos, "\\");
571 app->setHeader(request, a->first.c_str(), header.c_str());
574 // Check for REMOTE_USER.
575 bool remoteUserSet = false;
576 const vector<string>& rmids = app->getRemoteUserAttributeIds();
577 for (vector<string>::const_iterator rmid = rmids.begin(); !remoteUserSet && rmid != rmids.end(); ++rmid) {
578 pair<multimap<string,const Attribute*>::const_iterator,multimap<string,const Attribute*>::const_iterator> matches =
579 attributes.equal_range(*rmid);
580 for (; matches.first != matches.second; ++matches.first) {
581 const vector<string>& vals = matches.first->second->getSerializedValues();
584 request.setRemoteUser(encoder->encode(vals.front().c_str()).c_str());
586 request.setRemoteUser(vals.front().c_str());
587 remoteUserSet = true;
593 return make_pair(false,0L);
595 catch (exception& e) {
596 request.log(SPRequest::SPError, e.what());
597 TemplateParameters tp(&e, nullptr, session);
598 tp.m_map["requestURL"] = targetURL.substr(0,targetURL.find('?'));
599 return make_pair(true, sendError(log, request, app, "session", tp));
603 pair<bool,long> ServiceProvider::doHandler(SPRequest& request) const
606 xmltooling::NDC ndc("doHandler");
608 Category& log = Category::getInstance(SHIBSP_LOGCAT".ServiceProvider");
610 const Application* app = nullptr;
611 string targetURL = request.getRequestURL();
614 RequestMapper::Settings settings = request.getRequestSettings();
615 app = &(request.getApplication());
617 // If not SSL, check to see if we should block or redirect it.
618 if (!request.isSecure()) {
619 pair<bool,const char*> redirectToSSL = settings.first->getString("redirectToSSL");
620 if (redirectToSSL.first) {
621 #ifdef HAVE_STRCASECMP
622 if (!strcasecmp("GET",request.getMethod()) || !strcasecmp("HEAD",request.getMethod())) {
624 if (!stricmp("GET",request.getMethod()) || !stricmp("HEAD",request.getMethod())) {
626 // Compute the new target URL
627 string redirectURL = string("https://") + request.getHostname();
628 if (strcmp(redirectToSSL.second,"443")) {
629 redirectURL = redirectURL + ':' + redirectToSSL.second;
631 redirectURL += request.getRequestURI();
632 return make_pair(true, request.sendRedirect(redirectURL.c_str()));
635 TemplateParameters tp;
636 tp.m_map["requestURL"] = targetURL.substr(0,targetURL.find('?'));
637 return make_pair(true,sendError(log, request, app, "ssl", tp, false));
642 const char* handlerURL = request.getHandlerURL(targetURL.c_str());
644 throw ConfigurationException("Cannot determine handler from resource URL, check configuration.");
646 // Make sure we only process handler requests.
647 if (!boost::contains(targetURL, handlerURL))
648 return make_pair(true, request.returnDecline());
650 const PropertySet* sessionProps = app->getPropertySet("Sessions");
652 throw ConfigurationException("Unable to map request to application session settings, check configuration.");
654 // Process incoming request.
655 pair<bool,bool> handlerSSL = sessionProps->getBool("handlerSSL");
657 // Make sure this is SSL, if it should be
658 if ((!handlerSSL.first || handlerSSL.second) && !request.isSecure())
659 throw opensaml::FatalProfileException("Blocked non-SSL access to Shibboleth handler.");
661 // We dispatch based on our path info. We know the request URL begins with or equals the handler URL,
662 // so the path info is the next character (or null).
663 const Handler* handler = app->getHandler(targetURL.c_str() + strlen(handlerURL));
665 throw ConfigurationException("Shibboleth handler invoked at an unconfigured location.");
667 pair<bool,long> hret = handler->run(request);
669 // Did the handler run successfully?
673 throw ConfigurationException("Configured Shibboleth handler failed to process the request.");
675 catch (exception& e) {
676 request.log(SPRequest::SPError, e.what());
677 Session* session = nullptr;
679 session = request.getSession(false, true, false); // do not cache
683 Locker slocker(session, false); // pop existing lock on exit
684 TemplateParameters tp(&e, nullptr, session);
685 tp.m_map["requestURL"] = targetURL.substr(0, targetURL.find('?'));
686 tp.m_request = &request;
687 return make_pair(true, sendError(log, request, app, "session", tp));