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>
37 #include <saml/SAMLConfig.h>
38 #include <saml/binding/URLEncoder.h>
39 #include <xercesc/util/Base64.hpp>
40 #include <xmltooling/util/NDC.h>
41 #include <xmltooling/util/TemplateEngine.h>
43 #ifndef HAVE_STRCASECMP
44 # define strcasecmp stricmp
47 using namespace shibtarget;
48 using namespace shibboleth;
50 using namespace log4cpp;
53 using shibsp::PropertySet;
54 using xmltooling::TemplateEngine;
55 using xmltooling::XMLToolingException;
56 using xmltooling::XMLToolingConfig;
58 namespace shibtarget {
62 CgiParse(const ShibTarget* st);
65 typedef multimap<string,char*>::const_iterator walker;
66 pair<walker,walker> get_values(const char* name) const;
69 char* fmakeword(char stop, unsigned int *cl, const char** ppch);
70 char* makeword(char *line, char stop);
71 void plustospace(char *str);
73 multimap<string,char*> kvp_map;
76 class ExtTemplateParameters : public TemplateEngine::TemplateParameters
78 const PropertySet* m_props;
80 ExtTemplateParameters() : m_props(NULL) {}
81 ~ExtTemplateParameters() {}
83 void setPropertySet(const PropertySet* props) {
86 // Create a timestamp.
87 time_t now = time(NULL);
90 m_map["now"] = ctime_r(&now,timebuf);
92 m_map["now"] = ctime(&now);
96 const char* getParameter(const char* name) const {
97 const char* pch = TemplateParameters::getParameter(name);
100 pair<bool,const char*> p = m_props->getString(name);
101 return p.first ? p.second : NULL;
112 void get_application(ShibTarget* st, const string& protocol, const string& hostname, int port, const string& uri);
113 void* sendError(ShibTarget* st, const char* page, ExtTemplateParameters& tp, const XMLToolingException* ex=NULL);
114 void clearHeaders(ShibTarget* st);
117 friend class ShibTarget;
118 IRequestMapper::Settings m_settings;
119 const IApplication *m_app;
120 mutable string m_handlerURL;
121 mutable map<string,string> m_cookieMap;
122 mutable CgiParse* m_cgiParser;
124 ISessionCacheEntry* m_cacheEntry;
126 ShibTargetConfig* m_Config;
129 IRequestMapper* m_mapper;
134 /*************************************************************************
135 * Shib Target implementation
138 ShibTarget::ShibTarget() : m_priv(new ShibTargetPriv()) {}
140 ShibTarget::ShibTarget(const IApplication *app) : m_priv(new ShibTargetPriv())
145 ShibTarget::~ShibTarget(void)
150 void ShibTarget::init(
151 const char* protocol,
152 const char* hostname,
155 const char* content_type,
156 const char* remote_addr,
161 xmltooling::NDC ndc("init");
165 throw SAMLException("Request initialization occurred twice!");
167 if (method) m_method = method;
168 if (protocol) m_protocol = protocol;
169 if (hostname) m_hostname = hostname;
170 if (uri) m_uri = uri;
171 if (content_type) m_content_type = content_type;
172 if (remote_addr) m_remote_addr = remote_addr;
174 m_priv->m_Config = &ShibTargetConfig::getConfig();
175 m_priv->get_application(this, protocol, hostname, port, 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 xmltooling::NDC ndc("doCheckAuthN");
189 const char* procState = "Request Processing Error";
190 const char* targetURL = m_url.c_str();
191 ExtTemplateParameters tp;
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 tp.m_map["requestURL"] = m_url.substr(0,m_url.find('?'));
212 return make_pair(true,m_priv->sendError(this,"ssl", tp));
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 make_pair(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 make_pair(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 make_pair(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 IHandler* initiator=NULL;
260 if (requireSessionWith.first) {
261 initiator=m_priv->m_app->getSessionInitiatorById(requireSessionWith.second);
263 throw ConfigurationException(
264 "No session initiator found with id ($1), check requireSessionWith command.",
265 params(1,requireSessionWith.second)
269 initiator=m_priv->m_app->getDefaultSessionInitiator();
271 throw ConfigurationException("No default session initiator found, check configuration.");
274 return initiator->run(this,false);
277 procState = "Session Processing Error";
279 m_priv->m_cacheEntry=m_priv->m_conf->getSessionCache()->find(
282 m_remote_addr.c_str()
284 // Make a localized exception throw if the session isn't valid.
285 if (!m_priv->m_cacheEntry)
286 throw InvalidSessionException("Session no longer valid.");
288 catch (SAMLException& e) {
289 log(LogLevelError, string("session processing failed: ") + e.what());
291 // If no session is required, bail now.
292 if ((!requireSession.first || !requireSession.second) && !requireSessionWith.first)
293 // Has to be OK because DECLINED will just cause Apache
294 // to fail when it can't locate anything to process the
295 // AuthType. No session plus requireSession false means
296 // do not authenticate the user at this time.
297 return make_pair(true, returnOK());
299 // Try and cast down.
300 SAMLException* base = &e;
301 RetryableProfileException* trycast=dynamic_cast<RetryableProfileException*>(base);
303 // Session is invalid but we can retry -- initiate a new session.
304 procState = "Session Initiator Error";
305 const IHandler* initiator=NULL;
306 if (requireSessionWith.first) {
307 initiator=m_priv->m_app->getSessionInitiatorById(requireSessionWith.second);
309 throw ConfigurationException(
310 "No session initiator found with id ($1), check requireSessionWith command.",
311 params(1,requireSessionWith.second)
315 initiator=m_priv->m_app->getDefaultSessionInitiator();
317 throw ConfigurationException("No default session initiator found, check configuration.");
319 return initiator->run(this,false);
321 throw; // send it to the outer handler
324 // We're done. Everything is okay. Nothing to report. Nothing to do..
325 // Let the caller decide how to proceed.
326 log(LogLevelDebug, "doCheckAuthN succeeded");
327 return make_pair(false,(void*)NULL);
329 catch (SAMLException& e) { // TODO: we're going to yank this handler...
330 tp.m_map["errorType"] = procState;
331 tp.m_map["errorText"] = e.what();
333 tp.m_map["requestURL"] = m_url.substr(0,m_url.find('?'));
334 return make_pair(true,m_priv->sendError(this, "session", tp));
336 catch (XMLToolingException& e) {
337 tp.m_map["errorType"] = procState;
338 tp.m_map["errorText"] = e.what();
340 tp.m_map["requestURL"] = m_url.substr(0,m_url.find('?'));
341 return make_pair(true,m_priv->sendError(this, "session", tp, &e));
345 tp.m_map["errorType"] = procState;
346 tp.m_map["errorText"] = "Caught an unknown exception.";
348 tp.m_map["requestURL"] = m_url.substr(0,m_url.find('?'));
349 return make_pair(true,m_priv->sendError(this, "session", tp));
354 pair<bool,void*> ShibTarget::doHandler(void)
357 xmltooling::NDC ndc("doHandler");
360 ExtTemplateParameters tp;
361 const char* procState = "Shibboleth Handler Error";
362 const char* targetURL = m_url.c_str();
366 throw ConfigurationException("System uninitialized, application did not supply request information.");
368 string hURL = getHandlerURL(targetURL);
369 const char* handlerURL=hURL.c_str();
371 throw ConfigurationException("Cannot determine handler from resource URL, check configuration.");
373 // Make sure we only process handler requests.
374 if (!strstr(targetURL,handlerURL))
375 return make_pair(true, returnDecline());
377 const PropertySet* sessionProps=m_priv->m_app->getPropertySet("Sessions");
379 throw ConfigurationException("Unable to map request to application session settings, check configuration.");
381 // Process incoming request.
382 pair<bool,bool> handlerSSL=sessionProps->getBool("handlerSSL");
384 // Make sure this is SSL, if it should be
385 if ((!handlerSSL.first || handlerSSL.second) && m_protocol != "https")
386 throw FatalProfileException("Blocked non-SSL access to Shibboleth handler.");
388 // We dispatch based on our path info. We know the request URL begins with or equals the handler URL,
389 // so the path info is the next character (or null).
390 const IHandler* handler=m_priv->m_app->getHandler(targetURL + strlen(handlerURL));
392 throw SAMLException("Shibboleth handler invoked at an unconfigured location.");
394 if (saml::XML::isElementNamed(handler->getProperties()->getElement(),shibtarget::XML::SAML2META_NS,SHIBT_L(AssertionConsumerService)))
395 procState = "Session Creation Error";
396 else if (saml::XML::isElementNamed(handler->getProperties()->getElement(),shibtarget::XML::SHIBTARGET_NS,SHIBT_L(SessionInitiator)))
397 procState = "Session Initiator Error";
398 else if (saml::XML::isElementNamed(handler->getProperties()->getElement(),shibtarget::XML::SAML2META_NS,SHIBT_L(SingleLogoutService)))
399 procState = "Session Termination Error";
400 else if (saml::XML::isElementNamed(handler->getProperties()->getElement(),shibtarget::XML::SHIBTARGET_NS,SHIBT_L(DiagnosticService)))
401 procState = "Diagnostics Error";
403 procState = "Extension Service Error";
404 pair<bool,void*> hret=handler->run(this);
406 // Did the handler run successfully?
410 throw XMLToolingException("Configured Shibboleth handler failed to process the request.");
412 catch (MetadataException& e) {
413 tp.m_map["errorText"] = e.what();
414 // See if a metadata error page is installed.
415 const PropertySet* props=m_priv->m_app->getPropertySet("Errors");
417 pair<bool,const char*> p=props->getString("metadata");
419 tp.m_map["errorType"] = procState;
421 tp.m_map["requestURL"] = targetURL;
422 return make_pair(true,m_priv->sendError(this, "metadata", tp));
427 catch (SAMLException& e) {
428 tp.m_map["errorType"] = procState;
429 tp.m_map["errorText"] = e.what();
431 tp.m_map["requestURL"] = m_url.substr(0,m_url.find('?'));
432 return make_pair(true,m_priv->sendError(this, "session", tp));
434 catch (XMLToolingException& e) {
435 tp.m_map["errorType"] = procState;
436 tp.m_map["errorText"] = e.what();
438 tp.m_map["requestURL"] = m_url.substr(0,m_url.find('?'));
439 return make_pair(true,m_priv->sendError(this, "session", tp, &e));
443 tp.m_map["errorType"] = procState;
444 tp.m_map["errorText"] = "Caught an unknown exception.";
446 tp.m_map["requestURL"] = m_url.substr(0,m_url.find('?'));
447 return make_pair(true,m_priv->sendError(this, "session", tp));
452 pair<bool,void*> ShibTarget::doCheckAuthZ(void)
455 xmltooling::NDC ndc("doCheckAuthZ");
458 ExtTemplateParameters tp;
459 const char* procState = "Authorization Processing Error";
460 const char* targetURL = m_url.c_str();
464 throw ConfigurationException("System uninitialized, application did not supply request information.");
466 // Three settings dictate how to proceed.
467 pair<bool,const char*> authType = m_priv->m_settings.first->getString("authType");
468 pair<bool,bool> requireSession = m_priv->m_settings.first->getBool("requireSession");
469 pair<bool,const char*> requireSessionWith = m_priv->m_settings.first->getString("requireSessionWith");
471 // If no session is required AND the AuthType (an Apache-derived concept) isn't shibboleth,
472 // then we ignore this request and consider it unprotected. Apache might lie to us if
473 // ShibBasicHijack is on, but that's up to it.
474 if ((!requireSession.first || !requireSession.second) && !requireSessionWith.first &&
475 #ifdef HAVE_STRCASECMP
476 (!authType.first || strcasecmp(authType.second,"shibboleth")))
478 (!authType.first || _stricmp(authType.second,"shibboleth")))
480 return make_pair(true,returnDecline());
482 // Do we have an access control plugin?
483 if (m_priv->m_settings.second) {
485 if (!m_priv->m_cacheEntry) {
486 // No data yet, so we may need to try and get the session.
487 pair<string,const char*> shib_cookie=getCookieNameProps("_shibsession_");
488 const char *session_id = getCookie(shib_cookie.first);
490 if (session_id && *session_id) {
491 m_priv->m_cacheEntry=m_priv->m_conf->getSessionCache()->find(
494 m_remote_addr.c_str()
498 catch (SAMLException&) {
499 log(LogLevelError, "doCheckAuthZ: unable to obtain session information to pass to access control provider");
503 Locker acllock(m_priv->m_settings.second);
504 if (m_priv->m_settings.second->authorized(this,m_priv->m_cacheEntry)) {
505 // Let the caller decide how to proceed.
506 log(LogLevelDebug, "doCheckAuthZ: access control provider granted access");
507 return make_pair(false,(void*)NULL);
510 log(LogLevelWarn, "doCheckAuthZ: access control provider denied access");
512 tp.m_map["requestURL"] = targetURL;
513 return make_pair(true,m_priv->sendError(this, "access", tp));
517 return make_pair(true,returnDecline());
519 catch (SAMLException& e) {
520 tp.m_map["errorType"] = procState;
521 tp.m_map["errorText"] = e.what();
523 tp.m_map["requestURL"] = m_url.substr(0,m_url.find('?'));
524 return make_pair(true,m_priv->sendError(this, "access", tp));
526 catch (XMLToolingException& e) {
527 tp.m_map["errorType"] = procState;
528 tp.m_map["errorText"] = e.what();
530 tp.m_map["requestURL"] = m_url.substr(0,m_url.find('?'));
531 return make_pair(true,m_priv->sendError(this, "access", tp, &e));
535 tp.m_map["errorType"] = procState;
536 tp.m_map["errorText"] = "Caught an unknown exception.";
538 tp.m_map["requestURL"] = m_url.substr(0,m_url.find('?'));
539 return make_pair(true,m_priv->sendError(this, "access", tp));
544 pair<bool,void*> ShibTarget::doExportAssertions(bool requireSession)
547 xmltooling::NDC ndc("doExportAssertions");
550 ExtTemplateParameters tp;
551 const char* procState = "Attribute Processing Error";
552 const char* targetURL = m_url.c_str();
556 throw ConfigurationException("System uninitialized, application did not supply request information.");
558 if (!m_priv->m_cacheEntry) {
559 // No data yet, so we need to get the session. This can only happen
560 // if the call to doCheckAuthn doesn't happen in the same object lifetime.
561 pair<string,const char*> shib_cookie=getCookieNameProps("_shibsession_");
562 const char *session_id = getCookie(shib_cookie.first);
564 if (session_id && *session_id) {
565 m_priv->m_cacheEntry=m_priv->m_conf->getSessionCache()->find(
568 m_remote_addr.c_str()
572 catch (SAMLException&) {
573 log(LogLevelError, "unable to obtain session information to export into request headers");
574 // If we have to have a session, then this is a fatal error.
581 if (!m_priv->m_cacheEntry) {
583 throw InvalidSessionException("Unable to obtain session information for request.");
585 return make_pair(false,(void*)NULL); // just bail silently
588 // Extract data from session.
589 pair<const char*,const SAMLSubject*> sub=m_priv->m_cacheEntry->getSubject(false,true);
590 pair<const char*,const SAMLResponse*> unfiltered=m_priv->m_cacheEntry->getTokens(true,false);
591 pair<const char*,const SAMLResponse*> filtered=m_priv->m_cacheEntry->getTokens(false,true);
593 // Maybe export the tokens.
594 pair<bool,bool> exp=m_priv->m_settings.first->getBool("exportAssertion");
595 if (exp.first && exp.second && unfiltered.first && *unfiltered.first) {
597 XMLByte* serialized =
598 Base64::encode(reinterpret_cast<XMLByte*>((char*)unfiltered.first), XMLString::stringLen(unfiltered.first), &outlen);
600 for (pos=serialized, pos2=serialized; *pos2; pos2++)
604 setHeader("Shib-Attributes", reinterpret_cast<char*>(serialized));
605 XMLString::release(&serialized);
608 // Export the SAML AuthnMethod and the origin site name, and possibly the NameIdentifier.
609 setHeader("Shib-Origin-Site", m_priv->m_cacheEntry->getProviderId());
610 setHeader("Shib-Identity-Provider", m_priv->m_cacheEntry->getProviderId());
611 setHeader("Shib-Authentication-Method", m_priv->m_cacheEntry->getAuthnContext());
613 // Get the AAP providers, which contain the attribute policy info.
614 Iterator<IAAP*> provs=m_priv->m_app->getAAPProviders();
617 while (provs.hasNext()) {
618 IAAP* aap=provs.next();
620 const XMLCh* format = sub.second->getNameIdentifier()->getFormat();
621 const IAttributeRule* rule=aap->lookup(format ? format : SAMLNameIdentifier::UNSPECIFIED);
622 if (rule && rule->getHeader()) {
623 auto_ptr_char form(format ? format : SAMLNameIdentifier::UNSPECIFIED);
624 auto_ptr_char nameid(sub.second->getNameIdentifier()->getName());
625 setHeader("Shib-NameIdentifier-Format", form.get());
626 if (!strcmp(rule->getHeader(),"REMOTE_USER"))
627 setRemoteUser(nameid.get());
629 setHeader(rule->getHeader(), nameid.get());
633 setHeader("Shib-Application-ID", m_priv->m_app->getId());
635 // Export the attributes.
636 Iterator<SAMLAssertion*> a_iter(filtered.second ? filtered.second->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());
665 for (; vals.hasNext(); it++) {
666 string value = vals.next();
667 for (string::size_type pos = value.find_first_of(";", string::size_type(0));
669 pos = value.find_first_of(";", pos)) {
670 value.insert(pos, "\\");
677 setHeader(rule->getHeader(), header);
684 return make_pair(false,(void*)NULL);
686 catch (SAMLException& e) {
687 tp.m_map["errorType"] = procState;
688 tp.m_map["errorText"] = e.what();
690 tp.m_map["requestURL"] = m_url.substr(0,m_url.find('?'));
691 return make_pair(true,m_priv->sendError(this, "rm", tp));
693 catch (XMLToolingException& e) {
694 tp.m_map["errorType"] = procState;
695 tp.m_map["errorText"] = e.what();
697 tp.m_map["requestURL"] = m_url.substr(0,m_url.find('?'));
698 return make_pair(true,m_priv->sendError(this, "rm", tp, &e));
702 tp.m_map["errorType"] = procState;
703 tp.m_map["errorText"] = "Caught an unknown exception.";
705 tp.m_map["requestURL"] = m_url.substr(0,m_url.find('?'));
706 return make_pair(true,m_priv->sendError(this, "rm", tp));
711 const char* ShibTarget::getRequestParameter(const char* param, size_t index) const
713 if (!m_priv->m_cgiParser)
714 m_priv->m_cgiParser=new CgiParse(this);
716 pair<CgiParse::walker,CgiParse::walker> bounds=m_priv->m_cgiParser->get_values(param);
718 // Advance to the right index.
719 while (index && bounds.first!=bounds.second) {
724 return (bounds.first==bounds.second) ? NULL : bounds.first->second;
727 const char* ShibTarget::getCookie(const string& name) const
729 if (m_priv->m_cookieMap.empty()) {
730 string cookies=getCookies();
732 string::size_type pos=0,cname,namelen,val,vallen;
733 while (pos !=string::npos && pos < cookies.length()) {
734 while (isspace(cookies[pos])) pos++;
736 pos=cookies.find_first_of("=",pos);
737 if (pos == string::npos)
741 if (pos==cookies.length())
744 pos=cookies.find_first_of(";",pos);
745 if (pos != string::npos) {
748 m_priv->m_cookieMap.insert(make_pair(cookies.substr(cname,namelen),cookies.substr(val,vallen)));
751 m_priv->m_cookieMap.insert(make_pair(cookies.substr(cname,namelen),cookies.substr(val)));
754 map<string,string>::const_iterator lookup=m_priv->m_cookieMap.find(name);
755 return (lookup==m_priv->m_cookieMap.end()) ? NULL : lookup->second.c_str();
758 pair<string,const char*> ShibTarget::getCookieNameProps(const char* prefix) const
760 static const char* defProps="; path=/";
762 const PropertySet* props=m_priv->m_app ? m_priv->m_app->getPropertySet("Sessions") : NULL;
764 pair<bool,const char*> p=props->getString("cookieProps");
767 pair<bool,const char*> p2=props->getString("cookieName");
769 return make_pair(string(prefix) + p2.second,p.second);
770 return make_pair(string(prefix) + m_priv->m_app->getHash(),p.second);
773 // Shouldn't happen, but just in case..
774 return pair<string,const char*>(prefix,defProps);
777 string ShibTarget::getHandlerURL(const char* resource) const
779 if (!m_priv->m_handlerURL.empty() && resource && !strcmp(getRequestURL(),resource))
780 return m_priv->m_handlerURL;
783 throw ConfigurationException("Internal error in ShibTargetPriv::getHandlerURL, missing application pointer.");
786 const char* handler=NULL;
787 const PropertySet* props=m_priv->m_app->getPropertySet("Sessions");
789 pair<bool,bool> p=props->getBool("handlerSSL");
792 pair<bool,const char*> p2=props->getString("handlerURL");
797 // Should never happen...
798 if (!handler || (*handler!='/' && strncmp(handler,"http:",5) && strncmp(handler,"https:",6)))
799 throw ConfigurationException(
800 "Invalid handlerURL property ($1) in Application ($2)",
801 params(2, handler ? handler : "null", m_priv->m_app->getId())
804 // The "handlerURL" property can be in one of three formats:
806 // 1) a full URI: http://host/foo/bar
807 // 2) a hostless URI: http:///foo/bar
808 // 3) a relative path: /foo/bar
810 // # Protocol Host Path
811 // 1 handler handler handler
812 // 2 handler resource handler
813 // 3 resource resource handler
815 // note: if ssl_only is true, make sure the protocol is https
817 const char* path = NULL;
819 // Decide whether to use the handler or the resource for the "protocol"
821 if (*handler != '/') {
829 // break apart the "protocol" string into protocol, host, and "the rest"
830 const char* colon=strchr(prot,':');
832 const char* slash=strchr(colon,'/');
836 // Compute the actual protocol and store in member.
838 m_priv->m_handlerURL.assign("https://");
840 m_priv->m_handlerURL.assign(prot, colon-prot);
842 // create the "host" from either the colon/slash or from the target string
843 // If prot == handler then we're in either #1 or #2, else #3.
844 // If slash == colon then we're in #2.
845 if (prot != handler || slash == colon) {
846 colon = strchr(resource, ':');
847 colon += 3; // Get past the ://
848 slash = strchr(colon, '/');
850 string host(colon, (slash ? slash-colon : strlen(colon)));
852 // Build the handler URL
853 m_priv->m_handlerURL+=host + path;
854 return m_priv->m_handlerURL;
857 void ShibTarget::log(ShibLogLevel level, const string& msg)
859 Category::getInstance("shibtarget.ShibTarget").log(
860 (level == LogLevelDebug ? Priority::DEBUG :
861 (level == LogLevelInfo ? Priority::INFO :
862 (level == LogLevelWarn ? Priority::WARN : Priority::ERROR))),
867 const IApplication* ShibTarget::getApplication() const
869 return m_priv->m_app;
872 const IConfig* ShibTarget::getConfig() const
874 return m_priv->m_conf;
877 void* ShibTarget::returnDecline(void)
882 void* ShibTarget::returnOK(void)
887 /*************************************************************************
888 * Shib Target Private implementation
891 ShibTargetPriv::ShibTargetPriv()
892 : m_app(NULL), m_mapper(NULL), m_conf(NULL), m_Config(NULL), m_cacheEntry(NULL), m_cgiParser(NULL) {}
894 ShibTargetPriv::~ShibTargetPriv()
897 m_cacheEntry->unlock();
916 void ShibTargetPriv::get_application(ShibTarget* st, const string& protocol, const string& hostname, int port, const string& uri)
921 // XXX: Do we need to keep conf and mapper locked while we hold m_app?
922 // TODO: No, should be able to hold the conf but release the mapper.
924 // We lock the configuration system for the duration.
925 m_conf=m_Config->getINI();
928 // Map request to application and content settings.
929 m_mapper=m_conf->getRequestMapper();
932 // Obtain the application settings from the parsed URL
933 m_settings = m_mapper->getSettings(st);
935 // Now find the application from the URL settings
936 pair<bool,const char*> application_id=m_settings.first->getString("applicationId");
937 m_app=m_conf->getApplication(application_id.second);
943 throw ConfigurationException("Unable to map request to application settings, check configuration.");
946 // Compute the full target URL
947 st->m_url = protocol + "://" + hostname;
948 if ((protocol == "http" && port != 80) || (protocol == "https" && port != 443)) {
949 ostringstream portstr;
951 st->m_url += ":" + portstr.str();
956 void* ShibTargetPriv::sendError(
957 ShibTarget* st, const char* page, ExtTemplateParameters& tp, const XMLToolingException* ex
960 ShibTarget::header_t hdrs[] = {
961 ShibTarget::header_t("Expires","01-Jan-1997 12:00:00 GMT"),
962 ShibTarget::header_t("Cache-Control","private,no-store,no-cache")
965 TemplateEngine* engine = XMLToolingConfig::getConfig().getTemplateEngine();
966 const PropertySet* props=m_app->getPropertySet("Errors");
968 pair<bool,const char*> p=props->getString(page);
970 ifstream infile(p.second);
972 tp.setPropertySet(props);
974 engine->run(infile, ostr, tp, ex);
975 return st->sendPage(ostr.str().c_str(), 200, "text/html", ArrayIterator<ShibTarget::header_t>(hdrs,2));
978 else if (!strcmp(page,"access"))
979 return st->sendPage("Access Denied", 403, "text/html", ArrayIterator<ShibTarget::header_t>(hdrs,2));
982 string errstr = string("sendError could not process error template (") + page + ") for application (";
983 errstr += m_app->getId();
985 st->log(ShibTarget::LogLevelError, errstr);
987 "Internal Server Error. Please contact the site administrator.", 500, "text/html", ArrayIterator<ShibTarget::header_t>(hdrs,2)
991 void ShibTargetPriv::clearHeaders(ShibTarget* st)
993 // Clear invariant stuff.
994 st->clearHeader("Shib-Origin-Site");
995 st->clearHeader("Shib-Identity-Provider");
996 st->clearHeader("Shib-Authentication-Method");
997 st->clearHeader("Shib-NameIdentifier-Format");
998 st->clearHeader("Shib-Attributes");
999 st->clearHeader("Shib-Application-ID");
1001 // Clear out the list of mapped attributes
1002 Iterator<IAAP*> provs=m_app->getAAPProviders();
1003 while (provs.hasNext()) {
1004 IAAP* aap=provs.next();
1006 Iterator<const IAttributeRule*> rules=aap->getAttributeRules();
1007 while (rules.hasNext()) {
1008 const char* header=rules.next()->getHeader();
1010 st->clearHeader(header);
1015 /*************************************************************************
1016 * CGI Parser implementation
1019 CgiParse::CgiParse(const ShibTarget* st)
1021 const char* pch=NULL;
1022 if (!strcmp(st->getRequestMethod(),"POST"))
1023 pch=st->getRequestBody();
1025 pch=st->getQueryString();
1026 size_t cl=pch ? strlen(pch) : 0;
1032 value=fmakeword('&',&cl,&pch);
1034 opensaml::SAMLConfig::getConfig().getURLEncoder()->decode(value);
1035 name=makeword(value,'=');
1036 kvp_map.insert(pair<string,char*>(name,value));
1041 CgiParse::~CgiParse()
1043 for (multimap<string,char*>::iterator i=kvp_map.begin(); i!=kvp_map.end(); i++)
1047 pair<CgiParse::walker,CgiParse::walker> CgiParse::get_values(const char* name) const
1049 return kvp_map.equal_range(name);
1052 /* Parsing routines modified from NCSA source. */
1053 char* CgiParse::makeword(char *line, char stop)
1056 char *word = (char *) malloc(sizeof(char) * (strlen(line) + 1));
1058 for(x=0;((line[x]) && (line[x] != stop));x++)
1067 line[y++] = line[x++];
1072 char* CgiParse::fmakeword(char stop, size_t *cl, const char** ppch)
1080 word = (char *) malloc(sizeof(char) * (wsize + 1));
1084 word[ll] = *((*ppch)++);
1089 word = (char *)realloc(word,sizeof(char)*(wsize+1));
1092 if((word[ll] == stop) || word[ll] == EOF || (!(*cl)))
1094 if(word[ll] != stop)
1103 void CgiParse::plustospace(char *str)
1108 if(str[x] == '+') str[x] = ' ';