2 * The Shibboleth License, Version 1.
4 * University Corporation for Advanced Internet Development, Inc.
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions are met:
11 * Redistributions of source code must retain the above copyright notice, this
12 * list of conditions and the following disclaimer.
14 * Redistributions in binary form must reproduce the above copyright notice,
15 * this list of conditions and the following disclaimer in the documentation
16 * and/or other materials provided with the distribution, if any, must include
17 * the following acknowledgment: "This product includes software developed by
18 * the University Corporation for Advanced Internet Development
19 * <http://www.ucaid.edu>Internet2 Project. Alternately, this acknowledegement
20 * may appear in the software itself, if and wherever such third-party
21 * acknowledgments normally appear.
23 * Neither the name of Shibboleth nor the names of its contributors, nor
24 * Internet2, nor the University Corporation for Advanced Internet Development,
25 * Inc., nor UCAID may be used to endorse or promote products derived from this
26 * software without specific prior written permission. For written permission,
27 * please contact shibboleth@shibboleth.org
29 * Products derived from this software may not be called Shibboleth, Internet2,
30 * UCAID, or the University Corporation for Advanced Internet Development, nor
31 * may Shibboleth appear in their name, without prior written permission of the
32 * University Corporation for Advanced Internet Development.
35 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
36 * AND WITH ALL FAULTS. ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
37 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
38 * PARTICULAR PURPOSE, AND NON-INFRINGEMENT ARE DISCLAIMED AND THE ENTIRE RISK
39 * OF SATISFACTORY QUALITY, PERFORMANCE, ACCURACY, AND EFFORT IS WITH LICENSEE.
40 * IN NO EVENT SHALL THE COPYRIGHT OWNER, CONTRIBUTORS OR THE UNIVERSITY
41 * CORPORATION FOR ADVANCED INTERNET DEVELOPMENT, INC. BE LIABLE FOR ANY DIRECT,
42 * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
43 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
44 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
45 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
46 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
47 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
51 * shib-target.cpp -- The ShibTarget class, a superclass for general
54 * Created by: Derek Atkins <derek@ihtfp.com>
69 #include <shib/shib-threads.h>
70 #include <log4cpp/Category.hh>
71 #include <log4cpp/PropertyConfigurator.hh>
72 #include <xercesc/util/Base64.hpp>
73 #include <xercesc/util/regx/RegularExpression.hpp>
75 #ifndef HAVE_STRCASECMP
76 # define strcasecmp stricmp
81 using namespace shibboleth;
82 using namespace shibtarget;
83 using namespace log4cpp;
85 namespace shibtarget {
89 CgiParse(const char* data, unsigned int len);
91 const char* get_value(const char* name) const;
93 static char x2c(char *what);
94 static void url_decode(char *url);
95 static string url_encode(const char* s);
97 char * fmakeword(char stop, unsigned int *cl, const char** ppch);
98 char * makeword(char *line, char stop);
99 void plustospace(char *str);
101 map<string,char*> kvp_map;
111 void get_application(ShibTarget* st, const string& protocol, const string& hostname, int port, const string& uri);
112 const char* getCookie(ShibTarget* st, const string& name) const;
113 pair<string,const char*> getCookieNameProps(const char* prefix) const;
114 const char* getHandlerURL(const char* resource) const;
115 void* sendError(ShibTarget* st, const char* page, ShibMLP &mlp);
117 // Handlers do the real Shibboleth work
118 pair<bool,void*> doSessionInitiator(ShibTarget* st, const IPropertySet* handler, bool isHandler=true) const;
119 pair<bool,void*> doAssertionConsumer(ShibTarget* st, const IPropertySet* handler) const;
120 pair<bool,void*> doLogout(ShibTarget* st, const IPropertySet* handler) const;
122 // And the binding/profile handlers do the low level packing and unpacking.
123 pair<bool,void*> ShibAuthnRequest(
125 const IPropertySet* shire,
128 const char* providerId
132 friend class ShibTarget;
133 IRequestMapper::Settings m_settings;
134 const IApplication *m_app;
135 mutable string m_handlerURL;
136 mutable map<string,string> m_cookieMap;
138 ShibProfile m_sso_profile;
139 string m_provider_id;
140 SAMLAuthenticationStatement* m_sso_statement;
141 SAMLResponse* m_pre_response;
142 SAMLResponse* m_post_response;
144 ShibTargetConfig* m_Config;
147 IRequestMapper* m_mapper;
152 /*************************************************************************
153 * Shib Target implementation
156 ShibTarget::ShibTarget(void) : m_priv(NULL)
158 m_priv = new ShibTargetPriv();
161 ShibTarget::ShibTarget(const IApplication *app) : m_priv(NULL)
163 m_priv = new ShibTargetPriv();
167 ShibTarget::~ShibTarget(void)
169 if (m_priv) delete m_priv;
172 void ShibTarget::init(
173 const char* protocol,
174 const char* hostname,
177 const char* content_type,
178 const char* remote_addr,
183 saml::NDC ndc("init");
187 throw SAMLException("Request initialization occurred twice!");
189 if (method) m_method = method;
190 if (protocol) m_protocol = protocol;
191 if (hostname) m_hostname = hostname;
192 if (uri) m_uri = uri;
193 if (content_type) m_content_type = content_type;
194 if (remote_addr) m_remote_addr = remote_addr;
196 m_priv->m_Config = &ShibTargetConfig::getConfig();
197 m_priv->get_application(this, protocol, hostname, port, uri);
201 // These functions implement the server-agnostic shibboleth engine
202 // The web server modules implement a subclass and then call into
203 // these methods once they instantiate their request object.
205 pair<bool,void*> ShibTarget::doCheckAuthN(bool requireSessionFlag, bool handler)
208 saml::NDC ndc("doCheckAuthN");
211 const char* procState = "Request Processing Error";
212 const char* targetURL = m_url.c_str();
217 throw ConfigurationException("System uninitialized, application did not supply request information.");
219 const char* handlerURL = m_priv->getHandlerURL(targetURL);
221 throw ConfigurationException("Cannot determine handler from resource URL, check configuration.");
223 // If the request URL contains the handler base URL for this application, either dispatch
224 // directly (mainly Apache 2.0) or just pass back control.
225 if (strstr(targetURL,handlerURL)) {
229 return pair<bool,void*>(true, returnOK());
232 string auth_type = getAuthType();
233 if (strcasecmp(auth_type.c_str(),"shibboleth"))
234 return pair<bool,void*>(true,returnDecline());
236 pair<bool,bool> requireSession = m_priv->m_settings.first->getBool("requireSession");
237 if (!requireSession.first || !requireSession.second) {
238 // Web server might override.
239 if (requireSessionFlag)
240 requireSession.second=true;
243 pair<string,const char*> shib_cookie = m_priv->getCookieNameProps("_shibsession_");
244 const char* session_id = m_priv->getCookie(this,shib_cookie.first);
245 if (!session_id || !*session_id) {
246 // No session. Maybe that's acceptable?
247 if (!requireSession.second)
248 return pair<bool,void*>(true,returnOK());
250 // No cookie, but we require a session. Initiate a new session using the default method.
251 procState = "Session Initiator Error";
252 const IPropertySet* initiator=m_priv->m_app->getDefaultSessionInitiator();
253 return m_priv->doSessionInitiator(this, initiator ? initiator : m_priv->m_app->getPropertySet("Sessions"), false);
256 procState = "Session Processing Error";
258 // Localized exception throw if the session isn't valid.
261 m_remote_addr.c_str(),
262 m_priv->m_sso_profile,
263 m_priv->m_provider_id,
264 &m_priv->m_sso_statement,
265 &m_priv->m_pre_response,
266 &m_priv->m_post_response
269 catch (SAMLException& e) {
270 log(LogLevelError, string("session processing failed: ") + e.what());
272 // If no session is required, bail now.
273 if (!requireSession.second)
274 // Has to be OK because DECLINED will just cause Apache
275 // to fail when it can't locate anything to process the
276 // AuthType. No session plus requireSession false means
277 // do not authenticate the user at this time.
278 return pair<bool,void*>(true, returnOK());
280 // Try and cast down. This should throw an exception if it fails.
281 bool retryable=false;
283 RetryableProfileException& trycast=dynamic_cast<RetryableProfileException&>(e);
289 // Session is invalid but we can retry -- initiate a new session.
290 procState = "Session Initiator Error";
291 const IPropertySet* initiator=m_priv->m_app->getDefaultSessionInitiator();
292 return m_priv->doSessionInitiator(this, initiator ? initiator : m_priv->m_app->getPropertySet("Sessions"), false);
294 throw; // send it to the outer handler
297 // We're done. Everything is okay. Nothing to report. Nothing to do..
298 // Let the caller decide how to proceed.
299 log(LogLevelDebug, "doCheckAuthN succeeded");
300 return pair<bool,void*>(false,NULL);
302 catch (SAMLException& e) {
307 mlp.insert("errorText", "Caught an unknown exception.");
311 // If we get here then we've got an error.
312 mlp.insert("errorType", procState);
314 mlp.insert("requestURL", m_url.substr(0,m_url.find('?')));
316 return pair<bool,void*>(true,m_priv->sendError(this,"session", mlp));
319 pair<bool,void*> ShibTarget::doHandler(void)
322 saml::NDC ndc("doHandler");
325 const char* procState = "Shibboleth Handler Error";
326 const char* targetURL = m_url.c_str();
331 throw ConfigurationException("System uninitialized, application did not supply request information.");
333 const char* handlerURL = m_priv->getHandlerURL(targetURL);
335 throw ConfigurationException("Cannot determine handler from resource URL, check configuration.");
337 // Make sure we only process handler requests.
338 if (!strstr(targetURL,handlerURL))
339 return pair<bool,void*>(true, returnDecline());
341 const IPropertySet* sessionProps=m_priv->m_app->getPropertySet("Sessions");
343 throw ConfigurationException("Unable to map request to application session settings, check configuration.");
345 // Process incoming request.
346 pair<bool,bool> handlerSSL=sessionProps->getBool("handlerSSL");
348 // Make sure this is SSL, if it should be
349 if ((!handlerSSL.first || handlerSSL.second) && m_protocol != "https")
350 throw FatalProfileException("Blocked non-SSL access to Shibboleth handler.");
352 // We dispatch based on our path info. We know the request URL begins with or equals the handler URL,
353 // so the path info is the next character (or null).
354 const IPropertySet* handler=m_priv->m_app->getHandler(targetURL + strlen(handlerURL));
356 if (saml::XML::isElementNamed(handler->getElement(),shibtarget::XML::SAML2META_NS,SHIBT_L(AssertionConsumerService))) {
357 procState = "Session Creation Error";
358 return m_priv->doAssertionConsumer(this,handler);
360 else if (saml::XML::isElementNamed(handler->getElement(),ShibTargetConfig::SHIBTARGET_NS,SHIBT_L(SessionInitiator))) {
361 procState = "Session Initiator Error";
362 return m_priv->doSessionInitiator(this,handler);
364 else if (saml::XML::isElementNamed(handler->getElement(),shibtarget::XML::SAML2META_NS,SHIBT_L(SingleLogoutService))) {
365 procState = "Session Termination Error";
366 return m_priv->doLogout(this,handler);
369 throw ConfigurationException("Endpoint is mapped to unrecognized handler element.");
372 if (strlen(targetURL)>strlen(handlerURL) && targetURL[strlen(handlerURL)]!='?')
373 throw SAMLException("Shibboleth handler invoked at an unconfigured location.");
375 // This is a legacy direct execution of the handler (the old shireURL).
376 // If this is a GET, we see if it's a lazy session request, otherwise
377 // assume it's a SAML 1.x POST profile response and process it.
378 if (!strcasecmp(m_method.c_str(), "GET")) {
379 procState = "Session Initiator Error";
380 return m_priv->doSessionInitiator(this, sessionProps);
383 procState = "Session Creation Error";
384 return m_priv->doAssertionConsumer(this, sessionProps);
386 catch (MetadataException& e) {
388 // See if a metadata error page is installed.
389 const IPropertySet* props=m_priv->m_app->getPropertySet("Errors");
391 pair<bool,const char*> p=props->getString("metadata");
393 mlp.insert("errorType", procState);
395 mlp.insert("requestURL", targetURL);
396 return make_pair(true,m_priv->sendError(this,"metadata", mlp));
400 catch (SAMLException& e) {
405 mlp.insert("errorText", "Caught an unknown exception.");
409 // If we get here then we've got an error.
410 mlp.insert("errorType", procState);
413 mlp.insert("requestURL", m_url.substr(0,m_url.find('?')));
415 return make_pair(true,m_priv->sendError(this,"session", mlp));
418 pair<bool,void*> ShibTarget::doCheckAuthZ(void)
421 saml::NDC ndc("doCheckAuthZ");
425 const char* procState = "Authorization Processing Error";
426 const char* targetURL = m_url.c_str();
430 throw ConfigurationException("System uninitialized, application did not supply request information.");
432 // Do we have an access control plugin?
433 if (m_priv->m_settings.second) {
434 Locker acllock(m_priv->m_settings.second);
435 if (!m_priv->m_settings.second->authorized(m_priv->m_provider_id.c_str(), m_priv->m_sso_statement, m_priv->m_post_response, this)) {
436 log(LogLevelWarn, "doCheckAuthZ() access control provider denied access");
438 mlp.insert("requestURL", targetURL);
439 return make_pair(true,m_priv->sendError(this, "access", mlp));
443 // Perform HTAccess Checks
444 auto_ptr<HTAccessInfo> ht(getAccessInfo());
446 // No Info means OK. Just return
448 return pair<bool,void*>(false, NULL);
450 vector<bool> auth_OK(ht->elements.size(), false);
451 bool method_restricted=false;
452 string remote_user = getRemoteUser();
456 if (!ht->requireAll) { \
457 return pair<bool,void*>(false, NULL); \
463 for (int x = 0; x < ht->elements.size(); x++) {
465 HTAccessInfo::RequireLine *line = ht->elements[x];
466 if (! line->use_line)
468 method_restricted = true;
470 const char *w = line->tokens[0].c_str();
472 if (!strcasecmp(w,"Shibboleth")) {
473 // This is a dummy rule needed because Apache conflates authn and authz.
474 // Without some require rule, AuthType is ignored and no check_user hooks run.
477 else if (!strcmp(w,"valid-user")) {
478 log(LogLevelDebug, "doCheckAuthZ accepting valid-user");
481 else if (!strcmp(w,"user") && !remote_user.empty()) {
483 for (int i = 1; i < line->tokens.size(); i++) {
484 w = line->tokens[i].c_str();
492 // To do regex matching, we have to convert from UTF-8.
493 auto_ptr<XMLCh> trans(fromUTF8(w));
494 RegularExpression re(trans.get());
495 auto_ptr<XMLCh> trans2(fromUTF8(remote_user.c_str()));
496 if (re.matches(trans2.get())) {
497 log(LogLevelDebug, string("doCheckAuthZ accepting user: ") + w);
501 catch (XMLException& ex) {
502 auto_ptr_char tmp(ex.getMessage());
503 log(LogLevelError, string("doCheckAuthZ caught exception while parsing regular expression (")
504 + w + "): " + tmp.get());
507 else if (!strcmp(remote_user.c_str(), w)) {
508 log(LogLevelDebug, string("doCheckAuthZ accepting user: ") + w);
513 else if (!strcmp(w,"group")) {
514 auto_ptr<HTGroupTable> grpstatus(getGroupTable(remote_user));
515 if (!grpstatus.get()) {
516 return pair<bool,void*>(true, returnDecline());
519 for (int i = 1; i < line->tokens.size(); i++) {
520 w = line->tokens[i].c_str();
521 if (grpstatus->lookup(w)) {
522 log(LogLevelDebug, string("doCheckAuthZ accepting group: ") + w);
528 Iterator<IAAP*> provs = m_priv->m_app->getAAPProviders();
529 AAP wrapper(provs, w);
530 if (wrapper.fail()) {
531 log(LogLevelWarn, string("doCheckAuthZ didn't recognize require rule: ") + w);
536 string vals = getHeader(wrapper->getHeader());
537 for (int i = 1; i < line->tokens.size() && !vals.empty(); i++) {
538 w = line->tokens[i].c_str();
545 auto_ptr<RegularExpression> re;
548 auto_ptr<XMLCh> trans(fromUTF8(w));
549 auto_ptr<RegularExpression> temp(new RegularExpression(trans.get()));
553 string vals_str(vals);
555 for (int i = 0; i < vals_str.length(); i++) {
556 if (vals_str.at(i) == ';') {
558 log(LogLevelError, string("doCheckAuthZ invalid header encoding") +
559 vals + ": starts with a semicolon");
560 throw SAMLException("Invalid information supplied to authorization module.");
563 if (vals_str.at(i-1) == '\\') {
564 vals_str.erase(i-1, 1);
569 string val = vals_str.substr(j, i-j);
572 auto_ptr<XMLCh> trans(fromUTF8(val.c_str()));
573 if (re->matches(trans.get())) {
574 log(LogLevelDebug, string("doCheckAuthZ expecting ") + w +
575 ", got " + val + ": authorization granted");
579 else if ((wrapper->getCaseSensitive() && val==w) ||
580 (!wrapper->getCaseSensitive() && !strcasecmp(val.c_str(),w))) {
581 log(LogLevelDebug, string("doCheckAuthZ expecting ") + w +
582 ", got " + val + ": authorization granted.");
586 log(LogLevelDebug, string("doCheckAuthZ expecting ") + w +
587 ", got " + val + ": authoritzation not granted.");
592 string val = vals_str.substr(j, vals_str.length()-j);
594 auto_ptr<XMLCh> trans(fromUTF8(val.c_str()));
595 if (re->matches(trans.get())) {
596 log(LogLevelDebug, string("doCheckAuthZ expecting ") + w +
597 ", got " + val + ": authorization granted.");
601 else if ((wrapper->getCaseSensitive() && val==w) ||
602 (!wrapper->getCaseSensitive() && !strcasecmp(val.c_str(),w))) {
603 log(LogLevelDebug, string("doCheckAuthZ expecting ") + w +
604 ", got " + val + ": authorization granted");
608 log(LogLevelDebug, string("doCheckAuthZ expecting ") + w +
609 ", got " + val + ": authorization not granted");
612 catch (XMLException& ex) {
613 auto_ptr_char tmp(ex.getMessage());
614 log(LogLevelError, string("doCheckAuthZ caught exception while parsing regular expression (")
615 + w + "): " + tmp.get());
622 // check if all require directives are true
623 bool auth_all_OK = true;
624 for (int i = 0; i < ht->elements.size(); i++) {
625 auth_all_OK &= auth_OK[i];
628 if (auth_all_OK || !method_restricted)
629 return pair<bool,void*>(false, NULL);
631 // If we get here there's an access error, so just fall through
633 catch (SAMLException& e) {
638 mlp.insert("errorText", "Caught an unknown exception.");
642 // If we get here then we've got an error.
643 mlp.insert("errorType", procState);
646 mlp.insert("requestURL", m_url.substr(0,m_url.find('?')));
648 return make_pair(true,m_priv->sendError(this, "access", mlp));
651 pair<bool,void*> ShibTarget::doExportAssertions(bool exportAssertion)
654 saml::NDC ndc("doExportAssertions");
658 const char* procState = "Attribute Processing Error";
659 const char* targetURL = m_url.c_str();
663 throw ConfigurationException("System uninitialized, application did not supply request information.");
665 pair<string,const char*> shib_cookie=m_priv->getCookieNameProps("_shibsession_");
666 const char *session_id = m_priv->getCookie(this,shib_cookie.first);
668 if (!m_priv->m_sso_statement) {
669 // No data yet, so we need to get the session. This can only happen
670 // if the call to doCheckAuthn doesn't happen in the same object lifetime.
673 m_remote_addr.c_str(),
674 m_priv->m_sso_profile,
675 m_priv->m_provider_id,
676 &m_priv->m_sso_statement,
677 &m_priv->m_pre_response,
678 &m_priv->m_post_response
682 // Get the AAP providers, which contain the attribute policy info.
683 Iterator<IAAP*> provs=m_priv->m_app->getAAPProviders();
685 // Clear out the list of mapped attributes
686 while (provs.hasNext()) {
687 IAAP* aap=provs.next();
689 Iterator<const IAttributeRule*> rules=aap->getAttributeRules();
690 while (rules.hasNext()) {
691 const char* header=rules.next()->getHeader();
697 // Maybe export the first assertion.
698 clearHeader("Shib-Attributes");
699 pair<bool,bool> exp=m_priv->m_settings.first->getBool("exportAssertion");
700 if (!exp.first || !exp.second)
703 if (exp.second && m_priv->m_pre_response) {
705 os << *(m_priv->m_pre_response);
707 XMLByte* serialized = Base64::encode(reinterpret_cast<XMLByte*>((char*)os.str().c_str()), os.str().length(), &outlen);
709 for (pos=serialized, pos2=serialized; *pos2; pos2++)
713 setHeader("Shib-Attributes", reinterpret_cast<char*>(serialized));
714 XMLString::release(&serialized);
717 // Export the SAML AuthnMethod and the origin site name, and possibly the NameIdentifier.
718 clearHeader("Shib-Origin-Site");
719 clearHeader("Shib-Identity-Provider");
720 clearHeader("Shib-Authentication-Method");
721 clearHeader("Shib-NameIdentifier-Format");
722 setHeader("Shib-Origin-Site", m_priv->m_provider_id.c_str());
723 setHeader("Shib-Identity-Provider", m_priv->m_provider_id.c_str());
724 auto_ptr_char am(m_priv->m_sso_statement->getAuthMethod());
725 setHeader("Shib-Authentication-Method", am.get());
729 while (provs.hasNext()) {
730 IAAP* aap=provs.next();
732 const IAttributeRule* rule=aap->lookup(m_priv->m_sso_statement->getSubject()->getNameIdentifier()->getFormat());
733 if (rule && rule->getHeader()) {
734 auto_ptr_char form(m_priv->m_sso_statement->getSubject()->getNameIdentifier()->getFormat());
735 auto_ptr_char nameid(m_priv->m_sso_statement->getSubject()->getNameIdentifier()->getName());
736 setHeader("Shib-NameIdentifier-Format", form.get());
737 if (!strcmp(rule->getHeader(),"REMOTE_USER"))
738 setRemoteUser(nameid.get());
740 setHeader(rule->getHeader(), nameid.get());
744 clearHeader("Shib-Application-ID");
745 setHeader("Shib-Application-ID", m_priv->m_app->getId());
747 // Export the attributes.
748 Iterator<SAMLAssertion*> a_iter(m_priv->m_post_response ? m_priv->m_post_response->getAssertions() : EMPTY(SAMLAssertion*));
749 while (a_iter.hasNext()) {
750 SAMLAssertion* assert=a_iter.next();
751 Iterator<SAMLStatement*> statements=assert->getStatements();
752 while (statements.hasNext()) {
753 SAMLAttributeStatement* astate=dynamic_cast<SAMLAttributeStatement*>(statements.next());
756 Iterator<SAMLAttribute*> attrs=astate->getAttributes();
757 while (attrs.hasNext()) {
758 SAMLAttribute* attr=attrs.next();
760 // Are we supposed to export it?
762 while (provs.hasNext()) {
763 IAAP* aap=provs.next();
765 const IAttributeRule* rule=aap->lookup(attr->getName(),attr->getNamespace());
766 if (!rule || !rule->getHeader())
769 Iterator<string> vals=attr->getSingleByteValues();
770 if (!strcmp(rule->getHeader(),"REMOTE_USER") && vals.hasNext())
771 setRemoteUser(vals.next());
774 string header = getHeader(rule->getHeader());
777 for (; vals.hasNext(); it++) {
778 string value = vals.next();
779 for (string::size_type pos = value.find_first_of(";", string::size_type(0));
781 pos = value.find_first_of(";", pos)) {
782 value.insert(pos, "\\");
789 setHeader(rule->getHeader(), header);
796 return pair<bool,void*>(false,NULL);
798 catch (SAMLException& e) {
803 mlp.insert("errorText", "Caught an unknown exception.");
807 // If we get here then we've got an error.
808 mlp.insert("errorType", procState);
811 mlp.insert("requestURL", m_url.substr(0,m_url.find('?')));
813 return make_pair(true,m_priv->sendError(this, "rm", mlp));
817 void ShibTarget::sessionNew(
818 int supported_profiles,
819 const string& recipient,
828 saml::NDC ndc("sessionNew");
830 Category& log = Category::getInstance("shibtarget.ShibTarget");
832 if (!packet || !*packet) {
833 log.error("missing profile response");
834 throw FatalProfileException("Profile response missing.");
838 log.error("missing client address");
839 throw FatalProfileException("Invalid client address.");
842 if (supported_profiles <= 0) {
843 log.error("no profile support indicated");
844 throw FatalProfileException("No profile support indicated.");
847 shibrpc_new_session_args_2 arg;
848 arg.recipient = (char*)recipient.c_str();
849 arg.application_id = (char*)m_priv->m_app->getId();
850 arg.packet = (char*)packet;
851 arg.client_addr = (char*)ip;
852 arg.supported_profiles = supported_profiles;
854 log.info("create session for user at (%s) for application (%s)", ip, arg.application_id);
856 shibrpc_new_session_ret_2 ret;
857 memset(&ret, 0, sizeof(ret));
859 // Loop on the RPC in case we lost contact the first time through
864 clnt = rpc->connect();
865 clnt_stat status = shibrpc_new_session_2 (&arg, &ret, clnt);
866 if (status != RPC_SUCCESS) {
867 // FAILED. Release, disconnect, and retry
868 log.error("RPC Failure: %p (%p) (%d): %s", this, clnt, status, clnt_spcreateerror("shibrpc_new_session_2"));
873 throw ListenerException("Failure passing session setup information to listener.");
876 // SUCCESS. Pool and continue
881 if (ret.status && *ret.status)
882 log.debug("RPC completed with exception: %s", ret.status);
884 log.debug("RPC completed successfully");
886 SAMLException* except=NULL;
887 if (ret.status && *ret.status) {
888 // Reconstitute exception object.
890 istringstream estr(ret.status);
891 except=SAMLException::getInstance(estr);
893 catch (SAMLException& e) {
894 log.error("caught SAML Exception while building the SAMLException: %s", e.what());
895 log.error("XML was: %s", ret.status);
896 clnt_freeres(clnt, (xdrproc_t)xdr_shibrpc_new_session_ret_2, (caddr_t)&ret);
898 throw FatalProfileException("An unrecoverable error occurred while creating your session.");
902 log.error("caught unknown exception building SAMLException");
903 log.error("XML was: %s", ret.status);
904 clnt_freeres(clnt, (xdrproc_t)xdr_shibrpc_new_session_ret_2, (caddr_t)&ret);
911 log.debug("new session from IdP (%s) with key (%s)", ret.provider_id, ret.cookie);
913 provider_id = ret.provider_id;
918 clnt_freeres(clnt, (xdrproc_t)xdr_shibrpc_new_session_ret_2, (caddr_t)&ret);
921 auto_ptr<SAMLException> wrapper(except);
926 void ShibTarget::sessionGet(
929 ShibProfile& profile,
931 SAMLAuthenticationStatement** auth_statement,
932 SAMLResponse** attr_response_pre,
933 SAMLResponse** attr_response_post
937 saml::NDC ndc("sessionGet");
939 Category& log = Category::getInstance("shibtarget.ShibTarget");
941 if (!cookie || !*cookie) {
942 log.error("no session key provided");
943 throw InvalidSessionException("No session key was provided.");
945 else if (strchr(cookie,'=')) {
946 log.error("cookie value not extracted successfully, probably overlapping cookies across domains");
947 throw InvalidSessionException("The session key wasn't extracted successfully from the browser cookie.");
951 log.error("invalid client Address");
952 throw FatalProfileException("Invalid client address.");
955 log.info("getting session for client at (%s)", ip);
956 log.debug("session cookie (%s)", cookie);
958 shibrpc_get_session_args_2 arg;
959 arg.cookie = (char*)cookie;
960 arg.client_addr = (char*)ip;
961 arg.application_id = (char*)m_priv->m_app->getId();
963 shibrpc_get_session_ret_2 ret;
964 memset (&ret, 0, sizeof(ret));
966 // Loop on the RPC in case we lost contact the first time through
971 clnt = rpc->connect();
972 clnt_stat status = shibrpc_get_session_2(&arg, &ret, clnt);
973 if (status != RPC_SUCCESS) {
974 // FAILED. Release, disconnect, and try again...
975 log.error("RPC Failure: %p (%p) (%d) %s", this, clnt, status, clnt_spcreateerror("shibrpc_get_session_2"));
980 throw ListenerException("Failure requesting session information from listener.");
988 if (ret.status && *ret.status)
989 log.debug("RPC completed with exception: %s", ret.status);
991 log.debug("RPC completed successfully");
993 SAMLException* except=NULL;
994 if (ret.status && *ret.status) {
995 // Reconstitute exception object.
997 istringstream estr(ret.status);
998 except=SAMLException::getInstance(estr);
1000 catch (SAMLException& e) {
1001 log.error("caught SAML Exception while building the SAMLException: %s", e.what());
1002 log.error("XML was: %s", ret.status);
1003 clnt_freeres(clnt, (xdrproc_t)xdr_shibrpc_get_session_ret_2, (caddr_t)&ret);
1005 throw FatalProfileException("An unrecoverable error occurred while accessing your session.");
1008 log.error("caught unknown exception building SAMLException");
1009 log.error("XML was: %s", ret.status);
1010 clnt_freeres(clnt, (xdrproc_t)xdr_shibrpc_get_session_ret_2, (caddr_t)&ret);
1017 profile = ret.profile;
1018 provider_id = ret.provider_id;
1020 // return the Authentication Statement
1021 if (auth_statement) {
1022 istringstream authstream(ret.auth_statement);
1023 log.debugStream() << "trying to decode authentication statement: "
1024 << ret.auth_statement << CategoryStream::ENDLINE;
1025 *auth_statement = new SAMLAuthenticationStatement(authstream);
1028 // return the unfiltered Response
1029 if (attr_response_pre) {
1030 istringstream prestream(ret.attr_response_pre);
1031 log.debugStream() << "trying to decode unfiltered attribute response: "
1032 << ret.attr_response_pre << CategoryStream::ENDLINE;
1033 *attr_response_pre = new SAMLResponse(prestream);
1036 // return the filtered Response
1037 if (attr_response_post) {
1038 istringstream poststream(ret.attr_response_post);
1039 log.debugStream() << "trying to decode filtered attribute response: "
1040 << ret.attr_response_post << CategoryStream::ENDLINE;
1041 *attr_response_post = new SAMLResponse(poststream);
1044 catch (SAMLException& e) {
1045 log.error("caught SAML exception while reconstituting session objects: %s", e.what());
1046 clnt_freeres (clnt, (xdrproc_t)xdr_shibrpc_get_session_ret_2, (caddr_t)&ret);
1052 log.error("caught unknown exception while reconstituting session objects");
1053 clnt_freeres (clnt, (xdrproc_t)xdr_shibrpc_get_session_ret_2, (caddr_t)&ret);
1060 clnt_freeres (clnt, (xdrproc_t)xdr_shibrpc_get_session_ret_2, (caddr_t)&ret);
1063 auto_ptr<SAMLException> wrapper(except);
1068 void ShibTarget::sessionEnd(const char* cookie) const
1071 saml::NDC ndc("sessionEnd");
1073 Category& log = Category::getInstance("shibtarget.ShibTarget");
1075 if (!cookie || !*cookie) {
1076 log.error("no session key provided");
1077 throw InvalidSessionException("No session key was provided.");
1079 else if (strchr(cookie,'=')) {
1080 log.error("cookie value not extracted successfully, probably overlapping cookies across domains");
1081 throw InvalidSessionException("The session key wasn't extracted successfully from the browser cookie.");
1084 log.debug("ending session with cookie (%s)", cookie);
1086 shibrpc_end_session_args_2 arg;
1087 arg.cookie = (char*)cookie;
1089 shibrpc_end_session_ret_2 ret;
1090 memset (&ret, 0, sizeof(ret));
1092 // Loop on the RPC in case we lost contact the first time through
1097 clnt = rpc->connect();
1098 clnt_stat status = shibrpc_end_session_2(&arg, &ret, clnt);
1099 if (status != RPC_SUCCESS) {
1100 // FAILED. Release, disconnect, and try again...
1101 log.error("RPC Failure: %p (%p) (%d) %s", this, clnt, status, clnt_spcreateerror("shibrpc_end_session_2"));
1106 throw ListenerException("Failure ending session through listener.");
1114 if (ret.status && *ret.status)
1115 log.debug("RPC completed with exception: %s", ret.status);
1117 log.debug("RPC completed successfully");
1119 SAMLException* except=NULL;
1120 if (ret.status && *ret.status) {
1121 // Reconstitute exception object.
1123 istringstream estr(ret.status);
1124 except=SAMLException::getInstance(estr);
1126 catch (SAMLException& e) {
1127 log.error("caught SAML Exception while building the SAMLException: %s", e.what());
1128 log.error("XML was: %s", ret.status);
1129 clnt_freeres(clnt, (xdrproc_t)xdr_shibrpc_end_session_ret_2, (caddr_t)&ret);
1131 throw FatalProfileException("An unrecoverable error occurred while accessing your session.");
1134 log.error("caught unknown exception building SAMLException");
1135 log.error("XML was: %s", ret.status);
1136 clnt_freeres(clnt, (xdrproc_t)xdr_shibrpc_end_session_ret_2, (caddr_t)&ret);
1142 clnt_freeres (clnt, (xdrproc_t)xdr_shibrpc_end_session_ret_2, (caddr_t)&ret);
1145 auto_ptr<SAMLException> wrapper(except);
1150 /*************************************************************************
1151 * Shib Target Private implementation
1154 ShibTargetPriv::ShibTargetPriv() : m_app(NULL), m_mapper(NULL), m_conf(NULL), m_Config(NULL),
1155 m_sso_profile(PROFILE_UNSPECIFIED), m_sso_statement(NULL), m_pre_response(NULL), m_post_response(NULL) {}
1157 ShibTargetPriv::~ShibTargetPriv()
1159 delete m_sso_statement;
1160 m_sso_statement = NULL;
1162 delete m_pre_response;
1163 m_pre_response = NULL;
1165 delete m_post_response;
1166 m_post_response = NULL;
1180 void ShibTargetPriv::get_application(ShibTarget* st, const string& protocol, const string& hostname, int port, const string& uri)
1185 // XXX: Do we need to keep conf and mapper locked while we hold m_app?
1186 // TODO: No, should be able to hold the conf but release the mapper.
1188 // We lock the configuration system for the duration.
1189 m_conf=m_Config->getINI();
1192 // Map request to application and content settings.
1193 m_mapper=m_conf->getRequestMapper();
1196 // Obtain the application settings from the parsed URL
1197 m_settings = m_mapper->getSettingsFromParsedURL(protocol.c_str(),hostname.c_str(),port,uri.c_str(),st);
1199 // Now find the application from the URL settings
1200 pair<bool,const char*> application_id=m_settings.first->getString("applicationId");
1201 const IApplication* application=m_conf->getApplication(application_id.second);
1207 throw SAMLException("Unable to map request to application settings, check configuration.");
1210 // Store the application for later use
1211 m_app = application;
1213 // Compute the target URL
1214 st->m_url = protocol + "://" + hostname;
1215 if ((protocol == "http" && port != 80) || (protocol == "https" && port != 443))
1216 st->m_url += ":" + port;
1220 void* ShibTargetPriv::sendError(ShibTarget* st, const char* page, ShibMLP &mlp)
1222 ShibTarget::header_t hdrs[] = {
1223 ShibTarget::header_t("Expires","01-Jan-1997 12:00:00 GMT"),
1224 ShibTarget::header_t("Cache-Control","private,no-store,no-cache")
1227 const IPropertySet* props=m_app->getPropertySet("Errors");
1229 pair<bool,const char*> p=props->getString(page);
1231 ifstream infile(p.second);
1232 if (!infile.fail()) {
1233 const char* res = mlp.run(infile,props);
1235 return st->sendPage(res, 200, "text/html", ArrayIterator<ShibTarget::header_t>(hdrs,2));
1238 else if (!strcmp(page,"access"))
1239 return st->sendPage("Access Denied", 403, "text/html", ArrayIterator<ShibTarget::header_t>(hdrs,2));
1242 string errstr = string("sendError could not process error template (") + page + ") for application (";
1243 errstr += m_app->getId();
1245 st->log(ShibTarget::LogLevelError, errstr);
1246 return st->sendPage(
1247 "Internal Server Error. Please contact the site administrator.", 500, "text/html", ArrayIterator<ShibTarget::header_t>(hdrs,2)
1251 const char* ShibTargetPriv::getCookie(ShibTarget* st, const string& name) const
1253 if (m_cookieMap.empty()) {
1254 string cookies=st->getCookies();
1256 string::size_type pos=0,cname,namelen,val,vallen;
1257 while (pos !=string::npos && pos < cookies.length()) {
1258 while (isspace(cookies[pos])) pos++;
1260 pos=cookies.find_first_of("=",pos);
1261 if (pos == string::npos)
1265 if (pos==cookies.length())
1268 pos=cookies.find_first_of(";",pos);
1269 if (pos != string::npos) {
1272 m_cookieMap.insert(make_pair(cookies.substr(cname,namelen),cookies.substr(val,vallen)));
1275 m_cookieMap.insert(make_pair(cookies.substr(cname,namelen),cookies.substr(val)));
1278 map<string,string>::const_iterator lookup=m_cookieMap.find(name);
1279 return (lookup==m_cookieMap.end()) ? NULL : lookup->second.c_str();
1282 // Get the session cookie name and properties for the application
1283 pair<string,const char*> ShibTargetPriv::getCookieNameProps(const char* prefix) const
1285 static const char* defProps="; path=/";
1287 const IPropertySet* props=m_app ? m_app->getPropertySet("Sessions") : NULL;
1289 pair<bool,const char*> p=props->getString("cookieProps");
1292 pair<bool,const char*> p2=props->getString("cookieName");
1294 return make_pair(string(prefix) + p2.second,p.second);
1295 return make_pair(string(prefix) + m_app->getHash(),p.second);
1298 // Shouldn't happen, but just in case..
1299 return make_pair(prefix,defProps);
1302 const char* ShibTargetPriv::getHandlerURL(const char* resource) const
1304 if (!m_handlerURL.empty())
1305 return m_handlerURL.c_str();
1308 throw ConfigurationException("Internal error in ShibTargetPriv::getHandlerURL, missing application pointer.");
1310 bool ssl_only=false;
1311 const char* handler=NULL;
1312 const IPropertySet* props=m_app->getPropertySet("Sessions");
1314 pair<bool,bool> p=props->getBool("handlerSSL");
1317 pair<bool,const char*> p2=props->getString("handlerURL");
1322 // Should never happen...
1323 if (!handler || (*handler!='/' && strncmp(handler,"http:",5) && strncmp(handler,"https:",6)))
1324 throw ConfigurationException(
1325 "Invalid handlerURL property ($1) in Application ($2)",
1326 params(2, handler ? handler : "null", m_app->getId())
1329 // The "handlerURL" property can be in one of three formats:
1331 // 1) a full URI: http://host/foo/bar
1332 // 2) a hostless URI: http:///foo/bar
1333 // 3) a relative path: /foo/bar
1335 // # Protocol Host Path
1336 // 1 handler handler handler
1337 // 2 handler resource handler
1338 // 3 resource resource handler
1340 // note: if ssl_only is true, make sure the protocol is https
1342 const char* path = NULL;
1344 // Decide whether to use the handler or the resource for the "protocol"
1346 if (*handler != '/') {
1354 // break apart the "protocol" string into protocol, host, and "the rest"
1355 const char* colon=strchr(prot,':');
1357 const char* slash=strchr(colon,'/');
1361 // Compute the actual protocol and store in member.
1363 m_handlerURL.assign("https://");
1365 m_handlerURL.assign(prot, colon-prot);
1367 // create the "host" from either the colon/slash or from the target string
1368 // If prot == handler then we're in either #1 or #2, else #3.
1369 // If slash == colon then we're in #2.
1370 if (prot != handler || slash == colon) {
1371 colon = strchr(resource, ':');
1372 colon += 3; // Get past the ://
1373 slash = strchr(colon, '/');
1375 string host(colon, slash-colon);
1377 // Build the shire URL
1378 m_handlerURL+=host + path;
1379 return m_handlerURL.c_str();
1382 pair<bool,void*> ShibTargetPriv::doSessionInitiator(ShibTarget* st, const IPropertySet* handler, bool isHandler) const
1385 const char* resource=NULL;
1386 const IPropertySet* ACS=NULL;
1389 // We're running as an actual handler, so check to see if we understand the binding.
1390 pair<bool,const XMLCh*> binding=handler->getXMLString("Binding");
1391 if (binding.first && XMLString::compareString(binding.second,Constants::SHIB_SESSIONINIT_PROFILE_URI))
1392 throw UnsupportedProfileException(
1393 "Unsupported session initiator binding ($1).", params(1,handler->getString("Binding").second)
1397 * Binding is CGI query string with:
1398 * target the resource to direct back to later
1399 * acsIndex optional index of an ACS to use on the way back in
1400 * providerId optional direct invocation of a specific IdP
1402 string query=st->getArgs();
1403 CgiParse parser(query.c_str(),query.length());
1405 const char* option=parser.get_value("acsIndex");
1407 ACS=m_app->getAssertionConsumerServiceByIndex(atoi(option));
1408 option=parser.get_value("providerId");
1410 resource=parser.get_value("target");
1411 if (!resource || !*resource) {
1412 pair<bool,const char*> home=m_app->getString("homeURL");
1414 resource=home.second;
1416 throw FatalProfileException("Session initiator requires a target parameter or a homeURL application property.");
1419 dupresource=resource;
1420 resource=dupresource.c_str();
1424 // Here we actually use metadata to invoke the SSO service directly.
1425 // The only currently understood binding is the Shibboleth profile.
1426 Metadata m(m_app->getMetadataProviders());
1427 const IEntityDescriptor* entity=m.lookup(option);
1429 throw MetadataException("Session initiator unable to locate metadata for provider ($1).", params(1,option));
1430 const IIDPSSODescriptor* role=entity->getIDPSSODescriptor(saml::XML::SAML11_PROTOCOL_ENUM);
1432 throw MetadataException(
1433 "Session initiator unable to locate SAML identity provider role for provider ($1).", params(1,option)
1435 const IEndpointManager* SSO=role->getSingleSignOnServiceManager();
1436 const IEndpoint* ep=SSO->getEndpointByBinding(Constants::SHIB_AUTHNREQUEST_PROFILE_URI);
1438 throw MetadataException(
1439 "Session initiator unable to locate compatible SSO service for provider ($1).", params(1,option)
1441 auto_ptr_char dest(ep->getLocation());
1442 return ShibAuthnRequest(
1443 st,ACS ? ACS : m_app->getDefaultAssertionConsumerService(),dest.get(),resource,m_app->getString("providerId").second
1448 // We're running as a "virtual handler" from within the filter.
1449 // The target resource is the current one and everything else is defaulted.
1450 resource=st->m_url.c_str();
1453 if (!ACS) ACS=m_app->getDefaultAssertionConsumerService();
1455 // For now, we only support external session initiation via a wayfURL
1456 pair<bool,const char*> wayfURL=handler->getString("wayfURL");
1458 throw ConfigurationException("Session initiator is missing wayfURL property.");
1460 pair<bool,const XMLCh*> wayfBinding=handler->getXMLString("wayfBinding");
1461 if (!wayfBinding.first || !XMLString::compareString(wayfBinding.second,Constants::SHIB_AUTHNREQUEST_PROFILE_URI))
1462 // Standard Shib 1.x
1463 return ShibAuthnRequest(st,ACS,wayfURL.second,resource,m_app->getString("providerId").second);
1464 else if (!XMLString::compareString(wayfBinding.second,Constants::SHIB_LEGACY_AUTHNREQUEST_PROFILE_URI))
1466 return ShibAuthnRequest(st,ACS,wayfURL.second,resource,NULL);
1467 else if (!strcmp(handler->getString("wayfBinding").second,"urn:mace:shibboleth:1.0:profiles:EAuth")) {
1468 // TODO: Finalize E-Auth profile URI
1469 pair<bool,bool> localRelayState=m_conf->getPropertySet("Local")->getBool("localRelayState");
1470 if (!localRelayState.first || !localRelayState.second)
1471 throw ConfigurationException("Federal E-Authn requests cannot include relay state, so localRelayState must be enabled.");
1473 // Here we store the state in a cookie.
1474 pair<string,const char*> shib_cookie=getCookieNameProps("_shibstate_");
1475 st->setCookie(shib_cookie.first,CgiParse::url_encode(resource) + shib_cookie.second);
1476 return make_pair(true, st->sendRedirect(wayfURL.second));
1479 throw UnsupportedProfileException("Unsupported WAYF binding ($1).", params(1,handler->getString("wayfBinding").second));
1482 // Handles Shib 1.x AuthnRequest profile.
1483 pair<bool,void*> ShibTargetPriv::ShibAuthnRequest(
1485 const IPropertySet* shire,
1488 const char* providerId
1491 // Compute the ACS URL. We add the ACS location to the handler baseURL.
1492 // Legacy configs will not have an ACS specified, so no suffix will be added.
1493 string ACSloc=getHandlerURL(target);
1494 if (shire) ACSloc+=shire->getString("Location").second;
1497 sprintf(timebuf,"%u",time(NULL));
1498 string req=string(dest) + "?shire=" + CgiParse::url_encode(ACSloc.c_str()) + "&time=" + timebuf;
1500 // How should the resource value be preserved?
1501 pair<bool,bool> localRelayState=m_conf->getPropertySet("Local")->getBool("localRelayState");
1502 if (!localRelayState.first || !localRelayState.second) {
1503 // The old way, just send it along.
1504 req+="&target=" + CgiParse::url_encode(target);
1507 // Here we store the state in a cookie and send a fixed
1508 // value to the IdP so we can recognize it on the way back.
1509 pair<string,const char*> shib_cookie=getCookieNameProps("_shibstate_");
1510 st->setCookie(shib_cookie.first,CgiParse::url_encode(target) + shib_cookie.second);
1511 req+="&target=cookie";
1514 // Only omitted for 1.1 style requests.
1516 req+="&providerId=" + CgiParse::url_encode(providerId);
1518 return make_pair(true, st->sendRedirect(req));
1521 pair<bool,void*> ShibTargetPriv::doAssertionConsumer(ShibTarget* st, const IPropertySet* handler) const
1524 string input,cookie,target,providerId;
1526 // Right now, this only handles SAML 1.1.
1527 pair<bool,const XMLCh*> binding=handler->getXMLString("Binding");
1528 if (!binding.first || !XMLString::compareString(binding.second,SAMLBrowserProfile::BROWSER_POST)) {
1529 if (strcasecmp(st->m_method.c_str(), "POST"))
1530 throw FatalProfileException(
1531 "SAML 1.1 Browser/POST handler does not support HTTP method ($1).", params(1,st->m_method.c_str())
1534 if (st->m_content_type.empty() || strcasecmp(st->m_content_type.c_str(),"application/x-www-form-urlencoded"))
1535 throw FatalProfileException(
1536 "Blocked invalid content-type ($1) submitted to SAML 1.1 Browser/POST handler.", params(1,st->m_content_type.c_str())
1538 input=st->getPostData();
1539 profile|=SAML11_POST;
1541 else if (!XMLString::compareString(binding.second,SAMLBrowserProfile::BROWSER_ARTIFACT)) {
1542 if (strcasecmp(st->m_method.c_str(), "GET"))
1543 throw FatalProfileException(
1544 "SAML 1.1 Browser/Artifact handler does not support HTTP method ($1).", params(1,st->m_method.c_str())
1546 input=st->getArgs();
1547 profile|=SAML11_ARTIFACT;
1551 throw FatalProfileException("SAML 1.1 Browser Profile handler received no data from browser.");
1553 pair<bool,const char*> loc=handler->getString("Location");
1556 loc.first ? m_handlerURL + loc.second : m_handlerURL,
1558 st->m_remote_addr.c_str(),
1564 st->log(ShibTarget::LogLevelDebug, string("profile processing succeeded, new session created (") + cookie + ")");
1566 if (target=="default") {
1567 pair<bool,const char*> homeURL=m_app->getString("homeURL");
1568 target=homeURL.first ? homeURL.second : "/";
1570 else if (target=="cookie") {
1571 // Pull the target value from the "relay state" cookie.
1572 pair<string,const char*> relay_cookie = getCookieNameProps("_shibstate_");
1573 const char* relay_state = getCookie(st,relay_cookie.first);
1574 if (!relay_state || !*relay_state) {
1575 // No apparent relay state value to use, so fall back on the default.
1576 pair<bool,const char*> homeURL=m_app->getString("homeURL");
1577 target=homeURL.first ? homeURL.second : "/";
1580 char* rscopy=strdup(relay_state);
1581 CgiParse::url_decode(rscopy);
1587 // We've got a good session, set the session cookie.
1588 pair<string,const char*> shib_cookie=getCookieNameProps("_shibsession_");
1589 st->setCookie(shib_cookie.first, cookie + shib_cookie.second);
1591 const IPropertySet* sessionProps=m_app->getPropertySet("Sessions");
1592 pair<bool,bool> idpHistory=sessionProps->getBool("idpHistory");
1593 if (!idpHistory.first || idpHistory.second) {
1594 // Set an IdP history cookie locally (essentially just a CDC).
1595 CommonDomainCookie cdc(getCookie(st,CommonDomainCookie::CDCName));
1597 // Either leave in memory or set an expiration.
1598 pair<bool,unsigned int> days=sessionProps->getUnsignedInt("idpHistoryDays");
1599 if (!days.first || days.second==0)
1600 st->setCookie(CommonDomainCookie::CDCName,string(cdc.set(providerId.c_str())) + shib_cookie.second);
1602 time_t now=time(NULL) + (days.second * 24 * 60 * 60);
1603 #ifdef HAVE_GMTIME_R
1605 struct tm* ptime=gmtime_r(&now,&res);
1607 struct tm* ptime=gmtime(&now);
1610 strftime(timebuf,64,"%a, %d %b %Y %H:%M:%S GMT",ptime);
1612 CommonDomainCookie::CDCName,
1613 string(cdc.set(providerId.c_str())) + shib_cookie.second + "; expires=" + timebuf
1618 // Now redirect to the target.
1619 return make_pair(true, st->sendRedirect(target));
1622 pair<bool,void*> ShibTargetPriv::doLogout(ShibTarget* st, const IPropertySet* handler) const
1624 pair<bool,const XMLCh*> binding=handler->getXMLString("Binding");
1625 if (!binding.first || XMLString::compareString(binding.second,Constants::SHIB_LOGOUT_PROFILE_URI)) {
1627 throw UnsupportedProfileException("Missing Logout binding.");
1628 throw UnsupportedProfileException("Unsupported Logout binding ($1).", params(1,handler->getString("Binding").second));
1631 // Recover the session key.
1632 pair<string,const char*> shib_cookie = getCookieNameProps("_shibsession_");
1633 const char* session_id = getCookie(st,shib_cookie.first);
1635 // Logout is best effort.
1636 if (session_id && *session_id) {
1638 st->sessionEnd(session_id);
1640 catch (SAMLException& e) {
1641 st->log(ShibTarget::LogLevelError, string("logout processing failed with exception: ") + e.what());
1645 st->log(ShibTarget::LogLevelError, "logout processing failed with unknown exception");
1648 st->setCookie(shib_cookie.first,"");
1651 string query=st->getArgs();
1652 CgiParse parser(query.c_str(),query.length());
1654 const char* ret=parser.get_value("return");
1656 ret=handler->getString("ResponseLocation").second;
1658 ret=m_app->getString("homeURL").second;
1661 return make_pair(true, st->sendRedirect(ret));
1664 /*************************************************************************
1665 * CGI Parser implementation
1668 CgiParse::CgiParse(const char* data, unsigned int len)
1670 const char* pch = data;
1671 unsigned int cl = len;
1676 value=fmakeword('&',&cl,&pch);
1679 name=makeword(value,'=');
1680 kvp_map[name]=value;
1685 CgiParse::~CgiParse()
1687 for (map<string,char*>::iterator i=kvp_map.begin(); i!=kvp_map.end(); i++)
1692 CgiParse::get_value(const char* name) const
1694 map<string,char*>::const_iterator i=kvp_map.find(name);
1695 if (i==kvp_map.end())
1700 /* Parsing routines modified from NCSA source. */
1702 CgiParse::makeword(char *line, char stop)
1705 char *word = (char *) malloc(sizeof(char) * (strlen(line) + 1));
1707 for(x=0;((line[x]) && (line[x] != stop));x++)
1716 line[y++] = line[x++];
1722 CgiParse::fmakeword(char stop, unsigned int *cl, const char** ppch)
1730 word = (char *) malloc(sizeof(char) * (wsize + 1));
1734 word[ll] = *((*ppch)++);
1739 word = (char *)realloc(word,sizeof(char)*(wsize+1));
1742 if((word[ll] == stop) || word[ll] == EOF || (!(*cl)))
1744 if(word[ll] != stop)
1754 CgiParse::plustospace(char *str)
1759 if(str[x] == '+') str[x] = ' ';
1763 CgiParse::x2c(char *what)
1765 register char digit;
1767 digit = (what[0] >= 'A' ? ((what[0] & 0xdf) - 'A')+10 : (what[0] - '0'));
1769 digit += (what[1] >= 'A' ? ((what[1] & 0xdf) - 'A')+10 : (what[1] - '0'));
1774 CgiParse::url_decode(char *url)
1778 for(x=0,y=0;url[y];++x,++y)
1780 if((url[x] = url[y]) == '%')
1782 url[x] = x2c(&url[y+1]);
1789 static inline char hexchar(unsigned short s)
1791 return (s<=9) ? ('0' + s) : ('A' + s - 10);
1794 string CgiParse::url_encode(const char* s)
1796 static char badchars[]="\"\\+<>#%{}|^~[]`;/?:@=&";
1800 if (strchr(badchars,*s) || *s<=0x1F || *s>=0x7F) {
1802 ret+=hexchar(*s >> 4);
1803 ret+=hexchar(*s & 0x0F);
1810 // Subclasses may not need to override these particular virtual methods.
1811 string ShibTarget::getAuthType(void)
1813 return string("shibboleth");
1815 void* ShibTarget::returnDecline(void)
1819 void* ShibTarget::returnOK(void)
1823 HTAccessInfo* ShibTarget::getAccessInfo(void)
1827 HTGroupTable* ShibTarget::getGroupTable(string &user)
1832 // CDC implementation
1834 const char CommonDomainCookie::CDCName[] = "_saml_idp";
1836 CommonDomainCookie::CommonDomainCookie(const char* cookie) : m_decoded(NULL)
1841 // Copy it so we can URL-decode it.
1842 char* b64=strdup(cookie);
1843 CgiParse::url_decode(b64);
1845 // Now Base64 decode it into the decoded delimited list.
1847 m_decoded=Base64::decode(reinterpret_cast<XMLByte*>(b64),&len);
1850 Category::getInstance("CommonDomainCookie").warn("cookie does not appear to be base64-encoded");
1854 // Chop it up and save off pointers.
1855 char* ptr=reinterpret_cast<char*>(m_decoded);
1857 while (isspace(*ptr)) ptr++;
1858 m_list.push_back(ptr);
1859 while (*ptr && !isspace(*ptr)) ptr++;
1865 CommonDomainCookie::~CommonDomainCookie()
1868 XMLString::release(&m_decoded);
1871 const char* CommonDomainCookie::set(const char* providerId)
1873 // First scan the list for this IdP.
1874 for (vector<const char*>::iterator i=m_list.begin(); i!=m_list.end(); i++) {
1875 if (!strcmp(providerId,*i)) {
1881 // Append it to the end, after storing locally.
1882 m_additions.push_back(providerId);
1883 m_list.push_back(m_additions.back().c_str());
1885 // Now rebuild the delimited list.
1887 for (vector<const char*>::const_iterator j=m_list.begin(); j!=m_list.end(); j++) {
1888 if (!delimited.empty()) delimited += ' ';
1892 // Base64 and URL encode it.
1894 XMLByte* b64=Base64::encode(reinterpret_cast<const XMLByte*>(delimited.c_str()),delimited.length(),&len);
1895 XMLByte *pos, *pos2;
1896 for (pos=b64, pos2=b64; *pos2; pos2++)
1900 m_encoded=CgiParse::url_encode(reinterpret_cast<char*>(b64));
1901 XMLString::release(&b64);
1902 return m_encoded.c_str();