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>
42 #include <xmltooling/util/XMLHelper.h>
44 #ifndef HAVE_STRCASECMP
45 # define strcasecmp stricmp
48 using namespace shibsp;
49 using namespace shibtarget;
50 using namespace shibboleth;
52 using namespace opensaml::saml2md;
53 using namespace log4cpp;
56 using xmltooling::TemplateEngine;
57 using xmltooling::XMLToolingException;
58 using xmltooling::XMLToolingConfig;
59 using xmltooling::XMLHelper;
61 namespace shibtarget {
65 CgiParse(const ShibTarget* st);
68 typedef multimap<string,char*>::const_iterator walker;
69 pair<walker,walker> get_values(const char* name) const;
72 char* fmakeword(char stop, unsigned int *cl, const char** ppch);
73 char* makeword(char *line, char stop);
74 void plustospace(char *str);
76 multimap<string,char*> kvp_map;
79 class ExtTemplateParameters : public TemplateEngine::TemplateParameters
81 const PropertySet* m_props;
83 ExtTemplateParameters() : m_props(NULL) {}
84 ~ExtTemplateParameters() {}
86 void setPropertySet(const PropertySet* props) {
89 // Create a timestamp.
90 time_t now = time(NULL);
93 m_map["now"] = ctime_r(&now,timebuf);
95 m_map["now"] = ctime(&now);
99 const char* getParameter(const char* name) const {
100 const char* pch = TemplateParameters::getParameter(name);
103 pair<bool,const char*> p = m_props->getString(name);
104 return p.first ? p.second : NULL;
115 void get_application(ShibTarget* st, const string& protocol, const string& hostname, int port, const string& uri);
116 void* sendError(ShibTarget* st, const char* page, ExtTemplateParameters& tp, const XMLToolingException* ex=NULL);
117 void clearHeaders(ShibTarget* st);
120 friend class ShibTarget;
121 IRequestMapper::Settings m_settings;
122 const IApplication *m_app;
123 mutable string m_handlerURL;
124 mutable map<string,string> m_cookieMap;
125 mutable CgiParse* m_cgiParser;
127 ISessionCacheEntry* m_cacheEntry;
129 ShibTargetConfig* m_Config;
132 IRequestMapper* m_mapper;
137 /*************************************************************************
138 * Shib Target implementation
141 ShibTarget::ShibTarget() : m_priv(new ShibTargetPriv()) {}
143 ShibTarget::ShibTarget(const IApplication *app) : m_priv(new ShibTargetPriv())
148 ShibTarget::~ShibTarget(void)
153 void ShibTarget::init(
154 const char* protocol,
155 const char* hostname,
158 const char* content_type,
159 const char* remote_addr,
164 xmltooling::NDC ndc("init");
168 throw XMLToolingException("Request initialization occurred twice!");
170 if (method) m_method = method;
171 if (protocol) m_protocol = protocol;
172 if (hostname) m_hostname = hostname;
173 if (uri) m_uri = uri;
174 if (content_type) m_content_type = content_type;
175 if (remote_addr) m_remote_addr = remote_addr;
177 m_priv->m_Config = &ShibTargetConfig::getConfig();
178 m_priv->get_application(this, protocol, hostname, port, uri);
182 // These functions implement the server-agnostic shibboleth engine
183 // The web server modules implement a subclass and then call into
184 // these methods once they instantiate their request object.
186 pair<bool,void*> ShibTarget::doCheckAuthN(bool handler)
189 xmltooling::NDC ndc("doCheckAuthN");
192 const char* procState = "Request Processing Error";
193 const char* targetURL = m_url.c_str();
194 ExtTemplateParameters tp;
198 throw ConfigurationException("System uninitialized, application did not supply request information.");
200 // If not SSL, check to see if we should block or redirect it.
201 if (!strcmp("http",getProtocol())) {
202 pair<bool,const char*> redirectToSSL = m_priv->m_settings.first->getString("redirectToSSL");
203 if (redirectToSSL.first) {
204 if (!strcasecmp("GET",getRequestMethod()) || !strcasecmp("HEAD",getRequestMethod())) {
205 // Compute the new target URL
206 string redirectURL = string("https://") + getHostname();
207 if (strcmp(redirectToSSL.second,"443")) {
208 redirectURL = redirectURL + ':' + redirectToSSL.second;
210 redirectURL += getRequestURI();
211 return make_pair(true, sendRedirect(redirectURL));
214 tp.m_map["requestURL"] = m_url.substr(0,m_url.find('?'));
215 return make_pair(true,m_priv->sendError(this,"ssl", tp));
220 string hURL = getHandlerURL(targetURL);
221 const char* handlerURL=hURL.c_str();
223 throw ConfigurationException("Cannot determine handler from resource URL, check configuration.");
225 // If the request URL contains the handler base URL for this application, either dispatch
226 // directly (mainly Apache 2.0) or just pass back control.
227 if (strstr(targetURL,handlerURL)) {
231 return make_pair(true, returnOK());
234 // Three settings dictate how to proceed.
235 pair<bool,const char*> authType = m_priv->m_settings.first->getString("authType");
236 pair<bool,bool> requireSession = m_priv->m_settings.first->getBool("requireSession");
237 pair<bool,const char*> requireSessionWith = m_priv->m_settings.first->getString("requireSessionWith");
239 // If no session is required AND the AuthType (an Apache-derived concept) isn't shibboleth,
240 // then we ignore this request and consider it unprotected. Apache might lie to us if
241 // ShibBasicHijack is on, but that's up to it.
242 if ((!requireSession.first || !requireSession.second) && !requireSessionWith.first &&
243 #ifdef HAVE_STRCASECMP
244 (!authType.first || strcasecmp(authType.second,"shibboleth")))
246 (!authType.first || _stricmp(authType.second,"shibboleth")))
248 return make_pair(true,returnDecline());
250 // Fix for secadv 20050901
251 m_priv->clearHeaders(this);
253 pair<string,const char*> shib_cookie = getCookieNameProps("_shibsession_");
254 const char* session_id = getCookie(shib_cookie.first);
255 if (!session_id || !*session_id) {
256 // No session. Maybe that's acceptable?
257 if ((!requireSession.first || !requireSession.second) && !requireSessionWith.first)
258 return make_pair(true,returnOK());
260 // No cookie, but we require a session. Initiate a new session using the indicated method.
261 procState = "Session Initiator Error";
262 const IHandler* initiator=NULL;
263 if (requireSessionWith.first) {
264 initiator=m_priv->m_app->getSessionInitiatorById(requireSessionWith.second);
266 throw ConfigurationException(
267 "No session initiator found with id ($1), check requireSessionWith command.",
268 xmltooling::params(1,requireSessionWith.second)
272 initiator=m_priv->m_app->getDefaultSessionInitiator();
274 throw ConfigurationException("No default session initiator found, check configuration.");
277 return initiator->run(this,false);
280 procState = "Session Processing Error";
282 m_priv->m_cacheEntry=m_priv->m_conf->getSessionCache()->find(
285 m_remote_addr.c_str()
287 // Make a localized exception throw if the session isn't valid.
288 if (!m_priv->m_cacheEntry)
289 throw RetryableProfileException("Session no longer valid.");
291 catch (exception& e) {
292 log(LogLevelError, string("session processing failed: ") + e.what());
294 // If no session is required, bail now.
295 if ((!requireSession.first || !requireSession.second) && !requireSessionWith.first)
296 // Has to be OK because DECLINED will just cause Apache
297 // to fail when it can't locate anything to process the
298 // AuthType. No session plus requireSession false means
299 // do not authenticate the user at this time.
300 return make_pair(true, returnOK());
302 // Try and cast down.
303 exception* base = &e;
304 RetryableProfileException* trycast=dynamic_cast<RetryableProfileException*>(base);
306 // Session is invalid but we can retry -- initiate a new session.
307 procState = "Session Initiator Error";
308 const IHandler* initiator=NULL;
309 if (requireSessionWith.first) {
310 initiator=m_priv->m_app->getSessionInitiatorById(requireSessionWith.second);
312 throw ConfigurationException(
313 "No session initiator found with id ($1), check requireSessionWith command.",
314 xmltooling::params(1,requireSessionWith.second)
318 initiator=m_priv->m_app->getDefaultSessionInitiator();
320 throw ConfigurationException("No default session initiator found, check configuration.");
322 return initiator->run(this,false);
324 throw; // send it to the outer handler
327 // We're done. Everything is okay. Nothing to report. Nothing to do..
328 // Let the caller decide how to proceed.
329 log(LogLevelDebug, "doCheckAuthN succeeded");
330 return make_pair(false,(void*)NULL);
332 catch (XMLToolingException& e) {
333 tp.m_map["errorType"] = procState;
334 tp.m_map["errorText"] = e.what();
336 tp.m_map["requestURL"] = m_url.substr(0,m_url.find('?'));
337 return make_pair(true,m_priv->sendError(this, "session", tp, &e));
341 tp.m_map["errorType"] = procState;
342 tp.m_map["errorText"] = "Caught an unknown exception.";
344 tp.m_map["requestURL"] = m_url.substr(0,m_url.find('?'));
345 return make_pair(true,m_priv->sendError(this, "session", tp));
350 pair<bool,void*> ShibTarget::doHandler(void)
353 xmltooling::NDC ndc("doHandler");
356 ExtTemplateParameters tp;
357 const char* procState = "Shibboleth Handler Error";
358 const char* targetURL = m_url.c_str();
362 throw ConfigurationException("System uninitialized, application did not supply request information.");
364 string hURL = getHandlerURL(targetURL);
365 const char* handlerURL=hURL.c_str();
367 throw ConfigurationException("Cannot determine handler from resource URL, check configuration.");
369 // Make sure we only process handler requests.
370 if (!strstr(targetURL,handlerURL))
371 return make_pair(true, returnDecline());
373 const PropertySet* sessionProps=m_priv->m_app->getPropertySet("Sessions");
375 throw ConfigurationException("Unable to map request to application session settings, check configuration.");
377 // Process incoming request.
378 pair<bool,bool> handlerSSL=sessionProps->getBool("handlerSSL");
380 // Make sure this is SSL, if it should be
381 if ((!handlerSSL.first || handlerSSL.second) && m_protocol != "https")
382 throw opensaml::FatalProfileException("Blocked non-SSL access to Shibboleth handler.");
384 // We dispatch based on our path info. We know the request URL begins with or equals the handler URL,
385 // so the path info is the next character (or null).
386 const IHandler* handler=m_priv->m_app->getHandler(targetURL + strlen(handlerURL));
388 throw opensaml::BindingException("Shibboleth handler invoked at an unconfigured location.");
390 if (XMLHelper::isNodeNamed(handler->getProperties()->getElement(),samlconstants::SAML20MD_NS,SHIBT_L(AssertionConsumerService)))
391 procState = "Session Creation Error";
392 else if (XMLHelper::isNodeNamed(handler->getProperties()->getElement(),shibtarget::XML::SHIBTARGET_NS,SHIBT_L(SessionInitiator)))
393 procState = "Session Initiator Error";
394 else if (XMLHelper::isNodeNamed(handler->getProperties()->getElement(),samlconstants::SAML20MD_NS,SHIBT_L(SingleLogoutService)))
395 procState = "Session Termination Error";
396 else if (XMLHelper::isNodeNamed(handler->getProperties()->getElement(),shibtarget::XML::SHIBTARGET_NS,SHIBT_L(DiagnosticService)))
397 procState = "Diagnostics Error";
399 procState = "Extension Service Error";
400 pair<bool,void*> hret=handler->run(this);
402 // Did the handler run successfully?
406 throw opensaml::BindingException("Configured Shibboleth handler failed to process the request.");
408 catch (MetadataException& e) {
409 tp.m_map["errorText"] = e.what();
410 // See if a metadata error page is installed.
411 const PropertySet* props=m_priv->m_app->getPropertySet("Errors");
413 pair<bool,const char*> p=props->getString("metadata");
415 tp.m_map["errorType"] = procState;
417 tp.m_map["requestURL"] = targetURL;
418 return make_pair(true,m_priv->sendError(this, "metadata", tp));
423 catch (XMLToolingException& e) {
424 tp.m_map["errorType"] = procState;
425 tp.m_map["errorText"] = e.what();
427 tp.m_map["requestURL"] = m_url.substr(0,m_url.find('?'));
428 return make_pair(true,m_priv->sendError(this, "session", tp, &e));
432 tp.m_map["errorType"] = procState;
433 tp.m_map["errorText"] = "Caught an unknown exception.";
435 tp.m_map["requestURL"] = m_url.substr(0,m_url.find('?'));
436 return make_pair(true,m_priv->sendError(this, "session", tp));
441 pair<bool,void*> ShibTarget::doCheckAuthZ(void)
444 xmltooling::NDC ndc("doCheckAuthZ");
447 ExtTemplateParameters tp;
448 const char* procState = "Authorization Processing Error";
449 const char* targetURL = m_url.c_str();
453 throw ConfigurationException("System uninitialized, application did not supply request information.");
455 // Three settings dictate how to proceed.
456 pair<bool,const char*> authType = m_priv->m_settings.first->getString("authType");
457 pair<bool,bool> requireSession = m_priv->m_settings.first->getBool("requireSession");
458 pair<bool,const char*> requireSessionWith = m_priv->m_settings.first->getString("requireSessionWith");
460 // If no session is required AND the AuthType (an Apache-derived concept) isn't shibboleth,
461 // then we ignore this request and consider it unprotected. Apache might lie to us if
462 // ShibBasicHijack is on, but that's up to it.
463 if ((!requireSession.first || !requireSession.second) && !requireSessionWith.first &&
464 #ifdef HAVE_STRCASECMP
465 (!authType.first || strcasecmp(authType.second,"shibboleth")))
467 (!authType.first || _stricmp(authType.second,"shibboleth")))
469 return make_pair(true,returnDecline());
471 // Do we have an access control plugin?
472 if (m_priv->m_settings.second) {
474 if (!m_priv->m_cacheEntry) {
475 // No data yet, so we may need to try and get the session.
476 pair<string,const char*> shib_cookie=getCookieNameProps("_shibsession_");
477 const char *session_id = getCookie(shib_cookie.first);
479 if (session_id && *session_id) {
480 m_priv->m_cacheEntry=m_priv->m_conf->getSessionCache()->find(
483 m_remote_addr.c_str()
488 log(LogLevelError, "doCheckAuthZ: unable to obtain session information to pass to access control provider");
492 Locker acllock(m_priv->m_settings.second);
493 if (m_priv->m_settings.second->authorized(this,m_priv->m_cacheEntry)) {
494 // Let the caller decide how to proceed.
495 log(LogLevelDebug, "doCheckAuthZ: access control provider granted access");
496 return make_pair(false,(void*)NULL);
499 log(LogLevelWarn, "doCheckAuthZ: access control provider denied access");
501 tp.m_map["requestURL"] = targetURL;
502 return make_pair(true,m_priv->sendError(this, "access", tp));
506 return make_pair(true,returnDecline());
508 catch (exception& e) {
509 tp.m_map["errorType"] = procState;
510 tp.m_map["errorText"] = e.what();
512 tp.m_map["requestURL"] = m_url.substr(0,m_url.find('?'));
513 return make_pair(true,m_priv->sendError(this, "access", tp));
517 tp.m_map["errorType"] = procState;
518 tp.m_map["errorText"] = "Caught an unknown exception.";
520 tp.m_map["requestURL"] = m_url.substr(0,m_url.find('?'));
521 return make_pair(true,m_priv->sendError(this, "access", tp));
526 pair<bool,void*> ShibTarget::doExportAssertions(bool requireSession)
529 xmltooling::NDC ndc("doExportAssertions");
532 ExtTemplateParameters tp;
533 const char* procState = "Attribute Processing Error";
534 const char* targetURL = m_url.c_str();
538 throw ConfigurationException("System uninitialized, application did not supply request information.");
540 if (!m_priv->m_cacheEntry) {
541 // No data yet, so we need to get the session. This can only happen
542 // if the call to doCheckAuthn doesn't happen in the same object lifetime.
543 pair<string,const char*> shib_cookie=getCookieNameProps("_shibsession_");
544 const char *session_id = getCookie(shib_cookie.first);
546 if (session_id && *session_id) {
547 m_priv->m_cacheEntry=m_priv->m_conf->getSessionCache()->find(
550 m_remote_addr.c_str()
555 log(LogLevelError, "unable to obtain session information to export into request headers");
556 // If we have to have a session, then this is a fatal error.
563 if (!m_priv->m_cacheEntry) {
565 throw RetryableProfileException("Unable to obtain session information for request.");
567 return make_pair(false,(void*)NULL); // just bail silently
570 // Extract data from session.
571 pair<const char*,const SAMLSubject*> sub=m_priv->m_cacheEntry->getSubject(false,true);
572 pair<const char*,const SAMLResponse*> unfiltered=m_priv->m_cacheEntry->getTokens(true,false);
573 pair<const char*,const SAMLResponse*> filtered=m_priv->m_cacheEntry->getTokens(false,true);
575 // Maybe export the tokens.
576 pair<bool,bool> exp=m_priv->m_settings.first->getBool("exportAssertion");
577 if (exp.first && exp.second && unfiltered.first && *unfiltered.first) {
579 XMLByte* serialized =
580 Base64::encode(reinterpret_cast<XMLByte*>((char*)unfiltered.first), XMLString::stringLen(unfiltered.first), &outlen);
582 for (pos=serialized, pos2=serialized; *pos2; pos2++)
586 setHeader("Shib-Attributes", reinterpret_cast<char*>(serialized));
587 XMLString::release(&serialized);
590 // Export the SAML AuthnMethod and the origin site name, and possibly the NameIdentifier.
591 setHeader("Shib-Origin-Site", m_priv->m_cacheEntry->getProviderId());
592 setHeader("Shib-Identity-Provider", m_priv->m_cacheEntry->getProviderId());
593 setHeader("Shib-Authentication-Method", m_priv->m_cacheEntry->getAuthnContext());
595 // Get the AAP providers, which contain the attribute policy info.
596 Iterator<IAAP*> provs=m_priv->m_app->getAAPProviders();
599 while (provs.hasNext()) {
600 IAAP* aap=provs.next();
602 const XMLCh* format = sub.second->getNameIdentifier()->getFormat();
603 const IAttributeRule* rule=aap->lookup(format ? format : SAMLNameIdentifier::UNSPECIFIED);
604 if (rule && rule->getHeader()) {
605 auto_ptr_char form(format ? format : SAMLNameIdentifier::UNSPECIFIED);
606 auto_ptr_char nameid(sub.second->getNameIdentifier()->getName());
607 setHeader("Shib-NameIdentifier-Format", form.get());
608 if (!strcmp(rule->getHeader(),"REMOTE_USER"))
609 setRemoteUser(nameid.get());
611 setHeader(rule->getHeader(), nameid.get());
615 setHeader("Shib-Application-ID", m_priv->m_app->getId());
617 // Export the attributes.
618 Iterator<SAMLAssertion*> a_iter(filtered.second ? filtered.second->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());
647 for (; vals.hasNext(); it++) {
648 string value = vals.next();
649 for (string::size_type pos = value.find_first_of(";", string::size_type(0));
651 pos = value.find_first_of(";", pos)) {
652 value.insert(pos, "\\");
659 setHeader(rule->getHeader(), header);
666 return make_pair(false,(void*)NULL);
668 catch (XMLToolingException& e) {
669 tp.m_map["errorType"] = procState;
670 tp.m_map["errorText"] = e.what();
672 tp.m_map["requestURL"] = m_url.substr(0,m_url.find('?'));
673 return make_pair(true,m_priv->sendError(this, "rm", tp, &e));
677 tp.m_map["errorType"] = procState;
678 tp.m_map["errorText"] = "Caught an unknown exception.";
680 tp.m_map["requestURL"] = m_url.substr(0,m_url.find('?'));
681 return make_pair(true,m_priv->sendError(this, "rm", tp));
686 const char* ShibTarget::getRequestParameter(const char* param, size_t index) const
688 if (!m_priv->m_cgiParser)
689 m_priv->m_cgiParser=new CgiParse(this);
691 pair<CgiParse::walker,CgiParse::walker> bounds=m_priv->m_cgiParser->get_values(param);
693 // Advance to the right index.
694 while (index && bounds.first!=bounds.second) {
699 return (bounds.first==bounds.second) ? NULL : bounds.first->second;
702 const char* ShibTarget::getCookie(const string& name) const
704 if (m_priv->m_cookieMap.empty()) {
705 string cookies=getCookies();
707 string::size_type pos=0,cname,namelen,val,vallen;
708 while (pos !=string::npos && pos < cookies.length()) {
709 while (isspace(cookies[pos])) pos++;
711 pos=cookies.find_first_of("=",pos);
712 if (pos == string::npos)
716 if (pos==cookies.length())
719 pos=cookies.find_first_of(";",pos);
720 if (pos != string::npos) {
723 m_priv->m_cookieMap.insert(make_pair(cookies.substr(cname,namelen),cookies.substr(val,vallen)));
726 m_priv->m_cookieMap.insert(make_pair(cookies.substr(cname,namelen),cookies.substr(val)));
729 map<string,string>::const_iterator lookup=m_priv->m_cookieMap.find(name);
730 return (lookup==m_priv->m_cookieMap.end()) ? NULL : lookup->second.c_str();
733 pair<string,const char*> ShibTarget::getCookieNameProps(const char* prefix) const
735 static const char* defProps="; path=/";
737 const PropertySet* props=m_priv->m_app ? m_priv->m_app->getPropertySet("Sessions") : NULL;
739 pair<bool,const char*> p=props->getString("cookieProps");
742 pair<bool,const char*> p2=props->getString("cookieName");
744 return make_pair(string(prefix) + p2.second,p.second);
745 return make_pair(string(prefix) + m_priv->m_app->getHash(),p.second);
748 // Shouldn't happen, but just in case..
749 return pair<string,const char*>(prefix,defProps);
752 string ShibTarget::getHandlerURL(const char* resource) const
754 if (!m_priv->m_handlerURL.empty() && resource && !strcmp(getRequestURL(),resource))
755 return m_priv->m_handlerURL;
758 throw ConfigurationException("Internal error in ShibTargetPriv::getHandlerURL, missing application pointer.");
761 const char* handler=NULL;
762 const PropertySet* props=m_priv->m_app->getPropertySet("Sessions");
764 pair<bool,bool> p=props->getBool("handlerSSL");
767 pair<bool,const char*> p2=props->getString("handlerURL");
772 // Should never happen...
773 if (!handler || (*handler!='/' && strncmp(handler,"http:",5) && strncmp(handler,"https:",6)))
774 throw ConfigurationException(
775 "Invalid handlerURL property ($1) in Application ($2)",
776 xmltooling::params(2, handler ? handler : "null", m_priv->m_app->getId())
779 // The "handlerURL" property can be in one of three formats:
781 // 1) a full URI: http://host/foo/bar
782 // 2) a hostless URI: http:///foo/bar
783 // 3) a relative path: /foo/bar
785 // # Protocol Host Path
786 // 1 handler handler handler
787 // 2 handler resource handler
788 // 3 resource resource handler
790 // note: if ssl_only is true, make sure the protocol is https
792 const char* path = NULL;
794 // Decide whether to use the handler or the resource for the "protocol"
796 if (*handler != '/') {
804 // break apart the "protocol" string into protocol, host, and "the rest"
805 const char* colon=strchr(prot,':');
807 const char* slash=strchr(colon,'/');
811 // Compute the actual protocol and store in member.
813 m_priv->m_handlerURL.assign("https://");
815 m_priv->m_handlerURL.assign(prot, colon-prot);
817 // create the "host" from either the colon/slash or from the target string
818 // If prot == handler then we're in either #1 or #2, else #3.
819 // If slash == colon then we're in #2.
820 if (prot != handler || slash == colon) {
821 colon = strchr(resource, ':');
822 colon += 3; // Get past the ://
823 slash = strchr(colon, '/');
825 string host(colon, (slash ? slash-colon : strlen(colon)));
827 // Build the handler URL
828 m_priv->m_handlerURL+=host + path;
829 return m_priv->m_handlerURL;
832 void ShibTarget::log(ShibLogLevel level, const string& msg)
834 Category::getInstance("shibtarget.ShibTarget").log(
835 (level == LogLevelDebug ? Priority::DEBUG :
836 (level == LogLevelInfo ? Priority::INFO :
837 (level == LogLevelWarn ? Priority::WARN : Priority::ERROR))),
842 const IApplication* ShibTarget::getApplication() const
844 return m_priv->m_app;
847 const IConfig* ShibTarget::getConfig() const
849 return m_priv->m_conf;
852 void* ShibTarget::returnDecline(void)
857 void* ShibTarget::returnOK(void)
862 /*************************************************************************
863 * Shib Target Private implementation
866 ShibTargetPriv::ShibTargetPriv()
867 : m_app(NULL), m_mapper(NULL), m_conf(NULL), m_Config(NULL), m_cacheEntry(NULL), m_cgiParser(NULL) {}
869 ShibTargetPriv::~ShibTargetPriv()
872 m_cacheEntry->unlock();
891 void ShibTargetPriv::get_application(ShibTarget* st, const string& protocol, const string& hostname, int port, const string& uri)
896 // XXX: Do we need to keep conf and mapper locked while we hold m_app?
897 // TODO: No, should be able to hold the conf but release the mapper.
899 // We lock the configuration system for the duration.
900 m_conf=m_Config->getINI();
903 // Map request to application and content settings.
904 m_mapper=m_conf->getRequestMapper();
907 // Obtain the application settings from the parsed URL
908 m_settings = m_mapper->getSettings(st);
910 // Now find the application from the URL settings
911 pair<bool,const char*> application_id=m_settings.first->getString("applicationId");
912 m_app=m_conf->getApplication(application_id.second);
918 throw ConfigurationException("Unable to map request to application settings, check configuration.");
921 // Compute the full target URL
922 st->m_url = protocol + "://" + hostname;
923 if ((protocol == "http" && port != 80) || (protocol == "https" && port != 443)) {
924 ostringstream portstr;
926 st->m_url += ":" + portstr.str();
931 void* ShibTargetPriv::sendError(
932 ShibTarget* st, const char* page, ExtTemplateParameters& tp, const XMLToolingException* ex
935 ShibTarget::header_t hdrs[] = {
936 ShibTarget::header_t("Expires","01-Jan-1997 12:00:00 GMT"),
937 ShibTarget::header_t("Cache-Control","private,no-store,no-cache")
940 TemplateEngine* engine = XMLToolingConfig::getConfig().getTemplateEngine();
941 const PropertySet* props=m_app->getPropertySet("Errors");
943 pair<bool,const char*> p=props->getString(page);
945 ifstream infile(p.second);
947 tp.setPropertySet(props);
949 engine->run(infile, ostr, tp, ex);
950 return st->sendPage(ostr.str().c_str(), 200, "text/html", ArrayIterator<ShibTarget::header_t>(hdrs,2));
953 else if (!strcmp(page,"access"))
954 return st->sendPage("Access Denied", 403, "text/html", ArrayIterator<ShibTarget::header_t>(hdrs,2));
957 string errstr = string("sendError could not process error template (") + page + ") for application (";
958 errstr += m_app->getId();
960 st->log(ShibTarget::LogLevelError, errstr);
962 "Internal Server Error. Please contact the site administrator.", 500, "text/html", ArrayIterator<ShibTarget::header_t>(hdrs,2)
966 void ShibTargetPriv::clearHeaders(ShibTarget* st)
968 // Clear invariant stuff.
969 st->clearHeader("Shib-Origin-Site");
970 st->clearHeader("Shib-Identity-Provider");
971 st->clearHeader("Shib-Authentication-Method");
972 st->clearHeader("Shib-NameIdentifier-Format");
973 st->clearHeader("Shib-Attributes");
974 st->clearHeader("Shib-Application-ID");
976 // Clear out the list of mapped attributes
977 Iterator<IAAP*> provs=m_app->getAAPProviders();
978 while (provs.hasNext()) {
979 IAAP* aap=provs.next();
981 Iterator<const IAttributeRule*> rules=aap->getAttributeRules();
982 while (rules.hasNext()) {
983 const char* header=rules.next()->getHeader();
985 st->clearHeader(header);
990 /*************************************************************************
991 * CGI Parser implementation
994 CgiParse::CgiParse(const ShibTarget* st)
996 const char* pch=NULL;
997 if (!strcmp(st->getRequestMethod(),"POST"))
998 pch=st->getRequestBody();
1000 pch=st->getQueryString();
1001 size_t cl=pch ? strlen(pch) : 0;
1007 value=fmakeword('&',&cl,&pch);
1009 opensaml::SAMLConfig::getConfig().getURLEncoder()->decode(value);
1010 name=makeword(value,'=');
1011 kvp_map.insert(pair<string,char*>(name,value));
1016 CgiParse::~CgiParse()
1018 for (multimap<string,char*>::iterator i=kvp_map.begin(); i!=kvp_map.end(); i++)
1022 pair<CgiParse::walker,CgiParse::walker> CgiParse::get_values(const char* name) const
1024 return kvp_map.equal_range(name);
1027 /* Parsing routines modified from NCSA source. */
1028 char* CgiParse::makeword(char *line, char stop)
1031 char *word = (char *) malloc(sizeof(char) * (strlen(line) + 1));
1033 for(x=0;((line[x]) && (line[x] != stop));x++)
1042 line[y++] = line[x++];
1047 char* CgiParse::fmakeword(char stop, size_t *cl, const char** ppch)
1055 word = (char *) malloc(sizeof(char) * (wsize + 1));
1059 word[ll] = *((*ppch)++);
1064 word = (char *)realloc(word,sizeof(char)*(wsize+1));
1067 if((word[ll] == stop) || word[ll] == EOF || (!(*cl)))
1069 if(word[ll] != stop)
1078 void CgiParse::plustospace(char *str)
1083 if(str[x] == '+') str[x] = ' ';