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,
168 const char* protocol,
169 const char* hostname,
172 const char* content_type,
173 const char* remote_host,
178 saml::NDC ndc("ShibTarget::init");
182 throw runtime_error("ShibTarget Already Initialized");
184 throw runtime_error("config is NULL. Oops.");
186 if (protocol) m_priv->m_protocol = protocol;
187 if (content_type) m_priv->m_content_type = content_type;
188 if (remote_host) m_priv->m_remote_addr = remote_host;
189 if (method) m_priv->m_method = method;
190 m_priv->m_Config = config;
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.c_str())
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;
436 throw SAMLException("System uninitialized, application did not supply request information.");
438 targetURL = m_priv->m_url.c_str();
439 const char *session_id = m_priv->getSessionId(this);
441 // Do we have an access control plugin?
442 if (m_priv->m_settings.second) {
443 Locker acllock(m_priv->m_settings.second);
444 if (!m_priv->m_settings.second->authorized(*m_priv->m_sso_statement,
445 m_priv->m_post_response ? m_priv->m_post_response->getAssertions() : EMPTY(SAMLAssertion*))) {
446 log(LogLevelError, "doCheckAuthZ() access control provider denied access");
448 mlp.insert("requestURL", targetURL);
449 // TODO: check setting and return 403
450 return pair<bool,void*>(true,m_priv->sendError(this, "access", mlp));
454 // Perform HTAccess Checks
455 auto_ptr<HTAccessInfo> ht(getAccessInfo());
457 // No Info means OK. Just return
459 return pair<bool,void*>(false, NULL);
461 vector<bool> auth_OK(ht->elements.size(), false);
462 bool method_restricted=false;
463 string remote_user = getRemoteUser();
467 if (!ht->requireAll) { \
468 return pair<bool,void*>(false, NULL); \
474 for (int x = 0; x < ht->elements.size(); x++) {
476 HTAccessInfo::RequireLine *line = ht->elements[x];
477 if (! line->use_line)
479 method_restricted = true;
481 const char *w = line->tokens[0].c_str();
483 if (!strcasecmp(w,"Shibboleth")) {
484 // This is a dummy rule needed because Apache conflates authn and authz.
485 // Without some require rule, AuthType is ignored and no check_user hooks run.
488 else if (!strcmp(w,"valid-user")) {
489 log(LogLevelDebug, "doCheckAuthZ accepting valid-user");
492 else if (!strcmp(w,"user") && !remote_user.empty()) {
494 for (int i = 1; i < line->tokens.size(); i++) {
495 w = line->tokens[i].c_str();
503 // To do regex matching, we have to convert from UTF-8.
504 auto_ptr<XMLCh> trans(fromUTF8(w));
505 RegularExpression re(trans.get());
506 auto_ptr<XMLCh> trans2(fromUTF8(remote_user.c_str()));
507 if (re.matches(trans2.get())) {
508 log(LogLevelDebug, string("doCheckAuthZ accepting user: ") + w);
512 catch (XMLException& ex) {
513 auto_ptr_char tmp(ex.getMessage());
514 log(LogLevelError, string("doCheckAuthZ caught exception while parsing regular expression (")
515 + w + "): " + tmp.get());
518 else if (!strcmp(remote_user.c_str(), w)) {
519 log(LogLevelDebug, string("doCheckAuthZ accepting user: ") + w);
524 else if (!strcmp(w,"group")) {
525 auto_ptr<HTGroupTable> grpstatus(getGroupTable(remote_user));
526 if (!grpstatus.get()) {
527 return pair<bool,void*>(true, returnDecline());
530 for (int i = 1; i < line->tokens.size(); i++) {
531 w = line->tokens[i].c_str();
532 if (grpstatus->lookup(w)) {
533 log(LogLevelDebug, string("doCheckAuthZ accepting group: ") + w);
539 Iterator<IAAP*> provs = m_priv->m_app->getAAPProviders();
540 AAP wrapper(provs, w);
541 if (wrapper.fail()) {
542 log(LogLevelWarn, string("doCheckAuthZ didn't recognize require rule: ") + w);
547 string vals = getHeader(wrapper->getHeader());
548 for (int i = 1; i < line->tokens.size() && !vals.empty(); i++) {
549 w = line->tokens[i].c_str();
556 auto_ptr<RegularExpression> re;
559 auto_ptr<XMLCh> trans(fromUTF8(w));
560 auto_ptr<RegularExpression> temp(new RegularExpression(trans.get()));
564 string vals_str(vals);
566 for (int i = 0; i < vals_str.length(); i++) {
567 if (vals_str.at(i) == ';') {
569 log(LogLevelError, string("doCheckAuthZ invalid header encoding") +
570 vals + ": starts with a semicolon");
571 throw SAMLException("Invalid information supplied to authorization module.");
574 if (vals_str.at(i-1) == '\\') {
575 vals_str.erase(i-1, 1);
580 string val = vals_str.substr(j, i-j);
583 auto_ptr<XMLCh> trans(fromUTF8(val.c_str()));
584 if (re->matches(trans.get())) {
585 log(LogLevelDebug, string("doCheckAuthZ expecting ") + w +
586 ", got " + val + ": authorization granted");
590 else if ((wrapper->getCaseSensitive() && val==w) ||
591 (!wrapper->getCaseSensitive() && !strcasecmp(val.c_str(),w))) {
592 log(LogLevelDebug, string("doCheckAuthZ expecting ") + w +
593 ", got " + val + ": authorization granted.");
597 log(LogLevelDebug, string("doCheckAuthZ expecting ") + w +
598 ", got " + val + ": authoritzation not granted.");
603 string val = vals_str.substr(j, vals_str.length()-j);
605 auto_ptr<XMLCh> trans(fromUTF8(val.c_str()));
606 if (re->matches(trans.get())) {
607 log(LogLevelDebug, string("doCheckAuthZ expecting ") + w +
608 ", got " + val + ": authorization granted.");
612 else if ((wrapper->getCaseSensitive() && val==w) ||
613 (!wrapper->getCaseSensitive() && !strcasecmp(val.c_str(),w))) {
614 log(LogLevelDebug, string("doCheckAuthZ expecting ") + w +
615 ", got " + val + ": authorization granted");
619 log(LogLevelDebug, string("doCheckAuthZ expecting ") + w +
620 ", got " + val + ": authorization not granted");
623 catch (XMLException& ex) {
624 auto_ptr_char tmp(ex.getMessage());
625 log(LogLevelError, string("doCheckAuthZ caught exception while parsing regular expression (")
626 + w + "): " + tmp.get());
633 // check if all require directives are true
634 bool auth_all_OK = true;
635 for (int i = 0; i < ht->elements.size(); i++) {
636 auth_all_OK &= auth_OK[i];
639 if (auth_all_OK || !method_restricted)
640 return pair<bool,void*>(false, NULL);
642 // If we get here there's an access error, so just fall through
644 catch (SAMLException& e) {
649 mlp.insert("errorText", "Caught an unknown exception.");
653 // If we get here then we've got an error.
654 mlp.insert("errorType", procState);
657 mlp.insert("requestURL", targetURL);
659 return pair<bool,void*>(true,m_priv->sendError(this, "access", mlp));
663 ShibTarget::doExportAssertions(bool exportAssertion)
666 saml::NDC ndc("ShibTarget::doExportAssertions");
670 const char *procState = "Attribute Processing Error";
671 const char *targetURL = NULL;
676 throw SAMLException("System uninitialized, application did not supply request information.");
678 targetURL = m_priv->m_url.c_str();
679 const char *session_id = m_priv->getSessionId(this);
681 if (!m_priv->m_sso_statement) {
682 // No data yet, so we need to get the session. This can only happen
683 // if the call to doCheckAuthn doesn't happen in the same object lifetime.
686 m_priv->m_remote_addr.c_str(),
687 m_priv->m_sso_profile,
688 m_priv->m_provider_id,
689 &m_priv->m_sso_statement,
690 &m_priv->m_pre_response,
691 &m_priv->m_post_response
695 // Get the AAP providers, which contain the attribute policy info.
696 Iterator<IAAP*> provs=m_priv->m_app->getAAPProviders();
698 // Clear out the list of mapped attributes
699 while (provs.hasNext()) {
700 IAAP* aap=provs.next();
702 Iterator<const IAttributeRule*> rules=aap->getAttributeRules();
703 while (rules.hasNext()) {
704 const char* header=rules.next()->getHeader();
710 // Maybe export the first assertion.
711 clearHeader("Shib-Attributes");
712 pair<bool,bool> exp=m_priv->m_settings.first->getBool("exportAssertion");
713 if (!exp.first || !exp.second)
716 if (exp.second && m_priv->m_pre_response) {
718 os << *(m_priv->m_pre_response);
720 XMLByte* serialized = Base64::encode(reinterpret_cast<XMLByte*>((char*)os.str().c_str()), os.str().length(), &outlen);
721 for (XMLByte* pos=serialized, *pos2=serialized; *pos2; pos2++)
725 setHeader("Shib-Attributes", reinterpret_cast<char*>(serialized));
726 XMLString::release(&serialized);
729 // Export the SAML AuthnMethod and the origin site name, and possibly the NameIdentifier.
730 clearHeader("Shib-Origin-Site");
731 clearHeader("Shib-Identity-Provider");
732 clearHeader("Shib-Authentication-Method");
733 clearHeader("Shib-NameIdentifier-Format");
734 setHeader("Shib-Origin-Site", m_priv->m_provider_id.c_str());
735 setHeader("Shib-Identity-Provider", m_priv->m_provider_id.c_str());
736 auto_ptr_char am(m_priv->m_sso_statement->getAuthMethod());
737 setHeader("Shib-Authentication-Method", am.get());
741 while (provs.hasNext()) {
742 IAAP* aap=provs.next();
744 const IAttributeRule* rule=aap->lookup(m_priv->m_sso_statement->getSubject()->getNameIdentifier()->getFormat());
745 if (rule && rule->getHeader()) {
746 auto_ptr_char form(m_priv->m_sso_statement->getSubject()->getNameIdentifier()->getFormat());
747 auto_ptr_char nameid(m_priv->m_sso_statement->getSubject()->getNameIdentifier()->getName());
748 setHeader("Shib-NameIdentifier-Format", form.get());
749 if (!strcmp(rule->getHeader(),"REMOTE_USER"))
750 setRemoteUser(nameid.get());
752 setHeader(rule->getHeader(), nameid.get());
756 clearHeader("Shib-Application-ID");
757 setHeader("Shib-Application-ID", m_priv->m_app->getId());
759 // Export the attributes.
760 Iterator<SAMLAssertion*> a_iter(m_priv->m_post_response ? m_priv->m_post_response->getAssertions() : EMPTY(SAMLAssertion*));
761 while (a_iter.hasNext()) {
762 SAMLAssertion* assert=a_iter.next();
763 Iterator<SAMLStatement*> statements=assert->getStatements();
764 while (statements.hasNext()) {
765 SAMLAttributeStatement* astate=dynamic_cast<SAMLAttributeStatement*>(statements.next());
768 Iterator<SAMLAttribute*> attrs=astate->getAttributes();
769 while (attrs.hasNext()) {
770 SAMLAttribute* attr=attrs.next();
772 // Are we supposed to export it?
774 while (provs.hasNext()) {
775 IAAP* aap=provs.next();
777 const IAttributeRule* rule=aap->lookup(attr->getName(),attr->getNamespace());
778 if (!rule || !rule->getHeader())
781 Iterator<string> vals=attr->getSingleByteValues();
782 if (!strcmp(rule->getHeader(),"REMOTE_USER") && vals.hasNext())
783 setRemoteUser(vals.next());
786 string header = getHeader(rule->getHeader());
789 for (; vals.hasNext(); it++) {
790 string value = vals.next();
791 for (string::size_type pos = value.find_first_of(";", string::size_type(0));
793 pos = value.find_first_of(";", pos)) {
794 value.insert(pos, "\\");
801 setHeader(rule->getHeader(), header);
808 return pair<bool,void*>(false,NULL);
810 catch (SAMLException& e) {
815 mlp.insert("errorText", "Caught an unknown exception.");
819 // If we get here then we've got an error.
820 mlp.insert("errorType", procState);
823 mlp.insert("requestURL", targetURL);
825 return pair<bool,void*>(true,m_priv->sendError(this, page, mlp));
831 // Get the session cookie name and properties for the application
832 pair<string,const char*> ShibTarget::getCookieNameProps(const char* prefix) const
834 static const char* defProps="; path=/";
836 const IPropertySet* props=m_priv->m_app ? m_priv->m_app->getPropertySet("Sessions") : NULL;
838 pair<bool,const char*> p=props->getString("cookieProps");
841 pair<bool,const char*> p2=props->getString("cookieName");
843 return make_pair(string(prefix) + p2.second,p.second);
844 return make_pair(string(prefix) + m_priv->m_app->getHash(),p.second);
847 // Shouldn't happen, but just in case..
848 return make_pair(prefix,defProps);
851 // Find the default assertion consumer service for the resource
853 ShibTarget::getShireURL(const char* resource) const
855 if (!m_priv->m_shireURL.empty())
856 return m_priv->m_shireURL.c_str();
858 // XXX: what to do is m_app is NULL?
860 bool shire_ssl_only=false;
861 const char* shire=NULL;
862 const IPropertySet* props=m_priv->m_app->getPropertySet("Sessions");
864 pair<bool,bool> p=props->getBool("shireSSL");
866 shire_ssl_only=p.second;
867 pair<bool,const char*> p2=props->getString("shireURL");
872 // Should never happen...
873 if (!shire || (*shire!='/' && strncmp(shire,"http:",5) && strncmp(shire,"https:",6)))
876 // The "shireURL" property can be in one of three formats:
878 // 1) a full URI: http://host/foo/bar
879 // 2) a hostless URI: http:///foo/bar
880 // 3) a relative path: /foo/bar
882 // # Protocol Host Path
883 // 1 shire shire shire
884 // 2 shire resource shire
885 // 3 resource resource shire
887 // note: if shire_ssl_only is true, make sure the protocol is https
889 const char* path = NULL;
891 // Decide whether to use the shire or the resource for the "protocol"
901 // break apart the "protocol" string into protocol, host, and "the rest"
902 const char* colon=strchr(prot,':');
904 const char* slash=strchr(colon,'/');
908 // Compute the actual protocol and store in member.
910 m_priv->m_shireURL.assign("https://");
912 m_priv->m_shireURL.assign(prot, colon-prot);
914 // create the "host" from either the colon/slash or from the target string
915 // If prot == shire then we're in either #1 or #2, else #3.
916 // If slash == colon then we're in #2.
917 if (prot != shire || slash == colon) {
918 colon = strchr(resource, ':');
919 colon += 3; // Get past the ://
920 slash = strchr(colon, '/');
922 string host(colon, slash-colon);
924 // Build the shire URL
925 m_priv->m_shireURL+=host + path;
926 return m_priv->m_shireURL.c_str();
929 // Generate a Shib 1.x AuthnRequest redirect URL for the resource,
930 // using whatever relay state mechanism is specified for the app.
931 string ShibTarget::getAuthnRequest(const char* resource)
933 // XXX: what to do if m_app is NULL?
937 sprintf(timebuf,"%u",time(NULL));
939 const IPropertySet* props=m_priv->m_app ? m_priv->m_app->getPropertySet("Sessions") : NULL;
941 pair<bool,const char*> wayf=props->getString("wayfURL");
943 req=req + wayf.second + "?shire=" + m_priv->url_encode(getShireURL(resource)) + "&time=" + timebuf;
945 // How should the target value be preserved?
946 pair<bool,bool> localRelayState=m_priv->m_conf->getPropertySet("Local")->getBool("localRelayState");
947 if (!localRelayState.first || !localRelayState.second) {
948 // The old way, just send it along.
949 req = req + "&target=" + m_priv->url_encode(resource);
952 // Here we store the state in a cookie and send a fixed
953 // value to the IdP so we can recognize it on the way back.
954 pair<string,const char*> shib_cookie=getCookieNameProps("_shibstate_");
955 setCookie(shib_cookie.first,m_priv->url_encode(resource) + shib_cookie.second);
956 req += "&target=cookie";
959 pair<bool,bool> old=m_priv->m_app->getBool("oldAuthnRequest");
960 if (!old.first || !old.second) {
961 wayf=m_priv->m_app->getString("providerId");
963 req=req + "&providerId=" + m_priv->url_encode(wayf.second);
970 // Process a lazy session setup request and turn it into an AuthnRequest
971 string ShibTarget::getLazyAuthnRequest(const char* query_string)
973 CgiParse parser(query_string,strlen(query_string));
974 const char* target=parser.get_value("target");
975 if (!target || !*target)
977 return getAuthnRequest(target);
980 void ShibTarget::sessionNew(
981 int supported_profiles,
989 saml::NDC ndc("sessionNew");
991 Category& log = Category::getInstance("shibtarget.ShibTarget");
993 if (!packet || !*packet) {
994 log.error("missing profile response");
995 throw FatalProfileException("Profile response missing.");
999 log.error("missing client address");
1000 throw FatalProfileException("Invalid client address.");
1003 if (supported_profiles <= 0) {
1004 log.error("no profile support indicated");
1005 throw FatalProfileException("No profile support indicated.");
1008 shibrpc_new_session_args_2 arg;
1009 arg.recipient = (char*) m_priv->m_shireURL.c_str();
1010 arg.application_id = (char*) m_priv->m_app->getId();
1011 arg.packet = (char*)packet;
1012 arg.client_addr = (char*)ip;
1013 arg.supported_profiles = supported_profiles;
1015 log.info("create session for user at (%s) for application (%s)", ip, arg.application_id);
1017 shibrpc_new_session_ret_2 ret;
1018 memset(&ret, 0, sizeof(ret));
1020 // Loop on the RPC in case we lost contact the first time through
1025 clnt = rpc->connect();
1026 clnt_stat status = shibrpc_new_session_2 (&arg, &ret, clnt);
1027 if (status != RPC_SUCCESS) {
1028 // FAILED. Release, disconnect, and retry
1029 log.error("RPC Failure: %p (%p) (%d): %s", this, clnt, status, clnt_spcreateerror("shibrpc_new_session_2"));
1034 throw ListenerException("Failure passing session setup information to listener.");
1037 // SUCCESS. Pool and continue
1042 if (ret.status && *ret.status)
1043 log.debug("RPC completed with exception: %s", ret.status);
1045 log.debug("RPC completed successfully");
1047 SAMLException* except=NULL;
1048 if (ret.status && *ret.status) {
1049 // Reconstitute exception object.
1051 istringstream estr(ret.status);
1052 except=SAMLException::getInstance(estr);
1054 catch (SAMLException& e) {
1055 log.error("caught SAML Exception while building the SAMLException: %s", e.what());
1056 log.error("XML was: %s", ret.status);
1057 clnt_freeres(clnt, (xdrproc_t)xdr_shibrpc_new_session_ret_2, (caddr_t)&ret);
1059 throw FatalProfileException("An unrecoverable error occurred while creating your session.");
1063 log.error("caught unknown exception building SAMLException");
1064 log.error("XML was: %s", ret.status);
1065 clnt_freeres(clnt, (xdrproc_t)xdr_shibrpc_new_session_ret_2, (caddr_t)&ret);
1072 log.debug("new session cookie: %s", ret.cookie);
1073 cookie = ret.cookie;
1075 target = ret.target;
1078 clnt_freeres(clnt, (xdrproc_t)xdr_shibrpc_new_session_ret_2, (caddr_t)&ret);
1081 auto_ptr<SAMLException> wrapper(except);
1086 void ShibTarget::sessionGet(
1089 ShibProfile& profile,
1090 string& provider_id,
1091 SAMLAuthenticationStatement** auth_statement,
1092 SAMLResponse** attr_response_pre,
1093 SAMLResponse** attr_response_post
1097 saml::NDC ndc("sessionGet");
1099 Category& log = Category::getInstance("shibtarget.ShibTarget");
1101 if (!cookie || !*cookie) {
1102 log.error("no session key provided");
1103 throw InvalidSessionException("No session key was provided.");
1105 else if (strchr(cookie,'=')) {
1106 log.error("cookie value not extracted successfully, probably overlapping cookies across domains");
1107 throw InvalidSessionException("The session key wasn't extracted successfully from the browser cookie.");
1111 log.error("invalid client Address");
1112 throw FatalProfileException("Invalid client address.");
1115 log.info("getting session for client at (%s)", ip);
1116 log.debug("session cookie (%s)", cookie);
1118 shibrpc_get_session_args_2 arg;
1119 arg.cookie = (char*)cookie;
1120 arg.client_addr = (char*)ip;
1121 arg.application_id = (char*)m_priv->m_app->getId();
1123 shibrpc_get_session_ret_2 ret;
1124 memset (&ret, 0, sizeof(ret));
1126 // Loop on the RPC in case we lost contact the first time through
1131 clnt = rpc->connect();
1132 clnt_stat status = shibrpc_get_session_2(&arg, &ret, clnt);
1133 if (status != RPC_SUCCESS) {
1134 // FAILED. Release, disconnect, and try again...
1135 log.error("RPC Failure: %p (%p) (%d) %s", this, clnt, status, clnt_spcreateerror("shibrpc_get_session_2"));
1140 throw ListenerException("Failure requesting session information from listener.");
1148 if (ret.status && *ret.status)
1149 log.debug("RPC completed with exception: %s", ret.status);
1151 log.debug("RPC completed successfully");
1153 SAMLException* except=NULL;
1154 if (ret.status && *ret.status) {
1155 // Reconstitute exception object.
1157 istringstream estr(ret.status);
1158 except=SAMLException::getInstance(estr);
1160 catch (SAMLException& e) {
1161 log.error("caught SAML Exception while building the SAMLException: %s", e.what());
1162 log.error("XML was: %s", ret.status);
1163 clnt_freeres(clnt, (xdrproc_t)xdr_shibrpc_get_session_ret_2, (caddr_t)&ret);
1165 throw FatalProfileException("An unrecoverable error occurred while accessing your session.");
1168 log.error("caught unknown exception building SAMLException");
1169 log.error("XML was: %s", ret.status);
1170 clnt_freeres(clnt, (xdrproc_t)xdr_shibrpc_get_session_ret_2, (caddr_t)&ret);
1177 profile = ret.profile;
1178 provider_id = ret.provider_id;
1180 // return the Authentication Statement
1181 if (auth_statement) {
1182 istringstream authstream(ret.auth_statement);
1183 log.debugStream() << "trying to decode authentication statement: "
1184 << ret.auth_statement << CategoryStream::ENDLINE;
1185 *auth_statement = new SAMLAuthenticationStatement(authstream);
1188 // return the unfiltered Response
1189 if (attr_response_pre) {
1190 istringstream prestream(ret.attr_response_pre);
1191 log.debugStream() << "trying to decode unfiltered attribute response: "
1192 << ret.attr_response_pre << CategoryStream::ENDLINE;
1193 *attr_response_pre = new SAMLResponse(prestream);
1196 // return the filtered Response
1197 if (attr_response_post) {
1198 istringstream poststream(ret.attr_response_post);
1199 log.debugStream() << "trying to decode filtered attribute response: "
1200 << ret.attr_response_post << CategoryStream::ENDLINE;
1201 *attr_response_post = new SAMLResponse(poststream);
1204 catch (SAMLException& e) {
1205 log.error("caught SAML exception while reconstituting session objects: %s", e.what());
1206 clnt_freeres (clnt, (xdrproc_t)xdr_shibrpc_get_session_ret_2, (caddr_t)&ret);
1212 log.error("caught unknown exception while reconstituting session objects");
1213 clnt_freeres (clnt, (xdrproc_t)xdr_shibrpc_get_session_ret_2, (caddr_t)&ret);
1220 clnt_freeres (clnt, (xdrproc_t)xdr_shibrpc_get_session_ret_2, (caddr_t)&ret);
1223 auto_ptr<SAMLException> wrapper(except);
1228 /*************************************************************************
1229 * Shib Target Private implementation
1232 ShibTargetPriv::ShibTargetPriv() : m_app(NULL), m_mapper(NULL), m_conf(NULL), m_Config(NULL), session_id(NULL), relay_state(NULL),
1233 m_sso_profile(PROFILE_UNSPECIFIED), m_sso_statement(NULL), m_pre_response(NULL), m_post_response(NULL) {}
1235 ShibTargetPriv::~ShibTargetPriv()
1237 delete m_sso_statement;
1238 m_sso_statement = NULL;
1240 delete m_pre_response;
1241 m_pre_response = NULL;
1243 delete m_post_response;
1244 m_post_response = NULL;
1258 static inline char hexchar(unsigned short s)
1260 return (s<=9) ? ('0' + s) : ('A' + s - 10);
1264 ShibTargetPriv::url_encode(const char* s)
1266 static char badchars[]="\"\\+<>#%{}|^~[]`;/?:@=&";
1270 if (strchr(badchars,*s) || *s<=0x1F || *s>=0x7F) {
1272 ret+=hexchar(*s >> 4);
1273 ret+=hexchar(*s & 0x0F);
1282 ShibTargetPriv::get_application(const string& protocol, const string& hostname, int port, const string& uri)
1287 // XXX: Do we need to keep conf and mapper locked while we hold m_app?
1288 // TODO: No, should be able to hold the conf but release the mapper.
1290 // We lock the configuration system for the duration.
1291 m_conf=m_Config->getINI();
1294 // Map request to application and content settings.
1295 m_mapper=m_conf->getRequestMapper();
1298 // Obtain the application settings from the parsed URL
1299 m_settings = m_mapper->getSettingsFromParsedURL(protocol.c_str(),
1303 // Now find the application from the URL settings
1304 pair<bool,const char*> application_id=m_settings.first->getString("applicationId");
1305 const IApplication* application=m_conf->getApplication(application_id.second);
1311 throw SAMLException("Unable to map request to application settings, check configuration.");
1314 // Store the application for later use
1315 m_app = application;
1317 // Compute the target URL
1318 m_url = protocol + "://" + hostname;
1319 if ((protocol == "http" && port != 80) || (protocol == "https" && port != 443))
1320 m_url += ":" + port;
1326 ShibTargetPriv::sendError(ShibTarget* st, string page, ShibMLP &mlp)
1328 const IPropertySet* props=m_app->getPropertySet("Errors");
1330 pair<bool,const char*> p=props->getString(page.c_str());
1332 ifstream infile(p.second);
1333 if (!infile.fail()) {
1334 const char* res = mlp.run(infile,props);
1336 return st->sendPage(res);
1341 string errstr = "sendError could not process the error template for application (";
1342 errstr += m_app->getId();
1344 st->log(ShibTarget::LogLevelError, errstr);
1345 return st->sendPage("Internal Server Error. Please contact the site administrator.");
1348 const char* ShibTargetPriv::getSessionId(ShibTarget* st)
1351 //string m = string("getSessionId returning precreated session_id: ") + session_id;
1352 //st->log(ShibTarget::LogLevelDebug, m);
1357 pair<string,const char*> shib_cookie = st->getCookieNameProps("_shibsession_");
1358 if (m_cookies.empty())
1359 m_cookies = st->getCookies();
1360 if (!m_cookies.empty()) {
1361 if (sid = strstr(m_cookies.c_str(), shib_cookie.first.c_str())) {
1362 // We found a cookie. pull it out (our session_id)
1363 sid += shib_cookie.first.length() + 1; // skip over the '='
1364 char *cookieend = strchr(sid, ';');
1371 //string m = string("getSessionId returning new session_id: ") + session_id;
1372 //st->log(ShibTarget::LogLevelDebug, m);
1376 const char* ShibTargetPriv::getRelayState(ShibTarget* st)
1382 pair<string,const char*> shib_cookie = st->getCookieNameProps("_shibstate_");
1383 if (m_cookies.empty())
1384 m_cookies = st->getCookies();
1385 if (!m_cookies.empty()) {
1386 if (sid = strstr(m_cookies.c_str(), shib_cookie.first.c_str())) {
1387 // We found a cookie. pull it out
1388 sid += shib_cookie.first.length() + 1; // skip over the '='
1389 char *cookieend = strchr(sid, ';');
1399 /*************************************************************************
1400 * CGI Parser implementation
1403 CgiParse::CgiParse(const char* data, unsigned int len)
1405 const char* pch = data;
1406 unsigned int cl = len;
1411 value=fmakeword('&',&cl,&pch);
1414 name=makeword(value,'=');
1415 kvp_map[name]=value;
1420 CgiParse::~CgiParse()
1422 for (map<string,char*>::iterator i=kvp_map.begin(); i!=kvp_map.end(); i++)
1427 CgiParse::get_value(const char* name) const
1429 map<string,char*>::const_iterator i=kvp_map.find(name);
1430 if (i==kvp_map.end())
1435 /* Parsing routines modified from NCSA source. */
1437 CgiParse::makeword(char *line, char stop)
1440 char *word = (char *) malloc(sizeof(char) * (strlen(line) + 1));
1442 for(x=0;((line[x]) && (line[x] != stop));x++)
1451 line[y++] = line[x++];
1457 CgiParse::fmakeword(char stop, unsigned int *cl, const char** ppch)
1465 word = (char *) malloc(sizeof(char) * (wsize + 1));
1469 word[ll] = *((*ppch)++);
1474 word = (char *)realloc(word,sizeof(char)*(wsize+1));
1477 if((word[ll] == stop) || word[ll] == EOF || (!(*cl)))
1479 if(word[ll] != stop)
1489 CgiParse::plustospace(char *str)
1494 if(str[x] == '+') str[x] = ' ';
1498 CgiParse::x2c(char *what)
1500 register char digit;
1502 digit = (what[0] >= 'A' ? ((what[0] & 0xdf) - 'A')+10 : (what[0] - '0'));
1504 digit += (what[1] >= 'A' ? ((what[1] & 0xdf) - 'A')+10 : (what[1] - '0'));
1509 CgiParse::url_decode(char *url)
1513 for(x=0,y=0;url[y];++x,++y)
1515 if((url[x] = url[y]) == '%')
1517 url[x] = x2c(&url[y+1]);
1524 // Subclasses may not need to override these particular virtual methods.
1525 string ShibTarget::getAuthType(void)
1527 return string("shibboleth");
1529 void* ShibTarget::returnDecline(void)
1533 void* ShibTarget::returnOK(void)
1537 HTAccessInfo* ShibTarget::getAccessInfo(void)
1541 HTGroupTable* ShibTarget::getGroupTable(string &user)