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 != '%') {
154 if (!isxdigit(*uri) || !isxdigit(*(uri+1)))
155 throw SAMLException("Bad request, contained unsupported encoded characters.");
163 m_priv->m_Config = &ShibTargetConfig::getConfig();
164 m_priv->get_application(this, protocol, hostname, port, m_uri);
168 // These functions implement the server-agnostic shibboleth engine
169 // The web server modules implement a subclass and then call into
170 // these methods once they instantiate their request object.
172 pair<bool,void*> ShibTarget::doCheckAuthN(bool handler)
175 saml::NDC ndc("doCheckAuthN");
178 const char* procState = "Request Processing Error";
179 const char* targetURL = m_url.c_str();
184 throw ConfigurationException("System uninitialized, application did not supply request information.");
186 // If not SSL, check to see if we should block or redirect it.
187 if (!strcmp("http",getProtocol())) {
188 pair<bool,const char*> redirectToSSL = m_priv->m_settings.first->getString("redirectToSSL");
189 if (redirectToSSL.first) {
190 if (!strcasecmp("GET",getRequestMethod()) || !strcasecmp("HEAD",getRequestMethod())) {
191 // Compute the new target URL
192 string redirectURL = string("https://") + getHostname();
193 if (strcmp(redirectToSSL.second,"443")) {
194 redirectURL = redirectURL + ':' + redirectToSSL.second;
196 redirectURL += getRequestURI();
197 return make_pair(true, sendRedirect(redirectURL));
200 mlp.insert("requestURL", m_url.substr(0,m_url.find('?')));
201 return make_pair(true,m_priv->sendError(this,"ssl", mlp));
206 string hURL = getHandlerURL(targetURL);
207 const char* handlerURL=hURL.c_str();
209 throw ConfigurationException("Cannot determine handler from resource URL, check configuration.");
211 // If the request URL contains the handler base URL for this application, either dispatch
212 // directly (mainly Apache 2.0) or just pass back control.
213 if (strstr(targetURL,handlerURL)) {
217 return pair<bool,void*>(true, returnOK());
220 // Three settings dictate how to proceed.
221 pair<bool,const char*> authType = m_priv->m_settings.first->getString("authType");
222 pair<bool,bool> requireSession = m_priv->m_settings.first->getBool("requireSession");
223 pair<bool,const char*> requireSessionWith = m_priv->m_settings.first->getString("requireSessionWith");
225 // If no session is required AND the AuthType (an Apache-derived concept) isn't shibboleth,
226 // then we ignore this request and consider it unprotected. Apache might lie to us if
227 // ShibBasicHijack is on, but that's up to it.
228 if ((!requireSession.first || !requireSession.second) && !requireSessionWith.first &&
229 #ifdef HAVE_STRCASECMP
230 (!authType.first || strcasecmp(authType.second,"shibboleth")))
232 (!authType.first || stricmp(authType.second,"shibboleth")))
234 return pair<bool,void*>(true,returnDecline());
236 // Fix for secadv 20050901
237 m_priv->clearHeaders(this);
239 pair<string,const char*> shib_cookie = getCookieNameProps("_shibsession_");
240 const char* session_id = getCookie(shib_cookie.first);
241 if (!session_id || !*session_id) {
242 // No session. Maybe that's acceptable?
243 if ((!requireSession.first || !requireSession.second) && !requireSessionWith.first)
244 return pair<bool,void*>(true,returnOK());
246 // No cookie, but we require a session. Initiate a new session using the indicated method.
247 procState = "Session Initiator Error";
248 const IPropertySet* initiator=NULL;
249 if (requireSessionWith.first)
250 initiator=m_priv->m_app->getSessionInitiatorById(requireSessionWith.second);
252 initiator=m_priv->m_app->getDefaultSessionInitiator();
254 // Standard handler element, so we dispatch normally.
256 return m_priv->dispatch(this,initiator,false);
258 // Legacy config support maps the Sessions element to the Shib profile.
259 auto_ptr_char binding(Constants::SHIB_SESSIONINIT_PROFILE_URI);
260 return m_priv->dispatch(this, m_priv->m_app->getPropertySet("Sessions"), false, binding.get());
264 procState = "Session Processing Error";
266 // Localized exception throw if the session isn't valid.
267 m_priv->m_conf->getListener()->sessionGet(
270 m_remote_addr.c_str(),
271 &m_priv->m_cacheEntry
274 catch (SAMLException& e) {
275 log(LogLevelError, string("session processing failed: ") + e.what());
277 // If no session is required, bail now.
278 if ((!requireSession.first || !requireSession.second) && !requireSessionWith.first)
279 // Has to be OK because DECLINED will just cause Apache
280 // to fail when it can't locate anything to process the
281 // AuthType. No session plus requireSession false means
282 // do not authenticate the user at this time.
283 return pair<bool,void*>(true, returnOK());
285 // Try and cast down.
286 SAMLException* base = &e;
287 RetryableProfileException* trycast=dynamic_cast<RetryableProfileException*>(base);
289 // Session is invalid but we can retry -- initiate a new session.
290 procState = "Session Initiator Error";
291 const IPropertySet* initiator=NULL;
292 if (requireSessionWith.first)
293 initiator=m_priv->m_app->getSessionInitiatorById(requireSessionWith.second);
295 initiator=m_priv->m_app->getDefaultSessionInitiator();
296 // Standard handler element, so we dispatch normally.
298 return m_priv->dispatch(this,initiator,false);
300 // Legacy config support maps the Sessions element to the Shib profile.
301 auto_ptr_char binding(Constants::SHIB_SESSIONINIT_PROFILE_URI);
302 return m_priv->dispatch(this, m_priv->m_app->getPropertySet("Sessions"), false, binding.get());
305 throw; // send it to the outer handler
308 // We're done. Everything is okay. Nothing to report. Nothing to do..
309 // Let the caller decide how to proceed.
310 log(LogLevelDebug, "doCheckAuthN succeeded");
311 return pair<bool,void*>(false,NULL);
313 catch (SAMLException& e) {
316 catch (exception& e) {
317 mlp.insert("errorText", e.what());
320 // If we get here then we've got an error.
321 mlp.insert("errorType", procState);
323 mlp.insert("requestURL", m_url.substr(0,m_url.find('?')));
325 return pair<bool,void*>(true,m_priv->sendError(this,"session", mlp));
328 pair<bool,void*> ShibTarget::doHandler(void)
331 saml::NDC ndc("doHandler");
334 const char* procState = "Shibboleth Handler Error";
335 const char* targetURL = m_url.c_str();
340 throw ConfigurationException("System uninitialized, application did not supply request information.");
342 string hURL = getHandlerURL(targetURL);
343 const char* handlerURL=hURL.c_str();
345 throw ConfigurationException("Cannot determine handler from resource URL, check configuration.");
347 // Make sure we only process handler requests.
348 if (!strstr(targetURL,handlerURL))
349 return pair<bool,void*>(true, returnDecline());
351 const IPropertySet* sessionProps=m_priv->m_app->getPropertySet("Sessions");
353 throw ConfigurationException("Unable to map request to application session settings, check configuration.");
355 // Process incoming request.
356 pair<bool,bool> handlerSSL=sessionProps->getBool("handlerSSL");
358 // Make sure this is SSL, if it should be
359 if ((!handlerSSL.first || handlerSSL.second) && m_protocol != "https")
360 throw FatalProfileException("Blocked non-SSL access to Shibboleth handler.");
362 // We dispatch based on our path info. We know the request URL begins with or equals the handler URL,
363 // so the path info is the next character (or null).
364 const IPropertySet* handler=m_priv->m_app->getHandlerConfig(targetURL + strlen(handlerURL));
366 if (saml::XML::isElementNamed(handler->getElement(),shibtarget::XML::SAML2META_NS,SHIBT_L(AssertionConsumerService))) {
367 procState = "Session Creation Error";
368 return m_priv->dispatch(this,handler);
370 else if (saml::XML::isElementNamed(handler->getElement(),shibtarget::XML::SHIBTARGET_NS,SHIBT_L(SessionInitiator))) {
371 procState = "Session Initiator Error";
372 return m_priv->dispatch(this,handler);
374 else if (saml::XML::isElementNamed(handler->getElement(),shibtarget::XML::SAML2META_NS,SHIBT_L(SingleLogoutService))) {
375 procState = "Session Termination Error";
376 return m_priv->dispatch(this,handler);
378 else if (saml::XML::isElementNamed(handler->getElement(),shibtarget::XML::SHIBTARGET_NS,SHIBT_L(DiagnosticService))) {
379 procState = "Diagnostics Error";
380 return m_priv->dispatch(this,handler);
383 procState = "Extension Service Error";
384 return m_priv->dispatch(this,handler);
388 if (strlen(targetURL)>strlen(handlerURL) && targetURL[strlen(handlerURL)]!='?')
389 throw SAMLException("Shibboleth handler invoked at an unconfigured location.");
391 // This is a legacy direct execution of the handler (the old shireURL).
392 // If this is a GET, we see if it's a lazy session request, otherwise
393 // assume it's a SAML 1.x POST profile response and process it.
394 if (!strcasecmp(m_method.c_str(), "GET")) {
395 procState = "Session Initiator Error";
396 auto_ptr_char binding(Constants::SHIB_SESSIONINIT_PROFILE_URI);
397 return m_priv->dispatch(this, sessionProps, true, binding.get());
400 procState = "Session Creation Error";
401 auto_ptr_char binding(SAMLBrowserProfile::BROWSER_POST);
402 return m_priv->dispatch(this, sessionProps, true, binding.get());
404 catch (MetadataException& e) {
406 // See if a metadata error page is installed.
407 const IPropertySet* props=m_priv->m_app->getPropertySet("Errors");
409 pair<bool,const char*> p=props->getString("metadata");
411 mlp.insert("errorType", procState);
413 mlp.insert("requestURL", targetURL);
414 return make_pair(true,m_priv->sendError(this,"metadata", mlp));
418 catch (SAMLException& e) {
421 catch (exception& e) {
422 mlp.insert("errorText", e.what());
425 // If we get here then we've got an error.
426 mlp.insert("errorType", procState);
429 mlp.insert("requestURL", m_url.substr(0,m_url.find('?')));
431 return make_pair(true,m_priv->sendError(this,"session", mlp));
434 pair<bool,void*> ShibTarget::doCheckAuthZ(void)
437 saml::NDC ndc("doCheckAuthZ");
441 const char* procState = "Authorization Processing Error";
442 const char* targetURL = m_url.c_str();
446 throw ConfigurationException("System uninitialized, application did not supply request information.");
448 // Three settings dictate how to proceed.
449 pair<bool,const char*> authType = m_priv->m_settings.first->getString("authType");
450 pair<bool,bool> requireSession = m_priv->m_settings.first->getBool("requireSession");
451 pair<bool,const char*> requireSessionWith = m_priv->m_settings.first->getString("requireSessionWith");
453 // If no session is required AND the AuthType (an Apache-derived concept) isn't shibboleth,
454 // then we ignore this request and consider it unprotected. Apache might lie to us if
455 // ShibBasicHijack is on, but that's up to it.
456 if ((!requireSession.first || !requireSession.second) && !requireSessionWith.first &&
457 #ifdef HAVE_STRCASECMP
458 (!authType.first || strcasecmp(authType.second,"shibboleth")))
460 (!authType.first || stricmp(authType.second,"shibboleth")))
462 return pair<bool,void*>(true,returnDecline());
464 // Do we have an access control plugin?
465 if (m_priv->m_settings.second) {
467 if (!m_priv->m_cacheEntry) {
468 // No data yet, so we may need to try and get the session.
469 pair<string,const char*> shib_cookie=getCookieNameProps("_shibsession_");
470 const char *session_id = getCookie(shib_cookie.first);
472 if (session_id && *session_id) {
473 m_priv->m_conf->getListener()->sessionGet(
476 m_remote_addr.c_str(),
477 &m_priv->m_cacheEntry
481 catch (SAMLException&) {
482 log(LogLevelError, "doCheckAuthZ: unable to obtain session information to pass to access control provider");
486 Locker acllock(m_priv->m_settings.second);
487 if (m_priv->m_settings.second->authorized(this,m_priv->m_cacheEntry)) {
488 // Let the caller decide how to proceed.
489 log(LogLevelDebug, "doCheckAuthZ: access control provider granted access");
490 return pair<bool,void*>(false,NULL);
493 log(LogLevelWarn, "doCheckAuthZ: access control provider denied access");
495 mlp.insert("requestURL", targetURL);
496 return make_pair(true,m_priv->sendError(this, "access", mlp));
500 return make_pair(true,returnDecline());
502 catch (SAMLException& e) {
505 catch (exception& e) {
506 mlp.insert("errorText", e.what());
509 // If we get here then we've got an error.
510 mlp.insert("errorType", procState);
513 mlp.insert("requestURL", m_url.substr(0,m_url.find('?')));
515 return make_pair(true,m_priv->sendError(this, "access", mlp));
518 pair<bool,void*> ShibTarget::doExportAssertions(bool requireSession)
521 saml::NDC ndc("doExportAssertions");
525 const char* procState = "Attribute Processing Error";
526 const char* targetURL = m_url.c_str();
530 throw ConfigurationException("System uninitialized, application did not supply request information.");
532 if (!m_priv->m_cacheEntry) {
533 // No data yet, so we need to get the session. This can only happen
534 // if the call to doCheckAuthn doesn't happen in the same object lifetime.
535 pair<string,const char*> shib_cookie=getCookieNameProps("_shibsession_");
536 const char *session_id = getCookie(shib_cookie.first);
538 if (session_id && *session_id) {
539 m_priv->m_conf->getListener()->sessionGet(
542 m_remote_addr.c_str(),
543 &m_priv->m_cacheEntry
547 catch (SAMLException&) {
548 log(LogLevelError, "unable to obtain session information to export into request headers");
549 // If we have to have a session, then this is a fatal error.
556 if (!m_priv->m_cacheEntry) {
558 throw InvalidSessionException("Unable to obtain session information for request.");
560 return pair<bool,void*>(false,NULL); // just bail silently
563 ISessionCacheEntry::CachedResponse cr=m_priv->m_cacheEntry->getResponse();
565 // Maybe export the response.
566 pair<bool,bool> exp=m_priv->m_settings.first->getBool("exportAssertion");
567 if (exp.first && exp.second && cr.unfiltered) {
569 os << *cr.unfiltered;
571 XMLByte* serialized = Base64::encode(reinterpret_cast<XMLByte*>((char*)os.str().c_str()), os.str().length(), &outlen);
573 for (pos=serialized, pos2=serialized; *pos2; pos2++)
577 setHeader("Shib-Attributes", reinterpret_cast<char*>(serialized));
578 XMLString::release(&serialized);
581 // Export the SAML AuthnMethod and the origin site name, and possibly the NameIdentifier.
582 setHeader("Shib-Origin-Site", m_priv->m_cacheEntry->getProviderId());
583 setHeader("Shib-Identity-Provider", m_priv->m_cacheEntry->getProviderId());
584 auto_ptr_char am(m_priv->m_cacheEntry->getAuthnStatement()->getAuthMethod());
585 setHeader("Shib-Authentication-Method", am.get());
587 // Get the AAP providers, which contain the attribute policy info.
588 Iterator<IAAP*> provs=m_priv->m_app->getAAPProviders();
591 while (provs.hasNext()) {
592 IAAP* aap=provs.next();
594 const XMLCh* format = m_priv->m_cacheEntry->getAuthnStatement()->getSubject()->getNameIdentifier()->getFormat();
595 const IAttributeRule* rule=aap->lookup(format ? format : SAMLNameIdentifier::UNSPECIFIED);
596 if (rule && rule->getHeader()) {
597 auto_ptr_char form(format ? format : SAMLNameIdentifier::UNSPECIFIED);
598 auto_ptr_char nameid(m_priv->m_cacheEntry->getAuthnStatement()->getSubject()->getNameIdentifier()->getName());
599 setHeader("Shib-NameIdentifier-Format", form.get());
600 if (!strcmp(rule->getHeader(),"REMOTE_USER"))
601 setRemoteUser(nameid.get());
603 setHeader(rule->getHeader(), nameid.get());
607 setHeader("Shib-Application-ID", m_priv->m_app->getId());
609 string strUnsetValue;
610 const IPropertySet* localProps=m_priv->m_Config->getINI()->getPropertySet("Local");
612 pair<bool,const char*> unsetValue=localProps->getString("unsetHeaderValue");
613 if (unsetValue.first)
614 strUnsetValue = unsetValue.second;
617 // Export the attributes.
618 Iterator<SAMLAssertion*> a_iter(cr.filtered ? cr.filtered->getAssertions() : EMPTY(SAMLAssertion*));
619 while (a_iter.hasNext()) {
620 SAMLAssertion* assert=a_iter.next();
621 Iterator<SAMLStatement*> statements=assert->getStatements();
622 while (statements.hasNext()) {
623 SAMLAttributeStatement* astate=dynamic_cast<SAMLAttributeStatement*>(statements.next());
626 Iterator<SAMLAttribute*> attrs=astate->getAttributes();
627 while (attrs.hasNext()) {
628 SAMLAttribute* attr=attrs.next();
630 // Are we supposed to export it?
632 while (provs.hasNext()) {
633 IAAP* aap=provs.next();
635 const IAttributeRule* rule=aap->lookup(attr->getName(),attr->getNamespace());
636 if (!rule || !rule->getHeader())
639 Iterator<string> vals=attr->getSingleByteValues();
640 if (!strcmp(rule->getHeader(),"REMOTE_USER") && vals.hasNext())
641 setRemoteUser(vals.next());
644 string header = getHeader(rule->getHeader());
645 if (header == strUnsetValue)
649 for (; vals.hasNext(); it++) {
650 string value = vals.next();
651 for (string::size_type pos = value.find_first_of(";", string::size_type(0));
653 pos = value.find_first_of(";", pos)) {
654 value.insert(pos, "\\");
661 setHeader(rule->getHeader(), header);
668 return pair<bool,void*>(false,NULL);
670 catch (SAMLException& e) {
673 catch (exception& e) {
674 mlp.insert("errorText", e.what());
677 // If we get here then we've got an error.
678 mlp.insert("errorType", procState);
681 mlp.insert("requestURL", m_url.substr(0,m_url.find('?')));
683 return make_pair(true,m_priv->sendError(this, "rm", mlp));
686 const char* ShibTarget::getCookie(const string& name) const
688 if (m_priv->m_cookieMap.empty()) {
689 string cookies=getCookies();
691 string::size_type pos=0,cname,namelen,val,vallen;
692 while (pos !=string::npos && pos < cookies.length()) {
693 while (isspace(cookies[pos])) pos++;
695 pos=cookies.find_first_of("=",pos);
696 if (pos == string::npos)
700 if (pos==cookies.length())
703 pos=cookies.find_first_of(";",pos);
704 if (pos != string::npos) {
707 m_priv->m_cookieMap.insert(make_pair(cookies.substr(cname,namelen),cookies.substr(val,vallen)));
710 m_priv->m_cookieMap.insert(make_pair(cookies.substr(cname,namelen),cookies.substr(val)));
713 map<string,string>::const_iterator lookup=m_priv->m_cookieMap.find(name);
714 return (lookup==m_priv->m_cookieMap.end()) ? NULL : lookup->second.c_str();
717 pair<string,const char*> ShibTarget::getCookieNameProps(const char* prefix) const
719 static const char* defProps="; path=/";
721 const IPropertySet* props=m_priv->m_app ? m_priv->m_app->getPropertySet("Sessions") : NULL;
723 pair<bool,const char*> p=props->getString("cookieProps");
726 pair<bool,const char*> p2=props->getString("cookieName");
728 return make_pair(string(prefix) + p2.second,p.second);
729 return make_pair(string(prefix) + m_priv->m_app->getHash(),p.second);
732 // Shouldn't happen, but just in case..
733 return pair<string,const char*>(prefix,defProps);
736 string ShibTarget::getHandlerURL(const char* resource) const
738 if (!m_priv->m_handlerURL.empty() && resource && !strcmp(getRequestURL(),resource))
739 return m_priv->m_handlerURL;
742 throw ConfigurationException("Internal error in ShibTargetPriv::getHandlerURL, missing application pointer.");
744 #ifdef HAVE_STRCASECMP
745 if (!resource || (strncasecmp(resource,"http://",7) && strncasecmp(resource,"https://",8)))
747 if (!resource || (strnicmp(resource,"http://",7) && strnicmp(resource,"https://",8)))
749 throw SAMLException("Target resource was not an absolute URL.");
754 const char* handler=NULL;
755 const IPropertySet* props=m_priv->m_app->getPropertySet("Sessions");
757 pair<bool,bool> p=props->getBool("handlerSSL");
760 pair<bool,const char*> p2=props->getString("handlerURL");
765 // Should never happen...
766 if (!handler || (*handler!='/' && strncmp(handler,"http:",5) && strncmp(handler,"https:",6)))
767 throw ConfigurationException(
768 "Invalid handlerURL property ($1) in Application ($2)",
769 params(2, handler ? handler : "null", m_priv->m_app->getId())
772 // The "handlerURL" property can be in one of three formats:
774 // 1) a full URI: http://host/foo/bar
775 // 2) a hostless URI: http:///foo/bar
776 // 3) a relative path: /foo/bar
778 // # Protocol Host Path
779 // 1 handler handler handler
780 // 2 handler resource handler
781 // 3 resource resource handler
783 // note: if ssl_only is true, make sure the protocol is https
785 const char* path = NULL;
787 // Decide whether to use the handler or the resource for the "protocol"
789 if (*handler != '/') {
797 // break apart the "protocol" string into protocol, host, and "the rest"
798 const char* colon=strchr(prot,':');
800 const char* slash=strchr(colon,'/');
804 // Compute the actual protocol and store in member.
806 m_priv->m_handlerURL.assign("https://");
808 m_priv->m_handlerURL.assign(prot, colon-prot);
810 // create the "host" from either the colon/slash or from the target string
811 // If prot == handler then we're in either #1 or #2, else #3.
812 // If slash == colon then we're in #2.
813 if (prot != handler || slash == colon) {
814 colon = strchr(resource, ':');
815 colon += 3; // Get past the ://
816 slash = strchr(colon, '/');
818 string host(colon, (slash ? slash-colon : strlen(colon)));
820 // Build the handler URL
821 m_priv->m_handlerURL+=host + path;
822 return m_priv->m_handlerURL;
825 void ShibTarget::log(ShibLogLevel level, const string& msg)
827 Category::getInstance("shibtarget.ShibTarget").log(
828 (level == LogLevelDebug ? Priority::DEBUG :
829 (level == LogLevelInfo ? Priority::INFO :
830 (level == LogLevelWarn ? Priority::WARN : Priority::ERROR))),
835 const IApplication* ShibTarget::getApplication() const
837 return m_priv->m_app;
840 const IConfig* ShibTarget::getConfig() const
842 return m_priv->m_conf;
845 void* ShibTarget::returnDecline(void)
850 void* ShibTarget::returnOK(void)
856 /*************************************************************************
857 * Shib Target Private implementation
860 ShibTargetPriv::ShibTargetPriv() : m_app(NULL), m_cacheEntry(NULL), m_Config(NULL), m_conf(NULL), m_mapper(NULL) {}
862 ShibTargetPriv::~ShibTargetPriv()
865 m_cacheEntry->unlock();
883 void ShibTargetPriv::get_application(ShibTarget* st, const string& protocol, const string& hostname, int port, const string& uri)
888 // XXX: Do we need to keep conf and mapper locked while we hold m_app?
889 // TODO: No, should be able to hold the conf but release the mapper.
891 // We lock the configuration system for the duration.
892 m_conf=m_Config->getINI();
895 // Map request to application and content settings.
896 m_mapper=m_conf->getRequestMapper();
899 // Obtain the application settings from the parsed URL
900 m_settings = m_mapper->getSettings(st);
902 // Now find the application from the URL settings
903 pair<bool,const char*> application_id=m_settings.first->getString("applicationId");
904 m_app=m_conf->getApplication(application_id.second);
910 throw ConfigurationException("Unable to map request to application settings, check configuration.");
913 // Compute the full target URL
914 st->m_url = protocol + "://" + hostname;
915 if ((protocol == "http" && port != 80) || (protocol == "https" && port != 443)) {
916 ostringstream portstr;
918 st->m_url += ":" + portstr.str();
923 void* ShibTargetPriv::sendError(ShibTarget* st, const char* page, ShibMLP &mlp)
925 ShibTarget::header_t hdrs[] = {
926 ShibTarget::header_t("Expires","01-Jan-1997 12:00:00 GMT"),
927 ShibTarget::header_t("Cache-Control","private,no-store,no-cache")
930 const IPropertySet* props=m_app->getPropertySet("Errors");
932 pair<bool,const char*> p=props->getString(page);
934 ifstream infile(p.second);
935 if (!infile.fail()) {
936 const char* res = mlp.run(infile,props);
938 return st->sendPage(res, 200, "text/html", ArrayIterator<ShibTarget::header_t>(hdrs,2));
941 else if (!strcmp(page,"access"))
942 return st->sendPage("Access Denied", 403, "text/html", ArrayIterator<ShibTarget::header_t>(hdrs,2));
945 string errstr = string("sendError could not process error template (") + page + ") for application (";
946 errstr += m_app->getId();
948 st->log(ShibTarget::LogLevelError, errstr);
950 "Internal Server Error. Please contact the site administrator.", 500, "text/html", ArrayIterator<ShibTarget::header_t>(hdrs,2)
954 void ShibTargetPriv::clearHeaders(ShibTarget* st)
956 // Clear invariant stuff.
957 st->clearHeader("Shib-Origin-Site");
958 st->clearHeader("Shib-Identity-Provider");
959 st->clearHeader("Shib-Authentication-Method");
960 st->clearHeader("Shib-NameIdentifier-Format");
961 st->clearHeader("Shib-Attributes");
962 st->clearHeader("Shib-Application-ID");
964 // Clear out the list of mapped attributes
965 Iterator<IAAP*> provs=m_app->getAAPProviders();
966 while (provs.hasNext()) {
967 IAAP* aap=provs.next();
969 Iterator<const IAttributeRule*> rules=aap->getAttributeRules();
970 while (rules.hasNext()) {
971 const char* header=rules.next()->getHeader();
973 st->clearHeader(header);
978 pair<bool,void*> ShibTargetPriv::dispatch(
980 const IPropertySet* config,
982 const char* forceType
985 pair<bool,const char*> binding=forceType ? make_pair(true,forceType) : config->getString("Binding");
987 auto_ptr<IPlugIn> plugin(SAMLConfig::getConfig().getPlugMgr().newPlugin(binding.second,config->getElement()));
988 IHandler* handler=dynamic_cast<IHandler*>(plugin.get());
990 throw UnsupportedProfileException(
991 "Plugin for binding ($1) does not implement IHandler interface.",params(1,binding.second)
993 return handler->run(st,config,isHandler);
995 throw UnsupportedProfileException("Handler element is missing Binding attribute to determine what handler to run.");