Eliminated some extra string wrapping.
[shibboleth/sp.git] / shib-target / shib-target.cpp
1 /*
2  * The Shibboleth License, Version 1.
3  * Copyright (c) 2002
4  * University Corporation for Advanced Internet Development, Inc.
5  * All rights reserved
6  *
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions are met:
10  *
11  * Redistributions of source code must retain the above copyright notice, this
12  * list of conditions and the following disclaimer.
13  *
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.
22  *
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
28  *
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.
33  *
34  *
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.
48  */
49
50 /*
51  * shib-target.cpp -- The ShibTarget class, a superclass for general
52  *                    target code
53  *
54  * Created by:  Derek Atkins <derek@ihtfp.com>
55  *
56  * $Id$
57  */
58
59 #include "internal.h"
60
61 #ifdef HAVE_UNISTD_H
62 # include <unistd.h>
63 #endif
64
65 #include <sstream>
66 #include <fstream>
67 #include <stdexcept>
68
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>
74
75 #ifndef HAVE_STRCASECMP
76 # define strcasecmp stricmp
77 #endif
78
79 using namespace std;
80 using namespace saml;
81 using namespace shibboleth;
82 using namespace shibtarget;
83 using namespace log4cpp;
84
85 namespace shibtarget {
86   class CgiParse
87   {
88   public:
89     CgiParse(const char* data, unsigned int len);
90     ~CgiParse();
91     const char* get_value(const char* name) const;
92     
93     static char x2c(char *what);
94     static void url_decode(char *url);
95   private:
96     char * fmakeword(char stop, unsigned int *cl, const char** ppch);
97     char * makeword(char *line, char stop);
98     void plustospace(char *str);
99
100     map<string,char*> kvp_map;
101   };
102
103   class ShibTargetPriv
104   {
105   public:
106     ShibTargetPriv();
107     ~ShibTargetPriv();
108
109     string url_encode(const char* s);
110     void get_application(const string& protocol, const string& hostname, int port, const string& uri);
111     void* sendError(ShibTarget* st, string page, ShibMLP &mlp);
112     const char* getSessionId(ShibTarget* st);
113     const char* getRelayState(ShibTarget* st);
114
115   private:
116     friend class ShibTarget;
117     IRequestMapper::Settings m_settings;
118     const IApplication *m_app;
119     string m_shireURL;
120
121     string m_cookies;
122     const char* session_id;
123     const char* relay_state;
124
125     ShibProfile m_sso_profile;
126     string m_provider_id;
127     SAMLAuthenticationStatement* m_sso_statement;
128     SAMLResponse* m_pre_response;
129     SAMLResponse* m_post_response;
130     
131     // These are the actual request parameters set via the init method.
132     string m_url;
133     string m_method;
134     string m_protocol;
135     string m_content_type;
136     string m_remote_addr;
137
138     ShibTargetConfig* m_Config;
139
140     IConfig* m_conf;
141     IRequestMapper* m_mapper;
142   };
143 }
144
145
146 /*************************************************************************
147  * Shib Target implementation
148  */
149
150 ShibTarget::ShibTarget(void) : m_priv(NULL)
151 {
152   m_priv = new ShibTargetPriv();
153 }
154
155 ShibTarget::ShibTarget(const IApplication *app) : m_priv(NULL)
156 {
157   m_priv = new ShibTargetPriv();
158   m_priv->m_app = app;
159 }
160
161 ShibTarget::~ShibTarget(void)
162 {
163   if (m_priv) delete m_priv;
164 }
165
166 void ShibTarget::init(
167     ShibTargetConfig *config,
168     const char* protocol,
169     const char* hostname,
170     int port,
171     const char* uri,
172     const char* content_type,
173     const char* remote_host,
174     const char* method
175     )
176 {
177 #ifdef _DEBUG
178   saml::NDC ndc("ShibTarget::init");
179 #endif
180
181   if (m_priv->m_app)
182     throw runtime_error("ShibTarget Already Initialized");
183   if (!config)
184     throw runtime_error("config is NULL.  Oops.");
185
186   if (protocol) m_priv->m_protocol = protocol;
187   if (content_type) m_priv->m_content_type = content_type;
188   if (remote_host) m_priv->m_remote_addr = remote_host;
189   if (method) m_priv->m_method = method;
190   m_priv->m_Config = config;
191   m_priv->get_application(protocol, hostname, port, uri);
192 }
193
194
195 // These functions implement the server-agnostic shibboleth engine
196 // The web server modules implement a subclass and then call into 
197 // these methods once they instantiate their request object.
198 pair<bool,void*>
199 ShibTarget::doCheckAuthN(bool requireSessionFlag, bool handleProfile)
200 {
201 #ifdef _DEBUG
202     saml::NDC ndc("ShibTarget::doCheckAuthN");
203 #endif
204
205     const char *targetURL = NULL;
206     const char *procState = "Request Setup Error";
207     ShibMLP mlp;
208
209     try {
210         if (!m_priv->m_app)
211             throw SAMLException("System uninitialized, application did not supply request information.");
212
213         targetURL = m_priv->m_url.c_str();
214         const char *shireURL = getShireURL(targetURL);
215         if (!shireURL)
216             throw SAMLException("Cannot determine assertion consumer service from resource URL, check configuration.");
217
218         if (strstr(targetURL,shireURL)) {
219             if (handleProfile)
220                 return doHandleProfile();
221             else
222                 return pair<bool,void*>(true, returnOK());
223         }
224
225         string auth_type = getAuthType();
226         if (strcasecmp(auth_type.c_str(),"shibboleth"))
227             return pair<bool,void*>(true,returnDecline());
228
229         pair<bool,bool> requireSession = m_priv->m_settings.first->getBool("requireSession");
230         if (!requireSession.first || !requireSession.second) {
231             // Web server might override.
232             if (requireSessionFlag)
233                 requireSession.second=true;
234         }
235
236         const char* session_id = m_priv->getSessionId(this);
237         if (!session_id || !*session_id) {
238             // No session.  Maybe that's acceptable?
239             if (!requireSession.second)
240                 return pair<bool,void*>(true,returnOK());
241
242             // No cookie, but we require a session.  Generate an AuthnRequest.
243             return pair<bool,void*>(true,sendRedirect(getAuthnRequest(targetURL)));
244         }
245
246         procState = "Session Processing Error";
247         try {
248             // Localized exception throw if the session isn't valid.
249             sessionGet(
250                 session_id,
251                 m_priv->m_remote_addr.c_str(),
252                 m_priv->m_sso_profile,
253                 m_priv->m_provider_id,
254                 &m_priv->m_sso_statement,
255                 &m_priv->m_pre_response,
256                 &m_priv->m_post_response
257                 );
258         }
259         catch (SAMLException& e) {
260             // If no session is required, bail now.
261             if (!requireSession.second)
262                 // Has to be OK because DECLINED will just cause Apache
263                 // to fail when it can't locate anything to process the
264                 // AuthType.  No session plus requireSession false means
265                 // do not authenticate the user at this time.
266                 return pair<bool,void*>(true, returnOK());
267             
268             // TODO: need to test this...may need an actual reference cast
269             if (typeid(e)==typeid(RetryableProfileException)) {
270                 // Session is invalid but we can retry -- generate an AuthnRequest
271                 return pair<bool,void*>(true,sendRedirect(getAuthnRequest(targetURL)));
272             }
273             throw;    // send it to the outer handler
274         }
275
276         // We're done.  Everything is okay.  Nothing to report.  Nothing to do..
277         // Let the caller decide how to proceed.
278         log(LogLevelInfo, "doCheckAuthN succeeded");
279         return pair<bool,void*>(false,NULL);
280     }
281     catch (SAMLException& e) {
282         mlp.insert(e);
283     }
284 #ifndef _DEBUG
285     catch (...) {
286         mlp.insert("errorText", "Caught an unknown exception.");
287     }
288 #endif
289
290     // If we get here then we've got an error.
291     mlp.insert("errorType", procState);
292     if (targetURL)
293         mlp.insert("requestURL", targetURL);
294
295     return pair<bool,void*>(true,m_priv->sendError(this, "session", mlp));
296 }
297
298 pair<bool,void*>
299 ShibTarget::doHandleProfile(void)
300 {
301 #ifdef _DEBUG
302     saml::NDC ndc("ShibTarget::doHandleProfile");
303 #endif
304
305     const char *targetURL = NULL;
306     const char *procState = "Session Creation Service Error";
307     ShibMLP mlp;
308
309     try {
310         if (!m_priv->m_app)
311             throw SAMLException("System uninitialized, application did not supply request information.");
312
313         targetURL = m_priv->m_url.c_str();
314         const char* shireURL = getShireURL(targetURL);
315
316         if (!shireURL)
317             throw SAMLException("Cannot determine assertion consumer service, check configuration.");
318
319         // Make sure we only process the SHIRE requests.
320         if (!strstr(targetURL, shireURL))
321             return pair<bool,void*>(true, returnDecline());
322
323         const IPropertySet* sessionProps=m_priv->m_app->getPropertySet("Sessions");
324         if (!sessionProps)
325             throw SAMLException("Unable to map request to application session settings, check configuration.");
326
327         // Process incoming request.
328         pair<bool,bool> shireSSL=sessionProps->getBool("shireSSL");
329       
330         // Make sure this is SSL, if it should be
331         if ((!shireSSL.first || shireSSL.second) && m_priv->m_protocol != "https")
332             throw FatalProfileException("Blocked non-SSL access to session creation service.");
333
334         // If this is a GET, we see if it's a lazy session request, otherwise
335         // assume it's a profile response and process it.
336         string cgistr;
337         if (!strcasecmp(m_priv->m_method.c_str(), "GET")) {
338             cgistr = getArgs();
339             string areq;
340             if (!cgistr.empty())
341                 areq=getLazyAuthnRequest(cgistr.c_str());
342             if (!areq.empty())
343                 return pair<bool,void*>(true, sendRedirect(areq));
344         }
345         else if (!strcasecmp(m_priv->m_method.c_str(), "POST")) {
346             if (m_priv->m_content_type.empty() || strcasecmp(m_priv->m_content_type.c_str(),"application/x-www-form-urlencoded")) {
347                 throw FatalProfileException(
348                     "Blocked invalid POST content-type ($1) to session creation service.",
349                     params(1,m_priv->m_content_type.c_str())
350                     );
351             }
352             // Read the POST Data
353             cgistr = getPostData();
354         }
355         
356         // Process the submission
357         string cookie,target;
358         try {
359             sessionNew(
360                 SAML11_POST | SAML11_ARTIFACT,
361                 cgistr.c_str(),
362                 m_priv->m_remote_addr.c_str(),
363                 cookie,
364                 target
365                 );
366         }
367         catch (SAMLException& e) {
368             log(LogLevelError, string("profile processing failed: ") + e.what());
369     
370             // TODO: need to test this...may need an actual reference cast
371             if (typeid(e)==typeid(RetryableProfileException)) {
372                 return pair<bool,void*>(true, sendRedirect(getAuthnRequest(target.c_str())));
373             }
374             throw;    // send it to the outer handler
375         }
376
377         log(LogLevelDebug, string("profile processing succeeded, new session created (") + cookie + ")");
378
379         if (target=="default") {
380             pair<bool,const char*> homeURL=m_priv->m_app->getString("homeURL");
381             target=homeURL.first ? homeURL.second : "/";
382         }
383         else if (target=="cookie") {
384             // Pull the target value from the "relay state" cookie.
385             const char* relay_state = m_priv->getRelayState(this);
386             if (!relay_state || !*relay_state) {
387                 // No apparent relay state value to use, so fall back on the default.
388                 pair<bool,const char*> homeURL=m_priv->m_app->getString("homeURL");
389                 target=homeURL.first ? homeURL.second : "/";
390             }
391             else {
392                 CgiParse::url_decode((char*)relay_state);
393                 target=relay_state;
394             }
395         }
396     
397         // We've got a good session, set the cookie...
398         pair<string,const char*> shib_cookie=getCookieNameProps("_shibsession_");
399         cookie += shib_cookie.second;
400         setCookie(shib_cookie.first, cookie);
401     
402         // ... and redirect to the target
403         return pair<bool,void*>(true, sendRedirect(target));
404     }
405     catch (SAMLException& e) {
406         mlp.insert(e);
407     }
408 #ifndef _DEBUG
409     catch (...) {
410         mlp.insert("errorText", "Caught an unknown exception.");
411     }
412 #endif
413
414     // If we get here then we've got an error.
415     mlp.insert("errorType", procState);
416
417     if (targetURL)
418         mlp.insert("requestURL", targetURL);
419
420     return pair<bool,void*>(true,m_priv->sendError(this, "session", mlp));
421 }
422
423 pair<bool,void*>
424 ShibTarget::doCheckAuthZ(void)
425 {
426 #ifdef _DEBUG
427     saml::NDC ndc("ShibTarget::doCheckAuthZ");
428 #endif
429
430     ShibMLP mlp;
431     const char *procState = "Authorization Processing Error";
432     const char *targetURL = NULL;
433
434     try {
435         if (!m_priv->m_app)
436             throw SAMLException("System uninitialized, application did not supply request information.");
437
438         targetURL = m_priv->m_url.c_str();
439         const char *session_id = m_priv->getSessionId(this);
440
441         // Do we have an access control plugin?
442         if (m_priv->m_settings.second) {
443             Locker acllock(m_priv->m_settings.second);
444             if (!m_priv->m_settings.second->authorized(*m_priv->m_sso_statement,
445                 m_priv->m_post_response ? m_priv->m_post_response->getAssertions() : EMPTY(SAMLAssertion*))) {
446                 log(LogLevelError, "doCheckAuthZ() access control provider denied access");
447                 if (targetURL)
448                     mlp.insert("requestURL", targetURL);
449                 // TODO: check setting and return 403
450                 return pair<bool,void*>(true,m_priv->sendError(this, "access", mlp));
451             }
452         }
453
454         // Perform HTAccess Checks
455         auto_ptr<HTAccessInfo> ht(getAccessInfo());
456
457         // No Info means OK.  Just return
458         if (!ht.get())
459             return pair<bool,void*>(false, NULL);
460
461         vector<bool> auth_OK(ht->elements.size(), false);
462         bool method_restricted=false;
463         string remote_user = getRemoteUser();
464
465 #define CHECK_OK \
466     do { \
467         if (!ht->requireAll) { \
468             return pair<bool,void*>(false, NULL); \
469         } \
470         auth_OK[x] = true; \
471         continue; \
472     } while (0)
473
474         for (int x = 0; x < ht->elements.size(); x++) {
475             auth_OK[x] = false;
476             HTAccessInfo::RequireLine *line = ht->elements[x];
477             if (! line->use_line)
478                 continue;
479             method_restricted = true;
480
481             const char *w = line->tokens[0].c_str();
482
483             if (!strcasecmp(w,"Shibboleth")) {
484                 // This is a dummy rule needed because Apache conflates authn and authz.
485                 // Without some require rule, AuthType is ignored and no check_user hooks run.
486                 CHECK_OK;
487             }
488             else if (!strcmp(w,"valid-user")) {
489                 log(LogLevelDebug, "doCheckAuthZ accepting valid-user");
490                 CHECK_OK;
491             }
492             else if (!strcmp(w,"user") && !remote_user.empty()) {
493                 bool regexp=false;
494                 for (int i = 1; i < line->tokens.size(); i++) {
495                     w = line->tokens[i].c_str();
496                     if (*w == '~') {
497                         regexp = true;
498                         continue;
499                     }
500                 
501                     if (regexp) {
502                         try {
503                             // To do regex matching, we have to convert from UTF-8.
504                             auto_ptr<XMLCh> trans(fromUTF8(w));
505                             RegularExpression re(trans.get());
506                             auto_ptr<XMLCh> trans2(fromUTF8(remote_user.c_str()));
507                             if (re.matches(trans2.get())) {
508                                 log(LogLevelDebug, string("doCheckAuthZ accepting user: ") + w);
509                                 CHECK_OK;
510                             }
511                         }
512                         catch (XMLException& ex) {
513                             auto_ptr_char tmp(ex.getMessage());
514                             log(LogLevelError, string("doCheckAuthZ caught exception while parsing regular expression (")
515                                + w + "): " + tmp.get());
516                         }
517                     }
518                     else if (!strcmp(remote_user.c_str(), w)) {
519                         log(LogLevelDebug, string("doCheckAuthZ accepting user: ") + w);
520                         CHECK_OK;
521                     }
522                 }
523             }
524             else if (!strcmp(w,"group")) {
525                 auto_ptr<HTGroupTable> grpstatus(getGroupTable(remote_user));
526                 if (!grpstatus.get()) {
527                     return pair<bool,void*>(true, returnDecline());
528                 }
529     
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);
534                         CHECK_OK;
535                     }
536                 }
537             }
538             else {
539                 Iterator<IAAP*> provs = m_priv->m_app->getAAPProviders();
540                 AAP wrapper(provs, w);
541                 if (wrapper.fail()) {
542                     log(LogLevelWarn, string("doCheckAuthZ didn't recognize require rule: ") + w);
543                     continue;
544                 }
545
546                 bool regexp = false;
547                 string vals = getHeader(wrapper->getHeader());
548                 for (int i = 1; i < line->tokens.size() && !vals.empty(); i++) {
549                     w = line->tokens[i].c_str();
550                     if (*w == '~') {
551                         regexp = true;
552                         continue;
553                     }
554
555                     try {
556                         auto_ptr<RegularExpression> re;
557                         if (regexp) {
558                             delete re.release();
559                             auto_ptr<XMLCh> trans(fromUTF8(w));
560                             auto_ptr<RegularExpression> temp(new RegularExpression(trans.get()));
561                             re=temp;
562                         }
563                     
564                         string vals_str(vals);
565                         int j = 0;
566                         for (int i = 0;  i < vals_str.length();  i++) {
567                             if (vals_str.at(i) == ';') {
568                                 if (i == 0) {
569                                     log(LogLevelError, string("doCheckAuthZ invalid header encoding") +
570                                         vals + ": starts with a semicolon");
571                                     throw SAMLException("Invalid information supplied to authorization module.");
572                                 }
573
574                                 if (vals_str.at(i-1) == '\\') {
575                                     vals_str.erase(i-1, 1);
576                                     i--;
577                                     continue;
578                                 }
579
580                                 string val = vals_str.substr(j, i-j);
581                                 j = i+1;
582                                 if (regexp) {
583                                     auto_ptr<XMLCh> trans(fromUTF8(val.c_str()));
584                                     if (re->matches(trans.get())) {
585                                         log(LogLevelDebug, string("doCheckAuthZ expecting ") + w +
586                                            ", got " + val + ": authorization granted");
587                                         CHECK_OK;
588                                     }
589                                 }
590                                 else if ((wrapper->getCaseSensitive() && val==w) ||
591                                         (!wrapper->getCaseSensitive() && !strcasecmp(val.c_str(),w))) {
592                                     log(LogLevelDebug, string("doCheckAuthZ expecting ") + w +
593                                         ", got " + val + ": authorization granted.");
594                                     CHECK_OK;
595                                 }
596                                 else {
597                                     log(LogLevelDebug, string("doCheckAuthZ expecting ") + w +
598                                         ", got " + val + ": authoritzation not granted.");
599                                 }
600                             }
601                         }
602     
603                         string val = vals_str.substr(j, vals_str.length()-j);
604                         if (regexp) {
605                             auto_ptr<XMLCh> trans(fromUTF8(val.c_str()));
606                             if (re->matches(trans.get())) {
607                                 log(LogLevelDebug, string("doCheckAuthZ expecting ") + w +
608                                     ", got " + val + ": authorization granted.");
609                                 CHECK_OK;
610                             }
611                         }
612                         else if ((wrapper->getCaseSensitive() && val==w) ||
613                                 (!wrapper->getCaseSensitive() && !strcasecmp(val.c_str(),w))) {
614                             log(LogLevelDebug, string("doCheckAuthZ expecting ") + w +
615                                 ", got " + val + ": authorization granted");
616                             CHECK_OK;
617                         }
618                         else {
619                             log(LogLevelDebug, string("doCheckAuthZ expecting ") + w +
620                                 ", got " + val + ": authorization not granted");
621                         }
622                     }
623                     catch (XMLException& ex) {
624                         auto_ptr_char tmp(ex.getMessage());
625                             log(LogLevelError, string("doCheckAuthZ caught exception while parsing regular expression (")
626                                 + w + "): " + tmp.get());
627                     }
628                 }
629             }
630         } // for x
631
632
633         // check if all require directives are true
634         bool auth_all_OK = true;
635         for (int i = 0; i < ht->elements.size(); i++) {
636             auth_all_OK &= auth_OK[i];
637         }
638
639         if (auth_all_OK || !method_restricted)
640             return pair<bool,void*>(false, NULL);
641
642         // If we get here there's an access error, so just fall through
643     }
644     catch (SAMLException& e) {
645         mlp.insert(e);
646     }
647 #ifndef _DEBUG
648     catch (...) {
649         mlp.insert("errorText", "Caught an unknown exception.");
650     }
651 #endif
652
653     // If we get here then we've got an error.
654     mlp.insert("errorType", procState);
655
656     if (targetURL)
657         mlp.insert("requestURL", targetURL);
658
659     return pair<bool,void*>(true,m_priv->sendError(this, "access", mlp));
660 }
661
662 pair<bool,void*>
663 ShibTarget::doExportAssertions(bool exportAssertion)
664 {
665 #ifdef _DEBUG
666     saml::NDC ndc("ShibTarget::doExportAssertions");
667 #endif
668
669     ShibMLP mlp;
670     const char *procState = "Attribute Processing Error";
671     const char *targetURL = NULL;
672     char *page = "rm";
673
674     try {
675         if (!m_priv->m_app)
676             throw SAMLException("System uninitialized, application did not supply request information.");
677
678         targetURL = m_priv->m_url.c_str();
679         const char *session_id = m_priv->getSessionId(this);
680
681         if (!m_priv->m_sso_statement) {
682             // No data yet, so we need to get the session. This can only happen
683             // if the call to doCheckAuthn doesn't happen in the same object lifetime.
684             sessionGet(
685                 session_id,
686                 m_priv->m_remote_addr.c_str(),
687                 m_priv->m_sso_profile,
688                 m_priv->m_provider_id,
689                 &m_priv->m_sso_statement,
690                 &m_priv->m_pre_response,
691                 &m_priv->m_post_response
692                 );
693         }
694
695         // Get the AAP providers, which contain the attribute policy info.
696         Iterator<IAAP*> provs=m_priv->m_app->getAAPProviders();
697
698         // Clear out the list of mapped attributes
699         while (provs.hasNext()) {
700             IAAP* aap=provs.next();
701             Locker locker(aap);
702             Iterator<const IAttributeRule*> rules=aap->getAttributeRules();
703             while (rules.hasNext()) {
704                 const char* header=rules.next()->getHeader();
705                 if (header)
706                     clearHeader(header);
707             }
708         }
709         
710         // Maybe export the first assertion.
711         clearHeader("Shib-Attributes");
712         pair<bool,bool> exp=m_priv->m_settings.first->getBool("exportAssertion");
713         if (!exp.first || !exp.second)
714             if (exportAssertion)
715                 exp.second=true;
716         if (exp.second && m_priv->m_pre_response) {
717             ostringstream os;
718             os << *(m_priv->m_pre_response);
719             unsigned int outlen;
720             XMLByte* serialized = Base64::encode(reinterpret_cast<XMLByte*>((char*)os.str().c_str()), os.str().length(), &outlen);
721             for (XMLByte* pos=serialized, *pos2=serialized; *pos2; pos2++)
722                 if (isgraph(*pos2))
723                     *pos++=*pos2;
724             *pos=0;
725             setHeader("Shib-Attributes", reinterpret_cast<char*>(serialized));
726             XMLString::release(&serialized);
727         }
728     
729         // Export the SAML AuthnMethod and the origin site name, and possibly the NameIdentifier.
730         clearHeader("Shib-Origin-Site");
731         clearHeader("Shib-Identity-Provider");
732         clearHeader("Shib-Authentication-Method");
733         clearHeader("Shib-NameIdentifier-Format");
734         setHeader("Shib-Origin-Site", m_priv->m_provider_id.c_str());
735         setHeader("Shib-Identity-Provider", m_priv->m_provider_id.c_str());
736         auto_ptr_char am(m_priv->m_sso_statement->getAuthMethod());
737         setHeader("Shib-Authentication-Method", am.get());
738         
739         // Export NameID?
740         provs.reset();
741         while (provs.hasNext()) {
742             IAAP* aap=provs.next();
743             Locker locker(aap);
744             const IAttributeRule* rule=aap->lookup(m_priv->m_sso_statement->getSubject()->getNameIdentifier()->getFormat());
745             if (rule && rule->getHeader()) {
746                 auto_ptr_char form(m_priv->m_sso_statement->getSubject()->getNameIdentifier()->getFormat());
747                 auto_ptr_char nameid(m_priv->m_sso_statement->getSubject()->getNameIdentifier()->getName());
748                 setHeader("Shib-NameIdentifier-Format", form.get());
749                 if (!strcmp(rule->getHeader(),"REMOTE_USER"))
750                     setRemoteUser(nameid.get());
751                 else
752                     setHeader(rule->getHeader(), nameid.get());
753             }
754         }
755         
756         clearHeader("Shib-Application-ID");
757         setHeader("Shib-Application-ID", m_priv->m_app->getId());
758     
759         // Export the attributes.
760         Iterator<SAMLAssertion*> a_iter(m_priv->m_post_response ? m_priv->m_post_response->getAssertions() : EMPTY(SAMLAssertion*));
761         while (a_iter.hasNext()) {
762             SAMLAssertion* assert=a_iter.next();
763             Iterator<SAMLStatement*> statements=assert->getStatements();
764             while (statements.hasNext()) {
765                 SAMLAttributeStatement* astate=dynamic_cast<SAMLAttributeStatement*>(statements.next());
766                 if (!astate)
767                     continue;
768                 Iterator<SAMLAttribute*> attrs=astate->getAttributes();
769                 while (attrs.hasNext()) {
770                     SAMLAttribute* attr=attrs.next();
771             
772                     // Are we supposed to export it?
773                     provs.reset();
774                     while (provs.hasNext()) {
775                         IAAP* aap=provs.next();
776                         Locker locker(aap);
777                         const IAttributeRule* rule=aap->lookup(attr->getName(),attr->getNamespace());
778                         if (!rule || !rule->getHeader())
779                             continue;
780                     
781                         Iterator<string> vals=attr->getSingleByteValues();
782                         if (!strcmp(rule->getHeader(),"REMOTE_USER") && vals.hasNext())
783                             setRemoteUser(vals.next());
784                         else {
785                             int it=0;
786                             string header = getHeader(rule->getHeader());
787                             if (!header.empty())
788                                 it++;
789                             for (; vals.hasNext(); it++) {
790                                 string value = vals.next();
791                                 for (string::size_type pos = value.find_first_of(";", string::size_type(0));
792                                         pos != string::npos;
793                                         pos = value.find_first_of(";", pos)) {
794                                     value.insert(pos, "\\");
795                                     pos += 2;
796                                 }
797                                 if (it)
798                                     header += ";";
799                                 header += value;
800                             }
801                             setHeader(rule->getHeader(), header);
802                         }
803                     }
804                 }
805             }
806         }
807     
808         return pair<bool,void*>(false,NULL);
809     }
810     catch (SAMLException& e) {
811         mlp.insert(e);
812     }
813 #ifndef _DEBUG
814     catch (...) {
815         mlp.insert("errorText", "Caught an unknown exception.");
816     }
817 #endif
818
819     // If we get here then we've got an error.
820     mlp.insert("errorType", procState);
821
822     if (targetURL)
823         mlp.insert("requestURL", targetURL);
824
825     return pair<bool,void*>(true,m_priv->sendError(this, page, mlp));
826 }
827
828
829 // Low level APIs
830
831 // Get the session cookie name and properties for the application
832 pair<string,const char*> ShibTarget::getCookieNameProps(const char* prefix) const
833 {
834     static const char* defProps="; path=/";
835     
836     const IPropertySet* props=m_priv->m_app ? m_priv->m_app->getPropertySet("Sessions") : NULL;
837     if (props) {
838         pair<bool,const char*> p=props->getString("cookieProps");
839         if (!p.first)
840             p.second=defProps;
841         pair<bool,const char*> p2=props->getString("cookieName");
842         if (p2.first)
843             return make_pair(string(prefix) + p2.second,p.second);
844         return make_pair(string(prefix) + m_priv->m_app->getHash(),p.second);
845     }
846     
847     // Shouldn't happen, but just in case..
848     return make_pair(prefix,defProps);
849 }
850         
851 // Find the default assertion consumer service for the resource
852 const char*
853 ShibTarget::getShireURL(const char* resource) const
854 {
855     if (!m_priv->m_shireURL.empty())
856         return m_priv->m_shireURL.c_str();
857
858     // XXX: what to do is m_app is NULL?
859
860     bool shire_ssl_only=false;
861     const char* shire=NULL;
862     const IPropertySet* props=m_priv->m_app->getPropertySet("Sessions");
863     if (props) {
864         pair<bool,bool> p=props->getBool("shireSSL");
865         if (p.first)
866             shire_ssl_only=p.second;
867         pair<bool,const char*> p2=props->getString("shireURL");
868         if (p2.first)
869             shire=p2.second;
870     }
871     
872     // Should never happen...
873     if (!shire || (*shire!='/' && strncmp(shire,"http:",5) && strncmp(shire,"https:",6)))
874         return NULL;
875
876     // The "shireURL" property can be in one of three formats:
877     //
878     // 1) a full URI:       http://host/foo/bar
879     // 2) a hostless URI:   http:///foo/bar
880     // 3) a relative path:  /foo/bar
881     //
882     // #  Protocol  Host        Path
883     // 1  shire     shire       shire
884     // 2  shire     resource    shire
885     // 3  resource  resource    shire
886     //
887     // note: if shire_ssl_only is true, make sure the protocol is https
888
889     const char* path = NULL;
890
891     // Decide whether to use the shire or the resource for the "protocol"
892     const char* prot;
893     if (*shire != '/') {
894         prot = shire;
895     }
896     else {
897         prot = resource;
898         path = shire;
899     }
900
901     // break apart the "protocol" string into protocol, host, and "the rest"
902     const char* colon=strchr(prot,':');
903     colon += 3;
904     const char* slash=strchr(colon,'/');
905     if (!path)
906         path = slash;
907
908     // Compute the actual protocol and store in member.
909     if (shire_ssl_only)
910         m_priv->m_shireURL.assign("https://");
911     else
912         m_priv->m_shireURL.assign(prot, colon-prot);
913
914     // create the "host" from either the colon/slash or from the target string
915     // If prot == shire then we're in either #1 or #2, else #3.
916     // If slash == colon then we're in #2.
917     if (prot != shire || slash == colon) {
918         colon = strchr(resource, ':');
919         colon += 3;      // Get past the ://
920         slash = strchr(colon, '/');
921     }
922     string host(colon, slash-colon);
923
924     // Build the shire URL
925     m_priv->m_shireURL+=host + path;
926     return m_priv->m_shireURL.c_str();
927 }
928         
929 // Generate a Shib 1.x AuthnRequest redirect URL for the resource,
930 // using whatever relay state mechanism is specified for the app.
931 string ShibTarget::getAuthnRequest(const char* resource)
932 {
933     // XXX: what to do if m_app is NULL?
934
935     string req;
936     char timebuf[16];
937     sprintf(timebuf,"%u",time(NULL));
938     
939     const IPropertySet* props=m_priv->m_app ? m_priv->m_app->getPropertySet("Sessions") : NULL;
940     if (props) {
941         pair<bool,const char*> wayf=props->getString("wayfURL");
942         if (wayf.first) {
943             req=req + wayf.second + "?shire=" + m_priv->url_encode(getShireURL(resource)) + "&time=" + timebuf;
944             
945             // How should the target value be preserved?
946             pair<bool,bool> localRelayState=m_priv->m_conf->getPropertySet("Local")->getBool("localRelayState");
947             if (!localRelayState.first || !localRelayState.second) {
948                 // The old way, just send it along.
949                 req = req + "&target=" + m_priv->url_encode(resource);
950             }
951             else {
952                 // Here we store the state in a cookie and send a fixed
953                 // value to the IdP so we can recognize it on the way back.
954                 pair<string,const char*> shib_cookie=getCookieNameProps("_shibstate_");
955                 setCookie(shib_cookie.first,m_priv->url_encode(resource) + shib_cookie.second);
956                 req += "&target=cookie";
957             }
958             
959             pair<bool,bool> old=m_priv->m_app->getBool("oldAuthnRequest");
960             if (!old.first || !old.second) {
961                 wayf=m_priv->m_app->getString("providerId");
962                 if (wayf.first)
963                     req=req + "&providerId=" + m_priv->url_encode(wayf.second);
964             }
965         }
966     }
967     return req;
968 }
969         
970 // Process a lazy session setup request and turn it into an AuthnRequest
971 string ShibTarget::getLazyAuthnRequest(const char* query_string)
972 {
973     CgiParse parser(query_string,strlen(query_string));
974     const char* target=parser.get_value("target");
975     if (!target || !*target)
976         return "";
977     return getAuthnRequest(target);
978 }
979
980 void ShibTarget::sessionNew(
981     int supported_profiles,
982     const char* packet,
983     const char* ip,
984     string& cookie,
985     string& target
986     ) const
987 {
988 #ifdef _DEBUG
989     saml::NDC ndc("sessionNew");
990 #endif
991     Category& log = Category::getInstance("shibtarget.ShibTarget");
992
993     if (!packet || !*packet) {
994         log.error("missing profile response");
995         throw FatalProfileException("Profile response missing.");
996     }
997
998     if (!ip || !*ip) {
999         log.error("missing client address");
1000         throw FatalProfileException("Invalid client address.");
1001     }
1002   
1003     if (supported_profiles <= 0) {
1004         log.error("no profile support indicated");
1005         throw FatalProfileException("No profile support indicated.");
1006     }
1007   
1008     shibrpc_new_session_args_2 arg;
1009     arg.recipient = (char*) m_priv->m_shireURL.c_str();
1010     arg.application_id = (char*) m_priv->m_app->getId();
1011     arg.packet = (char*)packet;
1012     arg.client_addr = (char*)ip;
1013     arg.supported_profiles = supported_profiles;
1014
1015     log.info("create session for user at (%s) for application (%s)", ip, arg.application_id);
1016
1017     shibrpc_new_session_ret_2 ret;
1018     memset(&ret, 0, sizeof(ret));
1019
1020     // Loop on the RPC in case we lost contact the first time through
1021     int retry = 1;
1022     CLIENT* clnt;
1023     RPC rpc;
1024     do {
1025         clnt = rpc->connect();
1026         clnt_stat status = shibrpc_new_session_2 (&arg, &ret, clnt);
1027         if (status != RPC_SUCCESS) {
1028             // FAILED.  Release, disconnect, and retry
1029             log.error("RPC Failure: %p (%p) (%d): %s", this, clnt, status, clnt_spcreateerror("shibrpc_new_session_2"));
1030             rpc->disconnect();
1031             if (retry)
1032                 retry--;
1033             else
1034                 throw ListenerException("Failure passing session setup information to listener.");
1035         }
1036         else {
1037             // SUCCESS.  Pool and continue
1038             retry = -1;
1039         }
1040     } while (retry>=0);
1041
1042     if (ret.status && *ret.status)
1043         log.debug("RPC completed with exception: %s", ret.status);
1044     else
1045         log.debug("RPC completed successfully");
1046
1047     SAMLException* except=NULL;
1048     if (ret.status && *ret.status) {
1049         // Reconstitute exception object.
1050         try { 
1051             istringstream estr(ret.status);
1052             except=SAMLException::getInstance(estr);
1053         }
1054         catch (SAMLException& e) {
1055             log.error("caught SAML Exception while building the SAMLException: %s", e.what());
1056             log.error("XML was: %s", ret.status);
1057             clnt_freeres(clnt, (xdrproc_t)xdr_shibrpc_new_session_ret_2, (caddr_t)&ret);
1058             rpc.pool();
1059             throw FatalProfileException("An unrecoverable error occurred while creating your session.");
1060         }
1061 #ifndef _DEBUG
1062         catch (...) {
1063             log.error("caught unknown exception building SAMLException");
1064             log.error("XML was: %s", ret.status);
1065             clnt_freeres(clnt, (xdrproc_t)xdr_shibrpc_new_session_ret_2, (caddr_t)&ret);
1066             rpc.pool();
1067             throw;
1068         }
1069 #endif
1070     }
1071     else {
1072         log.debug("new session cookie: %s", ret.cookie);
1073         cookie = ret.cookie;
1074         if (ret.target)
1075             target = ret.target;
1076     }
1077
1078     clnt_freeres(clnt, (xdrproc_t)xdr_shibrpc_new_session_ret_2, (caddr_t)&ret);
1079     rpc.pool();
1080     if (except) {
1081         auto_ptr<SAMLException> wrapper(except);
1082         throw *wrapper;
1083     }
1084 }
1085
1086 void ShibTarget::sessionGet(
1087     const char* cookie,
1088     const char* ip,
1089     ShibProfile& profile,
1090     string& provider_id,
1091     SAMLAuthenticationStatement** auth_statement,
1092     SAMLResponse** attr_response_pre,
1093     SAMLResponse** attr_response_post
1094     ) const
1095 {
1096 #ifdef _DEBUG
1097     saml::NDC ndc("sessionGet");
1098 #endif
1099     Category& log = Category::getInstance("shibtarget.ShibTarget");
1100
1101     if (!cookie || !*cookie) {
1102         log.error("no session key provided");
1103         throw InvalidSessionException("No session key was provided.");
1104     }
1105     else if (strchr(cookie,'=')) {
1106         log.error("cookie value not extracted successfully, probably overlapping cookies across domains");
1107         throw InvalidSessionException("The session key wasn't extracted successfully from the browser cookie.");
1108     }
1109
1110     if (!ip || !*ip) {
1111         log.error("invalid client Address");
1112         throw FatalProfileException("Invalid client address.");
1113     }
1114
1115     log.info("getting session for client at (%s)", ip);
1116     log.debug("session cookie (%s)", cookie);
1117
1118     shibrpc_get_session_args_2 arg;
1119     arg.cookie = (char*)cookie;
1120     arg.client_addr = (char*)ip;
1121     arg.application_id = (char*)m_priv->m_app->getId();
1122
1123     shibrpc_get_session_ret_2 ret;
1124     memset (&ret, 0, sizeof(ret));
1125
1126     // Loop on the RPC in case we lost contact the first time through
1127     int retry = 1;
1128     CLIENT *clnt;
1129     RPC rpc;
1130     do {
1131         clnt = rpc->connect();
1132         clnt_stat status = shibrpc_get_session_2(&arg, &ret, clnt);
1133         if (status != RPC_SUCCESS) {
1134             // FAILED.  Release, disconnect, and try again...
1135             log.error("RPC Failure: %p (%p) (%d) %s", this, clnt, status, clnt_spcreateerror("shibrpc_get_session_2"));
1136             rpc->disconnect();
1137             if (retry)
1138                 retry--;
1139             else
1140                 throw ListenerException("Failure requesting session information from listener.");
1141         }
1142         else {
1143             // SUCCESS
1144             retry = -1;
1145         }
1146     } while (retry>=0);
1147
1148     if (ret.status && *ret.status)
1149         log.debug("RPC completed with exception: %s", ret.status);
1150     else
1151         log.debug("RPC completed successfully");
1152
1153     SAMLException* except=NULL;
1154     if (ret.status && *ret.status) {
1155         // Reconstitute exception object.
1156         try { 
1157             istringstream estr(ret.status);
1158             except=SAMLException::getInstance(estr);
1159         }
1160         catch (SAMLException& e) {
1161             log.error("caught SAML Exception while building the SAMLException: %s", e.what());
1162             log.error("XML was: %s", ret.status);
1163             clnt_freeres(clnt, (xdrproc_t)xdr_shibrpc_get_session_ret_2, (caddr_t)&ret);
1164             rpc.pool();
1165             throw FatalProfileException("An unrecoverable error occurred while accessing your session.");
1166         }
1167         catch (...) {
1168             log.error("caught unknown exception building SAMLException");
1169             log.error("XML was: %s", ret.status);
1170             clnt_freeres(clnt, (xdrproc_t)xdr_shibrpc_get_session_ret_2, (caddr_t)&ret);
1171             rpc.pool();
1172             throw;
1173         }
1174     }
1175     else {
1176         try {
1177             profile = ret.profile;
1178             provider_id = ret.provider_id;
1179         
1180             // return the Authentication Statement
1181             if (auth_statement) {
1182                 istringstream authstream(ret.auth_statement);
1183                 log.debugStream() << "trying to decode authentication statement: "
1184                     << ret.auth_statement << CategoryStream::ENDLINE;
1185                 *auth_statement = new SAMLAuthenticationStatement(authstream);
1186             }
1187     
1188             // return the unfiltered Response
1189             if (attr_response_pre) {
1190                 istringstream prestream(ret.attr_response_pre);
1191                 log.debugStream() << "trying to decode unfiltered attribute response: "
1192                     << ret.attr_response_pre << CategoryStream::ENDLINE;
1193                 *attr_response_pre = new SAMLResponse(prestream);
1194             }
1195     
1196             // return the filtered Response
1197             if (attr_response_post) {
1198                 istringstream poststream(ret.attr_response_post);
1199                 log.debugStream() << "trying to decode filtered attribute response: "
1200                     << ret.attr_response_post << CategoryStream::ENDLINE;
1201                 *attr_response_post = new SAMLResponse(poststream);
1202             }
1203         }
1204         catch (SAMLException& e) {
1205             log.error("caught SAML exception while reconstituting session objects: %s", e.what());
1206             clnt_freeres (clnt, (xdrproc_t)xdr_shibrpc_get_session_ret_2, (caddr_t)&ret);
1207             rpc.pool();
1208             throw;
1209         }
1210 #ifndef _DEBUG
1211         catch (...) {
1212             log.error("caught unknown exception while reconstituting session objects");
1213             clnt_freeres (clnt, (xdrproc_t)xdr_shibrpc_get_session_ret_2, (caddr_t)&ret);
1214             rpc.pool();
1215             throw;
1216         }
1217 #endif
1218     }
1219
1220     clnt_freeres (clnt, (xdrproc_t)xdr_shibrpc_get_session_ret_2, (caddr_t)&ret);
1221     rpc.pool();
1222     if (except) {
1223         auto_ptr<SAMLException> wrapper(except);
1224         throw *wrapper;
1225     }
1226 }
1227
1228 /*************************************************************************
1229  * Shib Target Private implementation
1230  */
1231
1232 ShibTargetPriv::ShibTargetPriv() : m_app(NULL), m_mapper(NULL), m_conf(NULL), m_Config(NULL), session_id(NULL), relay_state(NULL),
1233     m_sso_profile(PROFILE_UNSPECIFIED), m_sso_statement(NULL), m_pre_response(NULL), m_post_response(NULL) {}
1234
1235 ShibTargetPriv::~ShibTargetPriv()
1236 {
1237   delete m_sso_statement;
1238   m_sso_statement = NULL;
1239
1240   delete m_pre_response;
1241   m_pre_response = NULL;
1242   
1243   delete m_post_response;
1244   m_post_response = NULL;
1245
1246   if (m_mapper) {
1247     m_mapper->unlock();
1248     m_mapper = NULL;
1249   }
1250   if (m_conf) {
1251     m_conf->unlock();
1252     m_conf = NULL;
1253   }
1254   m_app = NULL;
1255   m_Config = NULL;
1256 }
1257
1258 static inline char hexchar(unsigned short s)
1259 {
1260     return (s<=9) ? ('0' + s) : ('A' + s - 10);
1261 }
1262
1263 string
1264 ShibTargetPriv::url_encode(const char* s)
1265 {
1266     static char badchars[]="\"\\+<>#%{}|^~[]`;/?:@=&";
1267
1268     string ret;
1269     for (; *s; s++) {
1270         if (strchr(badchars,*s) || *s<=0x1F || *s>=0x7F) {
1271             ret+='%';
1272         ret+=hexchar(*s >> 4);
1273         ret+=hexchar(*s & 0x0F);
1274         }
1275         else
1276             ret+=*s;
1277     }
1278     return ret;
1279 }
1280
1281 void
1282 ShibTargetPriv::get_application(const string& protocol, const string& hostname, int port, const string& uri)
1283 {
1284   if (m_app)
1285     return;
1286
1287   // XXX: Do we need to keep conf and mapper locked while we hold m_app?
1288   // TODO: No, should be able to hold the conf but release the mapper.
1289
1290   // We lock the configuration system for the duration.
1291   m_conf=m_Config->getINI();
1292   m_conf->lock();
1293     
1294   // Map request to application and content settings.
1295   m_mapper=m_conf->getRequestMapper();
1296   m_mapper->lock();
1297
1298   // Obtain the application settings from the parsed URL
1299   m_settings = m_mapper->getSettingsFromParsedURL(protocol.c_str(),
1300                                                   hostname.c_str(),
1301                                                   port, uri.c_str());
1302
1303   // Now find the application from the URL settings
1304   pair<bool,const char*> application_id=m_settings.first->getString("applicationId");
1305   const IApplication* application=m_conf->getApplication(application_id.second);
1306   if (!application) {
1307     m_mapper->unlock();
1308     m_mapper = NULL;
1309     m_conf->unlock();
1310     m_conf = NULL;
1311     throw SAMLException("Unable to map request to application settings, check configuration.");
1312   }
1313
1314   // Store the application for later use
1315   m_app = application;
1316
1317   // Compute the target URL
1318   m_url = protocol + "://" + hostname;
1319   if ((protocol == "http" && port != 80) || (protocol == "https" && port != 443))
1320     m_url += ":" + port;
1321   m_url += uri;
1322 }
1323
1324
1325 void*
1326 ShibTargetPriv::sendError(ShibTarget* st, string page, ShibMLP &mlp)
1327 {
1328     const IPropertySet* props=m_app->getPropertySet("Errors");
1329     if (props) {
1330         pair<bool,const char*> p=props->getString(page.c_str());
1331         if (p.first) {
1332             ifstream infile(p.second);
1333             if (!infile.fail()) {
1334                 const char* res = mlp.run(infile,props);
1335                 if (res)
1336                     return st->sendPage(res);
1337             }
1338         }
1339     }
1340
1341     string errstr = "sendError could not process the error template for application (";
1342     errstr += m_app->getId();
1343     errstr += ")";
1344     st->log(ShibTarget::LogLevelError, errstr);
1345     return st->sendPage("Internal Server Error. Please contact the site administrator.");
1346 }
1347
1348 const char* ShibTargetPriv::getSessionId(ShibTarget* st)
1349 {
1350   if (session_id) {
1351     //string m = string("getSessionId returning precreated session_id: ") + session_id;
1352     //st->log(ShibTarget::LogLevelDebug, m);
1353     return session_id;
1354   }
1355
1356   char *sid;
1357   pair<string,const char*> shib_cookie = st->getCookieNameProps("_shibsession_");
1358   if (m_cookies.empty())
1359       m_cookies = st->getCookies();
1360   if (!m_cookies.empty()) {
1361     if (sid = strstr(m_cookies.c_str(), shib_cookie.first.c_str())) {
1362       // We found a cookie.  pull it out (our session_id)
1363       sid += shib_cookie.first.length() + 1; // skip over the '='
1364       char *cookieend = strchr(sid, ';');
1365       if (cookieend)
1366         *cookieend = '\0';
1367       session_id = sid;
1368     }
1369   }
1370
1371   //string m = string("getSessionId returning new session_id: ") + session_id;
1372   //st->log(ShibTarget::LogLevelDebug, m);
1373   return session_id;
1374 }
1375
1376 const char* ShibTargetPriv::getRelayState(ShibTarget* st)
1377 {
1378   if (relay_state)
1379     return relay_state;
1380
1381   char *sid;
1382   pair<string,const char*> shib_cookie = st->getCookieNameProps("_shibstate_");
1383   if (m_cookies.empty())
1384       m_cookies = st->getCookies();
1385   if (!m_cookies.empty()) {
1386     if (sid = strstr(m_cookies.c_str(), shib_cookie.first.c_str())) {
1387       // We found a cookie.  pull it out
1388       sid += shib_cookie.first.length() + 1; // skip over the '='
1389       char *cookieend = strchr(sid, ';');
1390       if (cookieend)
1391         *cookieend = '\0';
1392       relay_state = sid;
1393     }
1394   }
1395
1396   return relay_state;
1397 }
1398
1399 /*************************************************************************
1400  * CGI Parser implementation
1401  */
1402
1403 CgiParse::CgiParse(const char* data, unsigned int len)
1404 {
1405     const char* pch = data;
1406     unsigned int cl = len;
1407         
1408     while (cl && pch) {
1409         char *name;
1410         char *value;
1411         value=fmakeword('&',&cl,&pch);
1412         plustospace(value);
1413         url_decode(value);
1414         name=makeword(value,'=');
1415         kvp_map[name]=value;
1416         free(name);
1417     }
1418 }
1419
1420 CgiParse::~CgiParse()
1421 {
1422     for (map<string,char*>::iterator i=kvp_map.begin(); i!=kvp_map.end(); i++)
1423         free(i->second);
1424 }
1425
1426 const char*
1427 CgiParse::get_value(const char* name) const
1428 {
1429     map<string,char*>::const_iterator i=kvp_map.find(name);
1430     if (i==kvp_map.end())
1431         return NULL;
1432     return i->second;
1433 }
1434
1435 /* Parsing routines modified from NCSA source. */
1436 char *
1437 CgiParse::makeword(char *line, char stop)
1438 {
1439     int x = 0,y;
1440     char *word = (char *) malloc(sizeof(char) * (strlen(line) + 1));
1441
1442     for(x=0;((line[x]) && (line[x] != stop));x++)
1443         word[x] = line[x];
1444
1445     word[x] = '\0';
1446     if(line[x])
1447         ++x;
1448     y=0;
1449
1450     while(line[x])
1451       line[y++] = line[x++];
1452     line[y] = '\0';
1453     return word;
1454 }
1455
1456 char *
1457 CgiParse::fmakeword(char stop, unsigned int *cl, const char** ppch)
1458 {
1459     int wsize;
1460     char *word;
1461     int ll;
1462
1463     wsize = 1024;
1464     ll=0;
1465     word = (char *) malloc(sizeof(char) * (wsize + 1));
1466
1467     while(1)
1468     {
1469         word[ll] = *((*ppch)++);
1470         if(ll==wsize-1)
1471         {
1472             word[ll+1] = '\0';
1473             wsize+=1024;
1474             word = (char *)realloc(word,sizeof(char)*(wsize+1));
1475         }
1476         --(*cl);
1477         if((word[ll] == stop) || word[ll] == EOF || (!(*cl)))
1478         {
1479             if(word[ll] != stop)
1480                 ll++;
1481             word[ll] = '\0';
1482             return word;
1483         }
1484         ++ll;
1485     }
1486 }
1487
1488 void
1489 CgiParse::plustospace(char *str)
1490 {
1491     register int x;
1492
1493     for(x=0;str[x];x++)
1494         if(str[x] == '+') str[x] = ' ';
1495 }
1496
1497 char
1498 CgiParse::x2c(char *what)
1499 {
1500     register char digit;
1501
1502     digit = (what[0] >= 'A' ? ((what[0] & 0xdf) - 'A')+10 : (what[0] - '0'));
1503     digit *= 16;
1504     digit += (what[1] >= 'A' ? ((what[1] & 0xdf) - 'A')+10 : (what[1] - '0'));
1505     return(digit);
1506 }
1507
1508 void
1509 CgiParse::url_decode(char *url)
1510 {
1511     register int x,y;
1512
1513     for(x=0,y=0;url[y];++x,++y)
1514     {
1515         if((url[x] = url[y]) == '%')
1516         {
1517             url[x] = x2c(&url[y+1]);
1518             y+=2;
1519         }
1520     }
1521     url[x] = '\0';
1522 }
1523
1524 // Subclasses may not need to override these particular virtual methods.
1525 string ShibTarget::getAuthType(void)
1526 {
1527   return string("shibboleth");
1528 }
1529 void* ShibTarget::returnDecline(void)
1530 {
1531   return NULL;
1532 }
1533 void* ShibTarget::returnOK(void)
1534 {
1535   return NULL;
1536 }
1537 HTAccessInfo* ShibTarget::getAccessInfo(void)
1538 {
1539   return NULL;
1540 }
1541 HTGroupTable* ShibTarget::getGroupTable(string &user)
1542 {
1543   return NULL;
1544 }