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
45 using namespace shibboleth;
46 using namespace shibtarget;
47 using namespace log4cpp;
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 ShibTarget::ShibTarget(void) : m_priv(NULL)
92 m_priv = new ShibTargetPriv();
95 ShibTarget::ShibTarget(const IApplication *app) : m_priv(NULL)
97 m_priv = new ShibTargetPriv();
101 ShibTarget::~ShibTarget(void)
103 if (m_priv) delete m_priv;
106 void ShibTarget::init(
107 const char* protocol,
108 const char* hostname,
111 const char* content_type,
112 const char* remote_addr,
117 saml::NDC ndc("init");
121 throw SAMLException("Request initialization occurred twice!");
123 if (method) m_method = method;
124 if (protocol) m_protocol = protocol;
125 if (hostname) m_hostname = hostname;
126 if (uri) m_uri = uri;
127 if (content_type) m_content_type = content_type;
128 if (remote_addr) m_remote_addr = remote_addr;
130 m_priv->m_Config = &ShibTargetConfig::getConfig();
131 m_priv->get_application(this, protocol, hostname, port, uri);
135 // These functions implement the server-agnostic shibboleth engine
136 // The web server modules implement a subclass and then call into
137 // these methods once they instantiate their request object.
139 pair<bool,void*> ShibTarget::doCheckAuthN(bool handler)
142 saml::NDC ndc("doCheckAuthN");
145 const char* procState = "Request Processing Error";
146 const char* targetURL = m_url.c_str();
151 throw ConfigurationException("System uninitialized, application did not supply request information.");
153 // If not SSL, check to see if we should block or redirect it.
154 if (!strcmp("http",getProtocol())) {
155 pair<bool,const char*> redirectToSSL = m_priv->m_settings.first->getString("redirectToSSL");
156 if (redirectToSSL.first) {
157 if (!strcasecmp("GET",getRequestMethod()) || !strcasecmp("HEAD",getRequestMethod())) {
158 // Compute the new target URL
159 string redirectURL = string("https://") + getHostname();
160 if (strcmp(redirectToSSL.second,"443")) {
161 redirectURL = redirectURL + ':' + redirectToSSL.second;
163 redirectURL += getRequestURI();
164 return make_pair(true, sendRedirect(redirectURL));
167 mlp.insert("requestURL", m_url.substr(0,m_url.find('?')));
168 return make_pair(true,m_priv->sendError(this,"ssl", mlp));
173 string hURL = getHandlerURL(targetURL);
174 const char* handlerURL=hURL.c_str();
176 throw ConfigurationException("Cannot determine handler from resource URL, check configuration.");
178 // If the request URL contains the handler base URL for this application, either dispatch
179 // directly (mainly Apache 2.0) or just pass back control.
180 if (strstr(targetURL,handlerURL)) {
184 return pair<bool,void*>(true, returnOK());
187 // Three settings dictate how to proceed.
188 pair<bool,const char*> authType = m_priv->m_settings.first->getString("authType");
189 pair<bool,bool> requireSession = m_priv->m_settings.first->getBool("requireSession");
190 pair<bool,const char*> requireSessionWith = m_priv->m_settings.first->getString("requireSessionWith");
192 // If no session is required AND the AuthType (an Apache-derived concept) isn't shibboleth,
193 // then we ignore this request and consider it unprotected. Apache might lie to us if
194 // ShibBasicHijack is on, but that's up to it.
195 if ((!requireSession.first || !requireSession.second) && !requireSessionWith.first &&
196 #ifdef HAVE_STRCASECMP
197 (!authType.first || strcasecmp(authType.second,"shibboleth")))
199 (!authType.first || stricmp(authType.second,"shibboleth")))
201 return pair<bool,void*>(true,returnDecline());
203 // Fix for secadv 20050901
204 m_priv->clearHeaders(this);
206 pair<string,const char*> shib_cookie = getCookieNameProps("_shibsession_");
207 const char* session_id = getCookie(shib_cookie.first);
208 if (!session_id || !*session_id) {
209 // No session. Maybe that's acceptable?
210 if ((!requireSession.first || !requireSession.second) && !requireSessionWith.first)
211 return pair<bool,void*>(true,returnOK());
213 // No cookie, but we require a session. Initiate a new session using the indicated method.
214 procState = "Session Initiator Error";
215 const IPropertySet* initiator=NULL;
216 if (requireSessionWith.first)
217 initiator=m_priv->m_app->getSessionInitiatorById(requireSessionWith.second);
219 initiator=m_priv->m_app->getDefaultSessionInitiator();
221 // Standard handler element, so we dispatch normally.
223 return m_priv->dispatch(this,initiator,false);
225 // Legacy config support maps the Sessions element to the Shib profile.
226 auto_ptr_char binding(Constants::SHIB_SESSIONINIT_PROFILE_URI);
227 return m_priv->dispatch(this, m_priv->m_app->getPropertySet("Sessions"), false, binding.get());
231 procState = "Session Processing Error";
233 // Localized exception throw if the session isn't valid.
234 m_priv->m_conf->getListener()->sessionGet(
237 m_remote_addr.c_str(),
238 &m_priv->m_cacheEntry
241 catch (SAMLException& e) {
242 log(LogLevelError, string("session processing failed: ") + e.what());
244 // If no session is required, bail now.
245 if ((!requireSession.first || !requireSession.second) && !requireSessionWith.first)
246 // Has to be OK because DECLINED will just cause Apache
247 // to fail when it can't locate anything to process the
248 // AuthType. No session plus requireSession false means
249 // do not authenticate the user at this time.
250 return pair<bool,void*>(true, returnOK());
252 // Try and cast down.
253 SAMLException* base = &e;
254 RetryableProfileException* trycast=dynamic_cast<RetryableProfileException*>(base);
256 // Session is invalid but we can retry -- initiate a new session.
257 procState = "Session Initiator Error";
258 const IPropertySet* initiator=NULL;
259 if (requireSessionWith.first)
260 initiator=m_priv->m_app->getSessionInitiatorById(requireSessionWith.second);
262 initiator=m_priv->m_app->getDefaultSessionInitiator();
263 // Standard handler element, so we dispatch normally.
265 return m_priv->dispatch(this,initiator,false);
267 // Legacy config support maps the Sessions element to the Shib profile.
268 auto_ptr_char binding(Constants::SHIB_SESSIONINIT_PROFILE_URI);
269 return m_priv->dispatch(this, m_priv->m_app->getPropertySet("Sessions"), false, binding.get());
272 throw; // send it to the outer handler
275 // We're done. Everything is okay. Nothing to report. Nothing to do..
276 // Let the caller decide how to proceed.
277 log(LogLevelDebug, "doCheckAuthN succeeded");
278 return pair<bool,void*>(false,NULL);
280 catch (SAMLException& e) {
285 mlp.insert("errorText", "Caught an unknown exception.");
289 // If we get here then we've got an error.
290 mlp.insert("errorType", procState);
292 mlp.insert("requestURL", m_url.substr(0,m_url.find('?')));
294 return pair<bool,void*>(true,m_priv->sendError(this,"session", mlp));
297 pair<bool,void*> ShibTarget::doHandler(void)
300 saml::NDC ndc("doHandler");
303 const char* procState = "Shibboleth Handler Error";
304 const char* targetURL = m_url.c_str();
309 throw ConfigurationException("System uninitialized, application did not supply request information.");
311 string hURL = getHandlerURL(targetURL);
312 const char* handlerURL=hURL.c_str();
314 throw ConfigurationException("Cannot determine handler from resource URL, check configuration.");
316 // Make sure we only process handler requests.
317 if (!strstr(targetURL,handlerURL))
318 return pair<bool,void*>(true, returnDecline());
320 const IPropertySet* sessionProps=m_priv->m_app->getPropertySet("Sessions");
322 throw ConfigurationException("Unable to map request to application session settings, check configuration.");
324 // Process incoming request.
325 pair<bool,bool> handlerSSL=sessionProps->getBool("handlerSSL");
327 // Make sure this is SSL, if it should be
328 if ((!handlerSSL.first || handlerSSL.second) && m_protocol != "https")
329 throw FatalProfileException("Blocked non-SSL access to Shibboleth handler.");
331 // We dispatch based on our path info. We know the request URL begins with or equals the handler URL,
332 // so the path info is the next character (or null).
333 const IPropertySet* handler=m_priv->m_app->getHandlerConfig(targetURL + strlen(handlerURL));
335 if (saml::XML::isElementNamed(handler->getElement(),shibtarget::XML::SAML2META_NS,SHIBT_L(AssertionConsumerService))) {
336 procState = "Session Creation Error";
337 return m_priv->dispatch(this,handler);
339 else if (saml::XML::isElementNamed(handler->getElement(),shibtarget::XML::SHIBTARGET_NS,SHIBT_L(SessionInitiator))) {
340 procState = "Session Initiator Error";
341 return m_priv->dispatch(this,handler);
343 else if (saml::XML::isElementNamed(handler->getElement(),shibtarget::XML::SAML2META_NS,SHIBT_L(SingleLogoutService))) {
344 procState = "Session Termination Error";
345 return m_priv->dispatch(this,handler);
347 else if (saml::XML::isElementNamed(handler->getElement(),shibtarget::XML::SHIBTARGET_NS,SHIBT_L(DiagnosticService))) {
348 procState = "Diagnostics Error";
349 return m_priv->dispatch(this,handler);
352 procState = "Extension Service Error";
353 return m_priv->dispatch(this,handler);
357 if (strlen(targetURL)>strlen(handlerURL) && targetURL[strlen(handlerURL)]!='?')
358 throw SAMLException("Shibboleth handler invoked at an unconfigured location.");
360 // This is a legacy direct execution of the handler (the old shireURL).
361 // If this is a GET, we see if it's a lazy session request, otherwise
362 // assume it's a SAML 1.x POST profile response and process it.
363 if (!strcasecmp(m_method.c_str(), "GET")) {
364 procState = "Session Initiator Error";
365 auto_ptr_char binding(Constants::SHIB_SESSIONINIT_PROFILE_URI);
366 return m_priv->dispatch(this, sessionProps, true, binding.get());
369 procState = "Session Creation Error";
370 auto_ptr_char binding(SAMLBrowserProfile::BROWSER_POST);
371 return m_priv->dispatch(this, sessionProps, true, binding.get());
373 catch (MetadataException& e) {
375 // See if a metadata error page is installed.
376 const IPropertySet* props=m_priv->m_app->getPropertySet("Errors");
378 pair<bool,const char*> p=props->getString("metadata");
380 mlp.insert("errorType", procState);
382 mlp.insert("requestURL", targetURL);
383 return make_pair(true,m_priv->sendError(this,"metadata", mlp));
387 catch (SAMLException& e) {
392 mlp.insert("errorText", "Caught an unknown exception.");
396 // If we get here then we've got an error.
397 mlp.insert("errorType", procState);
400 mlp.insert("requestURL", m_url.substr(0,m_url.find('?')));
402 return make_pair(true,m_priv->sendError(this,"session", mlp));
405 pair<bool,void*> ShibTarget::doCheckAuthZ(void)
408 saml::NDC ndc("doCheckAuthZ");
412 const char* procState = "Authorization Processing Error";
413 const char* targetURL = m_url.c_str();
417 throw ConfigurationException("System uninitialized, application did not supply request information.");
419 // Three settings dictate how to proceed.
420 pair<bool,const char*> authType = m_priv->m_settings.first->getString("authType");
421 pair<bool,bool> requireSession = m_priv->m_settings.first->getBool("requireSession");
422 pair<bool,const char*> requireSessionWith = m_priv->m_settings.first->getString("requireSessionWith");
424 // If no session is required AND the AuthType (an Apache-derived concept) isn't shibboleth,
425 // then we ignore this request and consider it unprotected. Apache might lie to us if
426 // ShibBasicHijack is on, but that's up to it.
427 if ((!requireSession.first || !requireSession.second) && !requireSessionWith.first &&
428 #ifdef HAVE_STRCASECMP
429 (!authType.first || strcasecmp(authType.second,"shibboleth")))
431 (!authType.first || stricmp(authType.second,"shibboleth")))
433 return pair<bool,void*>(true,returnDecline());
435 // Do we have an access control plugin?
436 if (m_priv->m_settings.second) {
438 if (!m_priv->m_cacheEntry) {
439 // No data yet, so we may need to try and get the session.
440 pair<string,const char*> shib_cookie=getCookieNameProps("_shibsession_");
441 const char *session_id = getCookie(shib_cookie.first);
443 if (session_id && *session_id) {
444 m_priv->m_conf->getListener()->sessionGet(
447 m_remote_addr.c_str(),
448 &m_priv->m_cacheEntry
452 catch (SAMLException&) {
453 log(LogLevelError, "doCheckAuthZ: unable to obtain session information to pass to access control provider");
457 Locker acllock(m_priv->m_settings.second);
458 if (m_priv->m_settings.second->authorized(this,m_priv->m_cacheEntry)) {
459 // Let the caller decide how to proceed.
460 log(LogLevelDebug, "doCheckAuthZ: access control provider granted access");
461 return pair<bool,void*>(false,NULL);
464 log(LogLevelWarn, "doCheckAuthZ: access control provider denied access");
466 mlp.insert("requestURL", targetURL);
467 return make_pair(true,m_priv->sendError(this, "access", mlp));
471 return make_pair(true,returnDecline());
473 catch (SAMLException& e) {
478 mlp.insert("errorText", "Caught an unknown exception.");
482 // If we get here then we've got an error.
483 mlp.insert("errorType", procState);
486 mlp.insert("requestURL", m_url.substr(0,m_url.find('?')));
488 return make_pair(true,m_priv->sendError(this, "access", mlp));
491 pair<bool,void*> ShibTarget::doExportAssertions(bool requireSession)
494 saml::NDC ndc("doExportAssertions");
498 const char* procState = "Attribute Processing Error";
499 const char* targetURL = m_url.c_str();
503 throw ConfigurationException("System uninitialized, application did not supply request information.");
505 if (!m_priv->m_cacheEntry) {
506 // No data yet, so we need to get the session. This can only happen
507 // if the call to doCheckAuthn doesn't happen in the same object lifetime.
508 pair<string,const char*> shib_cookie=getCookieNameProps("_shibsession_");
509 const char *session_id = getCookie(shib_cookie.first);
511 if (session_id && *session_id) {
512 m_priv->m_conf->getListener()->sessionGet(
515 m_remote_addr.c_str(),
516 &m_priv->m_cacheEntry
520 catch (SAMLException&) {
521 log(LogLevelError, "unable to obtain session information to export into request headers");
522 // If we have to have a session, then this is a fatal error.
529 if (!m_priv->m_cacheEntry) {
531 throw InvalidSessionException("Unable to obtain session information for request.");
533 return pair<bool,void*>(false,NULL); // just bail silently
536 ISessionCacheEntry::CachedResponse cr=m_priv->m_cacheEntry->getResponse();
538 // Maybe export the response.
539 pair<bool,bool> exp=m_priv->m_settings.first->getBool("exportAssertion");
540 if (exp.first && exp.second && cr.unfiltered) {
542 os << *cr.unfiltered;
544 XMLByte* serialized = Base64::encode(reinterpret_cast<XMLByte*>((char*)os.str().c_str()), os.str().length(), &outlen);
546 for (pos=serialized, pos2=serialized; *pos2; pos2++)
550 setHeader("Shib-Attributes", reinterpret_cast<char*>(serialized));
551 XMLString::release(&serialized);
554 // Export the SAML AuthnMethod and the origin site name, and possibly the NameIdentifier.
555 setHeader("Shib-Origin-Site", m_priv->m_cacheEntry->getProviderId());
556 setHeader("Shib-Identity-Provider", m_priv->m_cacheEntry->getProviderId());
557 auto_ptr_char am(m_priv->m_cacheEntry->getAuthnStatement()->getAuthMethod());
558 setHeader("Shib-Authentication-Method", am.get());
560 // Get the AAP providers, which contain the attribute policy info.
561 Iterator<IAAP*> provs=m_priv->m_app->getAAPProviders();
564 while (provs.hasNext()) {
565 IAAP* aap=provs.next();
567 const XMLCh* format = m_priv->m_cacheEntry->getAuthnStatement()->getSubject()->getNameIdentifier()->getFormat();
568 const IAttributeRule* rule=aap->lookup(format ? format : SAMLNameIdentifier::UNSPECIFIED);
569 if (rule && rule->getHeader()) {
570 auto_ptr_char form(format ? format : SAMLNameIdentifier::UNSPECIFIED);
571 auto_ptr_char nameid(m_priv->m_cacheEntry->getAuthnStatement()->getSubject()->getNameIdentifier()->getName());
572 setHeader("Shib-NameIdentifier-Format", form.get());
573 if (!strcmp(rule->getHeader(),"REMOTE_USER"))
574 setRemoteUser(nameid.get());
576 setHeader(rule->getHeader(), nameid.get());
580 setHeader("Shib-Application-ID", m_priv->m_app->getId());
582 string strUnsetValue;
583 const IPropertySet* localProps=m_priv->m_Config->getINI()->getPropertySet("Local");
585 pair<bool,const char*> unsetValue=localProps->getString("unsetHeaderValue");
586 if (unsetValue.first)
587 strUnsetValue = unsetValue.second;
590 // Export the attributes.
591 Iterator<SAMLAssertion*> a_iter(cr.filtered ? cr.filtered->getAssertions() : EMPTY(SAMLAssertion*));
592 while (a_iter.hasNext()) {
593 SAMLAssertion* assert=a_iter.next();
594 Iterator<SAMLStatement*> statements=assert->getStatements();
595 while (statements.hasNext()) {
596 SAMLAttributeStatement* astate=dynamic_cast<SAMLAttributeStatement*>(statements.next());
599 Iterator<SAMLAttribute*> attrs=astate->getAttributes();
600 while (attrs.hasNext()) {
601 SAMLAttribute* attr=attrs.next();
603 // Are we supposed to export it?
605 while (provs.hasNext()) {
606 IAAP* aap=provs.next();
608 const IAttributeRule* rule=aap->lookup(attr->getName(),attr->getNamespace());
609 if (!rule || !rule->getHeader())
612 Iterator<string> vals=attr->getSingleByteValues();
613 if (!strcmp(rule->getHeader(),"REMOTE_USER") && vals.hasNext())
614 setRemoteUser(vals.next());
617 string header = getHeader(rule->getHeader());
618 if (header == strUnsetValue)
622 for (; vals.hasNext(); it++) {
623 string value = vals.next();
624 for (string::size_type pos = value.find_first_of(";", string::size_type(0));
626 pos = value.find_first_of(";", pos)) {
627 value.insert(pos, "\\");
634 setHeader(rule->getHeader(), header);
641 return pair<bool,void*>(false,NULL);
643 catch (SAMLException& e) {
648 mlp.insert("errorText", "Caught an unknown exception.");
652 // If we get here then we've got an error.
653 mlp.insert("errorType", procState);
656 mlp.insert("requestURL", m_url.substr(0,m_url.find('?')));
658 return make_pair(true,m_priv->sendError(this, "rm", mlp));
661 const char* ShibTarget::getCookie(const string& name) const
663 if (m_priv->m_cookieMap.empty()) {
664 string cookies=getCookies();
666 string::size_type pos=0,cname,namelen,val,vallen;
667 while (pos !=string::npos && pos < cookies.length()) {
668 while (isspace(cookies[pos])) pos++;
670 pos=cookies.find_first_of("=",pos);
671 if (pos == string::npos)
675 if (pos==cookies.length())
678 pos=cookies.find_first_of(";",pos);
679 if (pos != string::npos) {
682 m_priv->m_cookieMap.insert(make_pair(cookies.substr(cname,namelen),cookies.substr(val,vallen)));
685 m_priv->m_cookieMap.insert(make_pair(cookies.substr(cname,namelen),cookies.substr(val)));
688 map<string,string>::const_iterator lookup=m_priv->m_cookieMap.find(name);
689 return (lookup==m_priv->m_cookieMap.end()) ? NULL : lookup->second.c_str();
692 pair<string,const char*> ShibTarget::getCookieNameProps(const char* prefix) const
694 static const char* defProps="; path=/";
696 const IPropertySet* props=m_priv->m_app ? m_priv->m_app->getPropertySet("Sessions") : NULL;
698 pair<bool,const char*> p=props->getString("cookieProps");
701 pair<bool,const char*> p2=props->getString("cookieName");
703 return make_pair(string(prefix) + p2.second,p.second);
704 return make_pair(string(prefix) + m_priv->m_app->getHash(),p.second);
707 // Shouldn't happen, but just in case..
708 return pair<string,const char*>(prefix,defProps);
711 string ShibTarget::getHandlerURL(const char* resource) const
713 if (!m_priv->m_handlerURL.empty() && resource && !strcmp(getRequestURL(),resource))
714 return m_priv->m_handlerURL;
717 throw ConfigurationException("Internal error in ShibTargetPriv::getHandlerURL, missing application pointer.");
720 const char* handler=NULL;
721 const IPropertySet* props=m_priv->m_app->getPropertySet("Sessions");
723 pair<bool,bool> p=props->getBool("handlerSSL");
726 pair<bool,const char*> p2=props->getString("handlerURL");
731 // Should never happen...
732 if (!handler || (*handler!='/' && strncmp(handler,"http:",5) && strncmp(handler,"https:",6)))
733 throw ConfigurationException(
734 "Invalid handlerURL property ($1) in Application ($2)",
735 params(2, handler ? handler : "null", m_priv->m_app->getId())
738 // The "handlerURL" property can be in one of three formats:
740 // 1) a full URI: http://host/foo/bar
741 // 2) a hostless URI: http:///foo/bar
742 // 3) a relative path: /foo/bar
744 // # Protocol Host Path
745 // 1 handler handler handler
746 // 2 handler resource handler
747 // 3 resource resource handler
749 // note: if ssl_only is true, make sure the protocol is https
751 const char* path = NULL;
753 // Decide whether to use the handler or the resource for the "protocol"
755 if (*handler != '/') {
763 // break apart the "protocol" string into protocol, host, and "the rest"
764 const char* colon=strchr(prot,':');
766 const char* slash=strchr(colon,'/');
770 // Compute the actual protocol and store in member.
772 m_priv->m_handlerURL.assign("https://");
774 m_priv->m_handlerURL.assign(prot, colon-prot);
776 // create the "host" from either the colon/slash or from the target string
777 // If prot == handler then we're in either #1 or #2, else #3.
778 // If slash == colon then we're in #2.
779 if (prot != handler || slash == colon) {
780 colon = strchr(resource, ':');
781 colon += 3; // Get past the ://
782 slash = strchr(colon, '/');
784 string host(colon, slash-colon);
786 // Build the handler URL
787 m_priv->m_handlerURL+=host + path;
788 return m_priv->m_handlerURL;
791 void ShibTarget::log(ShibLogLevel level, const string& msg)
793 Category::getInstance("shibtarget.ShibTarget").log(
794 (level == LogLevelDebug ? Priority::DEBUG :
795 (level == LogLevelInfo ? Priority::INFO :
796 (level == LogLevelWarn ? Priority::WARN : Priority::ERROR))),
801 const IApplication* ShibTarget::getApplication() const
803 return m_priv->m_app;
806 const IConfig* ShibTarget::getConfig() const
808 return m_priv->m_conf;
811 void* ShibTarget::returnDecline(void)
816 void* ShibTarget::returnOK(void)
822 /*************************************************************************
823 * Shib Target Private implementation
826 ShibTargetPriv::ShibTargetPriv() : m_app(NULL), m_cacheEntry(NULL), m_Config(NULL), m_conf(NULL), m_mapper(NULL) {}
828 ShibTargetPriv::~ShibTargetPriv()
831 m_cacheEntry->unlock();
849 void ShibTargetPriv::get_application(ShibTarget* st, const string& protocol, const string& hostname, int port, const string& uri)
854 // XXX: Do we need to keep conf and mapper locked while we hold m_app?
855 // TODO: No, should be able to hold the conf but release the mapper.
857 // We lock the configuration system for the duration.
858 m_conf=m_Config->getINI();
861 // Map request to application and content settings.
862 m_mapper=m_conf->getRequestMapper();
865 // Obtain the application settings from the parsed URL
866 m_settings = m_mapper->getSettings(st);
868 // Now find the application from the URL settings
869 pair<bool,const char*> application_id=m_settings.first->getString("applicationId");
870 m_app=m_conf->getApplication(application_id.second);
876 throw ConfigurationException("Unable to map request to application settings, check configuration.");
879 // Compute the full target URL
880 st->m_url = protocol + "://" + hostname;
881 if ((protocol == "http" && port != 80) || (protocol == "https" && port != 443)) {
882 ostringstream portstr;
884 st->m_url += ":" + portstr.str();
889 void* ShibTargetPriv::sendError(ShibTarget* st, const char* page, ShibMLP &mlp)
891 ShibTarget::header_t hdrs[] = {
892 ShibTarget::header_t("Expires","01-Jan-1997 12:00:00 GMT"),
893 ShibTarget::header_t("Cache-Control","private,no-store,no-cache")
896 const IPropertySet* props=m_app->getPropertySet("Errors");
898 pair<bool,const char*> p=props->getString(page);
900 ifstream infile(p.second);
901 if (!infile.fail()) {
902 const char* res = mlp.run(infile,props);
904 return st->sendPage(res, 200, "text/html", ArrayIterator<ShibTarget::header_t>(hdrs,2));
907 else if (!strcmp(page,"access"))
908 return st->sendPage("Access Denied", 403, "text/html", ArrayIterator<ShibTarget::header_t>(hdrs,2));
911 string errstr = string("sendError could not process error template (") + page + ") for application (";
912 errstr += m_app->getId();
914 st->log(ShibTarget::LogLevelError, errstr);
916 "Internal Server Error. Please contact the site administrator.", 500, "text/html", ArrayIterator<ShibTarget::header_t>(hdrs,2)
920 void ShibTargetPriv::clearHeaders(ShibTarget* st)
922 // Clear invariant stuff.
923 st->clearHeader("Shib-Origin-Site");
924 st->clearHeader("Shib-Identity-Provider");
925 st->clearHeader("Shib-Authentication-Method");
926 st->clearHeader("Shib-NameIdentifier-Format");
927 st->clearHeader("Shib-Attributes");
928 st->clearHeader("Shib-Application-ID");
930 // Clear out the list of mapped attributes
931 Iterator<IAAP*> provs=m_app->getAAPProviders();
932 while (provs.hasNext()) {
933 IAAP* aap=provs.next();
935 Iterator<const IAttributeRule*> rules=aap->getAttributeRules();
936 while (rules.hasNext()) {
937 const char* header=rules.next()->getHeader();
939 st->clearHeader(header);
944 pair<bool,void*> ShibTargetPriv::dispatch(
946 const IPropertySet* config,
948 const char* forceType
951 pair<bool,const char*> binding=forceType ? make_pair(true,forceType) : config->getString("Binding");
953 auto_ptr<IPlugIn> plugin(SAMLConfig::getConfig().getPlugMgr().newPlugin(binding.second,config->getElement()));
954 IHandler* handler=dynamic_cast<IHandler*>(plugin.get());
956 throw UnsupportedProfileException(
957 "Plugin for binding ($1) does not implement IHandler interface.",params(1,binding.second)
959 return handler->run(st,config,isHandler);
961 throw UnsupportedProfileException("Handler element is missing Binding attribute to determine what handler to run.");