2 * Copyright 2001-2005 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.
18 * shib-target.cpp -- The ShibTarget class, a superclass for general
21 * Created by: Derek Atkins <derek@ihtfp.com>
36 #include <shib/shib-threads.h>
37 #include <xercesc/util/Base64.hpp>
39 #ifndef HAVE_STRCASECMP
40 # define strcasecmp stricmp
43 using namespace shibtarget::logging;
44 using namespace shibtarget;
45 using namespace shibboleth;
49 namespace shibtarget {
57 void get_application(ShibTarget* st, const string& protocol, const string& hostname, int port, const string& uri);
58 void* sendError(ShibTarget* st, const char* page, ShibMLP &mlp);
59 void clearHeaders(ShibTarget* st);
61 // Handlers do the real Shibboleth work
62 pair<bool,void*> dispatch(
64 const IPropertySet* handler,
66 const char* forceType=NULL
70 friend class ShibTarget;
71 IRequestMapper::Settings m_settings;
72 const IApplication *m_app;
73 mutable string m_handlerURL;
74 mutable map<string,string> m_cookieMap;
76 ISessionCacheEntry* m_cacheEntry;
78 ShibTargetConfig* m_Config;
81 IRequestMapper* m_mapper;
86 /*************************************************************************
87 * Shib Target implementation
90 static char _x2c(const char *what)
94 digit = (what[0] >= 'A' ? ((what[0] & 0xdf) - 'A')+10 : (what[0] - '0'));
96 digit += (what[1] >= 'A' ? ((what[1] & 0xdf) - 'A')+10 : (what[1] - '0'));
100 ShibTarget::ShibTarget(void) : m_priv(NULL)
102 m_priv = new ShibTargetPriv();
105 ShibTarget::ShibTarget(const IApplication *app) : m_priv(NULL)
107 m_priv = new ShibTargetPriv();
111 ShibTarget::~ShibTarget(void)
113 if (m_priv) delete m_priv;
116 void ShibTarget::init(
117 const char* protocol,
118 const char* hostname,
121 const char* content_type,
122 const char* remote_addr,
127 saml::NDC ndc("init");
131 throw SAMLException("Request initialization occurred twice!");
133 if (method) m_method = method;
134 if (protocol) m_protocol = protocol;
135 if (hostname) m_hostname = hostname;
136 if (content_type) m_content_type = content_type;
137 if (remote_addr) m_remote_addr = remote_addr;
140 // Fix for bug 574, secadv 20061002
141 // Unescape URI up to query string delimiter by looking for %XX escapes.
142 // Adapted from Apache's util.c, ap_unescape_url function.
149 else if (*uri == ';') {
150 // If this is Java being stupid, skip everything up to the query string, if any.
151 if (!strncmp(uri, ";jsessionid=", 12)) {
152 if (uri = strchr(uri, '?'))
160 else if (*uri != '%') {
165 if (!isxdigit(*uri) || !isxdigit(*(uri+1)))
166 throw SAMLException("Bad request, contained unsupported encoded characters.");
174 m_priv->m_Config = &ShibTargetConfig::getConfig();
175 m_priv->get_application(this, protocol, hostname, port, m_uri);
179 // These functions implement the server-agnostic shibboleth engine
180 // The web server modules implement a subclass and then call into
181 // these methods once they instantiate their request object.
183 pair<bool,void*> ShibTarget::doCheckAuthN(bool handler)
186 saml::NDC ndc("doCheckAuthN");
189 const char* procState = "Request Processing Error";
190 const char* targetURL = m_url.c_str();
195 throw ConfigurationException("System uninitialized, application did not supply request information.");
197 // If not SSL, check to see if we should block or redirect it.
198 if (!strcmp("http",getProtocol())) {
199 pair<bool,const char*> redirectToSSL = m_priv->m_settings.first->getString("redirectToSSL");
200 if (redirectToSSL.first) {
201 if (!strcasecmp("GET",getRequestMethod()) || !strcasecmp("HEAD",getRequestMethod())) {
202 // Compute the new target URL
203 string redirectURL = string("https://") + getHostname();
204 if (strcmp(redirectToSSL.second,"443")) {
205 redirectURL = redirectURL + ':' + redirectToSSL.second;
207 redirectURL += getRequestURI();
208 return make_pair(true, sendRedirect(redirectURL));
211 mlp.insert("requestURL", m_url.substr(0,m_url.find('?')));
212 return make_pair(true,m_priv->sendError(this,"ssl", mlp));
217 string hURL = getHandlerURL(targetURL);
218 const char* handlerURL=hURL.c_str();
220 throw ConfigurationException("Cannot determine handler from resource URL, check configuration.");
222 // If the request URL contains the handler base URL for this application, either dispatch
223 // directly (mainly Apache 2.0) or just pass back control.
224 if (strstr(targetURL,handlerURL)) {
228 return pair<bool,void*>(true, returnOK());
231 // Three settings dictate how to proceed.
232 pair<bool,const char*> authType = m_priv->m_settings.first->getString("authType");
233 pair<bool,bool> requireSession = m_priv->m_settings.first->getBool("requireSession");
234 pair<bool,const char*> requireSessionWith = m_priv->m_settings.first->getString("requireSessionWith");
236 // If no session is required AND the AuthType (an Apache-derived concept) isn't shibboleth,
237 // then we ignore this request and consider it unprotected. Apache might lie to us if
238 // ShibBasicHijack is on, but that's up to it.
239 if ((!requireSession.first || !requireSession.second) && !requireSessionWith.first &&
240 #ifdef HAVE_STRCASECMP
241 (!authType.first || strcasecmp(authType.second,"shibboleth")))
243 (!authType.first || stricmp(authType.second,"shibboleth")))
245 return pair<bool,void*>(true,returnDecline());
247 // Fix for secadv 20050901
248 m_priv->clearHeaders(this);
250 pair<string,const char*> shib_cookie = getCookieNameProps("_shibsession_");
251 const char* session_id = getCookie(shib_cookie.first);
252 if (!session_id || !*session_id) {
253 // No session. Maybe that's acceptable?
254 if ((!requireSession.first || !requireSession.second) && !requireSessionWith.first)
255 return pair<bool,void*>(true,returnOK());
257 // No cookie, but we require a session. Initiate a new session using the indicated method.
258 procState = "Session Initiator Error";
259 const IPropertySet* initiator=NULL;
260 if (requireSessionWith.first)
261 initiator=m_priv->m_app->getSessionInitiatorById(requireSessionWith.second);
263 initiator=m_priv->m_app->getDefaultSessionInitiator();
265 // Standard handler element, so we dispatch normally.
267 return m_priv->dispatch(this,initiator,false);
269 // Legacy config support maps the Sessions element to the Shib profile.
270 auto_ptr_char binding(Constants::SHIB_SESSIONINIT_PROFILE_URI);
271 return m_priv->dispatch(this, m_priv->m_app->getPropertySet("Sessions"), false, binding.get());
275 procState = "Session Processing Error";
277 // Localized exception throw if the session isn't valid.
278 m_priv->m_conf->getListener()->sessionGet(
281 m_remote_addr.c_str(),
282 &m_priv->m_cacheEntry
285 catch (SAMLException& e) {
286 log(LogLevelError, string("session processing failed: ") + e.what());
288 // If no session is required, bail now.
289 if ((!requireSession.first || !requireSession.second) && !requireSessionWith.first)
290 // Has to be OK because DECLINED will just cause Apache
291 // to fail when it can't locate anything to process the
292 // AuthType. No session plus requireSession false means
293 // do not authenticate the user at this time.
294 return pair<bool,void*>(true, returnOK());
296 // Try and cast down.
297 SAMLException* base = &e;
298 RetryableProfileException* trycast=dynamic_cast<RetryableProfileException*>(base);
300 // Session is invalid but we can retry -- initiate a new session.
301 procState = "Session Initiator Error";
302 const IPropertySet* initiator=NULL;
303 if (requireSessionWith.first)
304 initiator=m_priv->m_app->getSessionInitiatorById(requireSessionWith.second);
306 initiator=m_priv->m_app->getDefaultSessionInitiator();
307 // Standard handler element, so we dispatch normally.
309 return m_priv->dispatch(this,initiator,false);
311 // Legacy config support maps the Sessions element to the Shib profile.
312 auto_ptr_char binding(Constants::SHIB_SESSIONINIT_PROFILE_URI);
313 return m_priv->dispatch(this, m_priv->m_app->getPropertySet("Sessions"), false, binding.get());
316 throw; // send it to the outer handler
319 // We're done. Everything is okay. Nothing to report. Nothing to do..
320 // Let the caller decide how to proceed.
321 log(LogLevelDebug, "doCheckAuthN succeeded");
322 return pair<bool,void*>(false,NULL);
324 catch (SAMLException& e) {
325 log(LogLevelError, e.what());
328 catch (exception& e) {
329 log(LogLevelError, e.what());
330 mlp.insert("errorText", e.what());
333 // If we get here then we've got an error.
334 mlp.insert("errorType", procState);
336 mlp.insert("requestURL", m_url.substr(0,m_url.find('?')));
338 return pair<bool,void*>(true,m_priv->sendError(this,"session", mlp));
341 pair<bool,void*> ShibTarget::doHandler(void)
344 saml::NDC ndc("doHandler");
347 const char* procState = "Shibboleth Handler Error";
348 const char* targetURL = m_url.c_str();
353 throw ConfigurationException("System uninitialized, application did not supply request information.");
355 string hURL = getHandlerURL(targetURL);
356 const char* handlerURL=hURL.c_str();
358 throw ConfigurationException("Cannot determine handler from resource URL, check configuration.");
360 // Make sure we only process handler requests.
361 if (!strstr(targetURL,handlerURL))
362 return pair<bool,void*>(true, returnDecline());
364 const IPropertySet* sessionProps=m_priv->m_app->getPropertySet("Sessions");
366 throw ConfigurationException("Unable to map request to application session settings, check configuration.");
368 // Process incoming request.
369 pair<bool,bool> handlerSSL=sessionProps->getBool("handlerSSL");
371 // Make sure this is SSL, if it should be
372 if ((!handlerSSL.first || handlerSSL.second) && m_protocol != "https")
373 throw FatalProfileException("Blocked non-SSL access to Shibboleth handler.");
375 // We dispatch based on our path info. We know the request URL begins with or equals the handler URL,
376 // so the path info is the next character (or null).
377 const IPropertySet* handler=m_priv->m_app->getHandlerConfig(targetURL + strlen(handlerURL));
379 if (saml::XML::isElementNamed(handler->getElement(),shibtarget::XML::SAML2META_NS,SHIBT_L(AssertionConsumerService))) {
380 procState = "Session Creation Error";
381 return m_priv->dispatch(this,handler);
383 else if (saml::XML::isElementNamed(handler->getElement(),shibtarget::XML::SHIBTARGET_NS,SHIBT_L(SessionInitiator))) {
384 procState = "Session Initiator Error";
385 return m_priv->dispatch(this,handler);
387 else if (saml::XML::isElementNamed(handler->getElement(),shibtarget::XML::SAML2META_NS,SHIBT_L(SingleLogoutService))) {
388 procState = "Session Termination Error";
389 return m_priv->dispatch(this,handler);
391 else if (saml::XML::isElementNamed(handler->getElement(),shibtarget::XML::SHIBTARGET_NS,SHIBT_L(DiagnosticService))) {
392 procState = "Diagnostics Error";
393 return m_priv->dispatch(this,handler);
396 procState = "Extension Service Error";
397 return m_priv->dispatch(this,handler);
401 if (strlen(targetURL)>strlen(handlerURL) && targetURL[strlen(handlerURL)]!='?')
402 throw SAMLException("Shibboleth handler invoked at an unconfigured location.");
404 // This is a legacy direct execution of the handler (the old shireURL).
405 // If this is a GET, we see if it's a lazy session request, otherwise
406 // assume it's a SAML 1.x POST profile response and process it.
407 if (!strcasecmp(m_method.c_str(), "GET")) {
408 procState = "Session Initiator Error";
409 auto_ptr_char binding(Constants::SHIB_SESSIONINIT_PROFILE_URI);
410 return m_priv->dispatch(this, sessionProps, true, binding.get());
413 procState = "Session Creation Error";
414 auto_ptr_char binding(SAMLBrowserProfile::BROWSER_POST);
415 return m_priv->dispatch(this, sessionProps, true, binding.get());
417 catch (MetadataException& e) {
418 log(LogLevelError, e.what());
420 // See if a metadata error page is installed.
421 const IPropertySet* props=m_priv->m_app->getPropertySet("Errors");
423 pair<bool,const char*> p=props->getString("metadata");
425 mlp.insert("errorType", procState);
427 mlp.insert("requestURL", targetURL);
428 return make_pair(true,m_priv->sendError(this,"metadata", mlp));
432 catch (SAMLException& e) {
433 log(LogLevelError, e.what());
436 catch (exception& e) {
437 log(LogLevelError, e.what());
438 mlp.insert("errorText", e.what());
441 // If we get here then we've got an error.
442 mlp.insert("errorType", procState);
445 mlp.insert("requestURL", m_url.substr(0,m_url.find('?')));
447 return make_pair(true,m_priv->sendError(this,"session", mlp));
450 pair<bool,void*> ShibTarget::doCheckAuthZ(void)
453 saml::NDC ndc("doCheckAuthZ");
457 const char* procState = "Authorization Processing Error";
458 const char* targetURL = m_url.c_str();
462 throw ConfigurationException("System uninitialized, application did not supply request information.");
464 // Three settings dictate how to proceed.
465 pair<bool,const char*> authType = m_priv->m_settings.first->getString("authType");
466 pair<bool,bool> requireSession = m_priv->m_settings.first->getBool("requireSession");
467 pair<bool,const char*> requireSessionWith = m_priv->m_settings.first->getString("requireSessionWith");
469 // If no session is required AND the AuthType (an Apache-derived concept) isn't shibboleth,
470 // then we ignore this request and consider it unprotected. Apache might lie to us if
471 // ShibBasicHijack is on, but that's up to it.
472 if ((!requireSession.first || !requireSession.second) && !requireSessionWith.first &&
473 #ifdef HAVE_STRCASECMP
474 (!authType.first || strcasecmp(authType.second,"shibboleth")))
476 (!authType.first || stricmp(authType.second,"shibboleth")))
478 return pair<bool,void*>(true,returnDecline());
480 // Do we have an access control plugin?
481 if (m_priv->m_settings.second) {
483 if (!m_priv->m_cacheEntry) {
484 // No data yet, so we may need to try and get the session.
485 pair<string,const char*> shib_cookie=getCookieNameProps("_shibsession_");
486 const char *session_id = getCookie(shib_cookie.first);
488 if (session_id && *session_id) {
489 m_priv->m_conf->getListener()->sessionGet(
492 m_remote_addr.c_str(),
493 &m_priv->m_cacheEntry
497 catch (SAMLException&) {
498 log(LogLevelError, "doCheckAuthZ: unable to obtain session information to pass to access control provider");
502 Locker acllock(m_priv->m_settings.second);
503 if (m_priv->m_settings.second->authorized(this,m_priv->m_cacheEntry)) {
504 // Let the caller decide how to proceed.
505 log(LogLevelDebug, "doCheckAuthZ: access control provider granted access");
506 return pair<bool,void*>(false,NULL);
509 log(LogLevelWarn, "doCheckAuthZ: access control provider denied access");
511 mlp.insert("requestURL", targetURL);
512 return make_pair(true,m_priv->sendError(this, "access", mlp));
516 return make_pair(true,returnDecline());
518 catch (SAMLException& e) {
519 log(LogLevelError, e.what());
522 catch (exception& e) {
523 log(LogLevelError, e.what());
524 mlp.insert("errorText", e.what());
527 // If we get here then we've got an error.
528 mlp.insert("errorType", procState);
531 mlp.insert("requestURL", m_url.substr(0,m_url.find('?')));
533 return make_pair(true,m_priv->sendError(this, "access", mlp));
536 pair<bool,void*> ShibTarget::doExportAssertions(bool requireSession)
539 saml::NDC ndc("doExportAssertions");
543 const char* procState = "Attribute Processing Error";
544 const char* targetURL = m_url.c_str();
548 throw ConfigurationException("System uninitialized, application did not supply request information.");
550 if (!m_priv->m_cacheEntry) {
551 // No data yet, so we need to get the session. This can only happen
552 // if the call to doCheckAuthn doesn't happen in the same object lifetime.
553 pair<string,const char*> shib_cookie=getCookieNameProps("_shibsession_");
554 const char *session_id = getCookie(shib_cookie.first);
556 if (session_id && *session_id) {
557 m_priv->m_conf->getListener()->sessionGet(
560 m_remote_addr.c_str(),
561 &m_priv->m_cacheEntry
565 catch (SAMLException&) {
566 log(LogLevelError, "unable to obtain session information to export into request headers");
567 // If we have to have a session, then this is a fatal error.
574 if (!m_priv->m_cacheEntry) {
576 throw InvalidSessionException("Unable to obtain session information for request.");
578 return pair<bool,void*>(false,NULL); // just bail silently
581 ISessionCacheEntry::CachedResponse cr=m_priv->m_cacheEntry->getResponse();
583 // Maybe export the response.
584 pair<bool,bool> exp=m_priv->m_settings.first->getBool("exportAssertion");
585 if (exp.first && exp.second && cr.unfiltered) {
587 os << *cr.unfiltered;
589 XMLByte* serialized = Base64::encode(reinterpret_cast<XMLByte*>((char*)os.str().c_str()), os.str().length(), &outlen);
591 for (pos=serialized, pos2=serialized; *pos2; pos2++)
595 setHeader("Shib-Attributes", reinterpret_cast<char*>(serialized));
596 XMLString::release(&serialized);
599 // Export the SAML AuthnMethod and the origin site name, and possibly the NameIdentifier.
600 setHeader("Shib-Origin-Site", m_priv->m_cacheEntry->getProviderId());
601 setHeader("Shib-Identity-Provider", m_priv->m_cacheEntry->getProviderId());
602 auto_ptr_char am(m_priv->m_cacheEntry->getAuthnStatement()->getAuthMethod());
603 setHeader("Shib-Authentication-Method", am.get());
605 // Get the AAP providers, which contain the attribute policy info.
606 Iterator<IAAP*> provs=m_priv->m_app->getAAPProviders();
609 while (provs.hasNext()) {
610 IAAP* aap=provs.next();
612 const XMLCh* format = m_priv->m_cacheEntry->getAuthnStatement()->getSubject()->getNameIdentifier()->getFormat();
613 const IAttributeRule* rule=aap->lookup(format ? format : SAMLNameIdentifier::UNSPECIFIED);
614 if (rule && rule->getHeader()) {
615 auto_ptr_char form(format ? format : SAMLNameIdentifier::UNSPECIFIED);
616 auto_ptr_char nameid(m_priv->m_cacheEntry->getAuthnStatement()->getSubject()->getNameIdentifier()->getName());
617 setHeader("Shib-NameIdentifier-Format", form.get());
618 if (!strcmp(rule->getHeader(),"REMOTE_USER"))
619 setRemoteUser(nameid.get());
621 setHeader(rule->getHeader(), nameid.get());
625 setHeader("Shib-Application-ID", m_priv->m_app->getId());
627 string strUnsetValue;
628 const IPropertySet* localProps=m_priv->m_Config->getINI()->getPropertySet("Local");
630 pair<bool,const char*> unsetValue=localProps->getString("unsetHeaderValue");
631 if (unsetValue.first)
632 strUnsetValue = unsetValue.second;
635 // Export the attributes.
636 Iterator<SAMLAssertion*> a_iter(cr.filtered ? cr.filtered->getAssertions() : EMPTY(SAMLAssertion*));
637 while (a_iter.hasNext()) {
638 SAMLAssertion* assert=a_iter.next();
639 Iterator<SAMLStatement*> statements=assert->getStatements();
640 while (statements.hasNext()) {
641 SAMLAttributeStatement* astate=dynamic_cast<SAMLAttributeStatement*>(statements.next());
644 Iterator<SAMLAttribute*> attrs=astate->getAttributes();
645 while (attrs.hasNext()) {
646 SAMLAttribute* attr=attrs.next();
648 // Are we supposed to export it?
650 while (provs.hasNext()) {
651 IAAP* aap=provs.next();
653 const IAttributeRule* rule=aap->lookup(attr->getName(),attr->getNamespace());
654 if (!rule || !rule->getHeader())
657 Iterator<string> vals=attr->getSingleByteValues();
658 if (!strcmp(rule->getHeader(),"REMOTE_USER") && vals.hasNext())
659 setRemoteUser(vals.next());
662 string header = getHeader(rule->getHeader());
663 if (header == strUnsetValue)
667 for (; vals.hasNext(); it++) {
668 string value = vals.next();
669 for (string::size_type pos = value.find_first_of(";", string::size_type(0));
671 pos = value.find_first_of(";", pos)) {
672 value.insert(pos, "\\");
679 setHeader(rule->getHeader(), header);
686 return pair<bool,void*>(false,NULL);
688 catch (SAMLException& e) {
689 log(LogLevelError, e.what());
692 catch (exception& e) {
693 log(LogLevelError, e.what());
694 mlp.insert("errorText", e.what());
697 // If we get here then we've got an error.
698 mlp.insert("errorType", procState);
701 mlp.insert("requestURL", m_url.substr(0,m_url.find('?')));
703 return make_pair(true,m_priv->sendError(this, "rm", mlp));
706 const char* ShibTarget::getCookie(const string& name) const
708 if (m_priv->m_cookieMap.empty()) {
709 string cookies=getCookies();
711 string::size_type pos=0,cname,namelen,val,vallen;
712 while (pos !=string::npos && pos < cookies.length()) {
713 while (isspace(cookies[pos])) pos++;
715 pos=cookies.find_first_of("=",pos);
716 if (pos == string::npos)
720 if (pos==cookies.length())
723 pos=cookies.find_first_of(";",pos);
724 if (pos != string::npos) {
727 m_priv->m_cookieMap.insert(make_pair(cookies.substr(cname,namelen),cookies.substr(val,vallen)));
730 m_priv->m_cookieMap.insert(make_pair(cookies.substr(cname,namelen),cookies.substr(val)));
733 map<string,string>::const_iterator lookup=m_priv->m_cookieMap.find(name);
734 return (lookup==m_priv->m_cookieMap.end()) ? NULL : lookup->second.c_str();
737 pair<string,const char*> ShibTarget::getCookieNameProps(const char* prefix) const
739 static const char* defProps="; path=/";
741 const IPropertySet* props=m_priv->m_app ? m_priv->m_app->getPropertySet("Sessions") : NULL;
743 pair<bool,const char*> p=props->getString("cookieProps");
746 pair<bool,const char*> p2=props->getString("cookieName");
748 return make_pair(string(prefix) + p2.second,p.second);
749 return make_pair(string(prefix) + m_priv->m_app->getHash(),p.second);
752 // Shouldn't happen, but just in case..
753 return pair<string,const char*>(prefix,defProps);
756 string ShibTarget::getHandlerURL(const char* resource) const
758 if (!m_priv->m_handlerURL.empty() && resource && !strcmp(getRequestURL(),resource))
759 return m_priv->m_handlerURL;
762 throw ConfigurationException("Internal error in ShibTargetPriv::getHandlerURL, missing application pointer.");
764 #ifdef HAVE_STRCASECMP
765 if (!resource || (strncasecmp(resource,"http://",7) && strncasecmp(resource,"https://",8)))
767 if (!resource || (strnicmp(resource,"http://",7) && strnicmp(resource,"https://",8)))
769 throw SAMLException("Target resource was not an absolute URL.");
774 const char* handler=NULL;
775 const IPropertySet* props=m_priv->m_app->getPropertySet("Sessions");
777 pair<bool,bool> p=props->getBool("handlerSSL");
780 pair<bool,const char*> p2=props->getString("handlerURL");
785 // Should never happen...
786 if (!handler || (*handler!='/' && strncmp(handler,"http:",5) && strncmp(handler,"https:",6)))
787 throw ConfigurationException(
788 "Invalid handlerURL property ($1) in Application ($2)",
789 params(2, handler ? handler : "null", m_priv->m_app->getId())
792 // The "handlerURL" property can be in one of three formats:
794 // 1) a full URI: http://host/foo/bar
795 // 2) a hostless URI: http:///foo/bar
796 // 3) a relative path: /foo/bar
798 // # Protocol Host Path
799 // 1 handler handler handler
800 // 2 handler resource handler
801 // 3 resource resource handler
803 // note: if ssl_only is true, make sure the protocol is https
805 const char* path = NULL;
807 // Decide whether to use the handler or the resource for the "protocol"
809 if (*handler != '/') {
817 // break apart the "protocol" string into protocol, host, and "the rest"
818 const char* colon=strchr(prot,':');
820 const char* slash=strchr(colon,'/');
824 // Compute the actual protocol and store in member.
826 m_priv->m_handlerURL.assign("https://");
828 m_priv->m_handlerURL.assign(prot, colon-prot);
830 // create the "host" from either the colon/slash or from the target string
831 // If prot == handler then we're in either #1 or #2, else #3.
832 // If slash == colon then we're in #2.
833 if (prot != handler || slash == colon) {
834 colon = strchr(resource, ':');
835 colon += 3; // Get past the ://
836 slash = strchr(colon, '/');
838 string host(colon, (slash ? slash-colon : strlen(colon)));
840 // Build the handler URL
841 m_priv->m_handlerURL+=host + path;
842 return m_priv->m_handlerURL;
845 void ShibTarget::log(ShibLogLevel level, const string& msg)
847 Category::getInstance("shibtarget.ShibTarget").log(
848 (level == LogLevelDebug ? Priority::DEBUG :
849 (level == LogLevelInfo ? Priority::INFO :
850 (level == LogLevelWarn ? Priority::WARN : Priority::ERROR))),
855 const IApplication* ShibTarget::getApplication() const
857 return m_priv->m_app;
860 const IConfig* ShibTarget::getConfig() const
862 return m_priv->m_conf;
865 void* ShibTarget::returnDecline(void)
870 void* ShibTarget::returnOK(void)
876 /*************************************************************************
877 * Shib Target Private implementation
880 ShibTargetPriv::ShibTargetPriv() : m_app(NULL), m_cacheEntry(NULL), m_Config(NULL), m_conf(NULL), m_mapper(NULL) {}
882 ShibTargetPriv::~ShibTargetPriv()
885 m_cacheEntry->unlock();
903 void ShibTargetPriv::get_application(ShibTarget* st, const string& protocol, const string& hostname, int port, const string& uri)
908 // XXX: Do we need to keep conf and mapper locked while we hold m_app?
909 // TODO: No, should be able to hold the conf but release the mapper.
911 // We lock the configuration system for the duration.
912 m_conf=m_Config->getINI();
915 // Map request to application and content settings.
916 m_mapper=m_conf->getRequestMapper();
919 // Obtain the application settings from the parsed URL
920 m_settings = m_mapper->getSettings(st);
922 // Now find the application from the URL settings
923 pair<bool,const char*> application_id=m_settings.first->getString("applicationId");
924 m_app=m_conf->getApplication(application_id.second);
930 throw ConfigurationException("Unable to map request to application settings, check configuration.");
933 // Compute the full target URL
934 st->m_url = protocol + "://" + hostname;
935 if ((protocol == "http" && port != 80) || (protocol == "https" && port != 443)) {
936 ostringstream portstr;
938 st->m_url += ":" + portstr.str();
943 void* ShibTargetPriv::sendError(ShibTarget* st, const char* page, ShibMLP &mlp)
945 ShibTarget::header_t hdrs[] = {
946 ShibTarget::header_t("Expires","01-Jan-1997 12:00:00 GMT"),
947 ShibTarget::header_t("Cache-Control","private,no-store,no-cache")
950 const IPropertySet* props=m_app->getPropertySet("Errors");
952 pair<bool,const char*> p=props->getString(page);
954 ifstream infile(p.second);
955 if (!infile.fail()) {
956 const char* res = mlp.run(infile,props);
958 return st->sendPage(res, 200, "text/html", ArrayIterator<ShibTarget::header_t>(hdrs,2));
961 else if (!strcmp(page,"access"))
962 return st->sendPage("Access Denied", 403, "text/html", ArrayIterator<ShibTarget::header_t>(hdrs,2));
965 string errstr = string("sendError could not process error template (") + page + ") for application (";
966 errstr += m_app->getId();
968 st->log(ShibTarget::LogLevelError, errstr);
970 "Internal Server Error. Please contact the site administrator.", 500, "text/html", ArrayIterator<ShibTarget::header_t>(hdrs,2)
974 void ShibTargetPriv::clearHeaders(ShibTarget* st)
976 // Clear invariant stuff.
977 st->clearHeader("Shib-Origin-Site");
978 st->clearHeader("Shib-Identity-Provider");
979 st->clearHeader("Shib-Authentication-Method");
980 st->clearHeader("Shib-NameIdentifier-Format");
981 st->clearHeader("Shib-Attributes");
982 st->clearHeader("Shib-Application-ID");
984 // Clear out the list of mapped attributes
985 Iterator<IAAP*> provs=m_app->getAAPProviders();
986 while (provs.hasNext()) {
987 IAAP* aap=provs.next();
989 Iterator<const IAttributeRule*> rules=aap->getAttributeRules();
990 while (rules.hasNext()) {
991 const char* header=rules.next()->getHeader();
993 st->clearHeader(header);
998 pair<bool,void*> ShibTargetPriv::dispatch(
1000 const IPropertySet* config,
1002 const char* forceType
1005 pair<bool,const char*> binding=forceType ? make_pair(true,forceType) : config->getString("Binding");
1006 if (binding.first) {
1007 auto_ptr<IPlugIn> plugin(SAMLConfig::getConfig().getPlugMgr().newPlugin(binding.second,config->getElement()));
1008 IHandler* handler=dynamic_cast<IHandler*>(plugin.get());
1010 throw UnsupportedProfileException(
1011 "Plugin for binding ($1) does not implement IHandler interface.",params(1,binding.second)
1013 return handler->run(st,config,isHandler);
1015 throw UnsupportedProfileException("Handler element is missing Binding attribute to determine what handler to run.");