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);
96 char * fmakeword(char stop, unsigned int *cl, const char** ppch);
97 char * makeword(char *line, char stop);
98 void plustospace(char *str);
100 map<string,char*> kvp_map;
109 string url_encode(const char* s);
110 void get_application(const string& protocol, const string& hostname, int port, const string& uri);
111 void* sendError(ShibTarget* st, string page, ShibMLP &mlp);
112 const char* getSessionId(ShibTarget* st);
113 const char* getRelayState(ShibTarget* st);
116 friend class ShibTarget;
117 IRequestMapper::Settings m_settings;
118 const IApplication *m_app;
122 const char* session_id;
123 const char* relay_state;
125 ShibProfile m_sso_profile;
126 string m_provider_id;
127 SAMLAuthenticationStatement* m_sso_statement;
128 SAMLResponse* m_pre_response;
129 SAMLResponse* m_post_response;
131 // These are the actual request parameters set via the init method.
135 string m_content_type;
136 string m_remote_addr;
138 ShibTargetConfig* m_Config;
141 IRequestMapper* m_mapper;
146 /*************************************************************************
147 * Shib Target implementation
150 ShibTarget::ShibTarget(void) : m_priv(NULL)
152 m_priv = new ShibTargetPriv();
155 ShibTarget::ShibTarget(const IApplication *app) : m_priv(NULL)
157 m_priv = new ShibTargetPriv();
161 ShibTarget::~ShibTarget(void)
163 if (m_priv) delete m_priv;
166 void ShibTarget::init(
167 ShibTargetConfig *config,
178 saml::NDC ndc("ShibTarget::init");
182 throw runtime_error("ShibTarget Already Initialized");
184 throw runtime_error("config is NULL. Oops.");
186 m_priv->m_protocol = protocol;
187 m_priv->m_content_type = content_type;
188 m_priv->m_remote_addr = remote_host;
189 m_priv->m_Config = config;
190 m_priv->m_method = method;
191 m_priv->get_application(protocol, hostname, port, uri);
195 // These functions implement the server-agnostic shibboleth engine
196 // The web server modules implement a subclass and then call into
197 // these methods once they instantiate their request object.
199 ShibTarget::doCheckAuthN(bool requireSessionFlag, bool handleProfile)
202 saml::NDC ndc("ShibTarget::doCheckAuthN");
205 const char *targetURL = NULL;
206 const char *procState = "Request Setup Error";
211 throw SAMLException("System uninitialized, application did not supply request information.");
213 targetURL = m_priv->m_url.c_str();
214 const char *shireURL = getShireURL(targetURL);
216 throw SAMLException("Cannot determine assertion consumer service from resource URL, check configuration.");
218 if (strstr(targetURL,shireURL)) {
220 return doHandleProfile();
222 return pair<bool,void*>(true, returnOK());
225 string auth_type = getAuthType();
226 if (strcasecmp(auth_type.c_str(),"shibboleth"))
227 return pair<bool,void*>(true,returnDecline());
229 pair<bool,bool> requireSession = m_priv->m_settings.first->getBool("requireSession");
230 if (!requireSession.first || !requireSession.second) {
231 // Web server might override.
232 if (requireSessionFlag)
233 requireSession.second=true;
236 const char* session_id = m_priv->getSessionId(this);
237 if (!session_id || !*session_id) {
238 // No session. Maybe that's acceptable?
239 if (!requireSession.second)
240 return pair<bool,void*>(true,returnOK());
242 // No cookie, but we require a session. Generate an AuthnRequest.
243 return pair<bool,void*>(true,sendRedirect(getAuthnRequest(targetURL)));
246 procState = "Session Processing Error";
248 // Localized exception throw if the session isn't valid.
251 m_priv->m_remote_addr.c_str(),
252 m_priv->m_sso_profile,
253 m_priv->m_provider_id,
254 &m_priv->m_sso_statement,
255 &m_priv->m_pre_response,
256 &m_priv->m_post_response
259 catch (SAMLException& e) {
260 // If no session is required, bail now.
261 if (!requireSession.second)
262 // Has to be OK because DECLINED will just cause Apache
263 // to fail when it can't locate anything to process the
264 // AuthType. No session plus requireSession false means
265 // do not authenticate the user at this time.
266 return pair<bool,void*>(true, returnOK());
268 // TODO: need to test this...may need an actual reference cast
269 if (typeid(e)==typeid(RetryableProfileException)) {
270 // Session is invalid but we can retry -- generate an AuthnRequest
271 return pair<bool,void*>(true,sendRedirect(getAuthnRequest(targetURL)));
273 throw; // send it to the outer handler
276 // We're done. Everything is okay. Nothing to report. Nothing to do..
277 // Let the caller decide how to proceed.
278 log(LogLevelInfo, "doCheckAuthN succeeded");
279 return pair<bool,void*>(false,NULL);
281 catch (SAMLException& e) {
286 mlp.insert("errorText", "Caught an unknown exception.");
290 // If we get here then we've got an error.
291 mlp.insert("errorType", procState);
293 mlp.insert("requestURL", targetURL);
295 return pair<bool,void*>(true,m_priv->sendError(this, "session", mlp));
299 ShibTarget::doHandleProfile(void)
302 saml::NDC ndc("ShibTarget::doHandleProfile");
305 const char *targetURL = NULL;
306 const char *procState = "Session Creation Service Error";
311 throw SAMLException("System uninitialized, application did not supply request information.");
313 targetURL = m_priv->m_url.c_str();
314 const char* shireURL = getShireURL(targetURL);
317 throw SAMLException("Cannot determine assertion consumer service, check configuration.");
319 // Make sure we only process the SHIRE requests.
320 if (!strstr(targetURL, shireURL))
321 return pair<bool,void*>(true, returnDecline());
323 const IPropertySet* sessionProps=m_priv->m_app->getPropertySet("Sessions");
325 throw SAMLException("Unable to map request to application session settings, check configuration.");
327 // Process incoming request.
328 pair<bool,bool> shireSSL=sessionProps->getBool("shireSSL");
330 // Make sure this is SSL, if it should be
331 if ((!shireSSL.first || shireSSL.second) && m_priv->m_protocol != "https")
332 throw FatalProfileException("Blocked non-SSL access to session creation service.");
334 // If this is a GET, we see if it's a lazy session request, otherwise
335 // assume it's a profile response and process it.
337 if (!strcasecmp(m_priv->m_method.c_str(), "GET")) {
341 areq=getLazyAuthnRequest(cgistr.c_str());
343 return pair<bool,void*>(true, sendRedirect(areq));
345 else if (!strcasecmp(m_priv->m_method.c_str(), "POST")) {
346 if (m_priv->m_content_type.empty() || strcasecmp(m_priv->m_content_type.c_str(),"application/x-www-form-urlencoded")) {
347 throw FatalProfileException(
348 "Blocked invalid POST content-type ($1) to session creation service.",
349 params(1,m_priv->m_content_type)
352 // Read the POST Data
353 cgistr = getPostData();
356 // Process the submission
357 string cookie,target;
360 SAML11_POST | SAML11_ARTIFACT,
362 m_priv->m_remote_addr.c_str(),
367 catch (SAMLException& e) {
368 log(LogLevelError, string("profile processing failed: ") + e.what());
370 // TODO: need to test this...may need an actual reference cast
371 if (typeid(e)==typeid(RetryableProfileException)) {
372 return pair<bool,void*>(true, sendRedirect(getAuthnRequest(target.c_str())));
374 throw; // send it to the outer handler
377 log(LogLevelDebug, string("profile processing succeeded, new session created (") + cookie + ")");
379 if (target=="default") {
380 pair<bool,const char*> homeURL=m_priv->m_app->getString("homeURL");
381 target=homeURL.first ? homeURL.second : "/";
383 else if (target=="cookie") {
384 // Pull the target value from the "relay state" cookie.
385 const char* relay_state = m_priv->getRelayState(this);
386 if (!relay_state || !*relay_state) {
387 // No apparent relay state value to use, so fall back on the default.
388 pair<bool,const char*> homeURL=m_priv->m_app->getString("homeURL");
389 target=homeURL.first ? homeURL.second : "/";
392 CgiParse::url_decode((char*)relay_state);
397 // We've got a good session, set the cookie...
398 pair<string,const char*> shib_cookie=getCookieNameProps("_shibsession_");
399 cookie += shib_cookie.second;
400 setCookie(shib_cookie.first, cookie);
402 // ... and redirect to the target
403 return pair<bool,void*>(true, sendRedirect(target));
405 catch (SAMLException& e) {
410 mlp.insert("errorText", "Caught an unknown exception.");
414 // If we get here then we've got an error.
415 mlp.insert("errorType", procState);
418 mlp.insert("requestURL", targetURL);
420 return pair<bool,void*>(true,m_priv->sendError(this, "session", mlp));
424 ShibTarget::doCheckAuthZ(void)
427 saml::NDC ndc("ShibTarget::doCheckAuthZ");
431 const char *procState = "Authorization Processing Error";
432 const char *targetURL = NULL;
433 HTAccessInfo *ht = NULL;
434 HTGroupTable* grpstatus = NULL;
438 throw SAMLException("System uninitialized, application did not supply request information.");
440 targetURL = m_priv->m_url.c_str();
441 const char *session_id = m_priv->getSessionId(this);
443 // Do we have an access control plugin?
444 if (m_priv->m_settings.second) {
445 Locker acllock(m_priv->m_settings.second);
446 if (!m_priv->m_settings.second->authorized(*m_priv->m_sso_statement,
447 m_priv->m_post_response ? m_priv->m_post_response->getAssertions() : EMPTY(SAMLAssertion*))) {
448 log(LogLevelError, "doCheckAuthZ() access control provider denied access");
450 mlp.insert("requestURL", targetURL);
451 // TODO: check setting and return 403
452 return pair<bool,void*>(true,m_priv->sendError(this, "access", mlp));
456 // Perform HTAccess Checks
457 ht = getAccessInfo();
459 // No Info means OK. Just return
461 return pair<bool,void*>(false, NULL);
463 vector<bool> auth_OK(ht->elements.size(), false);
464 bool method_restricted=false;
465 string remote_user = getRemoteUser();
467 #define CHECK_OK do { \
468 if (ht->requireAll) { \
470 if (grpstatus) delete grpstatus; \
471 return pair<bool,void*>(false, NULL); \
477 for (int x = 0; x < ht->elements.size(); x++) {
479 HTAccessInfo::RequireLine *line = ht->elements[x];
480 if (! line->use_line)
482 method_restricted = true;
484 const char *w = line->tokens[0].c_str();
486 if (!strcasecmp(w,"Shibboleth")) {
487 // This is a dummy rule needed because Apache conflates authn and authz.
488 // Without some require rule, AuthType is ignored and no check_user hooks run.
491 else if (!strcmp(w,"valid-user")) {
492 log(LogLevelDebug, "doCheckAuthZ accepting valid-user");
495 else if (!strcmp(w,"user") && !remote_user.empty()) {
497 for (int i = 1; i < line->tokens.size(); i++) {
498 w = line->tokens[i].c_str();
506 // To do regex matching, we have to convert from UTF-8.
507 auto_ptr<XMLCh> trans(fromUTF8(w));
508 RegularExpression re(trans.get());
509 auto_ptr<XMLCh> trans2(fromUTF8(remote_user.c_str()));
510 if (re.matches(trans2.get())) {
511 log(LogLevelDebug, string("doCheckAuthZ accepting user: ") + w);
515 catch (XMLException& ex) {
516 auto_ptr_char tmp(ex.getMessage());
517 log(LogLevelError, string("doCheckAuthZ caught exception while parsing regular expression (")
518 + w + "): " + tmp.get());
521 else if (!strcmp(remote_user.c_str(), w)) {
522 log(LogLevelDebug, string("doCheckAuthZ accepting user: ") + w);
527 else if (!strcmp(w,"group")) {
528 grpstatus = getGroupTable(remote_user);
531 return pair<bool,void*>(true, returnDecline());
534 for (int i = 1; i < line->tokens.size(); i++) {
535 w = line->tokens[i].c_str();
536 if (grpstatus->lookup(w)) {
537 log(LogLevelDebug, string("doCheckAuthZ accepting group: ") + w);
545 Iterator<IAAP*> provs = m_priv->m_app->getAAPProviders();
546 AAP wrapper(provs, w);
547 if (wrapper.fail()) {
548 log(LogLevelWarn, string("doCheckAuthZ didn't recognize require rule: ") + w);
553 string vals = getHeader(wrapper->getHeader());
554 for (int i = 1; i < line->tokens.size() && !vals.empty(); i++) {
555 w = line->tokens[i].c_str();
562 auto_ptr<RegularExpression> re;
565 auto_ptr<XMLCh> trans(fromUTF8(w));
566 auto_ptr<RegularExpression> temp(new RegularExpression(trans.get()));
570 string vals_str(vals);
572 for (int i = 0; i < vals_str.length(); i++) {
573 if (vals_str.at(i) == ';') {
575 log(LogLevelError, string("doCheckAuthZ invalid header encoding") +
576 vals + ": starts with a semicolon");
577 throw SAMLException("Invalid information supplied to authorization module.");
580 if (vals_str.at(i-1) == '\\') {
581 vals_str.erase(i-1, 1);
586 string val = vals_str.substr(j, i-j);
589 auto_ptr<XMLCh> trans(fromUTF8(val.c_str()));
590 if (re->matches(trans.get())) {
591 log(LogLevelDebug, string("doCheckAuthZ expecting ") + w +
592 ", got " + val + ": authorization granted");
596 else if ((wrapper->getCaseSensitive() && val==w) ||
597 (!wrapper->getCaseSensitive() && !strcasecmp(val.c_str(),w))) {
598 log(LogLevelDebug, string("doCheckAuthZ expecting ") + w +
599 ", got " + val + ": authorization granted.");
603 log(LogLevelDebug, string("doCheckAuthZ expecting ") + w +
604 ", got " + val + ": authoritzation not granted.");
609 string val = vals_str.substr(j, vals_str.length()-j);
611 auto_ptr<XMLCh> trans(fromUTF8(val.c_str()));
612 if (re->matches(trans.get())) {
613 log(LogLevelDebug, string("doCheckAuthZ expecting ") + w +
614 ", got " + val + ": authorization granted.");
618 else if ((wrapper->getCaseSensitive() && val==w) ||
619 (!wrapper->getCaseSensitive() && !strcasecmp(val.c_str(),w))) {
620 log(LogLevelDebug, string("doCheckAuthZ expecting ") + w +
621 ", got " + val + ": authorization granted");
625 log(LogLevelDebug, string("doCheckAuthZ expecting ") + w +
626 ", got " + val + ": authorization not granted");
629 catch (XMLException& ex) {
630 auto_ptr_char tmp(ex.getMessage());
631 log(LogLevelError, string("doCheckAuthZ caught exception while parsing regular expression (")
632 + w + "): " + tmp.get());
639 // check if all require directives are true
640 bool auth_all_OK = true;
641 for (int i = 0; i < ht->elements.size(); i++) {
642 auth_all_OK &= auth_OK[i];
646 if (grpstatus) delete grpstatus;
647 if (auth_all_OK || !method_restricted)
648 return pair<bool,void*>(false, NULL);
650 // If we get here there's an access error, so just fall through
652 catch (SAMLException& e) {
657 mlp.insert("errorText", "Caught an unknown exception.");
661 // If we get here then we've got an error.
662 mlp.insert("errorType", procState);
665 mlp.insert("requestURL", targetURL);
669 return pair<bool,void*>(true,m_priv->sendError(this, "access", mlp));
673 ShibTarget::doExportAssertions(bool exportAssertion)
676 saml::NDC ndc("ShibTarget::doExportAssertions");
680 const char *procState = "Attribute Processing Error";
681 const char *targetURL = NULL;
686 throw SAMLException("System uninitialized, application did not supply request information.");
688 targetURL = m_priv->m_url.c_str();
689 const char *session_id = m_priv->getSessionId(this);
691 if (!m_priv->m_sso_statement) {
692 // No data yet, so we need to get the session. This can only happen
693 // if the call to doCheckAuthn doesn't happen in the same object lifetime.
696 m_priv->m_remote_addr.c_str(),
697 m_priv->m_sso_profile,
698 m_priv->m_provider_id,
699 &m_priv->m_sso_statement,
700 &m_priv->m_pre_response,
701 &m_priv->m_post_response
705 // Get the AAP providers, which contain the attribute policy info.
706 Iterator<IAAP*> provs=m_priv->m_app->getAAPProviders();
708 // Clear out the list of mapped attributes
709 while (provs.hasNext()) {
710 IAAP* aap=provs.next();
712 Iterator<const IAttributeRule*> rules=aap->getAttributeRules();
713 while (rules.hasNext()) {
714 const char* header=rules.next()->getHeader();
720 // Maybe export the first assertion.
721 clearHeader("Shib-Attributes");
722 pair<bool,bool> exp=m_priv->m_settings.first->getBool("exportAssertion");
723 if (!exp.first || !exp.second)
726 if (exp.second && m_priv->m_pre_response) {
728 os << *(m_priv->m_pre_response);
730 char* resp = (char*)os.str().c_str();
731 XMLByte* serialized = Base64::encode(reinterpret_cast<XMLByte*>(resp), os.str().length(), &outlen);
732 // TODO: strip linefeeds
733 setHeader("Shib-Attributes", reinterpret_cast<char*>(serialized));
734 XMLString::release(&serialized);
737 // Export the SAML AuthnMethod and the origin site name, and possibly the NameIdentifier.
738 clearHeader("Shib-Origin-Site");
739 clearHeader("Shib-Identity-Provider");
740 clearHeader("Shib-Authentication-Method");
741 clearHeader("Shib-NameIdentifier-Format");
742 setHeader("Shib-Origin-Site", m_priv->m_provider_id.c_str());
743 setHeader("Shib-Identity-Provider", m_priv->m_provider_id.c_str());
744 auto_ptr_char am(m_priv->m_sso_statement->getAuthMethod());
745 setHeader("Shib-Authentication-Method", am.get());
749 while (provs.hasNext()) {
750 IAAP* aap=provs.next();
752 const IAttributeRule* rule=aap->lookup(m_priv->m_sso_statement->getSubject()->getNameIdentifier()->getFormat());
753 if (rule && rule->getHeader()) {
754 auto_ptr_char form(m_priv->m_sso_statement->getSubject()->getNameIdentifier()->getFormat());
755 auto_ptr_char nameid(m_priv->m_sso_statement->getSubject()->getNameIdentifier()->getName());
756 setHeader("Shib-NameIdentifier-Format", form.get());
757 if (!strcmp(rule->getHeader(),"REMOTE_USER"))
758 setRemoteUser(nameid.get());
760 setHeader(rule->getHeader(), nameid.get());
764 clearHeader("Shib-Application-ID");
765 setHeader("Shib-Application-ID", m_priv->m_app->getId());
767 // Export the attributes.
768 Iterator<SAMLAssertion*> a_iter(m_priv->m_post_response ? m_priv->m_post_response->getAssertions() : EMPTY(SAMLAssertion*));
769 while (a_iter.hasNext()) {
770 SAMLAssertion* assert=a_iter.next();
771 Iterator<SAMLStatement*> statements=assert->getStatements();
772 while (statements.hasNext()) {
773 SAMLAttributeStatement* astate=dynamic_cast<SAMLAttributeStatement*>(statements.next());
776 Iterator<SAMLAttribute*> attrs=astate->getAttributes();
777 while (attrs.hasNext()) {
778 SAMLAttribute* attr=attrs.next();
780 // Are we supposed to export it?
782 while (provs.hasNext()) {
783 IAAP* aap=provs.next();
785 const IAttributeRule* rule=aap->lookup(attr->getName(),attr->getNamespace());
786 if (!rule || !rule->getHeader())
789 Iterator<string> vals=attr->getSingleByteValues();
790 if (!strcmp(rule->getHeader(),"REMOTE_USER") && vals.hasNext())
791 setRemoteUser(vals.next());
794 string header = getHeader(rule->getHeader());
797 for (; vals.hasNext(); it++) {
798 string value = vals.next();
799 for (string::size_type pos = value.find_first_of(";", string::size_type(0));
801 pos = value.find_first_of(";", pos)) {
802 value.insert(pos, "\\");
809 setHeader(rule->getHeader(), header);
816 return pair<bool,void*>(false,NULL);
818 catch (SAMLException& e) {
823 mlp.insert("errorText", "Caught an unknown exception.");
827 // If we get here then we've got an error.
828 mlp.insert("errorType", procState);
831 mlp.insert("requestURL", targetURL);
833 return pair<bool,void*>(true,m_priv->sendError(this, page, mlp));
839 // Get the session cookie name and properties for the application
840 pair<string,const char*> ShibTarget::getCookieNameProps(const char* prefix) const
842 static const char* defProps="; path=/";
844 const IPropertySet* props=m_priv->m_app ? m_priv->m_app->getPropertySet("Sessions") : NULL;
846 pair<bool,const char*> p=props->getString("cookieProps");
849 pair<bool,const char*> p2=props->getString("cookieName");
851 return make_pair(string(prefix) + p2.second,p.second);
852 return make_pair(string(prefix) + m_priv->m_app->getHash(),p.second);
855 // Shouldn't happen, but just in case..
856 return make_pair(prefix,defProps);
859 // Find the default assertion consumer service for the resource
861 ShibTarget::getShireURL(const char* resource) const
863 if (!m_priv->m_shireURL.empty())
864 return m_priv->m_shireURL.c_str();
866 // XXX: what to do is m_app is NULL?
868 bool shire_ssl_only=false;
869 const char* shire=NULL;
870 const IPropertySet* props=m_priv->m_app->getPropertySet("Sessions");
872 pair<bool,bool> p=props->getBool("shireSSL");
874 shire_ssl_only=p.second;
875 pair<bool,const char*> p2=props->getString("shireURL");
880 // Should never happen...
881 if (!shire || (*shire!='/' && strncmp(shire,"http:",5) && strncmp(shire,"https:",6)))
884 // The "shireURL" property can be in one of three formats:
886 // 1) a full URI: http://host/foo/bar
887 // 2) a hostless URI: http:///foo/bar
888 // 3) a relative path: /foo/bar
890 // # Protocol Host Path
891 // 1 shire shire shire
892 // 2 shire resource shire
893 // 3 resource resource shire
895 // note: if shire_ssl_only is true, make sure the protocol is https
897 const char* path = NULL;
899 // Decide whether to use the shire or the resource for the "protocol"
909 // break apart the "protocol" string into protocol, host, and "the rest"
910 const char* colon=strchr(prot,':');
912 const char* slash=strchr(colon,'/');
916 // Compute the actual protocol and store in member.
918 m_priv->m_shireURL.assign("https://");
920 m_priv->m_shireURL.assign(prot, colon-prot);
922 // create the "host" from either the colon/slash or from the target string
923 // If prot == shire then we're in either #1 or #2, else #3.
924 // If slash == colon then we're in #2.
925 if (prot != shire || slash == colon) {
926 colon = strchr(resource, ':');
927 colon += 3; // Get past the ://
928 slash = strchr(colon, '/');
930 string host(colon, slash-colon);
932 // Build the shire URL
933 m_priv->m_shireURL+=host + path;
934 return m_priv->m_shireURL.c_str();
937 // Generate a Shib 1.x AuthnRequest redirect URL for the resource,
938 // using whatever relay state mechanism is specified for the app.
939 string ShibTarget::getAuthnRequest(const char* resource)
941 // XXX: what to do if m_app is NULL?
945 sprintf(timebuf,"%u",time(NULL));
947 const IPropertySet* props=m_priv->m_app ? m_priv->m_app->getPropertySet("Sessions") : NULL;
949 pair<bool,const char*> wayf=props->getString("wayfURL");
951 req=req + wayf.second + "?shire=" + m_priv->url_encode(getShireURL(resource)) + "&time=" + timebuf;
953 // How should the target value be preserved?
954 pair<bool,bool> localRelayState=m_priv->m_conf->getPropertySet("Local")->getBool("localRelayState");
955 if (!localRelayState.first || !localRelayState.second) {
956 // The old way, just send it along.
957 req = req + "&target=" + m_priv->url_encode(resource);
960 // Here we store the state in a cookie and send a fixed
961 // value to the IdP so we can recognize it on the way back.
962 pair<string,const char*> shib_cookie=getCookieNameProps("_shibstate_");
963 setCookie(shib_cookie.first,m_priv->url_encode(resource) + shib_cookie.second);
964 req += "&target=cookie";
967 pair<bool,bool> old=m_priv->m_app->getBool("oldAuthnRequest");
968 if (!old.first || !old.second) {
969 wayf=m_priv->m_app->getString("providerId");
971 req=req + "&providerId=" + m_priv->url_encode(wayf.second);
978 // Process a lazy session setup request and turn it into an AuthnRequest
979 string ShibTarget::getLazyAuthnRequest(const char* query_string)
981 CgiParse parser(query_string,strlen(query_string));
982 const char* target=parser.get_value("target");
983 if (!target || !*target)
985 return getAuthnRequest(target);
988 void ShibTarget::sessionNew(
989 int supported_profiles,
997 saml::NDC ndc("sessionNew");
999 Category& log = Category::getInstance("shibtarget.ShibTarget");
1001 if (!packet || !*packet) {
1002 log.error("missing profile response");
1003 throw FatalProfileException("Profile response missing.");
1007 log.error("missing client address");
1008 throw FatalProfileException("Invalid client address.");
1011 if (supported_profiles <= 0) {
1012 log.error("no profile support indicated");
1013 throw FatalProfileException("No profile support indicated.");
1016 shibrpc_new_session_args_2 arg;
1017 arg.recipient = (char*) m_priv->m_shireURL.c_str();
1018 arg.application_id = (char*) m_priv->m_app->getId();
1019 arg.packet = (char*)packet;
1020 arg.client_addr = (char*)ip;
1021 arg.supported_profiles = supported_profiles;
1023 log.info("create session for user at (%s) for application (%s)", ip, arg.application_id);
1025 shibrpc_new_session_ret_2 ret;
1026 memset(&ret, 0, sizeof(ret));
1028 // Loop on the RPC in case we lost contact the first time through
1033 clnt = rpc->connect();
1034 clnt_stat status = shibrpc_new_session_2 (&arg, &ret, clnt);
1035 if (status != RPC_SUCCESS) {
1036 // FAILED. Release, disconnect, and retry
1037 log.error("RPC Failure: %p (%p) (%d): %s", this, clnt, status, clnt_spcreateerror("shibrpc_new_session_2"));
1042 throw ListenerException("Failure passing session setup information to listener.");
1045 // SUCCESS. Pool and continue
1050 if (ret.status && *ret.status)
1051 log.debug("RPC completed with exception: %s", ret.status);
1053 log.debug("RPC completed successfully");
1055 SAMLException* except=NULL;
1056 if (ret.status && *ret.status) {
1057 // Reconstitute exception object.
1059 istringstream estr(ret.status);
1060 except=SAMLException::getInstance(estr);
1062 catch (SAMLException& e) {
1063 log.error("caught SAML Exception while building the SAMLException: %s", e.what());
1064 log.error("XML was: %s", ret.status);
1065 clnt_freeres(clnt, (xdrproc_t)xdr_shibrpc_new_session_ret_2, (caddr_t)&ret);
1067 throw FatalProfileException("An unrecoverable error occurred while creating your session.");
1071 log.error("caught unknown exception building SAMLException");
1072 log.error("XML was: %s", ret.status);
1073 clnt_freeres(clnt, (xdrproc_t)xdr_shibrpc_new_session_ret_2, (caddr_t)&ret);
1080 log.debug("new session cookie: %s", ret.cookie);
1081 cookie = ret.cookie;
1083 target = ret.target;
1086 clnt_freeres(clnt, (xdrproc_t)xdr_shibrpc_new_session_ret_2, (caddr_t)&ret);
1089 auto_ptr<SAMLException> wrapper(except);
1094 void ShibTarget::sessionGet(
1097 ShibProfile& profile,
1098 string& provider_id,
1099 SAMLAuthenticationStatement** auth_statement,
1100 SAMLResponse** attr_response_pre,
1101 SAMLResponse** attr_response_post
1105 saml::NDC ndc("sessionGet");
1107 Category& log = Category::getInstance("shibtarget.ShibTarget");
1109 if (!cookie || !*cookie) {
1110 log.error("no session key provided");
1111 throw InvalidSessionException("No session key was provided.");
1113 else if (strchr(cookie,'=')) {
1114 log.error("cookie value not extracted successfully, probably overlapping cookies across domains");
1115 throw InvalidSessionException("The session key wasn't extracted successfully from the browser cookie.");
1119 log.error("invalid client Address");
1120 throw FatalProfileException("Invalid client address.");
1123 log.info("getting session for client at (%s)", ip);
1124 log.debug("session cookie (%s)", cookie);
1126 shibrpc_get_session_args_2 arg;
1127 arg.cookie = (char*)cookie;
1128 arg.client_addr = (char*)ip;
1129 arg.application_id = (char*)m_priv->m_app->getId();
1131 shibrpc_get_session_ret_2 ret;
1132 memset (&ret, 0, sizeof(ret));
1134 // Loop on the RPC in case we lost contact the first time through
1139 clnt = rpc->connect();
1140 clnt_stat status = shibrpc_get_session_2(&arg, &ret, clnt);
1141 if (status != RPC_SUCCESS) {
1142 // FAILED. Release, disconnect, and try again...
1143 log.error("RPC Failure: %p (%p) (%d) %s", this, clnt, status, clnt_spcreateerror("shibrpc_get_session_2"));
1148 throw ListenerException("Failure requesting session information from listener.");
1156 if (ret.status && *ret.status)
1157 log.debug("RPC completed with exception: %s", ret.status);
1159 log.debug("RPC completed successfully");
1161 SAMLException* except=NULL;
1162 if (ret.status && *ret.status) {
1163 // Reconstitute exception object.
1165 istringstream estr(ret.status);
1166 except=SAMLException::getInstance(estr);
1168 catch (SAMLException& e) {
1169 log.error("caught SAML Exception while building the SAMLException: %s", e.what());
1170 log.error("XML was: %s", ret.status);
1171 clnt_freeres(clnt, (xdrproc_t)xdr_shibrpc_get_session_ret_2, (caddr_t)&ret);
1173 throw FatalProfileException("An unrecoverable error occurred while accessing your session.");
1176 log.error("caught unknown exception building SAMLException");
1177 log.error("XML was: %s", ret.status);
1178 clnt_freeres(clnt, (xdrproc_t)xdr_shibrpc_get_session_ret_2, (caddr_t)&ret);
1185 profile = ret.profile;
1186 provider_id = ret.provider_id;
1188 // return the Authentication Statement
1189 if (auth_statement) {
1190 istringstream authstream(ret.auth_statement);
1191 log.debugStream() << "trying to decode authentication statement: "
1192 << ret.auth_statement << CategoryStream::ENDLINE;
1193 *auth_statement = new SAMLAuthenticationStatement(authstream);
1196 // return the unfiltered Response
1197 if (attr_response_pre) {
1198 istringstream prestream(ret.attr_response_pre);
1199 log.debugStream() << "trying to decode unfiltered attribute response: "
1200 << ret.attr_response_pre << CategoryStream::ENDLINE;
1201 *attr_response_pre = new SAMLResponse(prestream);
1204 // return the filtered Response
1205 if (attr_response_post) {
1206 istringstream poststream(ret.attr_response_post);
1207 log.debugStream() << "trying to decode filtered attribute response: "
1208 << ret.attr_response_post << CategoryStream::ENDLINE;
1209 *attr_response_post = new SAMLResponse(poststream);
1212 catch (SAMLException& e) {
1213 log.error("caught SAML exception while reconstituting session objects: %s", e.what());
1214 clnt_freeres (clnt, (xdrproc_t)xdr_shibrpc_get_session_ret_2, (caddr_t)&ret);
1220 log.error("caught unknown exception while reconstituting session objects");
1221 clnt_freeres (clnt, (xdrproc_t)xdr_shibrpc_get_session_ret_2, (caddr_t)&ret);
1228 clnt_freeres (clnt, (xdrproc_t)xdr_shibrpc_get_session_ret_2, (caddr_t)&ret);
1231 auto_ptr<SAMLException> wrapper(except);
1236 /*************************************************************************
1237 * Shib Target Private implementation
1240 ShibTargetPriv::ShibTargetPriv() : m_app(NULL), m_mapper(NULL), m_conf(NULL), m_Config(NULL), session_id(NULL), relay_state(NULL),
1241 m_sso_profile(PROFILE_UNSPECIFIED), m_sso_statement(NULL), m_pre_response(NULL), m_post_response(NULL) {}
1243 ShibTargetPriv::~ShibTargetPriv()
1245 delete m_sso_statement;
1246 m_sso_statement = NULL;
1248 delete m_pre_response;
1249 m_pre_response = NULL;
1251 delete m_post_response;
1252 m_post_response = NULL;
1266 static inline char hexchar(unsigned short s)
1268 return (s<=9) ? ('0' + s) : ('A' + s - 10);
1272 ShibTargetPriv::url_encode(const char* s)
1274 static char badchars[]="\"\\+<>#%{}|^~[]`;/?:@=&";
1278 if (strchr(badchars,*s) || *s<=0x1F || *s>=0x7F) {
1280 ret+=hexchar(*s >> 4);
1281 ret+=hexchar(*s & 0x0F);
1290 ShibTargetPriv::get_application(const string& protocol, const string& hostname, int port, const string& uri)
1295 // XXX: Do we need to keep conf and mapper locked while we hold m_app?
1296 // TODO: No, should be able to hold the conf but release the mapper.
1298 // We lock the configuration system for the duration.
1299 m_conf=m_Config->getINI();
1302 // Map request to application and content settings.
1303 m_mapper=m_conf->getRequestMapper();
1306 // Obtain the application settings from the parsed URL
1307 m_settings = m_mapper->getSettingsFromParsedURL(protocol.c_str(),
1311 // Now find the application from the URL settings
1312 pair<bool,const char*> application_id=m_settings.first->getString("applicationId");
1313 const IApplication* application=m_conf->getApplication(application_id.second);
1319 throw SAMLException("Unable to map request to application settings, check configuration.");
1322 // Store the application for later use
1323 m_app = application;
1325 // Compute the target URL
1326 m_url = protocol + "://" + hostname;
1327 if ((protocol == "http" && port != 80) || (protocol == "https" && port != 443))
1328 m_url += ":" + port;
1334 ShibTargetPriv::sendError(ShibTarget* st, string page, ShibMLP &mlp)
1336 const IPropertySet* props=m_app->getPropertySet("Errors");
1338 pair<bool,const char*> p=props->getString(page.c_str());
1340 ifstream infile(p.second);
1341 if (!infile.fail()) {
1342 const char* res = mlp.run(infile,props);
1344 return st->sendPage(res);
1349 string errstr = "sendError could not process the error template for application (";
1350 errstr += m_app->getId();
1352 st->log(ShibTarget::LogLevelError, errstr);
1353 return st->sendPage("Internal Server Error. Please contact the site administrator.");
1356 const char* ShibTargetPriv::getSessionId(ShibTarget* st)
1359 //string m = string("getSessionId returning precreated session_id: ") + session_id;
1360 //st->log(ShibTarget::LogLevelDebug, m);
1365 pair<string,const char*> shib_cookie = st->getCookieNameProps("_shibsession_");
1366 if (m_cookies.empty())
1367 m_cookies = st->getCookies();
1368 if (!m_cookies.empty()) {
1369 if (sid = strstr(m_cookies.c_str(), shib_cookie.first.c_str())) {
1370 // We found a cookie. pull it out (our session_id)
1371 sid += shib_cookie.first.length() + 1; // skip over the '='
1372 char *cookieend = strchr(sid, ';');
1379 //string m = string("getSessionId returning new session_id: ") + session_id;
1380 //st->log(ShibTarget::LogLevelDebug, m);
1384 const char* ShibTargetPriv::getRelayState(ShibTarget* st)
1390 pair<string,const char*> shib_cookie = st->getCookieNameProps("_shibstate_");
1391 if (m_cookies.empty())
1392 m_cookies = st->getCookies();
1393 if (!m_cookies.empty()) {
1394 if (sid = strstr(m_cookies.c_str(), shib_cookie.first.c_str())) {
1395 // We found a cookie. pull it out
1396 sid += shib_cookie.first.length() + 1; // skip over the '='
1397 char *cookieend = strchr(sid, ';');
1407 /*************************************************************************
1408 * CGI Parser implementation
1411 CgiParse::CgiParse(const char* data, unsigned int len)
1413 const char* pch = data;
1414 unsigned int cl = len;
1419 value=fmakeword('&',&cl,&pch);
1422 name=makeword(value,'=');
1423 kvp_map[name]=value;
1428 CgiParse::~CgiParse()
1430 for (map<string,char*>::iterator i=kvp_map.begin(); i!=kvp_map.end(); i++)
1435 CgiParse::get_value(const char* name) const
1437 map<string,char*>::const_iterator i=kvp_map.find(name);
1438 if (i==kvp_map.end())
1443 /* Parsing routines modified from NCSA source. */
1445 CgiParse::makeword(char *line, char stop)
1448 char *word = (char *) malloc(sizeof(char) * (strlen(line) + 1));
1450 for(x=0;((line[x]) && (line[x] != stop));x++)
1459 line[y++] = line[x++];
1465 CgiParse::fmakeword(char stop, unsigned int *cl, const char** ppch)
1473 word = (char *) malloc(sizeof(char) * (wsize + 1));
1477 word[ll] = *((*ppch)++);
1482 word = (char *)realloc(word,sizeof(char)*(wsize+1));
1485 if((word[ll] == stop) || word[ll] == EOF || (!(*cl)))
1487 if(word[ll] != stop)
1497 CgiParse::plustospace(char *str)
1502 if(str[x] == '+') str[x] = ' ';
1506 CgiParse::x2c(char *what)
1508 register char digit;
1510 digit = (what[0] >= 'A' ? ((what[0] & 0xdf) - 'A')+10 : (what[0] - '0'));
1512 digit += (what[1] >= 'A' ? ((what[1] & 0xdf) - 'A')+10 : (what[1] - '0'));
1517 CgiParse::url_decode(char *url)
1521 for(x=0,y=0;url[y];++x,++y)
1523 if((url[x] = url[y]) == '%')
1525 url[x] = x2c(&url[y+1]);
1532 // Subclasses may not need to override these particular virtual methods.
1533 string ShibTarget::getAuthType(void)
1535 return string("shibboleth");
1537 void* ShibTarget::returnDecline(void)
1541 void* ShibTarget::returnOK(void)
1545 HTAccessInfo* ShibTarget::getAccessInfo(void)
1549 HTGroupTable* ShibTarget::getGroupTable(string &user)