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>
68 #include <shib/shib-threads.h>
69 #include <log4cpp/Category.hh>
70 #include <log4cpp/PropertyConfigurator.hh>
71 #include <xercesc/util/Base64.hpp>
75 using namespace shibboleth;
76 using namespace shibtarget;
77 using namespace log4cpp;
79 namespace shibtarget {
83 CgiParse(const char* data, unsigned int len);
85 const char* get_value(const char* name) const;
88 char * fmakeword(char stop, unsigned int *cl, const char** ppch);
89 char * makeword(char *line, char stop);
90 void plustospace(char *str);
92 void url_decode(char *url);
94 map<string,char*> kvp_map;
103 string url_encode(const char* s);
105 const IApplication *m_app;
108 string m_authnRequest;
114 /*************************************************************************
115 * Shib Target implementation
118 ShibTarget::ShibTarget(void) : m_priv(NULL)
121 m_priv = new ShibTargetPriv();
124 ShibTarget::ShibTarget(const IApplication *app) : m_priv(NULL)
127 m_priv = new ShibTargetPriv();
131 ShibTarget::~ShibTarget(void)
133 if (m_priv) delete m_priv;
137 // These functions implement the server-agnostic shibboleth engine
138 // The web server modules implement a subclass and then call into
139 // these methods once they instantiate their request object.
141 ShibTarget::doCheckAuthN(void)
147 ShibTarget::doHandlePOST(void)
153 ShibTarget::doCheckAuthZ(void)
161 // Get the session cookie name and properties for the application
162 std::pair<const char*,const char*>
163 ShibTarget::getCookieNameProps() const
165 static const char* defProps="; path=/";
166 static const char* defName="_shibsession_";
168 // XXX: What to do if m_app isn't set?
170 const IPropertySet* props=m_priv->m_app->getPropertySet("Sessions");
172 pair<bool,const char*> p=props->getString("cookieProps");
175 if (!m_priv->m_cookieName.empty())
176 return pair<const char*,const char*>(m_priv->m_cookieName.c_str(),
178 pair<bool,const char*> p2=props->getString("cookieName");
180 m_priv->m_cookieName=p2.second;
181 return pair<const char*,const char*>(p2.second,p.second);
183 m_priv->m_cookieName=defName;
184 m_priv->m_cookieName+=m_priv->m_app->getId();
185 return pair<const char*,const char*>(m_priv->m_cookieName.c_str(),p.second);
187 m_priv->m_cookieName=defName;
188 m_priv->m_cookieName+=m_priv->m_app->getId();
189 return pair<const char*,const char*>(m_priv->m_cookieName.c_str(),defProps);
192 // Find the default assertion consumer service for the resource
194 ShibTarget::getShireURL(const char* resource) const
196 if (!m_priv->m_shireURL.empty())
197 return m_priv->m_shireURL.c_str();
199 // XXX: what to do is m_app is NULL?
201 bool shire_ssl_only=false;
202 const char* shire=NULL;
203 const IPropertySet* props=m_priv->m_app->getPropertySet("Sessions");
205 pair<bool,bool> p=props->getBool("shireSSL");
207 shire_ssl_only=p.second;
208 pair<bool,const char*> p2=props->getString("shireURL");
213 // Should never happen...
214 if (!shire || (*shire!='/' && strncmp(shire,"http:",5) && strncmp(shire,"https:",6)))
217 // The "shireURL" property can be in one of three formats:
219 // 1) a full URI: http://host/foo/bar
220 // 2) a hostless URI: http:///foo/bar
221 // 3) a relative path: /foo/bar
223 // # Protocol Host Path
224 // 1 shire shire shire
225 // 2 shire resource shire
226 // 3 resource resource shire
228 // note: if shire_ssl_only is true, make sure the protocol is https
230 const char* path = NULL;
232 // Decide whether to use the shire or the resource for the "protocol"
242 // break apart the "protocol" string into protocol, host, and "the rest"
243 const char* colon=strchr(prot,':');
245 const char* slash=strchr(colon,'/');
249 // Compute the actual protocol and store in member.
251 m_priv->m_shireURL.assign("https://");
253 m_priv->m_shireURL.assign(prot, colon-prot);
255 // create the "host" from either the colon/slash or from the target string
256 // If prot == shire then we're in either #1 or #2, else #3.
257 // If slash == colon then we're in #2.
258 if (prot != shire || slash == colon) {
259 colon = strchr(resource, ':');
260 colon += 3; // Get past the ://
261 slash = strchr(colon, '/');
263 string host(colon, slash-colon);
265 // Build the shire URL
266 m_priv->m_shireURL+=host + path;
267 return m_priv->m_shireURL.c_str();
270 // Generate a Shib 1.x AuthnRequest redirect URL for the resource
272 ShibTarget::getAuthnRequest(const char* resource) const
274 if (!m_priv->m_authnRequest.empty())
275 return m_priv->m_authnRequest.c_str();
277 // XXX: what to do if m_app is NULL?
280 sprintf(timebuf,"%u",time(NULL));
282 const IPropertySet* props=m_priv->m_app->getPropertySet("Sessions");
284 pair<bool,const char*> wayf=props->getString("wayfURL");
286 m_priv->m_authnRequest=m_priv->m_authnRequest + wayf.second + "?shire=" + m_priv->url_encode(getShireURL(resource)) +
287 "&target=" + m_priv->url_encode(resource) + "&time=" + timebuf;
288 pair<bool,bool> old=m_priv->m_app->getBool("oldAuthnRequest");
289 if (!old.first || !old.second) {
290 wayf=m_priv->m_app->getString("providerId");
292 m_priv->m_authnRequest=m_priv->m_authnRequest + "&providerId=" + m_priv->url_encode(wayf.second);
296 return m_priv->m_authnRequest.c_str();
299 // Process a lazy session setup request and turn it into an AuthnRequest
301 ShibTarget::getLazyAuthnRequest(const char* query_string) const
303 CgiParse parser(query_string,strlen(query_string));
304 const char* target=parser.get_value("target");
305 if (!target || !*target)
307 return getAuthnRequest(target);
310 // Process a POST profile submission, and return (SAMLResponse,TARGET) pair.
311 std::pair<const char*,const char*>
312 ShibTarget::getFormSubmission(const char* post, unsigned int len) const
314 m_priv->m_parser = new CgiParse(post,len);
315 return pair<const char*,const char*>(m_priv->m_parser->get_value("SAMLResponse"),m_priv->m_parser->get_value("TARGET"));
319 ShibTarget::sessionCreate(const char* response, const char* ip, std::string &cookie)
322 saml::NDC ndc("sessionCreate");
323 Category& log = Category::getInstance("shibtarget.SHIRE");
325 if (!response || !*response) {
326 log.error ("Empty SAML response content");
327 return new RPCError(-1, "Empty SAML response content");
331 log.error ("Invalid IP address");
332 return new RPCError(-1, "Invalid IP address");
335 shibrpc_new_session_args_1 arg;
336 arg.shire_location = (char*) m_priv->m_shireURL.c_str();
337 arg.application_id = (char*) m_priv->m_app->getId();
338 arg.saml_post = (char*)response;
339 arg.client_addr = (char*)ip;
340 arg.checkIPAddress = true;
342 log.info ("create session for user at %s for application %s", ip, arg.application_id);
344 const IPropertySet* props=m_priv->m_app->getPropertySet("Sessions");
346 pair<bool,bool> pcheck=props->getBool("checkAddress");
348 arg.checkIPAddress = pcheck.second;
351 shibrpc_new_session_ret_1 ret;
352 memset (&ret, 0, sizeof(ret));
354 // Loop on the RPC in case we lost contact the first time through
359 clnt = rpc->connect();
360 clnt_stat status = shibrpc_new_session_1 (&arg, &ret, clnt);
361 if (status != RPC_SUCCESS) {
362 // FAILED. Release, disconnect, and retry
363 log.error("RPC Failure: %p (%p) (%d): %s", this, clnt, status, clnt_spcreateerror("shibrpc_new_session_1"));
368 return new RPCError(-1, "RPC Failure");
371 // SUCCESS. Pool and continue
376 log.debug("RPC completed with status %d (%p)", ret.status.status, this);
379 if (ret.status.status)
380 retval = new RPCError(&ret.status);
382 log.debug ("new cookie: %s", ret.cookie);
384 retval = new RPCError();
387 clnt_freeres(clnt, (xdrproc_t)xdr_shibrpc_new_session_ret_1, (caddr_t)&ret);
390 log.debug("returning");
395 ShibTarget::sessionIsValid(const char* session_id, const char* ip) const
397 saml::NDC ndc("sessionIsValid");
398 Category& log = Category::getInstance("shibtarget.SHIRE");
400 if (!session_id || !*session_id) {
401 log.error ("No cookie value was provided");
402 return new RPCError(SHIBRPC_NO_SESSION, "No cookie value was provided");
404 else if (strchr(session_id,'=')) {
405 log.error ("The cookie value wasn't extracted successfully, use a more unique cookie name for your installation.");
406 return new RPCError(SHIBRPC_INTERNAL_ERROR, "The cookie value wasn't extracted successfully, use a more unique cookie name for your installation.");
410 log.error ("Invalid IP Address");
411 return new RPCError(SHIBRPC_IPADDR_MISSING, "Invalid IP Address");
414 log.info ("is session valid: %s", ip);
415 log.debug ("session cookie: %s", session_id);
417 shibrpc_session_is_valid_args_1 arg;
419 arg.cookie.cookie = (char*)session_id;
420 arg.cookie.client_addr = (char *)ip;
421 arg.application_id = (char *)m_priv->m_app->getId();
423 // Get rest of input from the application Session properties.
426 arg.checkIPAddress = true;
427 const IPropertySet* props=m_priv->m_app->getPropertySet("Sessions");
429 pair<bool,unsigned int> p=props->getUnsignedInt("lifetime");
431 arg.lifetime = p.second;
432 p=props->getUnsignedInt("timeout");
434 arg.timeout = p.second;
435 pair<bool,bool> pcheck=props->getBool("checkAddress");
437 arg.checkIPAddress = pcheck.second;
440 shibrpc_session_is_valid_ret_1 ret;
441 memset (&ret, 0, sizeof(ret));
443 // Loop on the RPC in case we lost contact the first time through
448 clnt = rpc->connect();
449 clnt_stat status = shibrpc_session_is_valid_1(&arg, &ret, clnt);
450 if (status != RPC_SUCCESS) {
451 // FAILED. Release, disconnect, and try again...
452 log.error("RPC Failure: %p (%p) (%d) %s", this, clnt, status, clnt_spcreateerror("shibrpc_session_is_valid_1"));
457 return new RPCError(-1, "RPC Failure");
465 log.debug("RPC completed with status %d, %p", ret.status.status, this);
468 if (ret.status.status)
469 retval = new RPCError(&ret.status);
471 retval = new RPCError();
473 clnt_freeres (clnt, (xdrproc_t)xdr_shibrpc_session_is_valid_ret_1, (caddr_t)&ret);
476 log.debug("returning");
483 ShibTarget::getAssertions(const char* cookie, const char* ip,
484 std::vector<saml::SAMLAssertion*>& assertions,
485 saml::SAMLAuthenticationStatement **statement
488 saml::NDC ndc("getAssertions");
489 Category& log=Category::getInstance("shibtarget.RM");
490 log.info("get assertions...");
492 if (!cookie || !*cookie) {
493 log.error ("No cookie value provided.");
494 return new RPCError(-1, "No cookie value provided.");
498 log.error ("Invalid ip address");
499 return new RPCError(-1, "Invalid IP address");
502 log.debug("session cookie: %s", cookie);
504 shibrpc_get_assertions_args_1 arg;
505 arg.cookie.cookie = (char*)cookie;
506 arg.cookie.client_addr = (char*)ip;
507 arg.checkIPAddress = true;
508 arg.application_id = (char *)m_priv->m_app->getId();
510 log.info("request from %s for \"%s\"", ip, arg.application_id);
512 const IPropertySet* props=m_priv->m_app->getPropertySet("Sessions");
514 pair<bool,bool> pcheck=props->getBool("checkAddress");
516 arg.checkIPAddress = pcheck.second;
519 shibrpc_get_assertions_ret_1 ret;
520 memset (&ret, 0, sizeof(ret));
522 // Loop on the RPC in case we lost contact the first time through
527 clnt = rpc->connect();
528 clnt_stat status = shibrpc_get_assertions_1(&arg, &ret, clnt);
529 if (status != RPC_SUCCESS) {
530 // FAILED. Release, disconnect, and try again.
531 log.debug("RPC Failure: %p (%p) (%d): %s", this, clnt, status, clnt_spcreateerror("shibrpc_get_assertions_1"));
536 return new RPCError(-1, "RPC Failure");
539 // SUCCESS. Release back into pool
544 log.debug("RPC completed with status %d (%p)", ret.status.status, this);
546 RPCError* retval = NULL;
547 if (ret.status.status)
548 retval = new RPCError(&ret.status);
552 for (u_int i = 0; i < ret.assertions.assertions_len; i++) {
553 istringstream attrstream(ret.assertions.assertions_val[i].xml_string);
554 SAMLAssertion *as = NULL;
555 log.debugStream() << "Trying to decode assertion " << i << ": " <<
556 ret.assertions.assertions_val[i].xml_string << CategoryStream::ENDLINE;
557 assertions.push_back(new SAMLAssertion(attrstream));
560 // return the Authentication Statement
562 istringstream authstream(ret.auth_statement.xml_string);
563 SAMLAuthenticationStatement *auth = NULL;
565 log.debugStream() << "Trying to decode authentication statement: " <<
566 ret.auth_statement.xml_string << CategoryStream::ENDLINE;
567 auth = new SAMLAuthenticationStatement(authstream);
569 // Save off the statement
573 catch (SAMLException& e) {
574 log.error ("SAML Exception: %s", e.what());
577 throw ShibTargetException(SHIBRPC_SAML_EXCEPTION, os.str().c_str());
579 catch (XMLException& e) {
580 log.error ("XML Exception: %s", e.getMessage());
581 auto_ptr_char msg(e.getMessage());
582 throw ShibTargetException (SHIBRPC_XML_EXCEPTION, msg.get());
585 catch (ShibTargetException &e) {
586 retval = new RPCError(e);
590 retval = new RPCError();
593 clnt_freeres(clnt, (xdrproc_t)xdr_shibrpc_get_assertions_ret_1, (caddr_t)&ret);
596 log.debug ("returning..");
601 ShibTarget::serialize(saml::SAMLAssertion &assertion, std::string &result)
603 saml::NDC ndc("serialize");
604 Category& log=Category::getInstance("shibtarget.RM");
609 char* assn = (char*) os.str().c_str();
610 XMLByte* serialized = Base64::encode(reinterpret_cast<XMLByte*>(assn), os.str().length(), &outlen);
611 result = (char*) serialized;
612 XMLString::release(&serialized);
616 /*************************************************************************
617 * Shib Target Private implementation
620 ShibTargetPriv::ShibTargetPriv() : m_parser(NULL), m_app(NULL)
624 ShibTargetPriv::~ShibTargetPriv()
626 if (m_parser) delete m_parser;
627 //if (m_app) delete m_app;
630 static inline char hexchar(unsigned short s)
632 return (s<=9) ? ('0' + s) : ('A' + s - 10);
636 ShibTargetPriv::url_encode(const char* s)
638 static char badchars[]="\"\\+<>#%{}|^~[]`;/?:@=&";
642 if (strchr(badchars,*s) || *s<=0x1F || *s>=0x7F) {
644 ret+=hexchar(*s >> 4);
645 ret+=hexchar(*s & 0x0F);
653 /*************************************************************************
654 * CGI Parser implementation
657 CgiParse::CgiParse(const char* data, unsigned int len)
659 const char* pch = data;
660 unsigned int cl = len;
665 value=fmakeword('&',&cl,&pch);
668 name=makeword(value,'=');
674 CgiParse::~CgiParse()
676 for (map<string,char*>::iterator i=kvp_map.begin(); i!=kvp_map.end(); i++)
681 CgiParse::get_value(const char* name) const
683 map<string,char*>::const_iterator i=kvp_map.find(name);
684 if (i==kvp_map.end())
689 /* Parsing routines modified from NCSA source. */
691 CgiParse::makeword(char *line, char stop)
694 char *word = (char *) malloc(sizeof(char) * (strlen(line) + 1));
696 for(x=0;((line[x]) && (line[x] != stop));x++)
705 line[y++] = line[x++];
711 CgiParse::fmakeword(char stop, unsigned int *cl, const char** ppch)
719 word = (char *) malloc(sizeof(char) * (wsize + 1));
723 word[ll] = *((*ppch)++);
728 word = (char *)realloc(word,sizeof(char)*(wsize+1));
731 if((word[ll] == stop) || word[ll] == EOF || (!(*cl)))
743 CgiParse::plustospace(char *str)
748 if(str[x] == '+') str[x] = ' ';
752 CgiParse::x2c(char *what)
756 digit = (what[0] >= 'A' ? ((what[0] & 0xdf) - 'A')+10 : (what[0] - '0'));
758 digit += (what[1] >= 'A' ? ((what[1] & 0xdf) - 'A')+10 : (what[1] - '0'));
763 CgiParse::url_decode(char *url)
767 for(x=0,y=0;url[y];++x,++y)
769 if((url[x] = url[y]) == '%')
771 url[x] = x2c(&url[y+1]);
779 * We need to implement this so the SHIRE (and RM) recodes work
780 * in terms of the ShibTarget
782 void ShibTarget::log(ShibLogLevel level, string &msg)
784 throw runtime_error("Invalid Usage");
786 string ShibTarget::getCookie(std::string &name)
788 throw runtime_error("Invalid Usage");
790 void ShibTarget::setCookie(string &name, string &value)
792 throw runtime_error("Invalid Usage");
794 string ShibTarget::getPostData(void)
796 throw runtime_error("Invalid Usage");
798 string ShibTarget::getAuthType(void)
800 throw runtime_error("Invalid Usage");
802 void ShibTarget::setAuthType(std::string)
804 throw runtime_error("Invalid Usage");
806 //virtual HTAccessInfo& getAccessInfo(void);
807 void* ShibTarget::sendPage(string &msg, pair<string,string> headers[], int code)
809 throw runtime_error("Invalid Usage");
811 void* ShibTarget::sendRedirect(std::string url)
813 throw runtime_error("Invalid Usage");