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>
76 using namespace shibboleth;
77 using namespace shibtarget;
78 using namespace log4cpp;
80 namespace shibtarget {
84 CgiParse(const char* data, unsigned int len);
86 const char* get_value(const char* name) const;
89 char * fmakeword(char stop, unsigned int *cl, const char** ppch);
90 char * makeword(char *line, char stop);
91 void plustospace(char *str);
93 void url_decode(char *url);
95 map<string,char*> kvp_map;
104 string url_encode(const char* s);
105 void get_application(string protocol, string hostname, int port, string uri);
106 void* sendError(ShibTarget* st, string page, ShibMLP &mlp);
107 const char *getSessionId(ShibTarget* st);
109 IRequestMapper::Settings m_settings;
110 const IApplication *m_app;
113 string m_authnRequest;
116 const char *session_id;
119 // These are the actual request parameters set via the init method.
123 string m_content_type;
124 string m_remote_addr;
126 ShibTargetConfig* m_Config;
130 IRequestMapper* m_mapper;
135 /*************************************************************************
136 * Shib Target implementation
139 ShibTarget::ShibTarget(void) : m_priv(NULL)
141 m_priv = new ShibTargetPriv();
144 ShibTarget::ShibTarget(const IApplication *app) : m_priv(NULL)
146 m_priv = new ShibTargetPriv();
150 ShibTarget::~ShibTarget(void)
152 if (m_priv) delete m_priv;
155 void ShibTarget::init(ShibTargetConfig *config,
156 string protocol, string hostname, int port,
157 string uri, string content_type, string remote_host,
160 saml::NDC ndc("ShibTarget::init");
163 throw runtime_error("ShibTarget Already Initialized");
165 throw runtime_error("config is NULL. Oops.");
167 m_priv->m_protocol = protocol;
168 m_priv->m_content_type = content_type;
169 m_priv->m_remote_addr = remote_host;
170 m_priv->m_Config = config;
171 m_priv->m_method = method;
172 m_priv->get_application(protocol, hostname, port, uri);
176 // These functions implement the server-agnostic shibboleth engine
177 // The web server modules implement a subclass and then call into
178 // these methods once they instantiate their request object.
180 ShibTarget::doCheckAuthN(bool requireSessionFlag)
182 saml::NDC ndc("ShibTarget::doCheckAuthN");
184 const char *targetURL = NULL;
185 const char *procState = "Process Initialization Error";
190 throw ShibTargetException(SHIBRPC_OK, "ShibTarget Uninitialized. Application did not supply request information.");
192 targetURL = m_priv->m_url.c_str();
193 const char *shireURL = getShireURL(targetURL);
195 throw ShibTargetException(SHIBRPC_OK, "Cannot map target URL to Shire URL. Check configuration");
197 if (strstr(targetURL,shireURL))
198 return doHandlePOST();
200 string auth_type = getAuthType();
201 #ifdef HAVE_STRCASECMP
202 if (strcasecmp(auth_type.c_str(),"shibboleth"))
204 if (stricmp(auth_type.c_str(),"shibboleth"))
206 return pair<bool,void*>(true,returnDecline());
208 pair<bool,bool> requireSession =
209 m_priv->m_settings.first->getBool("requireSession");
210 if (!requireSession.first || !requireSession.second)
211 if (requireSessionFlag)
212 requireSession.second=true;
214 const char *session_id = m_priv->getSessionId(this);
216 if (!session_id || !*session_id) {
217 // No session. Maybe that's acceptable?
219 if (!requireSession.second)
220 return pair<bool,void*>(true,returnOK());
222 // No cookie, but we require a session. Generate an AuthnRequest.
223 return pair<bool,void*>(true,sendRedirect(getAuthnRequest(targetURL)));
226 procState = "Session Processing Error";
227 RPCError *status = sessionIsValid(session_id, m_priv->m_remote_addr.c_str());
229 if (status->isError()) {
231 // If no session is required, bail now.
232 if (!requireSession.second)
233 return pair<bool,void*>(true, returnOK());
234 // XXX: Or should this be DECLINED?
235 // Has to be OK because DECLINED will just cause Apache
236 // to fail when it can't locate anything to process the
237 // AuthType. No session plus requireSession false means
238 // do not authenticate the user at this time.
239 else if (status->isRetryable()) {
240 // Session is invalid but we can retry the auth -- generate an AuthnRequest
242 return pair<bool,void*>(true,sendRedirect(getAuthnRequest(targetURL)));
246 string er = "Unretryable error: " ;
247 er += status->getText();
248 log(LogLevelError, er);
258 // We're done. Everything is okay. Nothing to report. Nothing to do..
259 // Let the caller decide how to proceed.
260 log(LogLevelInfo, "doCheckAuthN Succeeded\n");
261 return pair<bool,void*>(false,NULL);
263 } catch (ShibTargetException &e) {
264 mlp.insert("errorText", e.what());
268 mlp.insert("errorText", "Unexpected Exception");
272 // If we get here then we've got an error.
273 mlp.insert("errorType", procState);
274 mlp.insert("errorDesc", "An error occurred while processing your request.");
278 mlp.insert("requestURL", targetURL);
280 return pair<bool,void*>(true,m_priv->sendError(this, "shire", mlp));
284 ShibTarget::doHandlePOST(void)
286 saml::NDC ndc("ShibTarget::doHandlePOST");
288 const char *targetURL = NULL;
289 const char *procState = "Session Creation Service Error";
294 throw ShibTargetException(SHIBRPC_OK, "ShibTarget Uninitialized. Application did not supply request information.");
296 targetURL = m_priv->m_url.c_str();
297 const char *shireURL = getShireURL(targetURL);
300 throw ShibTargetException(SHIBRPC_OK, "doHandlePOST: unable to map request to a proper shireURL setting. Check Configuration.");
303 // Make sure we only process the SHIRE requests.
304 if (!strstr(targetURL, shireURL))
305 return pair<bool,void*>(true, returnDecline());
307 const IPropertySet* sessionProps=m_priv->m_app->getPropertySet("Sessions");
309 throw ShibTargetException(SHIBRPC_OK, "doHandlePOST: unable to map request to application session settings. Check configuration");
311 // this always returns something
312 pair<const char*,const char*> shib_cookie=getCookieNameProps();
314 // Process SHIRE request
316 pair<bool,bool> shireSSL=sessionProps->getBool("shireSSL");
318 // Make sure this is SSL, if it should be
319 if ((!shireSSL.first || shireSSL.second) && m_priv->m_protocol == "https")
320 throw ShibTargetException(SHIBRPC_OK, "blocked non-SSL access to session creation service");
322 // If this is a GET, we manufacture an AuthnRequest.
323 if (!strcasecmp(m_priv->m_method.c_str(), "GET")) {
324 string args = getArgs();
325 const char* areq=args.empty() ? NULL : getLazyAuthnRequest(args.c_str());
327 throw ShibTargetException(SHIBRPC_OK, "malformed GET arguments to request a new session");
328 return pair<bool,void*>(true, sendRedirect(areq));
330 else if (strcasecmp(m_priv->m_method.c_str(), "POST")) {
331 throw ShibTargetException(SHIBRPC_OK, "blocked non-POST to SHIRE POST processor");
334 // Make sure this POST is an appropriate content type
335 if (m_priv->m_content_type.empty() ||
336 strcasecmp(m_priv->m_content_type.c_str(),
337 "application/x-www-form-urlencoded")) {
338 string er = string("blocked bad content-type to SHIRE POST processor: ") +
339 m_priv->m_content_type;
340 throw ShibTargetException(SHIBRPC_OK, er.c_str());
343 // Read the POST Data
344 string cgistr = getPostData();
346 // Parse the submission.
347 pair<const char*,const char*> elements =
348 getFormSubmission(cgistr.c_str(),cgistr.length());
350 // Make sure the SAML Response parameter exists
351 if (!elements.first || !*elements.first)
352 throw ShibTargetException(SHIBRPC_OK, "SHIRE POST failed to find SAMLResponse form element");
354 // Make sure the target parameter exists
355 if (!elements.second || !*elements.second)
356 throw ShibTargetException(SHIBRPC_OK, "SHIRE POST failed to find TARGET form element");
360 RPCError* status = sessionCreate(elements.first, m_priv->m_remote_addr.c_str(),
363 if (status->isError()) {
365 sprintf(buf, "(%d): ", status->getCode());
366 string er = string("doHandlePost() POST process failed ") + buf +
368 log(LogLevelError, er);
370 if (status->isRetryable()) {
373 return pair<bool,void*>(true, sendRedirect(getAuthnRequest(elements.second)));
376 // return this error to the user.
384 string("doHandlePost() POST process succeeded. New session: ") + cookie);
386 // We've got a good session, set the cookie...
387 cookie += shib_cookie.second;
388 setCookie(shib_cookie.first, cookie);
390 // ... and redirect to the target
391 return pair<bool,void*>(true, sendRedirect(elements.second));
393 } catch (ShibTargetException &e) {
394 mlp.insert("errorText", e.what());
398 mlp.insert("errorText", "Unexpected Exception");
402 // If we get here then we've got an error.
403 mlp.insert("errorType", procState);
404 mlp.insert("errorDesc", "An error occurred while processing your request.");
408 mlp.insert("requestURL", targetURL);
410 return pair<bool,void*>(true,m_priv->sendError(this, "shire", mlp));
414 ShibTarget::doCheckAuthZ(void)
416 saml::NDC ndc("ShibTarget::doCheckAuthZ");
418 return pair<bool,void*>(false,NULL);
422 ShibTarget::doExportAssertions(bool exportAssertion)
424 saml::NDC ndc("ShibTarget::doExportAssertions");
426 vector<SAMLAssertion*> assertions;
427 SAMLAuthenticationStatement* sso_statement=NULL;
428 RPCError *status = NULL;
430 const char *procState = "Attribute Processing Error";
431 const char *targetURL = NULL;
436 throw ShibTargetException(SHIBRPC_OK, "ShibTarget 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 status = getAssertions(session_id, m_priv->m_remote_addr.c_str(),
442 assertions, &sso_statement);
444 if (status->isError()) {
446 string er = "getAssertions failed: ";
447 er += status->getText();
448 log(LogLevelError, er);
455 // Do we have an access control plugin?
456 if (m_priv->m_settings.second) {
457 Locker acllock(m_priv->m_settings.second);
458 if (!m_priv->m_settings.second->authorized(*sso_statement,assertions)) {
459 log(LogLevelError, "doExportAssertions: access control provider denied access");
465 // Get the AAP providers, which contain the attribute policy info.
466 Iterator<IAAP*> provs=m_priv->m_app->getAAPProviders();
468 // Clear out the list of mapped attributes
469 while (provs.hasNext()) {
470 IAAP* aap=provs.next();
473 Iterator<const IAttributeRule*> rules=aap->getAttributeRules();
474 while (rules.hasNext()) {
475 const char* header=rules.next()->getHeader();
482 log(LogLevelError, "caught unexpected error while clearing headers");
489 // Maybe export the first assertion.
490 clearHeader("Shib-Attributes");
491 pair<bool,bool> exp=m_priv->m_settings.first->getBool("exportAssertion");
492 if (!exp.first || !exp.second)
495 if (exp.second && assertions.size()) {
497 RM::serialize(*(assertions[0]), assertion);
498 setHeader("Shib-Attributes", assertion.c_str());
501 // Export the SAML AuthnMethod and the origin site name, and possibly the NameIdentifier.
502 clearHeader("Shib-Origin-Site");
503 clearHeader("Shib-Authentication-Method");
504 clearHeader("Shib-NameIdentifier-Format");
505 auto_ptr_char os(sso_statement->getSubject()->getNameIdentifier()->getNameQualifier());
506 auto_ptr_char am(sso_statement->getAuthMethod());
507 setHeader("Shib-Origin-Site", os.get());
508 setHeader("Shib-Authentication-Method", am.get());
512 sso_statement->getSubject()->getNameIdentifier()->getFormat(),
513 Constants::SHIB_ATTRIBUTE_NAMESPACE_URI);
514 if (!wrapper.fail() && wrapper->getHeader()) {
515 auto_ptr_char form(sso_statement->getSubject()->getNameIdentifier()->getFormat());
516 auto_ptr_char nameid(sso_statement->getSubject()->getNameIdentifier()->getName());
517 setHeader("Shib-NameIdentifier-Format", form.get());
518 if (!strcmp(wrapper->getHeader(),"REMOTE_USER"))
519 setRemoteUser(nameid.get());
521 setHeader(wrapper->getHeader(), nameid.get());
524 clearHeader("Shib-Application-ID");
525 setHeader("Shib-Application-ID", m_priv->m_app->getId());
527 // Export the attributes.
528 Iterator<SAMLAssertion*> a_iter(assertions);
529 while (a_iter.hasNext()) {
530 SAMLAssertion* assert=a_iter.next();
531 Iterator<SAMLStatement*> statements=assert->getStatements();
532 while (statements.hasNext()) {
533 SAMLAttributeStatement* astate=dynamic_cast<SAMLAttributeStatement*>(statements.next());
536 Iterator<SAMLAttribute*> attrs=astate->getAttributes();
537 while (attrs.hasNext()) {
538 SAMLAttribute* attr=attrs.next();
540 // Are we supposed to export it?
541 AAP wrapper(provs,attr->getName(),attr->getNamespace());
542 if (wrapper.fail() || !wrapper->getHeader())
545 Iterator<string> vals=attr->getSingleByteValues();
546 if (!strcmp(wrapper->getHeader(),"REMOTE_USER") && vals.hasNext())
547 setRemoteUser(vals.next());
550 string header = getHeader(wrapper->getHeader());
551 if (! header.empty())
553 for (; vals.hasNext(); it++) {
554 string value = vals.next();
555 for (string::size_type pos = value.find_first_of(";", string::size_type(0));
557 pos = value.find_first_of(";", pos)) {
558 value.insert(pos, "\\");
565 setHeader(wrapper->getHeader(), header);
572 for (int k = 0; k < assertions.size(); k++)
573 delete assertions[k];
574 delete sso_statement;
576 return pair<bool,void*>(false,NULL);
578 } catch (ShibTargetException &e) {
579 mlp.insert("errorText", e.what());
583 mlp.insert("errorText", "Unexpected Exception");
588 // If we get here then we've got an error.
589 mlp.insert("errorType", procState);
590 mlp.insert("errorDesc", "An error occurred while processing your request.");
594 mlp.insert("requestURL", targetURL);
597 for (int k = 0; k < assertions.size(); k++)
598 delete assertions[k];
600 delete sso_statement;
602 return pair<bool,void*>(true,m_priv->sendError(this, page, mlp));
608 // Get the session cookie name and properties for the application
609 std::pair<const char*,const char*>
610 ShibTarget::getCookieNameProps() const
612 static const char* defProps="; path=/";
613 static const char* defName="_shibsession_";
615 // XXX: What to do if m_app isn't set?
617 const IPropertySet* props=m_priv->m_app->getPropertySet("Sessions");
619 pair<bool,const char*> p=props->getString("cookieProps");
622 if (!m_priv->m_cookieName.empty())
623 return pair<const char*,const char*>(m_priv->m_cookieName.c_str(),
625 pair<bool,const char*> p2=props->getString("cookieName");
627 m_priv->m_cookieName=p2.second;
628 return pair<const char*,const char*>(p2.second,p.second);
630 m_priv->m_cookieName=defName;
631 m_priv->m_cookieName+=m_priv->m_app->getId();
632 return pair<const char*,const char*>(m_priv->m_cookieName.c_str(),p.second);
634 m_priv->m_cookieName=defName;
635 m_priv->m_cookieName+=m_priv->m_app->getId();
636 return pair<const char*,const char*>(m_priv->m_cookieName.c_str(),defProps);
639 // Find the default assertion consumer service for the resource
641 ShibTarget::getShireURL(const char* resource) const
643 if (!m_priv->m_shireURL.empty())
644 return m_priv->m_shireURL.c_str();
646 // XXX: what to do is m_app is NULL?
648 bool shire_ssl_only=false;
649 const char* shire=NULL;
650 const IPropertySet* props=m_priv->m_app->getPropertySet("Sessions");
652 pair<bool,bool> p=props->getBool("shireSSL");
654 shire_ssl_only=p.second;
655 pair<bool,const char*> p2=props->getString("shireURL");
660 // Should never happen...
661 if (!shire || (*shire!='/' && strncmp(shire,"http:",5) && strncmp(shire,"https:",6)))
664 // The "shireURL" property can be in one of three formats:
666 // 1) a full URI: http://host/foo/bar
667 // 2) a hostless URI: http:///foo/bar
668 // 3) a relative path: /foo/bar
670 // # Protocol Host Path
671 // 1 shire shire shire
672 // 2 shire resource shire
673 // 3 resource resource shire
675 // note: if shire_ssl_only is true, make sure the protocol is https
677 const char* path = NULL;
679 // Decide whether to use the shire or the resource for the "protocol"
689 // break apart the "protocol" string into protocol, host, and "the rest"
690 const char* colon=strchr(prot,':');
692 const char* slash=strchr(colon,'/');
696 // Compute the actual protocol and store in member.
698 m_priv->m_shireURL.assign("https://");
700 m_priv->m_shireURL.assign(prot, colon-prot);
702 // create the "host" from either the colon/slash or from the target string
703 // If prot == shire then we're in either #1 or #2, else #3.
704 // If slash == colon then we're in #2.
705 if (prot != shire || slash == colon) {
706 colon = strchr(resource, ':');
707 colon += 3; // Get past the ://
708 slash = strchr(colon, '/');
710 string host(colon, slash-colon);
712 // Build the shire URL
713 m_priv->m_shireURL+=host + path;
714 return m_priv->m_shireURL.c_str();
717 // Generate a Shib 1.x AuthnRequest redirect URL for the resource
719 ShibTarget::getAuthnRequest(const char* resource) const
721 if (!m_priv->m_authnRequest.empty())
722 return m_priv->m_authnRequest.c_str();
724 // XXX: what to do if m_app is NULL?
727 sprintf(timebuf,"%u",time(NULL));
729 const IPropertySet* props=m_priv->m_app->getPropertySet("Sessions");
731 pair<bool,const char*> wayf=props->getString("wayfURL");
733 m_priv->m_authnRequest=m_priv->m_authnRequest + wayf.second + "?shire=" + m_priv->url_encode(getShireURL(resource)) +
734 "&target=" + m_priv->url_encode(resource) + "&time=" + timebuf;
735 pair<bool,bool> old=m_priv->m_app->getBool("oldAuthnRequest");
736 if (!old.first || !old.second) {
737 wayf=m_priv->m_app->getString("providerId");
739 m_priv->m_authnRequest=m_priv->m_authnRequest + "&providerId=" + m_priv->url_encode(wayf.second);
743 return m_priv->m_authnRequest.c_str();
746 // Process a lazy session setup request and turn it into an AuthnRequest
748 ShibTarget::getLazyAuthnRequest(const char* query_string) const
750 CgiParse parser(query_string,strlen(query_string));
751 const char* target=parser.get_value("target");
752 if (!target || !*target)
754 return getAuthnRequest(target);
757 // Process a POST profile submission, and return (SAMLResponse,TARGET) pair.
758 std::pair<const char*,const char*>
759 ShibTarget::getFormSubmission(const char* post, unsigned int len) const
761 m_priv->m_parser = new CgiParse(post,len);
762 return pair<const char*,const char*>(m_priv->m_parser->get_value("SAMLResponse"),m_priv->m_parser->get_value("TARGET"));
766 ShibTarget::sessionCreate(const char* response, const char* ip, std::string &cookie)
769 saml::NDC ndc("sessionCreate");
770 Category& log = Category::getInstance("shibtarget.SHIRE");
772 if (!response || !*response) {
773 log.error ("Empty SAML response content");
774 return new RPCError(-1, "Empty SAML response content");
778 log.error ("Invalid IP address");
779 return new RPCError(-1, "Invalid IP address");
782 shibrpc_new_session_args_1 arg;
783 arg.shire_location = (char*) m_priv->m_shireURL.c_str();
784 arg.application_id = (char*) m_priv->m_app->getId();
785 arg.saml_post = (char*)response;
786 arg.client_addr = (char*)ip;
787 arg.checkIPAddress = true;
789 log.info ("create session for user at %s for application %s", ip, arg.application_id);
791 const IPropertySet* props=m_priv->m_app->getPropertySet("Sessions");
793 pair<bool,bool> pcheck=props->getBool("checkAddress");
795 arg.checkIPAddress = pcheck.second;
798 shibrpc_new_session_ret_1 ret;
799 memset (&ret, 0, sizeof(ret));
801 // Loop on the RPC in case we lost contact the first time through
806 clnt = rpc->connect();
807 clnt_stat status = shibrpc_new_session_1 (&arg, &ret, clnt);
808 if (status != RPC_SUCCESS) {
809 // FAILED. Release, disconnect, and retry
810 log.error("RPC Failure: %p (%p) (%d): %s", this, clnt, status, clnt_spcreateerror("shibrpc_new_session_1"));
815 return new RPCError(-1, "RPC Failure");
818 // SUCCESS. Pool and continue
823 log.debug("RPC completed with status %d (%p)", ret.status.status, this);
826 if (ret.status.status)
827 retval = new RPCError(&ret.status);
829 log.debug ("new cookie: %s", ret.cookie);
831 retval = new RPCError();
834 clnt_freeres(clnt, (xdrproc_t)xdr_shibrpc_new_session_ret_1, (caddr_t)&ret);
837 log.debug("returning");
842 ShibTarget::sessionIsValid(const char* session_id, const char* ip) const
844 saml::NDC ndc("sessionIsValid");
845 Category& log = Category::getInstance("shibtarget.SHIRE");
847 if (!session_id || !*session_id) {
848 log.error ("No cookie value was provided");
849 return new RPCError(SHIBRPC_NO_SESSION, "No cookie value was provided");
851 else if (strchr(session_id,'=')) {
852 log.error ("The cookie value wasn't extracted successfully, use a more unique cookie name for your installation.");
853 return new RPCError(SHIBRPC_INTERNAL_ERROR, "The cookie value wasn't extracted successfully, use a more unique cookie name for your installation.");
857 log.error ("Invalid IP Address");
858 return new RPCError(SHIBRPC_IPADDR_MISSING, "Invalid IP Address");
861 log.info ("is session valid: %s", ip);
862 log.debug ("session cookie: %s", session_id);
864 shibrpc_session_is_valid_args_1 arg;
866 arg.cookie.cookie = (char*)session_id;
867 arg.cookie.client_addr = (char *)ip;
868 arg.application_id = (char *)m_priv->m_app->getId();
870 // Get rest of input from the application Session properties.
873 arg.checkIPAddress = true;
874 const IPropertySet* props=m_priv->m_app->getPropertySet("Sessions");
876 pair<bool,unsigned int> p=props->getUnsignedInt("lifetime");
878 arg.lifetime = p.second;
879 p=props->getUnsignedInt("timeout");
881 arg.timeout = p.second;
882 pair<bool,bool> pcheck=props->getBool("checkAddress");
884 arg.checkIPAddress = pcheck.second;
887 shibrpc_session_is_valid_ret_1 ret;
888 memset (&ret, 0, sizeof(ret));
890 // Loop on the RPC in case we lost contact the first time through
895 clnt = rpc->connect();
896 clnt_stat status = shibrpc_session_is_valid_1(&arg, &ret, clnt);
897 if (status != RPC_SUCCESS) {
898 // FAILED. Release, disconnect, and try again...
899 log.error("RPC Failure: %p (%p) (%d) %s", this, clnt, status, clnt_spcreateerror("shibrpc_session_is_valid_1"));
904 return new RPCError(-1, "RPC Failure");
912 log.debug("RPC completed with status %d, %p", ret.status.status, this);
915 if (ret.status.status)
916 retval = new RPCError(&ret.status);
918 retval = new RPCError();
920 clnt_freeres (clnt, (xdrproc_t)xdr_shibrpc_session_is_valid_ret_1, (caddr_t)&ret);
923 log.debug("returning");
930 ShibTarget::getAssertions(const char* cookie, const char* ip,
931 std::vector<saml::SAMLAssertion*>& assertions,
932 saml::SAMLAuthenticationStatement **statement
935 saml::NDC ndc("getAssertions");
936 Category& log=Category::getInstance("shibtarget.RM");
937 log.info("get assertions...");
939 if (!cookie || !*cookie) {
940 log.error ("No cookie value provided.");
941 return new RPCError(-1, "No cookie value provided.");
945 log.error ("Invalid ip address");
946 return new RPCError(-1, "Invalid IP address");
949 log.debug("session cookie: %s", cookie);
951 shibrpc_get_assertions_args_1 arg;
952 arg.cookie.cookie = (char*)cookie;
953 arg.cookie.client_addr = (char*)ip;
954 arg.checkIPAddress = true;
955 arg.application_id = (char *)m_priv->m_app->getId();
957 log.info("request from %s for \"%s\"", ip, arg.application_id);
959 const IPropertySet* props=m_priv->m_app->getPropertySet("Sessions");
961 pair<bool,bool> pcheck=props->getBool("checkAddress");
963 arg.checkIPAddress = pcheck.second;
966 shibrpc_get_assertions_ret_1 ret;
967 memset (&ret, 0, sizeof(ret));
969 // Loop on the RPC in case we lost contact the first time through
974 clnt = rpc->connect();
975 clnt_stat status = shibrpc_get_assertions_1(&arg, &ret, clnt);
976 if (status != RPC_SUCCESS) {
977 // FAILED. Release, disconnect, and try again.
978 log.debug("RPC Failure: %p (%p) (%d): %s", this, clnt, status, clnt_spcreateerror("shibrpc_get_assertions_1"));
983 return new RPCError(-1, "RPC Failure");
986 // SUCCESS. Release back into pool
991 log.debug("RPC completed with status %d (%p)", ret.status.status, this);
993 RPCError* retval = NULL;
994 if (ret.status.status)
995 retval = new RPCError(&ret.status);
999 for (u_int i = 0; i < ret.assertions.assertions_len; i++) {
1000 istringstream attrstream(ret.assertions.assertions_val[i].xml_string);
1001 SAMLAssertion *as = NULL;
1002 log.debugStream() << "Trying to decode assertion " << i << ": " <<
1003 ret.assertions.assertions_val[i].xml_string << CategoryStream::ENDLINE;
1004 assertions.push_back(new SAMLAssertion(attrstream));
1007 // return the Authentication Statement
1009 istringstream authstream(ret.auth_statement.xml_string);
1010 SAMLAuthenticationStatement *auth = NULL;
1012 log.debugStream() << "Trying to decode authentication statement: " <<
1013 ret.auth_statement.xml_string << CategoryStream::ENDLINE;
1014 auth = new SAMLAuthenticationStatement(authstream);
1016 // Save off the statement
1020 catch (SAMLException& e) {
1021 log.error ("SAML Exception: %s", e.what());
1024 throw ShibTargetException(SHIBRPC_SAML_EXCEPTION, os.str().c_str());
1026 catch (XMLException& e) {
1027 log.error ("XML Exception: %s", e.getMessage());
1028 auto_ptr_char msg(e.getMessage());
1029 throw ShibTargetException (SHIBRPC_XML_EXCEPTION, msg.get());
1032 catch (ShibTargetException &e) {
1033 retval = new RPCError(e);
1037 retval = new RPCError();
1040 clnt_freeres(clnt, (xdrproc_t)xdr_shibrpc_get_assertions_ret_1, (caddr_t)&ret);
1043 log.debug ("returning..");
1048 ShibTarget::serialize(saml::SAMLAssertion &assertion, std::string &result)
1050 saml::NDC ndc("serialize");
1051 Category& log=Category::getInstance("shibtarget.RM");
1055 unsigned int outlen;
1056 char* assn = (char*) os.str().c_str();
1057 XMLByte* serialized = Base64::encode(reinterpret_cast<XMLByte*>(assn), os.str().length(), &outlen);
1058 result = (char*) serialized;
1059 XMLString::release(&serialized);
1063 /*************************************************************************
1064 * Shib Target Private implementation
1067 ShibTargetPriv::ShibTargetPriv() : m_parser(NULL), m_app(NULL), m_mapper(NULL),
1068 m_conf(NULL), m_Config(NULL)
1073 ShibTargetPriv::~ShibTargetPriv()
1075 if (m_parser) delete m_parser;
1088 static inline char hexchar(unsigned short s)
1090 return (s<=9) ? ('0' + s) : ('A' + s - 10);
1094 ShibTargetPriv::url_encode(const char* s)
1096 static char badchars[]="\"\\+<>#%{}|^~[]`;/?:@=&";
1100 if (strchr(badchars,*s) || *s<=0x1F || *s>=0x7F) {
1102 ret+=hexchar(*s >> 4);
1103 ret+=hexchar(*s & 0x0F);
1112 ShibTargetPriv::get_application(string protocol, string hostname, int port,
1118 // XXX: Do we need to keep conf and mapper locked while we hold m_app?
1120 // We lock the configuration system for the duration.
1121 m_conf=m_Config->getINI();
1124 // Map request to application and content settings.
1125 m_mapper=m_conf->getRequestMapper();
1128 // Obtain the application settings from the parsed URL
1129 m_settings = m_mapper->getSettingsFromParsedURL(protocol.c_str(),
1133 // Now find the application from the URL settings
1134 pair<bool,const char*> application_id=m_settings.first->getString("applicationId");
1135 const IApplication* application=m_conf->getApplication(application_id.second);
1141 throw ShibTargetException(SHIBRPC_OK, "unable to map request to application settings. Check configuration");
1144 // Store the application for later use
1145 m_app = application;
1147 // Compute the target URL
1148 m_url = protocol + "://" + hostname;
1149 if ((protocol == "http" && port != 80) || (protocol == "https" && port != 443))
1150 m_url += ":" + port;
1156 ShibTargetPriv::sendError(ShibTarget* st, string page, ShibMLP &mlp)
1158 const IPropertySet* props=m_app->getPropertySet("Errors");
1160 pair<bool,const char*> p=props->getString(page.c_str());
1162 ifstream infile(p.second);
1163 if (!infile.fail()) {
1164 const char* res = mlp.run(infile,props);
1166 return st->sendPage(res);
1171 string errstr = "sendError could not process the error template for application ";
1172 errstr += m_app->getId();
1173 st->log(ShibTarget::LogLevelError, errstr);
1174 return st->sendPage("Internal Server Error. Please contact the server administrator.");
1178 ShibTargetPriv::getSessionId(ShibTarget* st)
1181 //string m = string("getSessionId returning precreated session_id: ") + session_id;
1182 //st->log(ShibTarget::LogLevelDebug, m);
1187 pair<const char*, const char *> shib_cookie = st->getCookieNameProps();
1188 m_cookies = st->getCookies();
1189 if (!m_cookies.empty()) {
1190 if (sid = strstr(m_cookies.c_str(), shib_cookie.first)) {
1191 // We found a cookie. pull it out (our session_id)
1192 sid += strlen(shib_cookie.first) + 1; // skip over the '='
1193 char *cookieend = strchr(sid, ';');
1200 //string m = string("getSessionId returning new session_id: ") + session_id;
1201 //st->log(ShibTarget::LogLevelDebug, m);
1205 /*************************************************************************
1206 * CGI Parser implementation
1209 CgiParse::CgiParse(const char* data, unsigned int len)
1211 const char* pch = data;
1212 unsigned int cl = len;
1217 value=fmakeword('&',&cl,&pch);
1220 name=makeword(value,'=');
1221 kvp_map[name]=value;
1226 CgiParse::~CgiParse()
1228 for (map<string,char*>::iterator i=kvp_map.begin(); i!=kvp_map.end(); i++)
1233 CgiParse::get_value(const char* name) const
1235 map<string,char*>::const_iterator i=kvp_map.find(name);
1236 if (i==kvp_map.end())
1241 /* Parsing routines modified from NCSA source. */
1243 CgiParse::makeword(char *line, char stop)
1246 char *word = (char *) malloc(sizeof(char) * (strlen(line) + 1));
1248 for(x=0;((line[x]) && (line[x] != stop));x++)
1257 line[y++] = line[x++];
1263 CgiParse::fmakeword(char stop, unsigned int *cl, const char** ppch)
1271 word = (char *) malloc(sizeof(char) * (wsize + 1));
1275 word[ll] = *((*ppch)++);
1280 word = (char *)realloc(word,sizeof(char)*(wsize+1));
1283 if((word[ll] == stop) || word[ll] == EOF || (!(*cl)))
1285 if(word[ll] != stop)
1295 CgiParse::plustospace(char *str)
1300 if(str[x] == '+') str[x] = ' ';
1304 CgiParse::x2c(char *what)
1306 register char digit;
1308 digit = (what[0] >= 'A' ? ((what[0] & 0xdf) - 'A')+10 : (what[0] - '0'));
1310 digit += (what[1] >= 'A' ? ((what[1] & 0xdf) - 'A')+10 : (what[1] - '0'));
1315 CgiParse::url_decode(char *url)
1319 for(x=0,y=0;url[y];++x,++y)
1321 if((url[x] = url[y]) == '%')
1323 url[x] = x2c(&url[y+1]);
1331 * We need to implement this so the SHIRE (and RM) recodes work
1332 * in terms of the ShibTarget
1334 void ShibTarget::log(ShibLogLevel level, const string &msg)
1336 throw runtime_error("Invalid Usage");
1338 string ShibTarget::getCookies(void)
1340 throw runtime_error("Invalid Usage");
1342 void ShibTarget::setCookie(const string &name, const string &value)
1344 throw runtime_error("Invalid Usage");
1346 void ShibTarget::clearHeader(const string &name)
1348 throw runtime_error("Invalid Usage");
1350 void ShibTarget::setHeader(const string &name, const string &value)
1352 throw runtime_error("Invalid Usage");
1354 string ShibTarget::getHeader(const string &name)
1356 throw runtime_error("Invalid Usage");
1358 void ShibTarget::setRemoteUser(const string &name)
1360 throw runtime_error("Invalid Usage");
1362 string ShibTarget::getArgs(void)
1364 throw runtime_error("Invalid Usage");
1366 string ShibTarget::getPostData(void)
1368 throw runtime_error("Invalid Usage");
1370 //virtual HTAccessInfo& getAccessInfo(void);
1371 void* ShibTarget::sendPage(const string &msg, const string content_type, const pair<string,string> headers[], int code)
1373 throw runtime_error("Invalid Usage");
1375 void* ShibTarget::sendRedirect(const std::string url)
1377 throw runtime_error("Invalid Usage");
1380 // Subclasses may not need to override these particular virtual methods.
1381 string ShibTarget::getAuthType(void)
1383 return string("shibboleth");
1385 void* ShibTarget::returnDecline(void)
1389 void* ShibTarget::returnOK(void)