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 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 != '%') {
153 m_uri += _x2c(++uri);
160 m_priv->m_Config = &ShibTargetConfig::getConfig();
161 m_priv->get_application(this, protocol, hostname, port, m_uri);
165 // These functions implement the server-agnostic shibboleth engine
166 // The web server modules implement a subclass and then call into
167 // these methods once they instantiate their request object.
169 pair<bool,void*> ShibTarget::doCheckAuthN(bool handler)
172 saml::NDC ndc("doCheckAuthN");
175 const char* procState = "Request Processing Error";
176 const char* targetURL = m_url.c_str();
181 throw ConfigurationException("System uninitialized, application did not supply request information.");
183 // If not SSL, check to see if we should block or redirect it.
184 if (!strcmp("http",getProtocol())) {
185 pair<bool,const char*> redirectToSSL = m_priv->m_settings.first->getString("redirectToSSL");
186 if (redirectToSSL.first) {
187 if (!strcasecmp("GET",getRequestMethod()) || !strcasecmp("HEAD",getRequestMethod())) {
188 // Compute the new target URL
189 string redirectURL = string("https://") + getHostname();
190 if (strcmp(redirectToSSL.second,"443")) {
191 redirectURL = redirectURL + ':' + redirectToSSL.second;
193 redirectURL += getRequestURI();
194 return make_pair(true, sendRedirect(redirectURL));
197 mlp.insert("requestURL", m_url.substr(0,m_url.find('?')));
198 return make_pair(true,m_priv->sendError(this,"ssl", mlp));
203 string hURL = getHandlerURL(targetURL);
204 const char* handlerURL=hURL.c_str();
206 throw ConfigurationException("Cannot determine handler from resource URL, check configuration.");
208 // If the request URL contains the handler base URL for this application, either dispatch
209 // directly (mainly Apache 2.0) or just pass back control.
210 if (strstr(targetURL,handlerURL)) {
214 return pair<bool,void*>(true, returnOK());
217 // Three settings dictate how to proceed.
218 pair<bool,const char*> authType = m_priv->m_settings.first->getString("authType");
219 pair<bool,bool> requireSession = m_priv->m_settings.first->getBool("requireSession");
220 pair<bool,const char*> requireSessionWith = m_priv->m_settings.first->getString("requireSessionWith");
222 // If no session is required AND the AuthType (an Apache-derived concept) isn't shibboleth,
223 // then we ignore this request and consider it unprotected. Apache might lie to us if
224 // ShibBasicHijack is on, but that's up to it.
225 if ((!requireSession.first || !requireSession.second) && !requireSessionWith.first &&
226 #ifdef HAVE_STRCASECMP
227 (!authType.first || strcasecmp(authType.second,"shibboleth")))
229 (!authType.first || stricmp(authType.second,"shibboleth")))
231 return pair<bool,void*>(true,returnDecline());
233 // Fix for secadv 20050901
234 m_priv->clearHeaders(this);
236 pair<string,const char*> shib_cookie = getCookieNameProps("_shibsession_");
237 const char* session_id = getCookie(shib_cookie.first);
238 if (!session_id || !*session_id) {
239 // No session. Maybe that's acceptable?
240 if ((!requireSession.first || !requireSession.second) && !requireSessionWith.first)
241 return pair<bool,void*>(true,returnOK());
243 // No cookie, but we require a session. Initiate a new session using the indicated method.
244 procState = "Session Initiator Error";
245 const IPropertySet* initiator=NULL;
246 if (requireSessionWith.first)
247 initiator=m_priv->m_app->getSessionInitiatorById(requireSessionWith.second);
249 initiator=m_priv->m_app->getDefaultSessionInitiator();
251 // Standard handler element, so we dispatch normally.
253 return m_priv->dispatch(this,initiator,false);
255 // Legacy config support maps the Sessions element to the Shib profile.
256 auto_ptr_char binding(Constants::SHIB_SESSIONINIT_PROFILE_URI);
257 return m_priv->dispatch(this, m_priv->m_app->getPropertySet("Sessions"), false, binding.get());
261 procState = "Session Processing Error";
263 // Localized exception throw if the session isn't valid.
264 m_priv->m_conf->getListener()->sessionGet(
267 m_remote_addr.c_str(),
268 &m_priv->m_cacheEntry
271 catch (SAMLException& e) {
272 log(LogLevelError, string("session processing failed: ") + e.what());
274 // If no session is required, bail now.
275 if ((!requireSession.first || !requireSession.second) && !requireSessionWith.first)
276 // Has to be OK because DECLINED will just cause Apache
277 // to fail when it can't locate anything to process the
278 // AuthType. No session plus requireSession false means
279 // do not authenticate the user at this time.
280 return pair<bool,void*>(true, returnOK());
282 // Try and cast down.
283 SAMLException* base = &e;
284 RetryableProfileException* trycast=dynamic_cast<RetryableProfileException*>(base);
286 // Session is invalid but we can retry -- initiate a new session.
287 procState = "Session Initiator Error";
288 const IPropertySet* initiator=NULL;
289 if (requireSessionWith.first)
290 initiator=m_priv->m_app->getSessionInitiatorById(requireSessionWith.second);
292 initiator=m_priv->m_app->getDefaultSessionInitiator();
293 // Standard handler element, so we dispatch normally.
295 return m_priv->dispatch(this,initiator,false);
297 // Legacy config support maps the Sessions element to the Shib profile.
298 auto_ptr_char binding(Constants::SHIB_SESSIONINIT_PROFILE_URI);
299 return m_priv->dispatch(this, m_priv->m_app->getPropertySet("Sessions"), false, binding.get());
302 throw; // send it to the outer handler
305 // We're done. Everything is okay. Nothing to report. Nothing to do..
306 // Let the caller decide how to proceed.
307 log(LogLevelDebug, "doCheckAuthN succeeded");
308 return pair<bool,void*>(false,NULL);
310 catch (SAMLException& e) {
315 mlp.insert("errorText", "Caught an unknown exception.");
319 // If we get here then we've got an error.
320 mlp.insert("errorType", procState);
322 mlp.insert("requestURL", m_url.substr(0,m_url.find('?')));
324 return pair<bool,void*>(true,m_priv->sendError(this,"session", mlp));
327 pair<bool,void*> ShibTarget::doHandler(void)
330 saml::NDC ndc("doHandler");
333 const char* procState = "Shibboleth Handler Error";
334 const char* targetURL = m_url.c_str();
339 throw ConfigurationException("System uninitialized, application did not supply request information.");
341 string hURL = getHandlerURL(targetURL);
342 const char* handlerURL=hURL.c_str();
344 throw ConfigurationException("Cannot determine handler from resource URL, check configuration.");
346 // Make sure we only process handler requests.
347 if (!strstr(targetURL,handlerURL))
348 return pair<bool,void*>(true, returnDecline());
350 const IPropertySet* sessionProps=m_priv->m_app->getPropertySet("Sessions");
352 throw ConfigurationException("Unable to map request to application session settings, check configuration.");
354 // Process incoming request.
355 pair<bool,bool> handlerSSL=sessionProps->getBool("handlerSSL");
357 // Make sure this is SSL, if it should be
358 if ((!handlerSSL.first || handlerSSL.second) && m_protocol != "https")
359 throw FatalProfileException("Blocked non-SSL access to Shibboleth handler.");
361 // We dispatch based on our path info. We know the request URL begins with or equals the handler URL,
362 // so the path info is the next character (or null).
363 const IPropertySet* handler=m_priv->m_app->getHandlerConfig(targetURL + strlen(handlerURL));
365 if (saml::XML::isElementNamed(handler->getElement(),shibtarget::XML::SAML2META_NS,SHIBT_L(AssertionConsumerService))) {
366 procState = "Session Creation Error";
367 return m_priv->dispatch(this,handler);
369 else if (saml::XML::isElementNamed(handler->getElement(),shibtarget::XML::SHIBTARGET_NS,SHIBT_L(SessionInitiator))) {
370 procState = "Session Initiator Error";
371 return m_priv->dispatch(this,handler);
373 else if (saml::XML::isElementNamed(handler->getElement(),shibtarget::XML::SAML2META_NS,SHIBT_L(SingleLogoutService))) {
374 procState = "Session Termination Error";
375 return m_priv->dispatch(this,handler);
377 else if (saml::XML::isElementNamed(handler->getElement(),shibtarget::XML::SHIBTARGET_NS,SHIBT_L(DiagnosticService))) {
378 procState = "Diagnostics Error";
379 return m_priv->dispatch(this,handler);
382 procState = "Extension Service Error";
383 return m_priv->dispatch(this,handler);
387 if (strlen(targetURL)>strlen(handlerURL) && targetURL[strlen(handlerURL)]!='?')
388 throw SAMLException("Shibboleth handler invoked at an unconfigured location.");
390 // This is a legacy direct execution of the handler (the old shireURL).
391 // If this is a GET, we see if it's a lazy session request, otherwise
392 // assume it's a SAML 1.x POST profile response and process it.
393 if (!strcasecmp(m_method.c_str(), "GET")) {
394 procState = "Session Initiator Error";
395 auto_ptr_char binding(Constants::SHIB_SESSIONINIT_PROFILE_URI);
396 return m_priv->dispatch(this, sessionProps, true, binding.get());
399 procState = "Session Creation Error";
400 auto_ptr_char binding(SAMLBrowserProfile::BROWSER_POST);
401 return m_priv->dispatch(this, sessionProps, true, binding.get());
403 catch (MetadataException& e) {
405 // See if a metadata error page is installed.
406 const IPropertySet* props=m_priv->m_app->getPropertySet("Errors");
408 pair<bool,const char*> p=props->getString("metadata");
410 mlp.insert("errorType", procState);
412 mlp.insert("requestURL", targetURL);
413 return make_pair(true,m_priv->sendError(this,"metadata", mlp));
417 catch (SAMLException& e) {
422 mlp.insert("errorText", "Caught an unknown exception.");
426 // If we get here then we've got an error.
427 mlp.insert("errorType", procState);
430 mlp.insert("requestURL", m_url.substr(0,m_url.find('?')));
432 return make_pair(true,m_priv->sendError(this,"session", mlp));
435 pair<bool,void*> ShibTarget::doCheckAuthZ(void)
438 saml::NDC ndc("doCheckAuthZ");
442 const char* procState = "Authorization Processing Error";
443 const char* targetURL = m_url.c_str();
447 throw ConfigurationException("System uninitialized, application did not supply request information.");
449 // Three settings dictate how to proceed.
450 pair<bool,const char*> authType = m_priv->m_settings.first->getString("authType");
451 pair<bool,bool> requireSession = m_priv->m_settings.first->getBool("requireSession");
452 pair<bool,const char*> requireSessionWith = m_priv->m_settings.first->getString("requireSessionWith");
454 // If no session is required AND the AuthType (an Apache-derived concept) isn't shibboleth,
455 // then we ignore this request and consider it unprotected. Apache might lie to us if
456 // ShibBasicHijack is on, but that's up to it.
457 if ((!requireSession.first || !requireSession.second) && !requireSessionWith.first &&
458 #ifdef HAVE_STRCASECMP
459 (!authType.first || strcasecmp(authType.second,"shibboleth")))
461 (!authType.first || stricmp(authType.second,"shibboleth")))
463 return pair<bool,void*>(true,returnDecline());
465 // Do we have an access control plugin?
466 if (m_priv->m_settings.second) {
468 if (!m_priv->m_cacheEntry) {
469 // No data yet, so we may need to try and get the session.
470 pair<string,const char*> shib_cookie=getCookieNameProps("_shibsession_");
471 const char *session_id = getCookie(shib_cookie.first);
473 if (session_id && *session_id) {
474 m_priv->m_conf->getListener()->sessionGet(
477 m_remote_addr.c_str(),
478 &m_priv->m_cacheEntry
482 catch (SAMLException&) {
483 log(LogLevelError, "doCheckAuthZ: unable to obtain session information to pass to access control provider");
487 Locker acllock(m_priv->m_settings.second);
488 if (m_priv->m_settings.second->authorized(this,m_priv->m_cacheEntry)) {
489 // Let the caller decide how to proceed.
490 log(LogLevelDebug, "doCheckAuthZ: access control provider granted access");
491 return pair<bool,void*>(false,NULL);
494 log(LogLevelWarn, "doCheckAuthZ: access control provider denied access");
496 mlp.insert("requestURL", targetURL);
497 return make_pair(true,m_priv->sendError(this, "access", mlp));
501 return make_pair(true,returnDecline());
503 catch (SAMLException& e) {
508 mlp.insert("errorText", "Caught an unknown exception.");
512 // If we get here then we've got an error.
513 mlp.insert("errorType", procState);
516 mlp.insert("requestURL", m_url.substr(0,m_url.find('?')));
518 return make_pair(true,m_priv->sendError(this, "access", mlp));
521 pair<bool,void*> ShibTarget::doExportAssertions(bool requireSession)
524 saml::NDC ndc("doExportAssertions");
528 const char* procState = "Attribute Processing Error";
529 const char* targetURL = m_url.c_str();
533 throw ConfigurationException("System uninitialized, application did not supply request information.");
535 if (!m_priv->m_cacheEntry) {
536 // No data yet, so we need to get the session. This can only happen
537 // if the call to doCheckAuthn doesn't happen in the same object lifetime.
538 pair<string,const char*> shib_cookie=getCookieNameProps("_shibsession_");
539 const char *session_id = getCookie(shib_cookie.first);
541 if (session_id && *session_id) {
542 m_priv->m_conf->getListener()->sessionGet(
545 m_remote_addr.c_str(),
546 &m_priv->m_cacheEntry
550 catch (SAMLException&) {
551 log(LogLevelError, "unable to obtain session information to export into request headers");
552 // If we have to have a session, then this is a fatal error.
559 if (!m_priv->m_cacheEntry) {
561 throw InvalidSessionException("Unable to obtain session information for request.");
563 return pair<bool,void*>(false,NULL); // just bail silently
566 ISessionCacheEntry::CachedResponse cr=m_priv->m_cacheEntry->getResponse();
568 // Maybe export the response.
569 pair<bool,bool> exp=m_priv->m_settings.first->getBool("exportAssertion");
570 if (exp.first && exp.second && cr.unfiltered) {
572 os << *cr.unfiltered;
574 XMLByte* serialized = Base64::encode(reinterpret_cast<XMLByte*>((char*)os.str().c_str()), os.str().length(), &outlen);
576 for (pos=serialized, pos2=serialized; *pos2; pos2++)
580 setHeader("Shib-Attributes", reinterpret_cast<char*>(serialized));
581 XMLString::release(&serialized);
584 // Export the SAML AuthnMethod and the origin site name, and possibly the NameIdentifier.
585 setHeader("Shib-Origin-Site", m_priv->m_cacheEntry->getProviderId());
586 setHeader("Shib-Identity-Provider", m_priv->m_cacheEntry->getProviderId());
587 auto_ptr_char am(m_priv->m_cacheEntry->getAuthnStatement()->getAuthMethod());
588 setHeader("Shib-Authentication-Method", am.get());
590 // Get the AAP providers, which contain the attribute policy info.
591 Iterator<IAAP*> provs=m_priv->m_app->getAAPProviders();
594 while (provs.hasNext()) {
595 IAAP* aap=provs.next();
597 const XMLCh* format = m_priv->m_cacheEntry->getAuthnStatement()->getSubject()->getNameIdentifier()->getFormat();
598 const IAttributeRule* rule=aap->lookup(format ? format : SAMLNameIdentifier::UNSPECIFIED);
599 if (rule && rule->getHeader()) {
600 auto_ptr_char form(format ? format : SAMLNameIdentifier::UNSPECIFIED);
601 auto_ptr_char nameid(m_priv->m_cacheEntry->getAuthnStatement()->getSubject()->getNameIdentifier()->getName());
602 setHeader("Shib-NameIdentifier-Format", form.get());
603 if (!strcmp(rule->getHeader(),"REMOTE_USER"))
604 setRemoteUser(nameid.get());
606 setHeader(rule->getHeader(), nameid.get());
610 setHeader("Shib-Application-ID", m_priv->m_app->getId());
612 string strUnsetValue;
613 const IPropertySet* localProps=m_priv->m_Config->getINI()->getPropertySet("Local");
615 pair<bool,const char*> unsetValue=localProps->getString("unsetHeaderValue");
616 if (unsetValue.first)
617 strUnsetValue = unsetValue.second;
620 // Export the attributes.
621 Iterator<SAMLAssertion*> a_iter(cr.filtered ? cr.filtered->getAssertions() : EMPTY(SAMLAssertion*));
622 while (a_iter.hasNext()) {
623 SAMLAssertion* assert=a_iter.next();
624 Iterator<SAMLStatement*> statements=assert->getStatements();
625 while (statements.hasNext()) {
626 SAMLAttributeStatement* astate=dynamic_cast<SAMLAttributeStatement*>(statements.next());
629 Iterator<SAMLAttribute*> attrs=astate->getAttributes();
630 while (attrs.hasNext()) {
631 SAMLAttribute* attr=attrs.next();
633 // Are we supposed to export it?
635 while (provs.hasNext()) {
636 IAAP* aap=provs.next();
638 const IAttributeRule* rule=aap->lookup(attr->getName(),attr->getNamespace());
639 if (!rule || !rule->getHeader())
642 Iterator<string> vals=attr->getSingleByteValues();
643 if (!strcmp(rule->getHeader(),"REMOTE_USER") && vals.hasNext())
644 setRemoteUser(vals.next());
647 string header = getHeader(rule->getHeader());
648 if (header == strUnsetValue)
652 for (; vals.hasNext(); it++) {
653 string value = vals.next();
654 for (string::size_type pos = value.find_first_of(";", string::size_type(0));
656 pos = value.find_first_of(";", pos)) {
657 value.insert(pos, "\\");
664 setHeader(rule->getHeader(), header);
671 return pair<bool,void*>(false,NULL);
673 catch (SAMLException& e) {
678 mlp.insert("errorText", "Caught an unknown exception.");
682 // If we get here then we've got an error.
683 mlp.insert("errorType", procState);
686 mlp.insert("requestURL", m_url.substr(0,m_url.find('?')));
688 return make_pair(true,m_priv->sendError(this, "rm", mlp));
691 const char* ShibTarget::getCookie(const string& name) const
693 if (m_priv->m_cookieMap.empty()) {
694 string cookies=getCookies();
696 string::size_type pos=0,cname,namelen,val,vallen;
697 while (pos !=string::npos && pos < cookies.length()) {
698 while (isspace(cookies[pos])) pos++;
700 pos=cookies.find_first_of("=",pos);
701 if (pos == string::npos)
705 if (pos==cookies.length())
708 pos=cookies.find_first_of(";",pos);
709 if (pos != string::npos) {
712 m_priv->m_cookieMap.insert(make_pair(cookies.substr(cname,namelen),cookies.substr(val,vallen)));
715 m_priv->m_cookieMap.insert(make_pair(cookies.substr(cname,namelen),cookies.substr(val)));
718 map<string,string>::const_iterator lookup=m_priv->m_cookieMap.find(name);
719 return (lookup==m_priv->m_cookieMap.end()) ? NULL : lookup->second.c_str();
722 pair<string,const char*> ShibTarget::getCookieNameProps(const char* prefix) const
724 static const char* defProps="; path=/";
726 const IPropertySet* props=m_priv->m_app ? m_priv->m_app->getPropertySet("Sessions") : NULL;
728 pair<bool,const char*> p=props->getString("cookieProps");
731 pair<bool,const char*> p2=props->getString("cookieName");
733 return make_pair(string(prefix) + p2.second,p.second);
734 return make_pair(string(prefix) + m_priv->m_app->getHash(),p.second);
737 // Shouldn't happen, but just in case..
738 return pair<string,const char*>(prefix,defProps);
741 string ShibTarget::getHandlerURL(const char* resource) const
743 if (!m_priv->m_handlerURL.empty() && resource && !strcmp(getRequestURL(),resource))
744 return m_priv->m_handlerURL;
747 throw ConfigurationException("Internal error in ShibTargetPriv::getHandlerURL, missing application pointer.");
750 const char* handler=NULL;
751 const IPropertySet* props=m_priv->m_app->getPropertySet("Sessions");
753 pair<bool,bool> p=props->getBool("handlerSSL");
756 pair<bool,const char*> p2=props->getString("handlerURL");
761 // Should never happen...
762 if (!handler || (*handler!='/' && strncmp(handler,"http:",5) && strncmp(handler,"https:",6)))
763 throw ConfigurationException(
764 "Invalid handlerURL property ($1) in Application ($2)",
765 params(2, handler ? handler : "null", m_priv->m_app->getId())
768 // The "handlerURL" property can be in one of three formats:
770 // 1) a full URI: http://host/foo/bar
771 // 2) a hostless URI: http:///foo/bar
772 // 3) a relative path: /foo/bar
774 // # Protocol Host Path
775 // 1 handler handler handler
776 // 2 handler resource handler
777 // 3 resource resource handler
779 // note: if ssl_only is true, make sure the protocol is https
781 const char* path = NULL;
783 // Decide whether to use the handler or the resource for the "protocol"
785 if (*handler != '/') {
793 // break apart the "protocol" string into protocol, host, and "the rest"
794 const char* colon=strchr(prot,':');
796 const char* slash=strchr(colon,'/');
800 // Compute the actual protocol and store in member.
802 m_priv->m_handlerURL.assign("https://");
804 m_priv->m_handlerURL.assign(prot, colon-prot);
806 // create the "host" from either the colon/slash or from the target string
807 // If prot == handler then we're in either #1 or #2, else #3.
808 // If slash == colon then we're in #2.
809 if (prot != handler || slash == colon) {
810 colon = strchr(resource, ':');
811 colon += 3; // Get past the ://
812 slash = strchr(colon, '/');
814 string host(colon, (slash ? slash-colon : strlen(colon)));
816 // Build the handler URL
817 m_priv->m_handlerURL+=host + path;
818 return m_priv->m_handlerURL;
821 void ShibTarget::log(ShibLogLevel level, const string& msg)
823 Category::getInstance("shibtarget.ShibTarget").log(
824 (level == LogLevelDebug ? Priority::DEBUG :
825 (level == LogLevelInfo ? Priority::INFO :
826 (level == LogLevelWarn ? Priority::WARN : Priority::ERROR))),
831 const IApplication* ShibTarget::getApplication() const
833 return m_priv->m_app;
836 const IConfig* ShibTarget::getConfig() const
838 return m_priv->m_conf;
841 void* ShibTarget::returnDecline(void)
846 void* ShibTarget::returnOK(void)
852 /*************************************************************************
853 * Shib Target Private implementation
856 ShibTargetPriv::ShibTargetPriv() : m_app(NULL), m_cacheEntry(NULL), m_Config(NULL), m_conf(NULL), m_mapper(NULL) {}
858 ShibTargetPriv::~ShibTargetPriv()
861 m_cacheEntry->unlock();
879 void ShibTargetPriv::get_application(ShibTarget* st, const string& protocol, const string& hostname, int port, const string& uri)
884 // XXX: Do we need to keep conf and mapper locked while we hold m_app?
885 // TODO: No, should be able to hold the conf but release the mapper.
887 // We lock the configuration system for the duration.
888 m_conf=m_Config->getINI();
891 // Map request to application and content settings.
892 m_mapper=m_conf->getRequestMapper();
895 // Obtain the application settings from the parsed URL
896 m_settings = m_mapper->getSettings(st);
898 // Now find the application from the URL settings
899 pair<bool,const char*> application_id=m_settings.first->getString("applicationId");
900 m_app=m_conf->getApplication(application_id.second);
906 throw ConfigurationException("Unable to map request to application settings, check configuration.");
909 // Compute the full target URL
910 st->m_url = protocol + "://" + hostname;
911 if ((protocol == "http" && port != 80) || (protocol == "https" && port != 443)) {
912 ostringstream portstr;
914 st->m_url += ":" + portstr.str();
919 void* ShibTargetPriv::sendError(ShibTarget* st, const char* page, ShibMLP &mlp)
921 ShibTarget::header_t hdrs[] = {
922 ShibTarget::header_t("Expires","01-Jan-1997 12:00:00 GMT"),
923 ShibTarget::header_t("Cache-Control","private,no-store,no-cache")
926 const IPropertySet* props=m_app->getPropertySet("Errors");
928 pair<bool,const char*> p=props->getString(page);
930 ifstream infile(p.second);
931 if (!infile.fail()) {
932 const char* res = mlp.run(infile,props);
934 return st->sendPage(res, 200, "text/html", ArrayIterator<ShibTarget::header_t>(hdrs,2));
937 else if (!strcmp(page,"access"))
938 return st->sendPage("Access Denied", 403, "text/html", ArrayIterator<ShibTarget::header_t>(hdrs,2));
941 string errstr = string("sendError could not process error template (") + page + ") for application (";
942 errstr += m_app->getId();
944 st->log(ShibTarget::LogLevelError, errstr);
946 "Internal Server Error. Please contact the site administrator.", 500, "text/html", ArrayIterator<ShibTarget::header_t>(hdrs,2)
950 void ShibTargetPriv::clearHeaders(ShibTarget* st)
952 // Clear invariant stuff.
953 st->clearHeader("Shib-Origin-Site");
954 st->clearHeader("Shib-Identity-Provider");
955 st->clearHeader("Shib-Authentication-Method");
956 st->clearHeader("Shib-NameIdentifier-Format");
957 st->clearHeader("Shib-Attributes");
958 st->clearHeader("Shib-Application-ID");
960 // Clear out the list of mapped attributes
961 Iterator<IAAP*> provs=m_app->getAAPProviders();
962 while (provs.hasNext()) {
963 IAAP* aap=provs.next();
965 Iterator<const IAttributeRule*> rules=aap->getAttributeRules();
966 while (rules.hasNext()) {
967 const char* header=rules.next()->getHeader();
969 st->clearHeader(header);
974 pair<bool,void*> ShibTargetPriv::dispatch(
976 const IPropertySet* config,
978 const char* forceType
981 pair<bool,const char*> binding=forceType ? make_pair(true,forceType) : config->getString("Binding");
983 auto_ptr<IPlugIn> plugin(SAMLConfig::getConfig().getPlugMgr().newPlugin(binding.second,config->getElement()));
984 IHandler* handler=dynamic_cast<IHandler*>(plugin.get());
986 throw UnsupportedProfileException(
987 "Plugin for binding ($1) does not implement IHandler interface.",params(1,binding.second)
989 return handler->run(st,config,isHandler);
991 throw UnsupportedProfileException("Handler element is missing Binding attribute to determine what handler to run.");