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)
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))
207 return doHandlePOST();
209 string auth_type = getAuthType();
210 if (strcasecmp(auth_type.c_str(),"shibboleth"))
211 return pair<bool,void*>(true,returnDecline());
213 pair<bool,bool> requireSession =
214 m_priv->m_settings.first->getBool("requireSession");
215 if (!requireSession.first || !requireSession.second)
216 if (requireSessionFlag)
217 requireSession.second=true;
219 const char *session_id = m_priv->getSessionId(this);
221 if (!session_id || !*session_id) {
222 // No session. Maybe that's acceptable?
224 if (!requireSession.second)
225 return pair<bool,void*>(true,returnOK());
227 // No cookie, but we require a session. Generate an AuthnRequest.
228 return pair<bool,void*>(true,sendRedirect(getAuthnRequest(targetURL)));
231 procState = "Session Processing Error";
232 RPCError *status = sessionIsValid(session_id, m_priv->m_remote_addr.c_str());
234 if (status->isError()) {
236 // If no session is required, bail now.
237 if (!requireSession.second)
238 return pair<bool,void*>(true, returnOK());
239 // XXX: Or should this be DECLINED?
240 // Has to be OK because DECLINED will just cause Apache
241 // to fail when it can't locate anything to process the
242 // AuthType. No session plus requireSession false means
243 // do not authenticate the user at this time.
244 else if (status->isRetryable()) {
245 // Session is invalid but we can retry the auth -- generate an AuthnRequest
247 return pair<bool,void*>(true,sendRedirect(getAuthnRequest(targetURL)));
251 string er = "Unretryable error: " ;
252 er += status->getText();
253 log(LogLevelError, er);
263 // We're done. Everything is okay. Nothing to report. Nothing to do..
264 // Let the caller decide how to proceed.
265 log(LogLevelInfo, "doCheckAuthN Succeeded\n");
266 return pair<bool,void*>(false,NULL);
268 } catch (ShibTargetException &e) {
269 mlp.insert("errorText", e.what());
273 mlp.insert("errorText", "Unexpected Exception");
277 // If we get here then we've got an error.
278 mlp.insert("errorType", procState);
279 mlp.insert("errorDesc", "An error occurred while processing your request.");
283 mlp.insert("requestURL", targetURL);
285 return pair<bool,void*>(true,m_priv->sendError(this, "shire", mlp));
289 ShibTarget::doHandlePOST(void)
291 saml::NDC ndc("ShibTarget::doHandlePOST");
293 const char *targetURL = NULL;
294 const char *procState = "Session Creation Service Error";
299 throw ShibTargetException(SHIBRPC_OK, "ShibTarget Uninitialized. Application did not supply request information.");
301 targetURL = m_priv->m_url.c_str();
302 const char *shireURL = getShireURL(targetURL);
305 throw ShibTargetException(SHIBRPC_OK, "doHandlePOST: unable to map request to a proper shireURL setting. Check Configuration.");
308 // Make sure we only process the SHIRE requests.
309 if (!strstr(targetURL, shireURL))
310 return pair<bool,void*>(true, returnDecline());
312 const IPropertySet* sessionProps=m_priv->m_app->getPropertySet("Sessions");
314 throw ShibTargetException(SHIBRPC_OK, "doHandlePOST: unable to map request to application session settings. Check configuration");
316 // this always returns something
317 pair<const char*,const char*> shib_cookie=getCookieNameProps();
319 // Process SHIRE request
321 pair<bool,bool> shireSSL=sessionProps->getBool("shireSSL");
323 // Make sure this is SSL, if it should be
324 if ((!shireSSL.first || shireSSL.second) && m_priv->m_protocol == "https")
325 throw ShibTargetException(SHIBRPC_OK, "blocked non-SSL access to session creation service");
327 // If this is a GET, we manufacture an AuthnRequest.
328 if (!strcasecmp(m_priv->m_method.c_str(), "GET")) {
329 string args = getArgs();
330 const char* areq=args.empty() ? NULL : getLazyAuthnRequest(args.c_str());
332 throw ShibTargetException(SHIBRPC_OK, "malformed GET arguments to request a new session");
333 return pair<bool,void*>(true, sendRedirect(areq));
335 else if (strcasecmp(m_priv->m_method.c_str(), "POST")) {
336 throw ShibTargetException(SHIBRPC_OK, "blocked non-POST to SHIRE POST processor");
339 // Make sure this POST is an appropriate content type
340 if (m_priv->m_content_type.empty() ||
341 strcasecmp(m_priv->m_content_type.c_str(),
342 "application/x-www-form-urlencoded")) {
343 string er = string("blocked bad content-type to SHIRE POST processor: ") +
344 m_priv->m_content_type;
345 throw ShibTargetException(SHIBRPC_OK, er.c_str());
348 // Read the POST Data
349 string cgistr = getPostData();
351 // Parse the submission.
352 pair<const char*,const char*> elements =
353 getFormSubmission(cgistr.c_str(),cgistr.length());
355 // Make sure the SAML Response parameter exists
356 if (!elements.first || !*elements.first)
357 throw ShibTargetException(SHIBRPC_OK, "SHIRE POST failed to find SAMLResponse form element");
359 // Make sure the target parameter exists
360 if (!elements.second || !*elements.second)
361 throw ShibTargetException(SHIBRPC_OK, "SHIRE POST failed to find TARGET form element");
365 RPCError* status = sessionCreate(elements.first, m_priv->m_remote_addr.c_str(),
368 if (status->isError()) {
370 sprintf(buf, "(%d): ", status->getCode());
371 string er = string("doHandlePost() POST process failed ") + buf +
373 log(LogLevelError, er);
375 if (status->isRetryable()) {
378 return pair<bool,void*>(true, sendRedirect(getAuthnRequest(elements.second)));
381 // return this error to the user.
389 string("doHandlePost() POST process succeeded. New session: ") + cookie);
391 // We've got a good session, set the cookie...
392 cookie += shib_cookie.second;
393 setCookie(shib_cookie.first, cookie);
395 // ... and redirect to the target
396 return pair<bool,void*>(true, sendRedirect(elements.second));
398 } catch (ShibTargetException &e) {
399 mlp.insert("errorText", e.what());
403 mlp.insert("errorText", "Unexpected Exception");
407 // If we get here then we've got an error.
408 mlp.insert("errorType", procState);
409 mlp.insert("errorDesc", "An error occurred while processing your request.");
413 mlp.insert("requestURL", targetURL);
415 return pair<bool,void*>(true,m_priv->sendError(this, "shire", mlp));
419 ShibTarget::doCheckAuthZ(void)
421 saml::NDC ndc("ShibTarget::doCheckAuthZ");
424 const char *procState = "Authorization Processing Error";
425 const char *targetURL = NULL;
426 HTAccessInfo *ht = NULL;
427 HTGroupTable* grpstatus = NULL;
431 throw ShibTargetException(SHIBRPC_OK, "ShibTarget Uninitialized. Application did not supply request information.");
433 targetURL = m_priv->m_url.c_str();
434 const char *session_id = m_priv->getSessionId(this);
436 // XXX: need to make sure that export assertions was already called.
437 //if (m_priv->get_assertions(this, session_id, mlp))
440 // Do we have an access control plugin?
441 if (m_priv->m_settings.second) {
442 Locker acllock(m_priv->m_settings.second);
443 if (!m_priv->m_settings.second->authorized(*m_priv->m_sso_statement,
444 m_priv->m_assertions)) {
445 log(LogLevelError, "doCheckAuthZ: access control provider denied access");
450 // Perform HTAccess Checks
451 ht = getAccessInfo();
453 // No Info means OK. Just return
455 return pair<bool,void*>(false, NULL);
457 vector<bool> auth_OK(ht->elements.size(), false);
458 bool method_restricted=false;
459 string remote_user = getRemoteUser();
462 if (ht->requireAll) { \
464 if (grpstatus) delete grpstatus; \
465 return pair<bool,void*>(false, NULL); \
471 for (int x = 0; x < ht->elements.size(); x++) {
473 HTAccessInfo::RequireLine *line = ht->elements[x];
474 if (! line->use_line)
476 method_restricted = true;
478 const char *w = line->tokens[0].c_str();
480 if (!strcasecmp(w,"Shibboleth")) {
481 // This is a dummy rule needed because Apache conflates authn and authz.
482 // Without some require rule, AuthType is ignored and no check_user hooks run.
485 else if (!strcmp(w,"valid-user")) {
486 log(LogLevelDebug, "doCheckAuthZ accepting valid-user");
490 else if (!strcmp(w,"user") && !remote_user.empty()) {
492 for (int i = 1; i < line->tokens.size(); i++) {
493 w = line->tokens[i].c_str();
501 // To do regex matching, we have to convert from UTF-8.
502 auto_ptr<XMLCh> trans(fromUTF8(w));
503 RegularExpression re(trans.get());
504 auto_ptr<XMLCh> trans2(fromUTF8(remote_user.c_str()));
505 if (re.matches(trans2.get())) {
506 log(LogLevelDebug, string("doCheckAuthZ accepting user: ") + w);
510 catch (XMLException& ex) {
511 auto_ptr_char tmp(ex.getMessage());
512 log(LogLevelError, string("doCheckAuthZ caught exception while parsing regular expression (")
513 + w + "): " + tmp.get());
516 else if (!strcmp(remote_user.c_str(), w)) {
517 log(LogLevelDebug, string("doCheckAuthZ accepting user: ") + w);
522 else if (!strcmp(w,"group")) {
523 grpstatus = getGroupTable(remote_user);
527 return pair<bool,void*>(true, returnDecline());
530 for (int i = 1; i < line->tokens.size(); i++) {
531 w = line->tokens[i].c_str();
532 if (grpstatus->lookup(w)) {
533 log(LogLevelDebug, string("doCheckAuthZ accepting group: ") + w);
541 Iterator<IAAP*> provs = m_priv->m_app->getAAPProviders();
542 AAP wrapper(provs, w);
543 if (wrapper.fail()) {
544 log(LogLevelWarn, string("doCheckAuthZ didn't recognize require rule: ")
550 string vals = getHeader(wrapper->getHeader());
551 for (int i = 1; i < line->tokens.size() && !vals.empty(); i++) {
552 w = line->tokens[i].c_str();
559 auto_ptr<RegularExpression> re;
562 auto_ptr<XMLCh> trans(fromUTF8(w));
563 auto_ptr<RegularExpression> temp(new RegularExpression(trans.get()));
567 string vals_str(vals);
569 for (int i = 0; i < vals_str.length(); i++) {
570 if (vals_str.at(i) == ';') {
572 log(LogLevelError, string("doCheckAuthZ invalid header encoding")+
573 vals + ": starts with a semicolon");
577 if (vals_str.at(i-1) == '\\') {
578 vals_str.erase(i-1, 1);
583 string val = vals_str.substr(j, i-j);
586 auto_ptr<XMLCh> trans(fromUTF8(val.c_str()));
587 if (re->matches(trans.get())) {
588 log(LogLevelDebug, string("doCheckAuthZ expecting ") + w +
589 ", got " + val + ": authorization granted");
593 else if ((wrapper->getCaseSensitive() && val==w) ||
594 (!wrapper->getCaseSensitive() && !strcasecmp(val.c_str(),w))) {
595 log(LogLevelDebug, string("doCheckAuthZ expecting ") + w +
596 ", got " + val + ": authorization granted.");
600 log(LogLevelDebug, string("doCheckAuthZ expecting ") + w +
601 ", got " + val + ": authoritzation not granted.");
606 string val = vals_str.substr(j, vals_str.length()-j);
608 auto_ptr<XMLCh> trans(fromUTF8(val.c_str()));
609 if (re->matches(trans.get())) {
610 log(LogLevelDebug, string("doCheckAuthZ expecting ") + w +
611 ", got " + val + ": authorization granted.");
615 else if ((wrapper->getCaseSensitive() && val==w) ||
616 (!wrapper->getCaseSensitive() && !strcasecmp(val.c_str(),w))) {
617 log(LogLevelDebug, string("doCheckAuthZ expecting ") + w +
618 ", got " + val + ": authorization granted");
622 log(LogLevelDebug, string("doCheckAuthZ expecting ") + w +
623 ", got " + val + ": authorization not granted");
626 catch (XMLException& ex) {
627 auto_ptr_char tmp(ex.getMessage());
628 log(LogLevelError, string("doCheckAuthZ caught exception while parsing regular expression (")
629 + w + "): " + tmp.get());
636 // check if all require directives are true
637 bool auth_all_OK = true;
638 for (int i = 0; i < ht->elements.size(); i++) {
639 auth_all_OK &= auth_OK[i];
643 if (grpstatus) delete grpstatus;
644 if (auth_all_OK || !method_restricted)
645 return pair<bool,void*>(false, NULL);
647 // If we get here there's an access error, so just fall through
649 } catch (ShibTargetException &e) {
650 mlp.insert("errorText", e.what());
654 mlp.insert("errorText", "Unexpected Exception");
658 // If we get here then we've got an error.
659 mlp.insert("errorType", procState);
660 mlp.insert("errorDesc", "An error occurred while processing your request.");
664 mlp.insert("requestURL", targetURL);
669 return pair<bool,void*>(true,m_priv->sendError(this, "access", mlp));
673 ShibTarget::doExportAssertions(bool exportAssertion)
675 saml::NDC ndc("ShibTarget::doExportAssertions");
678 const char *procState = "Attribute Processing Error";
679 const char *targetURL = NULL;
684 throw ShibTargetException(SHIBRPC_OK, "ShibTarget Uninitialized. Application did not supply request information.");
686 targetURL = m_priv->m_url.c_str();
687 const char *session_id = m_priv->getSessionId(this);
689 if (m_priv->get_assertions(this, session_id, mlp))
692 // Get the AAP providers, which contain the attribute policy info.
693 Iterator<IAAP*> provs=m_priv->m_app->getAAPProviders();
695 // Clear out the list of mapped attributes
696 while (provs.hasNext()) {
697 IAAP* aap=provs.next();
700 Iterator<const IAttributeRule*> rules=aap->getAttributeRules();
701 while (rules.hasNext()) {
702 const char* header=rules.next()->getHeader();
709 log(LogLevelError, "caught unexpected error while clearing headers");
716 // Maybe export the first assertion.
717 clearHeader("Shib-Attributes");
718 pair<bool,bool> exp=m_priv->m_settings.first->getBool("exportAssertion");
719 if (!exp.first || !exp.second)
722 if (exp.second && m_priv->m_assertions.size()) {
724 RM::serialize(*(m_priv->m_assertions[0]), assertion);
725 setHeader("Shib-Attributes", assertion.c_str());
728 // Export the SAML AuthnMethod and the origin site name, and possibly the NameIdentifier.
729 clearHeader("Shib-Origin-Site");
730 clearHeader("Shib-Authentication-Method");
731 clearHeader("Shib-NameIdentifier-Format");
732 auto_ptr_char os(m_priv->m_sso_statement->getSubject()->getNameIdentifier()->getNameQualifier());
733 auto_ptr_char am(m_priv->m_sso_statement->getAuthMethod());
734 setHeader("Shib-Origin-Site", os.get());
735 setHeader("Shib-Authentication-Method", am.get());
739 m_priv->m_sso_statement->getSubject()->getNameIdentifier()->getFormat(),
740 Constants::SHIB_ATTRIBUTE_NAMESPACE_URI);
741 if (!wrapper.fail() && wrapper->getHeader()) {
742 auto_ptr_char form(m_priv->m_sso_statement->getSubject()->getNameIdentifier()->getFormat());
743 auto_ptr_char nameid(m_priv->m_sso_statement->getSubject()->getNameIdentifier()->getName());
744 setHeader("Shib-NameIdentifier-Format", form.get());
745 if (!strcmp(wrapper->getHeader(),"REMOTE_USER"))
746 setRemoteUser(nameid.get());
748 setHeader(wrapper->getHeader(), nameid.get());
751 clearHeader("Shib-Application-ID");
752 setHeader("Shib-Application-ID", m_priv->m_app->getId());
754 // Export the attributes.
755 Iterator<SAMLAssertion*> a_iter(m_priv->m_assertions);
756 while (a_iter.hasNext()) {
757 SAMLAssertion* assert=a_iter.next();
758 Iterator<SAMLStatement*> statements=assert->getStatements();
759 while (statements.hasNext()) {
760 SAMLAttributeStatement* astate=dynamic_cast<SAMLAttributeStatement*>(statements.next());
763 Iterator<SAMLAttribute*> attrs=astate->getAttributes();
764 while (attrs.hasNext()) {
765 SAMLAttribute* attr=attrs.next();
767 // Are we supposed to export it?
768 AAP wrapper(provs,attr->getName(),attr->getNamespace());
769 if (wrapper.fail() || !wrapper->getHeader())
772 Iterator<string> vals=attr->getSingleByteValues();
773 if (!strcmp(wrapper->getHeader(),"REMOTE_USER") && vals.hasNext())
774 setRemoteUser(vals.next());
777 string header = getHeader(wrapper->getHeader());
778 if (! header.empty())
780 for (; vals.hasNext(); it++) {
781 string value = vals.next();
782 for (string::size_type pos = value.find_first_of(";", string::size_type(0));
784 pos = value.find_first_of(";", pos)) {
785 value.insert(pos, "\\");
792 setHeader(wrapper->getHeader(), header);
798 return pair<bool,void*>(false,NULL);
800 } catch (ShibTargetException &e) {
801 mlp.insert("errorText", e.what());
805 mlp.insert("errorText", "Unexpected Exception");
810 // If we get here then we've got an error.
811 mlp.insert("errorType", procState);
812 mlp.insert("errorDesc", "An error occurred while processing your request.");
816 mlp.insert("requestURL", targetURL);
818 return pair<bool,void*>(true,m_priv->sendError(this, page, mlp));
824 // Get the session cookie name and properties for the application
825 std::pair<const char*,const char*>
826 ShibTarget::getCookieNameProps() const
828 static const char* defProps="; path=/";
829 static const char* defName="_shibsession_";
831 // XXX: What to do if m_app isn't set?
833 const IPropertySet* props=m_priv->m_app->getPropertySet("Sessions");
835 pair<bool,const char*> p=props->getString("cookieProps");
838 if (!m_priv->m_cookieName.empty())
839 return pair<const char*,const char*>(m_priv->m_cookieName.c_str(),
841 pair<bool,const char*> p2=props->getString("cookieName");
843 m_priv->m_cookieName=p2.second;
844 return pair<const char*,const char*>(p2.second,p.second);
846 m_priv->m_cookieName=defName;
847 m_priv->m_cookieName+=m_priv->m_app->getId();
848 return pair<const char*,const char*>(m_priv->m_cookieName.c_str(),p.second);
850 m_priv->m_cookieName=defName;
851 m_priv->m_cookieName+=m_priv->m_app->getId();
852 return pair<const char*,const char*>(m_priv->m_cookieName.c_str(),defProps);
855 // Find the default assertion consumer service for the resource
857 ShibTarget::getShireURL(const char* resource) const
859 if (!m_priv->m_shireURL.empty())
860 return m_priv->m_shireURL.c_str();
862 // XXX: what to do is m_app is NULL?
864 bool shire_ssl_only=false;
865 const char* shire=NULL;
866 const IPropertySet* props=m_priv->m_app->getPropertySet("Sessions");
868 pair<bool,bool> p=props->getBool("shireSSL");
870 shire_ssl_only=p.second;
871 pair<bool,const char*> p2=props->getString("shireURL");
876 // Should never happen...
877 if (!shire || (*shire!='/' && strncmp(shire,"http:",5) && strncmp(shire,"https:",6)))
880 // The "shireURL" property can be in one of three formats:
882 // 1) a full URI: http://host/foo/bar
883 // 2) a hostless URI: http:///foo/bar
884 // 3) a relative path: /foo/bar
886 // # Protocol Host Path
887 // 1 shire shire shire
888 // 2 shire resource shire
889 // 3 resource resource shire
891 // note: if shire_ssl_only is true, make sure the protocol is https
893 const char* path = NULL;
895 // Decide whether to use the shire or the resource for the "protocol"
905 // break apart the "protocol" string into protocol, host, and "the rest"
906 const char* colon=strchr(prot,':');
908 const char* slash=strchr(colon,'/');
912 // Compute the actual protocol and store in member.
914 m_priv->m_shireURL.assign("https://");
916 m_priv->m_shireURL.assign(prot, colon-prot);
918 // create the "host" from either the colon/slash or from the target string
919 // If prot == shire then we're in either #1 or #2, else #3.
920 // If slash == colon then we're in #2.
921 if (prot != shire || slash == colon) {
922 colon = strchr(resource, ':');
923 colon += 3; // Get past the ://
924 slash = strchr(colon, '/');
926 string host(colon, slash-colon);
928 // Build the shire URL
929 m_priv->m_shireURL+=host + path;
930 return m_priv->m_shireURL.c_str();
933 // Generate a Shib 1.x AuthnRequest redirect URL for the resource
935 ShibTarget::getAuthnRequest(const char* resource) const
937 if (!m_priv->m_authnRequest.empty())
938 return m_priv->m_authnRequest.c_str();
940 // XXX: what to do if m_app is NULL?
943 sprintf(timebuf,"%u",time(NULL));
945 const IPropertySet* props=m_priv->m_app->getPropertySet("Sessions");
947 pair<bool,const char*> wayf=props->getString("wayfURL");
949 m_priv->m_authnRequest=m_priv->m_authnRequest + wayf.second + "?shire=" + m_priv->url_encode(getShireURL(resource)) +
950 "&target=" + m_priv->url_encode(resource) + "&time=" + timebuf;
951 pair<bool,bool> old=m_priv->m_app->getBool("oldAuthnRequest");
952 if (!old.first || !old.second) {
953 wayf=m_priv->m_app->getString("providerId");
955 m_priv->m_authnRequest=m_priv->m_authnRequest + "&providerId=" + m_priv->url_encode(wayf.second);
959 return m_priv->m_authnRequest.c_str();
962 // Process a lazy session setup request and turn it into an AuthnRequest
964 ShibTarget::getLazyAuthnRequest(const char* query_string) const
966 CgiParse parser(query_string,strlen(query_string));
967 const char* target=parser.get_value("target");
968 if (!target || !*target)
970 return getAuthnRequest(target);
973 // Process a POST profile submission, and return (SAMLResponse,TARGET) pair.
974 std::pair<const char*,const char*>
975 ShibTarget::getFormSubmission(const char* post, unsigned int len) const
977 m_priv->m_parser = new CgiParse(post,len);
978 return pair<const char*,const char*>(m_priv->m_parser->get_value("SAMLResponse"),m_priv->m_parser->get_value("TARGET"));
982 ShibTarget::sessionCreate(const char* response, const char* ip, std::string &cookie)
985 saml::NDC ndc("sessionCreate");
986 Category& log = Category::getInstance("shibtarget.SHIRE");
988 if (!response || !*response) {
989 log.error ("Empty SAML response content");
990 return new RPCError(-1, "Empty SAML response content");
994 log.error ("Invalid IP address");
995 return new RPCError(-1, "Invalid IP address");
998 shibrpc_new_session_args_1 arg;
999 arg.shire_location = (char*) m_priv->m_shireURL.c_str();
1000 arg.application_id = (char*) m_priv->m_app->getId();
1001 arg.saml_post = (char*)response;
1002 arg.client_addr = (char*)ip;
1003 arg.checkIPAddress = true;
1005 log.info ("create session for user at %s for application %s", ip, arg.application_id);
1007 const IPropertySet* props=m_priv->m_app->getPropertySet("Sessions");
1009 pair<bool,bool> pcheck=props->getBool("checkAddress");
1011 arg.checkIPAddress = pcheck.second;
1014 shibrpc_new_session_ret_1 ret;
1015 memset (&ret, 0, sizeof(ret));
1017 // Loop on the RPC in case we lost contact the first time through
1022 clnt = rpc->connect();
1023 clnt_stat status = shibrpc_new_session_1 (&arg, &ret, clnt);
1024 if (status != RPC_SUCCESS) {
1025 // FAILED. Release, disconnect, and retry
1026 log.error("RPC Failure: %p (%p) (%d): %s", this, clnt, status, clnt_spcreateerror("shibrpc_new_session_1"));
1031 return new RPCError(-1, "RPC Failure");
1034 // SUCCESS. Pool and continue
1039 log.debug("RPC completed with status %d (%p)", ret.status.status, this);
1042 if (ret.status.status)
1043 retval = new RPCError(&ret.status);
1045 log.debug ("new cookie: %s", ret.cookie);
1046 cookie = ret.cookie;
1047 retval = new RPCError();
1050 clnt_freeres(clnt, (xdrproc_t)xdr_shibrpc_new_session_ret_1, (caddr_t)&ret);
1053 log.debug("returning");
1058 ShibTarget::sessionIsValid(const char* session_id, const char* ip) const
1060 saml::NDC ndc("sessionIsValid");
1061 Category& log = Category::getInstance("shibtarget.SHIRE");
1063 if (!session_id || !*session_id) {
1064 log.error ("No cookie value was provided");
1065 return new RPCError(SHIBRPC_NO_SESSION, "No cookie value was provided");
1067 else if (strchr(session_id,'=')) {
1068 log.error ("The cookie value wasn't extracted successfully, use a more unique cookie name for your installation.");
1069 return new RPCError(SHIBRPC_INTERNAL_ERROR, "The cookie value wasn't extracted successfully, use a more unique cookie name for your installation.");
1073 log.error ("Invalid IP Address");
1074 return new RPCError(SHIBRPC_IPADDR_MISSING, "Invalid IP Address");
1077 log.info ("is session valid: %s", ip);
1078 log.debug ("session cookie: %s", session_id);
1080 shibrpc_session_is_valid_args_1 arg;
1082 arg.cookie.cookie = (char*)session_id;
1083 arg.cookie.client_addr = (char *)ip;
1084 arg.application_id = (char *)m_priv->m_app->getId();
1086 // Get rest of input from the application Session properties.
1087 arg.lifetime = 3600;
1089 arg.checkIPAddress = true;
1090 const IPropertySet* props=m_priv->m_app->getPropertySet("Sessions");
1092 pair<bool,unsigned int> p=props->getUnsignedInt("lifetime");
1094 arg.lifetime = p.second;
1095 p=props->getUnsignedInt("timeout");
1097 arg.timeout = p.second;
1098 pair<bool,bool> pcheck=props->getBool("checkAddress");
1100 arg.checkIPAddress = pcheck.second;
1103 shibrpc_session_is_valid_ret_1 ret;
1104 memset (&ret, 0, sizeof(ret));
1106 // Loop on the RPC in case we lost contact the first time through
1111 clnt = rpc->connect();
1112 clnt_stat status = shibrpc_session_is_valid_1(&arg, &ret, clnt);
1113 if (status != RPC_SUCCESS) {
1114 // FAILED. Release, disconnect, and try again...
1115 log.error("RPC Failure: %p (%p) (%d) %s", this, clnt, status, clnt_spcreateerror("shibrpc_session_is_valid_1"));
1120 return new RPCError(-1, "RPC Failure");
1128 log.debug("RPC completed with status %d, %p", ret.status.status, this);
1131 if (ret.status.status)
1132 retval = new RPCError(&ret.status);
1134 retval = new RPCError();
1136 clnt_freeres (clnt, (xdrproc_t)xdr_shibrpc_session_is_valid_ret_1, (caddr_t)&ret);
1139 log.debug("returning");
1146 ShibTarget::getAssertions(const char* cookie, const char* ip,
1147 std::vector<saml::SAMLAssertion*>& assertions,
1148 saml::SAMLAuthenticationStatement **statement
1151 saml::NDC ndc("getAssertions");
1152 Category& log=Category::getInstance("shibtarget.RM");
1153 log.info("get assertions...");
1155 if (!cookie || !*cookie) {
1156 log.error ("No cookie value provided.");
1157 return new RPCError(-1, "No cookie value provided.");
1161 log.error ("Invalid ip address");
1162 return new RPCError(-1, "Invalid IP address");
1165 log.debug("session cookie: %s", cookie);
1167 shibrpc_get_assertions_args_1 arg;
1168 arg.cookie.cookie = (char*)cookie;
1169 arg.cookie.client_addr = (char*)ip;
1170 arg.checkIPAddress = true;
1171 arg.application_id = (char *)m_priv->m_app->getId();
1173 log.info("request from %s for \"%s\"", ip, arg.application_id);
1175 const IPropertySet* props=m_priv->m_app->getPropertySet("Sessions");
1177 pair<bool,bool> pcheck=props->getBool("checkAddress");
1179 arg.checkIPAddress = pcheck.second;
1182 shibrpc_get_assertions_ret_1 ret;
1183 memset (&ret, 0, sizeof(ret));
1185 // Loop on the RPC in case we lost contact the first time through
1190 clnt = rpc->connect();
1191 clnt_stat status = shibrpc_get_assertions_1(&arg, &ret, clnt);
1192 if (status != RPC_SUCCESS) {
1193 // FAILED. Release, disconnect, and try again.
1194 log.debug("RPC Failure: %p (%p) (%d): %s", this, clnt, status, clnt_spcreateerror("shibrpc_get_assertions_1"));
1199 return new RPCError(-1, "RPC Failure");
1202 // SUCCESS. Release back into pool
1207 log.debug("RPC completed with status %d (%p)", ret.status.status, this);
1209 RPCError* retval = NULL;
1210 if (ret.status.status)
1211 retval = new RPCError(&ret.status);
1215 for (u_int i = 0; i < ret.assertions.assertions_len; i++) {
1216 istringstream attrstream(ret.assertions.assertions_val[i].xml_string);
1217 SAMLAssertion *as = NULL;
1218 log.debugStream() << "Trying to decode assertion " << i << ": " <<
1219 ret.assertions.assertions_val[i].xml_string << CategoryStream::ENDLINE;
1220 assertions.push_back(new SAMLAssertion(attrstream));
1223 // return the Authentication Statement
1225 istringstream authstream(ret.auth_statement.xml_string);
1226 SAMLAuthenticationStatement *auth = NULL;
1228 log.debugStream() << "Trying to decode authentication statement: " <<
1229 ret.auth_statement.xml_string << CategoryStream::ENDLINE;
1230 auth = new SAMLAuthenticationStatement(authstream);
1232 // Save off the statement
1236 catch (SAMLException& e) {
1237 log.error ("SAML Exception: %s", e.what());
1240 throw ShibTargetException(SHIBRPC_SAML_EXCEPTION, os.str().c_str());
1242 catch (XMLException& e) {
1243 log.error ("XML Exception: %s", e.getMessage());
1244 auto_ptr_char msg(e.getMessage());
1245 throw ShibTargetException (SHIBRPC_XML_EXCEPTION, msg.get());
1248 catch (ShibTargetException &e) {
1249 retval = new RPCError(e);
1253 retval = new RPCError();
1256 clnt_freeres(clnt, (xdrproc_t)xdr_shibrpc_get_assertions_ret_1, (caddr_t)&ret);
1259 log.debug ("returning..");
1264 ShibTarget::serialize(saml::SAMLAssertion &assertion, std::string &result)
1266 saml::NDC ndc("serialize");
1267 Category& log=Category::getInstance("shibtarget.RM");
1271 unsigned int outlen;
1272 char* assn = (char*) os.str().c_str();
1273 XMLByte* serialized = Base64::encode(reinterpret_cast<XMLByte*>(assn), os.str().length(), &outlen);
1274 result = (char*) serialized;
1275 XMLString::release(&serialized);
1279 /*************************************************************************
1280 * Shib Target Private implementation
1283 ShibTargetPriv::ShibTargetPriv() : m_parser(NULL), m_app(NULL), m_mapper(NULL),
1284 m_conf(NULL), m_Config(NULL), m_assertions()
1287 m_sso_statement = NULL;
1290 ShibTargetPriv::~ShibTargetPriv()
1292 if (m_sso_statement) {
1293 delete m_sso_statement;
1294 m_sso_statement = NULL;
1296 for (int k = 0; k < m_assertions.size(); k++)
1297 delete m_assertions[k];
1298 m_assertions = vector<SAMLAssertion*>();
1316 static inline char hexchar(unsigned short s)
1318 return (s<=9) ? ('0' + s) : ('A' + s - 10);
1322 ShibTargetPriv::url_encode(const char* s)
1324 static char badchars[]="\"\\+<>#%{}|^~[]`;/?:@=&";
1328 if (strchr(badchars,*s) || *s<=0x1F || *s>=0x7F) {
1330 ret+=hexchar(*s >> 4);
1331 ret+=hexchar(*s & 0x0F);
1340 ShibTargetPriv::get_application(string protocol, string hostname, int port,
1346 // XXX: Do we need to keep conf and mapper locked while we hold m_app?
1348 // We lock the configuration system for the duration.
1349 m_conf=m_Config->getINI();
1352 // Map request to application and content settings.
1353 m_mapper=m_conf->getRequestMapper();
1356 // Obtain the application settings from the parsed URL
1357 m_settings = m_mapper->getSettingsFromParsedURL(protocol.c_str(),
1361 // Now find the application from the URL settings
1362 pair<bool,const char*> application_id=m_settings.first->getString("applicationId");
1363 const IApplication* application=m_conf->getApplication(application_id.second);
1369 throw ShibTargetException(SHIBRPC_OK, "unable to map request to application settings. Check configuration");
1372 // Store the application for later use
1373 m_app = application;
1375 // Compute the target URL
1376 m_url = protocol + "://" + hostname;
1377 if ((protocol == "http" && port != 80) || (protocol == "https" && port != 443))
1378 m_url += ":" + port;
1384 ShibTargetPriv::sendError(ShibTarget* st, string page, ShibMLP &mlp)
1386 const IPropertySet* props=m_app->getPropertySet("Errors");
1388 pair<bool,const char*> p=props->getString(page.c_str());
1390 ifstream infile(p.second);
1391 if (!infile.fail()) {
1392 const char* res = mlp.run(infile,props);
1394 return st->sendPage(res);
1399 string errstr = "sendError could not process the error template for application ";
1400 errstr += m_app->getId();
1401 st->log(ShibTarget::LogLevelError, errstr);
1402 return st->sendPage("Internal Server Error. Please contact the server administrator.");
1406 ShibTargetPriv::getSessionId(ShibTarget* st)
1409 //string m = string("getSessionId returning precreated session_id: ") + session_id;
1410 //st->log(ShibTarget::LogLevelDebug, m);
1415 pair<const char*, const char *> shib_cookie = st->getCookieNameProps();
1416 m_cookies = st->getCookies();
1417 if (!m_cookies.empty()) {
1418 if (sid = strstr(m_cookies.c_str(), shib_cookie.first)) {
1419 // We found a cookie. pull it out (our session_id)
1420 sid += strlen(shib_cookie.first) + 1; // skip over the '='
1421 char *cookieend = strchr(sid, ';');
1428 //string m = string("getSessionId returning new session_id: ") + session_id;
1429 //st->log(ShibTarget::LogLevelDebug, m);
1434 ShibTargetPriv::get_assertions(ShibTarget* st, const char *session_id, ShibMLP &mlp)
1436 if (m_sso_statement)
1439 RPCError *status = NULL;
1440 status = st->getAssertions(session_id, m_remote_addr.c_str(),
1441 m_assertions, &m_sso_statement);
1443 if (status->isError()) {
1444 string er = "getAssertions failed: ";
1445 er += status->getText();
1446 st->log(ShibTarget::LogLevelError, er);
1447 mlp.insert(*status);
1456 /*************************************************************************
1457 * CGI Parser implementation
1460 CgiParse::CgiParse(const char* data, unsigned int len)
1462 const char* pch = data;
1463 unsigned int cl = len;
1468 value=fmakeword('&',&cl,&pch);
1471 name=makeword(value,'=');
1472 kvp_map[name]=value;
1477 CgiParse::~CgiParse()
1479 for (map<string,char*>::iterator i=kvp_map.begin(); i!=kvp_map.end(); i++)
1484 CgiParse::get_value(const char* name) const
1486 map<string,char*>::const_iterator i=kvp_map.find(name);
1487 if (i==kvp_map.end())
1492 /* Parsing routines modified from NCSA source. */
1494 CgiParse::makeword(char *line, char stop)
1497 char *word = (char *) malloc(sizeof(char) * (strlen(line) + 1));
1499 for(x=0;((line[x]) && (line[x] != stop));x++)
1508 line[y++] = line[x++];
1514 CgiParse::fmakeword(char stop, unsigned int *cl, const char** ppch)
1522 word = (char *) malloc(sizeof(char) * (wsize + 1));
1526 word[ll] = *((*ppch)++);
1531 word = (char *)realloc(word,sizeof(char)*(wsize+1));
1534 if((word[ll] == stop) || word[ll] == EOF || (!(*cl)))
1536 if(word[ll] != stop)
1546 CgiParse::plustospace(char *str)
1551 if(str[x] == '+') str[x] = ' ';
1555 CgiParse::x2c(char *what)
1557 register char digit;
1559 digit = (what[0] >= 'A' ? ((what[0] & 0xdf) - 'A')+10 : (what[0] - '0'));
1561 digit += (what[1] >= 'A' ? ((what[1] & 0xdf) - 'A')+10 : (what[1] - '0'));
1566 CgiParse::url_decode(char *url)
1570 for(x=0,y=0;url[y];++x,++y)
1572 if((url[x] = url[y]) == '%')
1574 url[x] = x2c(&url[y+1]);
1582 * We need to implement this so the SHIRE (and RM) recodes work
1583 * in terms of the ShibTarget
1585 void ShibTarget::log(ShibLogLevel level, const string &msg)
1587 throw runtime_error("Invalid Usage");
1589 string ShibTarget::getCookies(void)
1591 throw runtime_error("Invalid Usage");
1593 void ShibTarget::setCookie(const string &name, const string &value)
1595 throw runtime_error("Invalid Usage");
1597 void ShibTarget::clearHeader(const string &name)
1599 throw runtime_error("Invalid Usage");
1601 void ShibTarget::setHeader(const string &name, const string &value)
1603 throw runtime_error("Invalid Usage");
1605 string ShibTarget::getHeader(const string &name)
1607 throw runtime_error("Invalid Usage");
1609 void ShibTarget::setRemoteUser(const string &name)
1611 throw runtime_error("Invalid Usage");
1613 string ShibTarget::getRemoteUser(void)
1615 throw runtime_error("Invalid Usage");
1617 string ShibTarget::getArgs(void)
1619 throw runtime_error("Invalid Usage");
1621 string ShibTarget::getPostData(void)
1623 throw runtime_error("Invalid Usage");
1625 //virtual HTAccessInfo& getAccessInfo(void);
1626 void* ShibTarget::sendPage(const string &msg, const string content_type, const pair<string,string> headers[], int code)
1628 throw runtime_error("Invalid Usage");
1630 void* ShibTarget::sendRedirect(const std::string url)
1632 throw runtime_error("Invalid Usage");
1635 // Subclasses may not need to override these particular virtual methods.
1636 string ShibTarget::getAuthType(void)
1638 return string("shibboleth");
1640 void* ShibTarget::returnDecline(void)
1644 void* ShibTarget::returnOK(void)
1648 HTAccessInfo* ShibTarget::getAccessInfo(void)
1652 HTGroupTable* ShibTarget::getGroupTable(string &user)