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;
94 char * fmakeword(char stop, unsigned int *cl, const char** ppch);
95 char * makeword(char *line, char stop);
96 void plustospace(char *str);
98 void url_decode(char *url);
100 map<string,char*> kvp_map;
109 string url_encode(const char* s);
110 void get_application(string protocol, string hostname, int port, string uri);
111 void* sendError(ShibTarget* st, string page, ShibMLP &mlp);
112 const char *getSessionId(ShibTarget* st);
113 bool get_assertions(ShibTarget *st, const char *session_id, ShibMLP &mlp);
115 IRequestMapper::Settings m_settings;
116 const IApplication *m_app;
119 string m_authnRequest;
122 const char *session_id;
125 vector<SAMLAssertion*> m_assertions;
126 SAMLAuthenticationStatement* m_sso_statement;
128 // These are the actual request parameters set via the init method.
132 string m_content_type;
133 string m_remote_addr;
135 ShibTargetConfig* m_Config;
139 IRequestMapper* m_mapper;
144 /*************************************************************************
145 * Shib Target implementation
148 ShibTarget::ShibTarget(void) : m_priv(NULL)
150 m_priv = new ShibTargetPriv();
153 ShibTarget::ShibTarget(const IApplication *app) : m_priv(NULL)
155 m_priv = new ShibTargetPriv();
159 ShibTarget::~ShibTarget(void)
161 if (m_priv) delete m_priv;
164 void ShibTarget::init(ShibTargetConfig *config,
165 string protocol, string hostname, int port,
166 string uri, string content_type, string remote_host,
169 saml::NDC ndc("ShibTarget::init");
172 throw runtime_error("ShibTarget Already Initialized");
174 throw runtime_error("config is NULL. Oops.");
176 m_priv->m_protocol = protocol;
177 m_priv->m_content_type = content_type;
178 m_priv->m_remote_addr = remote_host;
179 m_priv->m_Config = config;
180 m_priv->m_method = method;
181 m_priv->get_application(protocol, hostname, port, uri);
185 // These functions implement the server-agnostic shibboleth engine
186 // The web server modules implement a subclass and then call into
187 // these methods once they instantiate their request object.
189 ShibTarget::doCheckAuthN(bool requireSessionFlag, bool handlePost)
191 saml::NDC ndc("ShibTarget::doCheckAuthN");
193 const char *targetURL = NULL;
194 const char *procState = "Process Initialization Error";
199 throw ShibTargetException(SHIBRPC_OK, "ShibTarget Uninitialized. Application did not supply request information.");
201 targetURL = m_priv->m_url.c_str();
202 const char *shireURL = getShireURL(targetURL);
204 throw ShibTargetException(SHIBRPC_OK, "Cannot map target URL to Shire URL. Check configuration");
206 if (strstr(targetURL,shireURL)) {
208 return doHandlePOST();
210 return pair<bool,void*>(true, returnOK());
213 string auth_type = getAuthType();
214 if (strcasecmp(auth_type.c_str(),"shibboleth"))
215 return pair<bool,void*>(true,returnDecline());
217 pair<bool,bool> requireSession =
218 m_priv->m_settings.first->getBool("requireSession");
219 if (!requireSession.first || !requireSession.second)
220 if (requireSessionFlag)
221 requireSession.second=true;
223 const char *session_id = m_priv->getSessionId(this);
225 if (!session_id || !*session_id) {
226 // No session. Maybe that's acceptable?
228 if (!requireSession.second)
229 return pair<bool,void*>(true,returnOK());
231 // No cookie, but we require a session. Generate an AuthnRequest.
232 return pair<bool,void*>(true,sendRedirect(getAuthnRequest(targetURL)));
235 procState = "Session Processing Error";
236 RPCError *status = sessionIsValid(session_id, m_priv->m_remote_addr.c_str());
238 if (status->isError()) {
240 // If no session is required, bail now.
241 if (!requireSession.second)
242 return pair<bool,void*>(true, returnOK());
243 // XXX: Or should this be DECLINED?
244 // Has to be OK because DECLINED will just cause Apache
245 // to fail when it can't locate anything to process the
246 // AuthType. No session plus requireSession false means
247 // do not authenticate the user at this time.
248 else if (status->isRetryable()) {
249 // Session is invalid but we can retry the auth -- generate an AuthnRequest
251 return pair<bool,void*>(true,sendRedirect(getAuthnRequest(targetURL)));
255 string er = "Unretryable error: " ;
256 er += status->getText();
257 log(LogLevelError, er);
267 // We're done. Everything is okay. Nothing to report. Nothing to do..
268 // Let the caller decide how to proceed.
269 log(LogLevelInfo, "doCheckAuthN Succeeded\n");
270 return pair<bool,void*>(false,NULL);
272 } catch (ShibTargetException &e) {
273 mlp.insert("errorText", e.what());
277 mlp.insert("errorText", "Unexpected Exception");
281 // If we get here then we've got an error.
282 mlp.insert("errorType", procState);
283 mlp.insert("errorDesc", "An error occurred while processing your request.");
287 mlp.insert("requestURL", targetURL);
289 return pair<bool,void*>(true,m_priv->sendError(this, "shire", mlp));
293 ShibTarget::doHandlePOST(void)
295 saml::NDC ndc("ShibTarget::doHandlePOST");
297 const char *targetURL = NULL;
298 const char *procState = "Session Creation Service Error";
303 throw ShibTargetException(SHIBRPC_OK, "ShibTarget Uninitialized. Application did not supply request information.");
305 targetURL = m_priv->m_url.c_str();
306 const char *shireURL = getShireURL(targetURL);
309 throw ShibTargetException(SHIBRPC_OK, "doHandlePOST: unable to map request to a proper shireURL setting. Check Configuration.");
312 // Make sure we only process the SHIRE requests.
313 if (!strstr(targetURL, shireURL))
314 return pair<bool,void*>(true, returnDecline());
316 const IPropertySet* sessionProps=m_priv->m_app->getPropertySet("Sessions");
318 throw ShibTargetException(SHIBRPC_OK, "doHandlePOST: unable to map request to application session settings. Check configuration");
320 // this always returns something
321 pair<const char*,const char*> shib_cookie=getCookieNameProps();
323 // Process SHIRE request
325 pair<bool,bool> shireSSL=sessionProps->getBool("shireSSL");
327 // Make sure this is SSL, if it should be
328 if ((!shireSSL.first || shireSSL.second) && m_priv->m_protocol == "https")
329 throw ShibTargetException(SHIBRPC_OK, "blocked non-SSL access to session creation service");
331 // If this is a GET, we manufacture an AuthnRequest.
332 if (!strcasecmp(m_priv->m_method.c_str(), "GET")) {
333 string args = getArgs();
334 const char* areq=args.empty() ? NULL : getLazyAuthnRequest(args.c_str());
336 throw ShibTargetException(SHIBRPC_OK, "malformed GET arguments to request a new session");
337 return pair<bool,void*>(true, sendRedirect(areq));
339 else if (strcasecmp(m_priv->m_method.c_str(), "POST")) {
340 throw ShibTargetException(SHIBRPC_OK, "blocked non-POST to SHIRE POST processor");
343 // Make sure this POST is an appropriate content type
344 if (m_priv->m_content_type.empty() ||
345 strcasecmp(m_priv->m_content_type.c_str(),
346 "application/x-www-form-urlencoded")) {
347 string er = string("blocked bad content-type to SHIRE POST processor: ") +
348 m_priv->m_content_type;
349 throw ShibTargetException(SHIBRPC_OK, er.c_str());
352 // Read the POST Data
353 string cgistr = getPostData();
355 // Parse the submission.
356 pair<const char*,const char*> elements =
357 getFormSubmission(cgistr.c_str(),cgistr.length());
359 // Make sure the SAML Response parameter exists
360 if (!elements.first || !*elements.first)
361 throw ShibTargetException(SHIBRPC_OK, "SHIRE POST failed to find SAMLResponse form element");
363 // Make sure the target parameter exists
364 if (!elements.second || !*elements.second)
365 throw ShibTargetException(SHIBRPC_OK, "SHIRE POST failed to find TARGET form element");
369 RPCError* status = sessionCreate(elements.first, m_priv->m_remote_addr.c_str(),
372 if (status->isError()) {
374 sprintf(buf, "(%d): ", status->getCode());
375 string er = string("doHandlePost() POST process failed ") + buf +
377 log(LogLevelError, er);
379 if (status->isRetryable()) {
382 return pair<bool,void*>(true, sendRedirect(getAuthnRequest(elements.second)));
385 // return this error to the user.
393 string("doHandlePost() POST process succeeded. New session: ") + cookie);
395 // We've got a good session, set the cookie...
396 cookie += shib_cookie.second;
397 setCookie(shib_cookie.first, cookie);
399 // ... and redirect to the target
400 return pair<bool,void*>(true, sendRedirect(elements.second));
402 } catch (ShibTargetException &e) {
403 mlp.insert("errorText", e.what());
407 mlp.insert("errorText", "Unexpected Exception");
411 // If we get here then we've got an error.
412 mlp.insert("errorType", procState);
413 mlp.insert("errorDesc", "An error occurred while processing your request.");
417 mlp.insert("requestURL", targetURL);
419 return pair<bool,void*>(true,m_priv->sendError(this, "shire", mlp));
423 ShibTarget::doCheckAuthZ(void)
425 saml::NDC ndc("ShibTarget::doCheckAuthZ");
428 const char *procState = "Authorization Processing Error";
429 const char *targetURL = NULL;
430 HTAccessInfo *ht = NULL;
431 HTGroupTable* grpstatus = NULL;
435 throw ShibTargetException(SHIBRPC_OK, "ShibTarget Uninitialized. Application did not supply request information.");
437 targetURL = m_priv->m_url.c_str();
438 const char *session_id = m_priv->getSessionId(this);
440 // XXX: need to make sure that export assertions was already called.
441 //if (m_priv->get_assertions(this, session_id, mlp))
444 // Do we have an access control plugin?
445 if (m_priv->m_settings.second) {
446 Locker acllock(m_priv->m_settings.second);
447 if (!m_priv->m_settings.second->authorized(*m_priv->m_sso_statement,
448 m_priv->m_assertions)) {
449 log(LogLevelError, "doCheckAuthZ: access control provider denied access");
454 // Perform HTAccess Checks
455 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();
466 if (ht->requireAll) { \
468 if (grpstatus) delete grpstatus; \
469 return pair<bool,void*>(false, NULL); \
475 for (int x = 0; x < ht->elements.size(); x++) {
477 HTAccessInfo::RequireLine *line = ht->elements[x];
478 if (! line->use_line)
480 method_restricted = true;
482 const char *w = line->tokens[0].c_str();
484 if (!strcasecmp(w,"Shibboleth")) {
485 // This is a dummy rule needed because Apache conflates authn and authz.
486 // Without some require rule, AuthType is ignored and no check_user hooks run.
489 else if (!strcmp(w,"valid-user")) {
490 log(LogLevelDebug, "doCheckAuthZ accepting valid-user");
493 else if (!strcmp(w,"user") && !remote_user.empty()) {
495 for (int i = 1; i < line->tokens.size(); i++) {
496 w = line->tokens[i].c_str();
504 // To do regex matching, we have to convert from UTF-8.
505 auto_ptr<XMLCh> trans(fromUTF8(w));
506 RegularExpression re(trans.get());
507 auto_ptr<XMLCh> trans2(fromUTF8(remote_user.c_str()));
508 if (re.matches(trans2.get())) {
509 log(LogLevelDebug, string("doCheckAuthZ accepting user: ") + w);
513 catch (XMLException& ex) {
514 auto_ptr_char tmp(ex.getMessage());
515 log(LogLevelError, string("doCheckAuthZ caught exception while parsing regular expression (")
516 + w + "): " + tmp.get());
519 else if (!strcmp(remote_user.c_str(), w)) {
520 log(LogLevelDebug, string("doCheckAuthZ accepting user: ") + w);
525 else if (!strcmp(w,"group")) {
526 grpstatus = getGroupTable(remote_user);
530 return pair<bool,void*>(true, returnDecline());
533 for (int i = 1; i < line->tokens.size(); i++) {
534 w = line->tokens[i].c_str();
535 if (grpstatus->lookup(w)) {
536 log(LogLevelDebug, string("doCheckAuthZ accepting group: ") + w);
544 Iterator<IAAP*> provs = m_priv->m_app->getAAPProviders();
545 AAP wrapper(provs, w);
546 if (wrapper.fail()) {
547 log(LogLevelWarn, string("doCheckAuthZ didn't recognize require rule: ")
553 string vals = getHeader(wrapper->getHeader());
554 for (int i = 1; i < line->tokens.size() && !vals.empty(); i++) {
555 w = line->tokens[i].c_str();
562 auto_ptr<RegularExpression> re;
565 auto_ptr<XMLCh> trans(fromUTF8(w));
566 auto_ptr<RegularExpression> temp(new RegularExpression(trans.get()));
570 string vals_str(vals);
572 for (int i = 0; i < vals_str.length(); i++) {
573 if (vals_str.at(i) == ';') {
575 log(LogLevelError, string("doCheckAuthZ invalid header encoding")+
576 vals + ": starts with a semicolon");
580 if (vals_str.at(i-1) == '\\') {
581 vals_str.erase(i-1, 1);
586 string val = vals_str.substr(j, i-j);
589 auto_ptr<XMLCh> trans(fromUTF8(val.c_str()));
590 if (re->matches(trans.get())) {
591 log(LogLevelDebug, string("doCheckAuthZ expecting ") + w +
592 ", got " + val + ": authorization granted");
596 else if ((wrapper->getCaseSensitive() && val==w) ||
597 (!wrapper->getCaseSensitive() && !strcasecmp(val.c_str(),w))) {
598 log(LogLevelDebug, string("doCheckAuthZ expecting ") + w +
599 ", got " + val + ": authorization granted.");
603 log(LogLevelDebug, string("doCheckAuthZ expecting ") + w +
604 ", got " + val + ": authoritzation not granted.");
609 string val = vals_str.substr(j, vals_str.length()-j);
611 auto_ptr<XMLCh> trans(fromUTF8(val.c_str()));
612 if (re->matches(trans.get())) {
613 log(LogLevelDebug, string("doCheckAuthZ expecting ") + w +
614 ", got " + val + ": authorization granted.");
618 else if ((wrapper->getCaseSensitive() && val==w) ||
619 (!wrapper->getCaseSensitive() && !strcasecmp(val.c_str(),w))) {
620 log(LogLevelDebug, string("doCheckAuthZ expecting ") + w +
621 ", got " + val + ": authorization granted");
625 log(LogLevelDebug, string("doCheckAuthZ expecting ") + w +
626 ", got " + val + ": authorization not granted");
629 catch (XMLException& ex) {
630 auto_ptr_char tmp(ex.getMessage());
631 log(LogLevelError, string("doCheckAuthZ caught exception while parsing regular expression (")
632 + w + "): " + tmp.get());
639 // check if all require directives are true
640 bool auth_all_OK = true;
641 for (int i = 0; i < ht->elements.size(); i++) {
642 auth_all_OK &= auth_OK[i];
646 if (grpstatus) delete grpstatus;
647 if (auth_all_OK || !method_restricted)
648 return pair<bool,void*>(false, NULL);
650 // If we get here there's an access error, so just fall through
652 } catch (ShibTargetException &e) {
653 mlp.insert("errorText", e.what());
657 mlp.insert("errorText", "Unexpected Exception");
661 // If we get here then we've got an error.
662 mlp.insert("errorType", procState);
663 mlp.insert("errorDesc", "An error occurred while processing your request.");
667 mlp.insert("requestURL", targetURL);
672 return pair<bool,void*>(true,m_priv->sendError(this, "access", mlp));
676 ShibTarget::doExportAssertions(bool exportAssertion)
678 saml::NDC ndc("ShibTarget::doExportAssertions");
681 const char *procState = "Attribute Processing Error";
682 const char *targetURL = NULL;
687 throw ShibTargetException(SHIBRPC_OK, "ShibTarget Uninitialized. Application did not supply request information.");
689 targetURL = m_priv->m_url.c_str();
690 const char *session_id = m_priv->getSessionId(this);
692 if (m_priv->get_assertions(this, session_id, mlp))
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();
703 Iterator<const IAttributeRule*> rules=aap->getAttributeRules();
704 while (rules.hasNext()) {
705 const char* header=rules.next()->getHeader();
712 log(LogLevelError, "caught unexpected error while clearing headers");
719 // Maybe export the first assertion.
720 clearHeader("Shib-Attributes");
721 pair<bool,bool> exp=m_priv->m_settings.first->getBool("exportAssertion");
722 if (!exp.first || !exp.second)
725 if (exp.second && m_priv->m_assertions.size()) {
727 RM::serialize(*(m_priv->m_assertions[0]), assertion);
728 setHeader("Shib-Attributes", assertion.c_str());
731 // Export the SAML AuthnMethod and the origin site name, and possibly the NameIdentifier.
732 clearHeader("Shib-Origin-Site");
733 clearHeader("Shib-Authentication-Method");
734 clearHeader("Shib-NameIdentifier-Format");
735 auto_ptr_char os(m_priv->m_sso_statement->getSubject()->getNameIdentifier()->getNameQualifier());
736 auto_ptr_char am(m_priv->m_sso_statement->getAuthMethod());
737 setHeader("Shib-Origin-Site", os.get());
738 setHeader("Shib-Authentication-Method", am.get());
742 m_priv->m_sso_statement->getSubject()->getNameIdentifier()->getFormat(),
743 Constants::SHIB_ATTRIBUTE_NAMESPACE_URI);
744 if (!wrapper.fail() && wrapper->getHeader()) {
745 auto_ptr_char form(m_priv->m_sso_statement->getSubject()->getNameIdentifier()->getFormat());
746 auto_ptr_char nameid(m_priv->m_sso_statement->getSubject()->getNameIdentifier()->getName());
747 setHeader("Shib-NameIdentifier-Format", form.get());
748 if (!strcmp(wrapper->getHeader(),"REMOTE_USER"))
749 setRemoteUser(nameid.get());
751 setHeader(wrapper->getHeader(), nameid.get());
754 clearHeader("Shib-Application-ID");
755 setHeader("Shib-Application-ID", m_priv->m_app->getId());
757 // Export the attributes.
758 Iterator<SAMLAssertion*> a_iter(m_priv->m_assertions);
759 while (a_iter.hasNext()) {
760 SAMLAssertion* assert=a_iter.next();
761 Iterator<SAMLStatement*> statements=assert->getStatements();
762 while (statements.hasNext()) {
763 SAMLAttributeStatement* astate=dynamic_cast<SAMLAttributeStatement*>(statements.next());
766 Iterator<SAMLAttribute*> attrs=astate->getAttributes();
767 while (attrs.hasNext()) {
768 SAMLAttribute* attr=attrs.next();
770 // Are we supposed to export it?
771 AAP wrapper(provs,attr->getName(),attr->getNamespace());
772 if (wrapper.fail() || !wrapper->getHeader())
775 Iterator<string> vals=attr->getSingleByteValues();
776 if (!strcmp(wrapper->getHeader(),"REMOTE_USER") && vals.hasNext())
777 setRemoteUser(vals.next());
780 string header = getHeader(wrapper->getHeader());
781 if (! header.empty())
783 for (; vals.hasNext(); it++) {
784 string value = vals.next();
785 for (string::size_type pos = value.find_first_of(";", string::size_type(0));
787 pos = value.find_first_of(";", pos)) {
788 value.insert(pos, "\\");
795 setHeader(wrapper->getHeader(), header);
801 return pair<bool,void*>(false,NULL);
803 } catch (ShibTargetException &e) {
804 mlp.insert("errorText", e.what());
808 mlp.insert("errorText", "Unexpected Exception");
813 // If we get here then we've got an error.
814 mlp.insert("errorType", procState);
815 mlp.insert("errorDesc", "An error occurred while processing your request.");
819 mlp.insert("requestURL", targetURL);
821 return pair<bool,void*>(true,m_priv->sendError(this, page, mlp));
827 // Get the session cookie name and properties for the application
828 std::pair<const char*,const char*>
829 ShibTarget::getCookieNameProps() const
831 static const char* defProps="; path=/";
832 static const char* defName="_shibsession_";
834 // XXX: What to do if m_app isn't set?
836 const IPropertySet* props=m_priv->m_app->getPropertySet("Sessions");
838 pair<bool,const char*> p=props->getString("cookieProps");
841 if (!m_priv->m_cookieName.empty())
842 return pair<const char*,const char*>(m_priv->m_cookieName.c_str(),
844 pair<bool,const char*> p2=props->getString("cookieName");
846 m_priv->m_cookieName=p2.second;
847 return pair<const char*,const char*>(p2.second,p.second);
849 m_priv->m_cookieName=defName;
850 m_priv->m_cookieName+=m_priv->m_app->getId();
851 return pair<const char*,const char*>(m_priv->m_cookieName.c_str(),p.second);
853 m_priv->m_cookieName=defName;
854 m_priv->m_cookieName+=m_priv->m_app->getId();
855 return pair<const char*,const char*>(m_priv->m_cookieName.c_str(),defProps);
858 // Find the default assertion consumer service for the resource
860 ShibTarget::getShireURL(const char* resource) const
862 if (!m_priv->m_shireURL.empty())
863 return m_priv->m_shireURL.c_str();
865 // XXX: what to do is m_app is NULL?
867 bool shire_ssl_only=false;
868 const char* shire=NULL;
869 const IPropertySet* props=m_priv->m_app->getPropertySet("Sessions");
871 pair<bool,bool> p=props->getBool("shireSSL");
873 shire_ssl_only=p.second;
874 pair<bool,const char*> p2=props->getString("shireURL");
879 // Should never happen...
880 if (!shire || (*shire!='/' && strncmp(shire,"http:",5) && strncmp(shire,"https:",6)))
883 // The "shireURL" property can be in one of three formats:
885 // 1) a full URI: http://host/foo/bar
886 // 2) a hostless URI: http:///foo/bar
887 // 3) a relative path: /foo/bar
889 // # Protocol Host Path
890 // 1 shire shire shire
891 // 2 shire resource shire
892 // 3 resource resource shire
894 // note: if shire_ssl_only is true, make sure the protocol is https
896 const char* path = NULL;
898 // Decide whether to use the shire or the resource for the "protocol"
908 // break apart the "protocol" string into protocol, host, and "the rest"
909 const char* colon=strchr(prot,':');
911 const char* slash=strchr(colon,'/');
915 // Compute the actual protocol and store in member.
917 m_priv->m_shireURL.assign("https://");
919 m_priv->m_shireURL.assign(prot, colon-prot);
921 // create the "host" from either the colon/slash or from the target string
922 // If prot == shire then we're in either #1 or #2, else #3.
923 // If slash == colon then we're in #2.
924 if (prot != shire || slash == colon) {
925 colon = strchr(resource, ':');
926 colon += 3; // Get past the ://
927 slash = strchr(colon, '/');
929 string host(colon, slash-colon);
931 // Build the shire URL
932 m_priv->m_shireURL+=host + path;
933 return m_priv->m_shireURL.c_str();
936 // Generate a Shib 1.x AuthnRequest redirect URL for the resource
938 ShibTarget::getAuthnRequest(const char* resource) const
940 if (!m_priv->m_authnRequest.empty())
941 return m_priv->m_authnRequest.c_str();
943 // XXX: what to do if m_app is NULL?
946 sprintf(timebuf,"%u",time(NULL));
948 const IPropertySet* props=m_priv->m_app->getPropertySet("Sessions");
950 pair<bool,const char*> wayf=props->getString("wayfURL");
952 m_priv->m_authnRequest=m_priv->m_authnRequest + wayf.second + "?shire=" + m_priv->url_encode(getShireURL(resource)) +
953 "&target=" + m_priv->url_encode(resource) + "&time=" + timebuf;
954 pair<bool,bool> old=m_priv->m_app->getBool("oldAuthnRequest");
955 if (!old.first || !old.second) {
956 wayf=m_priv->m_app->getString("providerId");
958 m_priv->m_authnRequest=m_priv->m_authnRequest + "&providerId=" + m_priv->url_encode(wayf.second);
962 return m_priv->m_authnRequest.c_str();
965 // Process a lazy session setup request and turn it into an AuthnRequest
967 ShibTarget::getLazyAuthnRequest(const char* query_string) const
969 CgiParse parser(query_string,strlen(query_string));
970 const char* target=parser.get_value("target");
971 if (!target || !*target)
973 return getAuthnRequest(target);
976 // Process a POST profile submission, and return (SAMLResponse,TARGET) pair.
977 std::pair<const char*,const char*>
978 ShibTarget::getFormSubmission(const char* post, unsigned int len) const
980 m_priv->m_parser = new CgiParse(post,len);
981 return pair<const char*,const char*>(m_priv->m_parser->get_value("SAMLResponse"),m_priv->m_parser->get_value("TARGET"));
985 ShibTarget::sessionCreate(const char* response, const char* ip, std::string &cookie)
988 saml::NDC ndc("sessionCreate");
989 Category& log = Category::getInstance("shibtarget.SHIRE");
991 if (!response || !*response) {
992 log.error ("Empty SAML response content");
993 return new RPCError(-1, "Empty SAML response content");
997 log.error ("Invalid IP address");
998 return new RPCError(-1, "Invalid IP address");
1001 shibrpc_new_session_args_1 arg;
1002 arg.shire_location = (char*) m_priv->m_shireURL.c_str();
1003 arg.application_id = (char*) m_priv->m_app->getId();
1004 arg.saml_post = (char*)response;
1005 arg.client_addr = (char*)ip;
1006 arg.checkIPAddress = true;
1008 log.info ("create session for user at %s for application %s", ip, arg.application_id);
1010 const IPropertySet* props=m_priv->m_app->getPropertySet("Sessions");
1012 pair<bool,bool> pcheck=props->getBool("checkAddress");
1014 arg.checkIPAddress = pcheck.second;
1017 shibrpc_new_session_ret_1 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_1 (&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_1"));
1034 return new RPCError(-1, "RPC Failure");
1037 // SUCCESS. Pool and continue
1042 log.debug("RPC completed with status %d (%p)", ret.status.status, this);
1045 if (ret.status.status)
1046 retval = new RPCError(&ret.status);
1048 log.debug ("new cookie: %s", ret.cookie);
1049 cookie = ret.cookie;
1050 retval = new RPCError();
1053 clnt_freeres(clnt, (xdrproc_t)xdr_shibrpc_new_session_ret_1, (caddr_t)&ret);
1056 log.debug("returning");
1061 ShibTarget::sessionIsValid(const char* session_id, const char* ip) const
1063 saml::NDC ndc("sessionIsValid");
1064 Category& log = Category::getInstance("shibtarget.SHIRE");
1066 if (!session_id || !*session_id) {
1067 log.error ("No cookie value was provided");
1068 return new RPCError(SHIBRPC_NO_SESSION, "No cookie value was provided");
1070 else if (strchr(session_id,'=')) {
1071 log.error ("The cookie value wasn't extracted successfully, use a more unique cookie name for your installation.");
1072 return new RPCError(SHIBRPC_INTERNAL_ERROR, "The cookie value wasn't extracted successfully, use a more unique cookie name for your installation.");
1076 log.error ("Invalid IP Address");
1077 return new RPCError(SHIBRPC_IPADDR_MISSING, "Invalid IP Address");
1080 log.info ("is session valid: %s", ip);
1081 log.debug ("session cookie: %s", session_id);
1083 shibrpc_session_is_valid_args_1 arg;
1085 arg.cookie.cookie = (char*)session_id;
1086 arg.cookie.client_addr = (char *)ip;
1087 arg.application_id = (char *)m_priv->m_app->getId();
1089 // Get rest of input from the application Session properties.
1090 arg.lifetime = 3600;
1092 arg.checkIPAddress = true;
1093 const IPropertySet* props=m_priv->m_app->getPropertySet("Sessions");
1095 pair<bool,unsigned int> p=props->getUnsignedInt("lifetime");
1097 arg.lifetime = p.second;
1098 p=props->getUnsignedInt("timeout");
1100 arg.timeout = p.second;
1101 pair<bool,bool> pcheck=props->getBool("checkAddress");
1103 arg.checkIPAddress = pcheck.second;
1106 shibrpc_session_is_valid_ret_1 ret;
1107 memset (&ret, 0, sizeof(ret));
1109 // Loop on the RPC in case we lost contact the first time through
1114 clnt = rpc->connect();
1115 clnt_stat status = shibrpc_session_is_valid_1(&arg, &ret, clnt);
1116 if (status != RPC_SUCCESS) {
1117 // FAILED. Release, disconnect, and try again...
1118 log.error("RPC Failure: %p (%p) (%d) %s", this, clnt, status, clnt_spcreateerror("shibrpc_session_is_valid_1"));
1123 return new RPCError(-1, "RPC Failure");
1131 log.debug("RPC completed with status %d, %p", ret.status.status, this);
1134 if (ret.status.status)
1135 retval = new RPCError(&ret.status);
1137 retval = new RPCError();
1139 clnt_freeres (clnt, (xdrproc_t)xdr_shibrpc_session_is_valid_ret_1, (caddr_t)&ret);
1142 log.debug("returning");
1149 ShibTarget::getAssertions(const char* cookie, const char* ip,
1150 std::vector<saml::SAMLAssertion*>& assertions,
1151 saml::SAMLAuthenticationStatement **statement
1154 saml::NDC ndc("getAssertions");
1155 Category& log=Category::getInstance("shibtarget.RM");
1156 log.info("get assertions...");
1158 if (!cookie || !*cookie) {
1159 log.error ("No cookie value provided.");
1160 return new RPCError(-1, "No cookie value provided.");
1164 log.error ("Invalid ip address");
1165 return new RPCError(-1, "Invalid IP address");
1168 log.debug("session cookie: %s", cookie);
1170 shibrpc_get_assertions_args_1 arg;
1171 arg.cookie.cookie = (char*)cookie;
1172 arg.cookie.client_addr = (char*)ip;
1173 arg.checkIPAddress = true;
1174 arg.application_id = (char *)m_priv->m_app->getId();
1176 log.info("request from %s for \"%s\"", ip, arg.application_id);
1178 const IPropertySet* props=m_priv->m_app->getPropertySet("Sessions");
1180 pair<bool,bool> pcheck=props->getBool("checkAddress");
1182 arg.checkIPAddress = pcheck.second;
1185 shibrpc_get_assertions_ret_1 ret;
1186 memset (&ret, 0, sizeof(ret));
1188 // Loop on the RPC in case we lost contact the first time through
1193 clnt = rpc->connect();
1194 clnt_stat status = shibrpc_get_assertions_1(&arg, &ret, clnt);
1195 if (status != RPC_SUCCESS) {
1196 // FAILED. Release, disconnect, and try again.
1197 log.debug("RPC Failure: %p (%p) (%d): %s", this, clnt, status, clnt_spcreateerror("shibrpc_get_assertions_1"));
1202 return new RPCError(-1, "RPC Failure");
1205 // SUCCESS. Release back into pool
1210 log.debug("RPC completed with status %d (%p)", ret.status.status, this);
1212 RPCError* retval = NULL;
1213 if (ret.status.status)
1214 retval = new RPCError(&ret.status);
1218 for (u_int i = 0; i < ret.assertions.assertions_len; i++) {
1219 istringstream attrstream(ret.assertions.assertions_val[i].xml_string);
1220 SAMLAssertion *as = NULL;
1221 log.debugStream() << "Trying to decode assertion " << i << ": " <<
1222 ret.assertions.assertions_val[i].xml_string << CategoryStream::ENDLINE;
1223 assertions.push_back(new SAMLAssertion(attrstream));
1226 // return the Authentication Statement
1228 istringstream authstream(ret.auth_statement.xml_string);
1229 SAMLAuthenticationStatement *auth = NULL;
1231 log.debugStream() << "Trying to decode authentication statement: " <<
1232 ret.auth_statement.xml_string << CategoryStream::ENDLINE;
1233 auth = new SAMLAuthenticationStatement(authstream);
1235 // Save off the statement
1239 catch (SAMLException& e) {
1240 log.error ("SAML Exception: %s", e.what());
1243 throw ShibTargetException(SHIBRPC_SAML_EXCEPTION, os.str().c_str());
1245 catch (XMLException& e) {
1246 log.error ("XML Exception: %s", e.getMessage());
1247 auto_ptr_char msg(e.getMessage());
1248 throw ShibTargetException (SHIBRPC_XML_EXCEPTION, msg.get());
1251 catch (ShibTargetException &e) {
1252 retval = new RPCError(e);
1256 retval = new RPCError();
1259 clnt_freeres(clnt, (xdrproc_t)xdr_shibrpc_get_assertions_ret_1, (caddr_t)&ret);
1262 log.debug ("returning..");
1267 ShibTarget::serialize(saml::SAMLAssertion &assertion, std::string &result)
1269 saml::NDC ndc("serialize");
1270 Category& log=Category::getInstance("shibtarget.RM");
1274 unsigned int outlen;
1275 char* assn = (char*) os.str().c_str();
1276 XMLByte* serialized = Base64::encode(reinterpret_cast<XMLByte*>(assn), os.str().length(), &outlen);
1277 result = (char*) serialized;
1278 XMLString::release(&serialized);
1282 /*************************************************************************
1283 * Shib Target Private implementation
1286 ShibTargetPriv::ShibTargetPriv() : m_parser(NULL), m_app(NULL), m_mapper(NULL),
1287 m_conf(NULL), m_Config(NULL), m_assertions()
1290 m_sso_statement = NULL;
1293 ShibTargetPriv::~ShibTargetPriv()
1295 if (m_sso_statement) {
1296 delete m_sso_statement;
1297 m_sso_statement = NULL;
1299 for (int k = 0; k < m_assertions.size(); k++)
1300 delete m_assertions[k];
1301 m_assertions = vector<SAMLAssertion*>();
1319 static inline char hexchar(unsigned short s)
1321 return (s<=9) ? ('0' + s) : ('A' + s - 10);
1325 ShibTargetPriv::url_encode(const char* s)
1327 static char badchars[]="\"\\+<>#%{}|^~[]`;/?:@=&";
1331 if (strchr(badchars,*s) || *s<=0x1F || *s>=0x7F) {
1333 ret+=hexchar(*s >> 4);
1334 ret+=hexchar(*s & 0x0F);
1343 ShibTargetPriv::get_application(string protocol, string hostname, int port,
1349 // XXX: Do we need to keep conf and mapper locked while we hold m_app?
1351 // We lock the configuration system for the duration.
1352 m_conf=m_Config->getINI();
1355 // Map request to application and content settings.
1356 m_mapper=m_conf->getRequestMapper();
1359 // Obtain the application settings from the parsed URL
1360 m_settings = m_mapper->getSettingsFromParsedURL(protocol.c_str(),
1364 // Now find the application from the URL settings
1365 pair<bool,const char*> application_id=m_settings.first->getString("applicationId");
1366 const IApplication* application=m_conf->getApplication(application_id.second);
1372 throw ShibTargetException(SHIBRPC_OK, "unable to map request to application settings. Check configuration");
1375 // Store the application for later use
1376 m_app = application;
1378 // Compute the target URL
1379 m_url = protocol + "://" + hostname;
1380 if ((protocol == "http" && port != 80) || (protocol == "https" && port != 443))
1381 m_url += ":" + port;
1387 ShibTargetPriv::sendError(ShibTarget* st, string page, ShibMLP &mlp)
1389 const IPropertySet* props=m_app->getPropertySet("Errors");
1391 pair<bool,const char*> p=props->getString(page.c_str());
1393 ifstream infile(p.second);
1394 if (!infile.fail()) {
1395 const char* res = mlp.run(infile,props);
1397 return st->sendPage(res);
1402 string errstr = "sendError could not process the error template for application ";
1403 errstr += m_app->getId();
1404 st->log(ShibTarget::LogLevelError, errstr);
1405 return st->sendPage("Internal Server Error. Please contact the server administrator.");
1409 ShibTargetPriv::getSessionId(ShibTarget* st)
1412 //string m = string("getSessionId returning precreated session_id: ") + session_id;
1413 //st->log(ShibTarget::LogLevelDebug, m);
1418 pair<const char*, const char *> shib_cookie = st->getCookieNameProps();
1419 m_cookies = st->getCookies();
1420 if (!m_cookies.empty()) {
1421 if (sid = strstr(m_cookies.c_str(), shib_cookie.first)) {
1422 // We found a cookie. pull it out (our session_id)
1423 sid += strlen(shib_cookie.first) + 1; // skip over the '='
1424 char *cookieend = strchr(sid, ';');
1431 //string m = string("getSessionId returning new session_id: ") + session_id;
1432 //st->log(ShibTarget::LogLevelDebug, m);
1437 ShibTargetPriv::get_assertions(ShibTarget* st, const char *session_id, ShibMLP &mlp)
1439 if (m_sso_statement)
1442 RPCError *status = NULL;
1443 status = st->getAssertions(session_id, m_remote_addr.c_str(),
1444 m_assertions, &m_sso_statement);
1446 if (status->isError()) {
1447 string er = "getAssertions failed: ";
1448 er += status->getText();
1449 st->log(ShibTarget::LogLevelError, er);
1450 mlp.insert(*status);
1459 /*************************************************************************
1460 * CGI Parser implementation
1463 CgiParse::CgiParse(const char* data, unsigned int len)
1465 const char* pch = data;
1466 unsigned int cl = len;
1471 value=fmakeword('&',&cl,&pch);
1474 name=makeword(value,'=');
1475 kvp_map[name]=value;
1480 CgiParse::~CgiParse()
1482 for (map<string,char*>::iterator i=kvp_map.begin(); i!=kvp_map.end(); i++)
1487 CgiParse::get_value(const char* name) const
1489 map<string,char*>::const_iterator i=kvp_map.find(name);
1490 if (i==kvp_map.end())
1495 /* Parsing routines modified from NCSA source. */
1497 CgiParse::makeword(char *line, char stop)
1500 char *word = (char *) malloc(sizeof(char) * (strlen(line) + 1));
1502 for(x=0;((line[x]) && (line[x] != stop));x++)
1511 line[y++] = line[x++];
1517 CgiParse::fmakeword(char stop, unsigned int *cl, const char** ppch)
1525 word = (char *) malloc(sizeof(char) * (wsize + 1));
1529 word[ll] = *((*ppch)++);
1534 word = (char *)realloc(word,sizeof(char)*(wsize+1));
1537 if((word[ll] == stop) || word[ll] == EOF || (!(*cl)))
1539 if(word[ll] != stop)
1549 CgiParse::plustospace(char *str)
1554 if(str[x] == '+') str[x] = ' ';
1558 CgiParse::x2c(char *what)
1560 register char digit;
1562 digit = (what[0] >= 'A' ? ((what[0] & 0xdf) - 'A')+10 : (what[0] - '0'));
1564 digit += (what[1] >= 'A' ? ((what[1] & 0xdf) - 'A')+10 : (what[1] - '0'));
1569 CgiParse::url_decode(char *url)
1573 for(x=0,y=0;url[y];++x,++y)
1575 if((url[x] = url[y]) == '%')
1577 url[x] = x2c(&url[y+1]);
1585 * We need to implement this so the SHIRE (and RM) recodes work
1586 * in terms of the ShibTarget
1588 void ShibTarget::log(ShibLogLevel level, const string &msg)
1590 throw runtime_error("Invalid Usage");
1592 string ShibTarget::getCookies(void)
1594 throw runtime_error("Invalid Usage");
1596 void ShibTarget::setCookie(const string &name, const string &value)
1598 throw runtime_error("Invalid Usage");
1600 void ShibTarget::clearHeader(const string &name)
1602 throw runtime_error("Invalid Usage");
1604 void ShibTarget::setHeader(const string &name, const string &value)
1606 throw runtime_error("Invalid Usage");
1608 string ShibTarget::getHeader(const string &name)
1610 throw runtime_error("Invalid Usage");
1612 void ShibTarget::setRemoteUser(const string &name)
1614 throw runtime_error("Invalid Usage");
1616 string ShibTarget::getRemoteUser(void)
1618 throw runtime_error("Invalid Usage");
1620 string ShibTarget::getArgs(void)
1622 throw runtime_error("Invalid Usage");
1624 string ShibTarget::getPostData(void)
1626 throw runtime_error("Invalid Usage");
1628 //virtual HTAccessInfo& getAccessInfo(void);
1629 void* ShibTarget::sendPage(const string &msg, const string content_type, const pair<string,string> headers[], int code)
1631 throw runtime_error("Invalid Usage");
1633 void* ShibTarget::sendRedirect(const std::string url)
1635 throw runtime_error("Invalid Usage");
1638 // Subclasses may not need to override these particular virtual methods.
1639 string ShibTarget::getAuthType(void)
1641 return string("shibboleth");
1643 void* ShibTarget::returnDecline(void)
1647 void* ShibTarget::returnOK(void)
1651 HTAccessInfo* ShibTarget::getAccessInfo(void)
1655 HTGroupTable* ShibTarget::getGroupTable(string &user)