Some API refactoring
[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     static string url_encode(const char* s);
96   private:
97     char * fmakeword(char stop, unsigned int *cl, const char** ppch);
98     char * makeword(char *line, char stop);
99     void plustospace(char *str);
100
101     map<string,char*> kvp_map;
102   };
103
104   class ShibTargetPriv
105   {
106   public:
107     ShibTargetPriv();
108     ~ShibTargetPriv();
109
110     // Helper functions
111     void get_application(ShibTarget* st, const string& protocol, const string& hostname, int port, const string& uri);
112     const char* getCookie(ShibTarget* st, const string& name) const;
113     pair<string,const char*> getCookieNameProps(const char* prefix) const;
114     const char* getHandlerURL(const char* resource) const;
115     void* sendError(ShibTarget* st, const char* page, ShibMLP &mlp);
116     
117     // Handlers do the real Shibboleth work
118     pair<bool,void*> doSessionInitiator(ShibTarget* st, const IPropertySet* handler, bool isHandler=true) const;
119     pair<bool,void*> doAssertionConsumer(ShibTarget* st, const IPropertySet* handler) const;
120     pair<bool,void*> doLogout(ShibTarget* st, const IPropertySet* handler) const;
121
122     // And the binding/profile handlers do the low level packing and unpacking.
123     pair<bool,void*> ShibAuthnRequest(
124         ShibTarget* st,
125         const IPropertySet* shire,
126         const char* dest,
127         const char* target,
128         const char* providerId
129         ) const;
130
131   private:
132     friend class ShibTarget;
133     IRequestMapper::Settings m_settings;
134     const IApplication *m_app;
135     mutable string m_handlerURL;
136     mutable map<string,string> m_cookieMap;
137
138     ShibProfile m_sso_profile;
139     string m_provider_id;
140     SAMLAuthenticationStatement* m_sso_statement;
141     SAMLResponse* m_pre_response;
142     SAMLResponse* m_post_response;
143     
144     ShibTargetConfig* m_Config;
145
146     IConfig* m_conf;
147     IRequestMapper* m_mapper;
148   };
149 }
150
151
152 /*************************************************************************
153  * Shib Target implementation
154  */
155
156 ShibTarget::ShibTarget(void) : m_priv(NULL)
157 {
158   m_priv = new ShibTargetPriv();
159 }
160
161 ShibTarget::ShibTarget(const IApplication *app) : m_priv(NULL)
162 {
163   m_priv = new ShibTargetPriv();
164   m_priv->m_app = app;
165 }
166
167 ShibTarget::~ShibTarget(void)
168 {
169   if (m_priv) delete m_priv;
170 }
171
172 void ShibTarget::init(
173     const char* protocol,
174     const char* hostname,
175     int port,
176     const char* uri,
177     const char* content_type,
178     const char* remote_addr,
179     const char* method
180     )
181 {
182 #ifdef _DEBUG
183   saml::NDC ndc("init");
184 #endif
185
186   if (m_priv->m_app)
187     throw SAMLException("Request initialization occurred twice!");
188
189   if (method) m_method = method;
190   if (protocol) m_protocol = protocol;
191   if (hostname) m_hostname = hostname;
192   if (uri) m_uri = uri;
193   if (content_type) m_content_type = content_type;
194   if (remote_addr) m_remote_addr = remote_addr;
195   m_port = port;
196   m_priv->m_Config = &ShibTargetConfig::getConfig();
197   m_priv->get_application(this, protocol, hostname, port, uri);
198 }
199
200
201 // These functions implement the server-agnostic shibboleth engine
202 // The web server modules implement a subclass and then call into 
203 // these methods once they instantiate their request object.
204
205 pair<bool,void*> ShibTarget::doCheckAuthN(bool requireSessionFlag, bool handler)
206 {
207 #ifdef _DEBUG
208     saml::NDC ndc("doCheckAuthN");
209 #endif
210
211     const char* procState = "Request Processing Error";
212     const char* targetURL = m_url.c_str();
213     ShibMLP mlp;
214
215     try {
216         if (!m_priv->m_app)
217             throw ConfigurationException("System uninitialized, application did not supply request information.");
218
219         const char* handlerURL = m_priv->getHandlerURL(targetURL);
220         if (!handlerURL)
221             throw ConfigurationException("Cannot determine handler from resource URL, check configuration.");
222
223         // If the request URL contains the handler base URL for this application, either dispatch
224         // directly (mainly Apache 2.0) or just pass back control.
225         if (strstr(targetURL,handlerURL)) {
226             if (handler)
227                 return doHandler();
228             else
229                 return pair<bool,void*>(true, returnOK());
230         }
231
232         string auth_type = getAuthType();
233         if (strcasecmp(auth_type.c_str(),"shibboleth"))
234             return pair<bool,void*>(true,returnDecline());
235
236         pair<bool,bool> requireSession = m_priv->m_settings.first->getBool("requireSession");
237         if (!requireSession.first || !requireSession.second) {
238             // Web server might override.
239             if (requireSessionFlag)
240                 requireSession.second=true;
241         }
242
243         pair<string,const char*> shib_cookie = m_priv->getCookieNameProps("_shibsession_");
244         const char* session_id = m_priv->getCookie(this,shib_cookie.first);
245         if (!session_id || !*session_id) {
246             // No session.  Maybe that's acceptable?
247             if (!requireSession.second)
248                 return pair<bool,void*>(true,returnOK());
249
250             // No cookie, but we require a session. Initiate a new session using the default method.
251             procState = "Session Initiator Error";
252             const IPropertySet* initiator=m_priv->m_app->getDefaultSessionInitiator();
253             return m_priv->doSessionInitiator(this, initiator ? initiator : m_priv->m_app->getPropertySet("Sessions"), false);
254         }
255
256         procState = "Session Processing Error";
257         try {
258             // Localized exception throw if the session isn't valid.
259             sessionGet(
260                 session_id,
261                 m_remote_addr.c_str(),
262                 m_priv->m_sso_profile,
263                 m_priv->m_provider_id,
264                 &m_priv->m_sso_statement,
265                 &m_priv->m_pre_response,
266                 &m_priv->m_post_response
267                 );
268         }
269         catch (SAMLException& e) {
270             log(LogLevelError, string("session processing failed: ") + e.what());
271
272             // If no session is required, bail now.
273             if (!requireSession.second)
274                 // Has to be OK because DECLINED will just cause Apache
275                 // to fail when it can't locate anything to process the
276                 // AuthType.  No session plus requireSession false means
277                 // do not authenticate the user at this time.
278                 return pair<bool,void*>(true, returnOK());
279
280             // Try and cast down. This should throw an exception if it fails.
281             bool retryable=false;
282             try {
283                 RetryableProfileException& trycast=dynamic_cast<RetryableProfileException&>(e);
284                 retryable=true;
285             }
286             catch (exception&) {
287             }
288             if (retryable) {
289                 // Session is invalid but we can retry -- initiate a new session.
290                 procState = "Session Initiator Error";
291                 const IPropertySet* initiator=m_priv->m_app->getDefaultSessionInitiator();
292                 return m_priv->doSessionInitiator(this, initiator ? initiator : m_priv->m_app->getPropertySet("Sessions"), false);
293             }
294             throw;    // send it to the outer handler
295         }
296
297         // We're done.  Everything is okay.  Nothing to report.  Nothing to do..
298         // Let the caller decide how to proceed.
299         log(LogLevelDebug, "doCheckAuthN succeeded");
300         return pair<bool,void*>(false,NULL);
301     }
302     catch (SAMLException& e) {
303         mlp.insert(e);
304     }
305 #ifndef _DEBUG
306     catch (...) {
307         mlp.insert("errorText", "Caught an unknown exception.");
308     }
309 #endif
310
311     // If we get here then we've got an error.
312     mlp.insert("errorType", procState);
313     if (targetURL)
314         mlp.insert("requestURL", m_url.substr(0,m_url.find('?')));
315
316     return pair<bool,void*>(true,m_priv->sendError(this,"session", mlp));
317 }
318
319 pair<bool,void*> ShibTarget::doHandler(void)
320 {
321 #ifdef _DEBUG
322     saml::NDC ndc("doHandler");
323 #endif
324
325     const char* procState = "Shibboleth Handler Error";
326     const char* targetURL = m_url.c_str();
327     ShibMLP mlp;
328
329     try {
330         if (!m_priv->m_app)
331             throw ConfigurationException("System uninitialized, application did not supply request information.");
332
333         const char* handlerURL = m_priv->getHandlerURL(targetURL);
334         if (!handlerURL)
335             throw ConfigurationException("Cannot determine handler from resource URL, check configuration.");
336
337         // Make sure we only process handler requests.
338         if (!strstr(targetURL,handlerURL))
339             return pair<bool,void*>(true, returnDecline());
340
341         const IPropertySet* sessionProps=m_priv->m_app->getPropertySet("Sessions");
342         if (!sessionProps)
343             throw ConfigurationException("Unable to map request to application session settings, check configuration.");
344
345         // Process incoming request.
346         pair<bool,bool> handlerSSL=sessionProps->getBool("handlerSSL");
347       
348         // Make sure this is SSL, if it should be
349         if ((!handlerSSL.first || handlerSSL.second) && m_protocol != "https")
350             throw FatalProfileException("Blocked non-SSL access to Shibboleth handler.");
351
352         // We dispatch based on our path info. We know the request URL begins with or equals the handler URL,
353         // so the path info is the next character (or null).
354         const IPropertySet* handler=m_priv->m_app->getHandler(targetURL + strlen(handlerURL));
355         if (handler) {
356             if (saml::XML::isElementNamed(handler->getElement(),shibtarget::XML::SAML2META_NS,SHIBT_L(AssertionConsumerService))) {
357                 procState = "Session Creation Error";
358                 return m_priv->doAssertionConsumer(this,handler);
359             }
360             else if (saml::XML::isElementNamed(handler->getElement(),ShibTargetConfig::SHIBTARGET_NS,SHIBT_L(SessionInitiator))) {
361                 procState = "Session Initiator Error";
362                 return m_priv->doSessionInitiator(this,handler);
363             }
364             else if (saml::XML::isElementNamed(handler->getElement(),shibtarget::XML::SAML2META_NS,SHIBT_L(SingleLogoutService))) {
365                 procState = "Session Termination Error";
366                 return m_priv->doLogout(this,handler);
367             }
368             else
369                 throw ConfigurationException("Endpoint is mapped to unrecognized handler element.");
370         }
371         
372         if (strlen(targetURL)>strlen(handlerURL) && targetURL[strlen(handlerURL)]!='?')
373             throw SAMLException("Shibboleth handler invoked at an unconfigured location.");
374         
375         // This is a legacy direct execution of the handler (the old shireURL).
376         // If this is a GET, we see if it's a lazy session request, otherwise
377         // assume it's a SAML 1.x POST profile response and process it.
378         if (!strcasecmp(m_method.c_str(), "GET")) {
379             procState = "Session Initiator Error";
380             return m_priv->doSessionInitiator(this, sessionProps);
381         }
382         
383         procState = "Session Creation Error";
384         return m_priv->doAssertionConsumer(this, sessionProps);
385     }
386     catch (MetadataException& e) {
387         mlp.insert(e);
388         // See if a metadata error page is installed.
389         const IPropertySet* props=m_priv->m_app->getPropertySet("Errors");
390         if (props) {
391             pair<bool,const char*> p=props->getString("metadata");
392             if (p.first) {
393                 mlp.insert("errorType", procState);
394                 if (targetURL)
395                     mlp.insert("requestURL", targetURL);
396                 return make_pair(true,m_priv->sendError(this,"metadata", mlp));
397             }
398         }
399     }
400     catch (SAMLException& e) {
401         mlp.insert(e);
402     }
403 #ifndef _DEBUG
404     catch (...) {
405         mlp.insert("errorText", "Caught an unknown exception.");
406     }
407 #endif
408
409     // If we get here then we've got an error.
410     mlp.insert("errorType", procState);
411
412     if (targetURL)
413         mlp.insert("requestURL", m_url.substr(0,m_url.find('?')));
414
415     return make_pair(true,m_priv->sendError(this,"session", mlp));
416 }
417
418 pair<bool,void*> ShibTarget::doCheckAuthZ(void)
419 {
420 #ifdef _DEBUG
421     saml::NDC ndc("doCheckAuthZ");
422 #endif
423
424     ShibMLP mlp;
425     const char* procState = "Authorization Processing Error";
426     const char* targetURL = m_url.c_str();
427
428     try {
429         if (!m_priv->m_app)
430             throw ConfigurationException("System uninitialized, application did not supply request information.");
431
432         // Do we have an access control plugin?
433         if (m_priv->m_settings.second) {
434             Locker acllock(m_priv->m_settings.second);
435             if (!m_priv->m_settings.second->authorized(m_priv->m_provider_id.c_str(), m_priv->m_sso_statement, m_priv->m_post_response, this)) {
436                 log(LogLevelWarn, "doCheckAuthZ() access control provider denied access");
437                 if (targetURL)
438                     mlp.insert("requestURL", targetURL);
439                 return make_pair(true,m_priv->sendError(this, "access", mlp));
440             }
441         }
442
443         // Perform HTAccess Checks
444         auto_ptr<HTAccessInfo> ht(getAccessInfo());
445
446         // No Info means OK.  Just return
447         if (!ht.get())
448             return pair<bool,void*>(false, NULL);
449
450         vector<bool> auth_OK(ht->elements.size(), false);
451         bool method_restricted=false;
452         string remote_user = getRemoteUser();
453
454 #define CHECK_OK \
455     do { \
456         if (!ht->requireAll) { \
457             return pair<bool,void*>(false, NULL); \
458         } \
459         auth_OK[x] = true; \
460         continue; \
461     } while (0)
462
463         for (int x = 0; x < ht->elements.size(); x++) {
464             auth_OK[x] = false;
465             HTAccessInfo::RequireLine *line = ht->elements[x];
466             if (! line->use_line)
467                 continue;
468             method_restricted = true;
469
470             const char *w = line->tokens[0].c_str();
471
472             if (!strcasecmp(w,"Shibboleth")) {
473                 // This is a dummy rule needed because Apache conflates authn and authz.
474                 // Without some require rule, AuthType is ignored and no check_user hooks run.
475                 CHECK_OK;
476             }
477             else if (!strcmp(w,"valid-user")) {
478                 log(LogLevelDebug, "doCheckAuthZ accepting valid-user");
479                 CHECK_OK;
480             }
481             else if (!strcmp(w,"user") && !remote_user.empty()) {
482                 bool regexp=false;
483                 for (int i = 1; i < line->tokens.size(); i++) {
484                     w = line->tokens[i].c_str();
485                     if (*w == '~') {
486                         regexp = true;
487                         continue;
488                     }
489                 
490                     if (regexp) {
491                         try {
492                             // To do regex matching, we have to convert from UTF-8.
493                             auto_ptr<XMLCh> trans(fromUTF8(w));
494                             RegularExpression re(trans.get());
495                             auto_ptr<XMLCh> trans2(fromUTF8(remote_user.c_str()));
496                             if (re.matches(trans2.get())) {
497                                 log(LogLevelDebug, string("doCheckAuthZ accepting user: ") + w);
498                                 CHECK_OK;
499                             }
500                         }
501                         catch (XMLException& ex) {
502                             auto_ptr_char tmp(ex.getMessage());
503                             log(LogLevelError, string("doCheckAuthZ caught exception while parsing regular expression (")
504                                + w + "): " + tmp.get());
505                         }
506                     }
507                     else if (!strcmp(remote_user.c_str(), w)) {
508                         log(LogLevelDebug, string("doCheckAuthZ accepting user: ") + w);
509                         CHECK_OK;
510                     }
511                 }
512             }
513             else if (!strcmp(w,"group")) {
514                 auto_ptr<HTGroupTable> grpstatus(getGroupTable(remote_user));
515                 if (!grpstatus.get()) {
516                     return pair<bool,void*>(true, returnDecline());
517                 }
518     
519                 for (int i = 1; i < line->tokens.size(); i++) {
520                     w = line->tokens[i].c_str();
521                     if (grpstatus->lookup(w)) {
522                         log(LogLevelDebug, string("doCheckAuthZ accepting group: ") + w);
523                         CHECK_OK;
524                     }
525                 }
526             }
527             else {
528                 Iterator<IAAP*> provs = m_priv->m_app->getAAPProviders();
529                 AAP wrapper(provs, w);
530                 if (wrapper.fail()) {
531                     log(LogLevelWarn, string("doCheckAuthZ didn't recognize require rule: ") + w);
532                     continue;
533                 }
534
535                 bool regexp = false;
536                 string vals = getHeader(wrapper->getHeader());
537                 for (int i = 1; i < line->tokens.size() && !vals.empty(); i++) {
538                     w = line->tokens[i].c_str();
539                     if (*w == '~') {
540                         regexp = true;
541                         continue;
542                     }
543
544                     try {
545                         auto_ptr<RegularExpression> re;
546                         if (regexp) {
547                             delete re.release();
548                             auto_ptr<XMLCh> trans(fromUTF8(w));
549                             auto_ptr<RegularExpression> temp(new RegularExpression(trans.get()));
550                             re=temp;
551                         }
552                     
553                         string vals_str(vals);
554                         int j = 0;
555                         for (int i = 0;  i < vals_str.length();  i++) {
556                             if (vals_str.at(i) == ';') {
557                                 if (i == 0) {
558                                     log(LogLevelError, string("doCheckAuthZ invalid header encoding") +
559                                         vals + ": starts with a semicolon");
560                                     throw SAMLException("Invalid information supplied to authorization module.");
561                                 }
562
563                                 if (vals_str.at(i-1) == '\\') {
564                                     vals_str.erase(i-1, 1);
565                                     i--;
566                                     continue;
567                                 }
568
569                                 string val = vals_str.substr(j, i-j);
570                                 j = i+1;
571                                 if (regexp) {
572                                     auto_ptr<XMLCh> trans(fromUTF8(val.c_str()));
573                                     if (re->matches(trans.get())) {
574                                         log(LogLevelDebug, string("doCheckAuthZ expecting ") + w +
575                                            ", got " + val + ": authorization granted");
576                                         CHECK_OK;
577                                     }
578                                 }
579                                 else if ((wrapper->getCaseSensitive() && val==w) ||
580                                         (!wrapper->getCaseSensitive() && !strcasecmp(val.c_str(),w))) {
581                                     log(LogLevelDebug, string("doCheckAuthZ expecting ") + w +
582                                         ", got " + val + ": authorization granted.");
583                                     CHECK_OK;
584                                 }
585                                 else {
586                                     log(LogLevelDebug, string("doCheckAuthZ expecting ") + w +
587                                         ", got " + val + ": authoritzation not granted.");
588                                 }
589                             }
590                         }
591     
592                         string val = vals_str.substr(j, vals_str.length()-j);
593                         if (regexp) {
594                             auto_ptr<XMLCh> trans(fromUTF8(val.c_str()));
595                             if (re->matches(trans.get())) {
596                                 log(LogLevelDebug, string("doCheckAuthZ expecting ") + w +
597                                     ", got " + val + ": authorization granted.");
598                                 CHECK_OK;
599                             }
600                         }
601                         else if ((wrapper->getCaseSensitive() && val==w) ||
602                                 (!wrapper->getCaseSensitive() && !strcasecmp(val.c_str(),w))) {
603                             log(LogLevelDebug, string("doCheckAuthZ expecting ") + w +
604                                 ", got " + val + ": authorization granted");
605                             CHECK_OK;
606                         }
607                         else {
608                             log(LogLevelDebug, string("doCheckAuthZ expecting ") + w +
609                                 ", got " + val + ": authorization not granted");
610                         }
611                     }
612                     catch (XMLException& ex) {
613                         auto_ptr_char tmp(ex.getMessage());
614                             log(LogLevelError, string("doCheckAuthZ caught exception while parsing regular expression (")
615                                 + w + "): " + tmp.get());
616                     }
617                 }
618             }
619         } // for x
620
621
622         // check if all require directives are true
623         bool auth_all_OK = true;
624         for (int i = 0; i < ht->elements.size(); i++) {
625             auth_all_OK &= auth_OK[i];
626         }
627
628         if (auth_all_OK || !method_restricted)
629             return pair<bool,void*>(false, NULL);
630
631         // If we get here there's an access error, so just fall through
632     }
633     catch (SAMLException& e) {
634         mlp.insert(e);
635     }
636 #ifndef _DEBUG
637     catch (...) {
638         mlp.insert("errorText", "Caught an unknown exception.");
639     }
640 #endif
641
642     // If we get here then we've got an error.
643     mlp.insert("errorType", procState);
644
645     if (targetURL)
646         mlp.insert("requestURL", m_url.substr(0,m_url.find('?')));
647
648     return make_pair(true,m_priv->sendError(this, "access", mlp));
649 }
650
651 pair<bool,void*> ShibTarget::doExportAssertions(bool exportAssertion)
652 {
653 #ifdef _DEBUG
654     saml::NDC ndc("doExportAssertions");
655 #endif
656
657     ShibMLP mlp;
658     const char* procState = "Attribute Processing Error";
659     const char* targetURL = m_url.c_str();
660
661     try {
662         if (!m_priv->m_app)
663             throw ConfigurationException("System uninitialized, application did not supply request information.");
664
665         pair<string,const char*> shib_cookie=m_priv->getCookieNameProps("_shibsession_");
666         const char *session_id = m_priv->getCookie(this,shib_cookie.first);
667
668         if (!m_priv->m_sso_statement) {
669             // No data yet, so we need to get the session. This can only happen
670             // if the call to doCheckAuthn doesn't happen in the same object lifetime.
671             sessionGet(
672                 session_id,
673                 m_remote_addr.c_str(),
674                 m_priv->m_sso_profile,
675                 m_priv->m_provider_id,
676                 &m_priv->m_sso_statement,
677                 &m_priv->m_pre_response,
678                 &m_priv->m_post_response
679                 );
680         }
681
682         // Get the AAP providers, which contain the attribute policy info.
683         Iterator<IAAP*> provs=m_priv->m_app->getAAPProviders();
684
685         // Clear out the list of mapped attributes
686         while (provs.hasNext()) {
687             IAAP* aap=provs.next();
688             Locker locker(aap);
689             Iterator<const IAttributeRule*> rules=aap->getAttributeRules();
690             while (rules.hasNext()) {
691                 const char* header=rules.next()->getHeader();
692                 if (header)
693                     clearHeader(header);
694             }
695         }
696         
697         // Maybe export the first assertion.
698         clearHeader("Shib-Attributes");
699         pair<bool,bool> exp=m_priv->m_settings.first->getBool("exportAssertion");
700         if (!exp.first || !exp.second)
701             if (exportAssertion)
702                 exp.second=true;
703         if (exp.second && m_priv->m_pre_response) {
704             ostringstream os;
705             os << *(m_priv->m_pre_response);
706             unsigned int outlen;
707             XMLByte* serialized = Base64::encode(reinterpret_cast<XMLByte*>((char*)os.str().c_str()), os.str().length(), &outlen);
708             XMLByte *pos, *pos2;
709             for (pos=serialized, pos2=serialized; *pos2; pos2++)
710                 if (isgraph(*pos2))
711                     *pos++=*pos2;
712             *pos=0;
713             setHeader("Shib-Attributes", reinterpret_cast<char*>(serialized));
714             XMLString::release(&serialized);
715         }
716     
717         // Export the SAML AuthnMethod and the origin site name, and possibly the NameIdentifier.
718         clearHeader("Shib-Origin-Site");
719         clearHeader("Shib-Identity-Provider");
720         clearHeader("Shib-Authentication-Method");
721         clearHeader("Shib-NameIdentifier-Format");
722         setHeader("Shib-Origin-Site", m_priv->m_provider_id.c_str());
723         setHeader("Shib-Identity-Provider", m_priv->m_provider_id.c_str());
724         auto_ptr_char am(m_priv->m_sso_statement->getAuthMethod());
725         setHeader("Shib-Authentication-Method", am.get());
726         
727         // Export NameID?
728         provs.reset();
729         while (provs.hasNext()) {
730             IAAP* aap=provs.next();
731             Locker locker(aap);
732             const IAttributeRule* rule=aap->lookup(m_priv->m_sso_statement->getSubject()->getNameIdentifier()->getFormat());
733             if (rule && rule->getHeader()) {
734                 auto_ptr_char form(m_priv->m_sso_statement->getSubject()->getNameIdentifier()->getFormat());
735                 auto_ptr_char nameid(m_priv->m_sso_statement->getSubject()->getNameIdentifier()->getName());
736                 setHeader("Shib-NameIdentifier-Format", form.get());
737                 if (!strcmp(rule->getHeader(),"REMOTE_USER"))
738                     setRemoteUser(nameid.get());
739                 else
740                     setHeader(rule->getHeader(), nameid.get());
741             }
742         }
743         
744         clearHeader("Shib-Application-ID");
745         setHeader("Shib-Application-ID", m_priv->m_app->getId());
746     
747         // Export the attributes.
748         Iterator<SAMLAssertion*> a_iter(m_priv->m_post_response ? m_priv->m_post_response->getAssertions() : EMPTY(SAMLAssertion*));
749         while (a_iter.hasNext()) {
750             SAMLAssertion* assert=a_iter.next();
751             Iterator<SAMLStatement*> statements=assert->getStatements();
752             while (statements.hasNext()) {
753                 SAMLAttributeStatement* astate=dynamic_cast<SAMLAttributeStatement*>(statements.next());
754                 if (!astate)
755                     continue;
756                 Iterator<SAMLAttribute*> attrs=astate->getAttributes();
757                 while (attrs.hasNext()) {
758                     SAMLAttribute* attr=attrs.next();
759             
760                     // Are we supposed to export it?
761                     provs.reset();
762                     while (provs.hasNext()) {
763                         IAAP* aap=provs.next();
764                         Locker locker(aap);
765                         const IAttributeRule* rule=aap->lookup(attr->getName(),attr->getNamespace());
766                         if (!rule || !rule->getHeader())
767                             continue;
768                     
769                         Iterator<string> vals=attr->getSingleByteValues();
770                         if (!strcmp(rule->getHeader(),"REMOTE_USER") && vals.hasNext())
771                             setRemoteUser(vals.next());
772                         else {
773                             int it=0;
774                             string header = getHeader(rule->getHeader());
775                             if (!header.empty())
776                                 it++;
777                             for (; vals.hasNext(); it++) {
778                                 string value = vals.next();
779                                 for (string::size_type pos = value.find_first_of(";", string::size_type(0));
780                                         pos != string::npos;
781                                         pos = value.find_first_of(";", pos)) {
782                                     value.insert(pos, "\\");
783                                     pos += 2;
784                                 }
785                                 if (it)
786                                     header += ";";
787                                 header += value;
788                             }
789                             setHeader(rule->getHeader(), header);
790                         }
791                     }
792                 }
793             }
794         }
795     
796         return pair<bool,void*>(false,NULL);
797     }
798     catch (SAMLException& e) {
799         mlp.insert(e);
800     }
801 #ifndef _DEBUG
802     catch (...) {
803         mlp.insert("errorText", "Caught an unknown exception.");
804     }
805 #endif
806
807     // If we get here then we've got an error.
808     mlp.insert("errorType", procState);
809
810     if (targetURL)
811         mlp.insert("requestURL", m_url.substr(0,m_url.find('?')));
812
813     return make_pair(true,m_priv->sendError(this, "rm", mlp));
814 }
815
816
817 void ShibTarget::sessionNew(
818     int supported_profiles,
819     const string& recipient,
820     const char* packet,
821     const char* ip,
822     string& target,
823     string& cookie,
824     string& provider_id
825     ) const
826 {
827 #ifdef _DEBUG
828     saml::NDC ndc("sessionNew");
829 #endif
830     Category& log = Category::getInstance("shibtarget.ShibTarget");
831
832     if (!packet || !*packet) {
833         log.error("missing profile response");
834         throw FatalProfileException("Profile response missing.");
835     }
836
837     if (!ip || !*ip) {
838         log.error("missing client address");
839         throw FatalProfileException("Invalid client address.");
840     }
841   
842     if (supported_profiles <= 0) {
843         log.error("no profile support indicated");
844         throw FatalProfileException("No profile support indicated.");
845     }
846   
847     shibrpc_new_session_args_2 arg;
848     arg.recipient = (char*)recipient.c_str();
849     arg.application_id = (char*)m_priv->m_app->getId();
850     arg.packet = (char*)packet;
851     arg.client_addr = (char*)ip;
852     arg.supported_profiles = supported_profiles;
853
854     log.info("create session for user at (%s) for application (%s)", ip, arg.application_id);
855
856     shibrpc_new_session_ret_2 ret;
857     memset(&ret, 0, sizeof(ret));
858
859     // Loop on the RPC in case we lost contact the first time through
860     int retry = 1;
861     CLIENT* clnt;
862     RPC rpc;
863     do {
864         clnt = rpc->connect();
865         clnt_stat status = shibrpc_new_session_2 (&arg, &ret, clnt);
866         if (status != RPC_SUCCESS) {
867             // FAILED.  Release, disconnect, and retry
868             log.error("RPC Failure: %p (%p) (%d): %s", this, clnt, status, clnt_spcreateerror("shibrpc_new_session_2"));
869             rpc->disconnect();
870             if (retry)
871                 retry--;
872             else
873                 throw ListenerException("Failure passing session setup information to listener.");
874         }
875         else {
876             // SUCCESS.  Pool and continue
877             retry = -1;
878         }
879     } while (retry>=0);
880
881     if (ret.status && *ret.status)
882         log.debug("RPC completed with exception: %s", ret.status);
883     else
884         log.debug("RPC completed successfully");
885
886     SAMLException* except=NULL;
887     if (ret.status && *ret.status) {
888         // Reconstitute exception object.
889         try { 
890             istringstream estr(ret.status);
891             except=SAMLException::getInstance(estr);
892         }
893         catch (SAMLException& e) {
894             log.error("caught SAML Exception while building the SAMLException: %s", e.what());
895             log.error("XML was: %s", ret.status);
896             clnt_freeres(clnt, (xdrproc_t)xdr_shibrpc_new_session_ret_2, (caddr_t)&ret);
897             rpc.pool();
898             throw FatalProfileException("An unrecoverable error occurred while creating your session.");
899         }
900 #ifndef _DEBUG
901         catch (...) {
902             log.error("caught unknown exception building SAMLException");
903             log.error("XML was: %s", ret.status);
904             clnt_freeres(clnt, (xdrproc_t)xdr_shibrpc_new_session_ret_2, (caddr_t)&ret);
905             rpc.pool();
906             throw;
907         }
908 #endif
909     }
910     else {
911         log.debug("new session from IdP (%s) with key (%s)", ret.provider_id, ret.cookie);
912         cookie = ret.cookie;
913         provider_id = ret.provider_id;
914         if (ret.target)
915             target = ret.target;
916     }
917
918     clnt_freeres(clnt, (xdrproc_t)xdr_shibrpc_new_session_ret_2, (caddr_t)&ret);
919     rpc.pool();
920     if (except) {
921         auto_ptr<SAMLException> wrapper(except);
922         wrapper->raise();
923     }
924 }
925
926 void ShibTarget::sessionGet(
927     const char* cookie,
928     const char* ip,
929     ShibProfile& profile,
930     string& provider_id,
931     SAMLAuthenticationStatement** auth_statement,
932     SAMLResponse** attr_response_pre,
933     SAMLResponse** attr_response_post
934     ) const
935 {
936 #ifdef _DEBUG
937     saml::NDC ndc("sessionGet");
938 #endif
939     Category& log = Category::getInstance("shibtarget.ShibTarget");
940
941     if (!cookie || !*cookie) {
942         log.error("no session key provided");
943         throw InvalidSessionException("No session key was provided.");
944     }
945     else if (strchr(cookie,'=')) {
946         log.error("cookie value not extracted successfully, probably overlapping cookies across domains");
947         throw InvalidSessionException("The session key wasn't extracted successfully from the browser cookie.");
948     }
949
950     if (!ip || !*ip) {
951         log.error("invalid client Address");
952         throw FatalProfileException("Invalid client address.");
953     }
954
955     log.info("getting session for client at (%s)", ip);
956     log.debug("session cookie (%s)", cookie);
957
958     shibrpc_get_session_args_2 arg;
959     arg.cookie = (char*)cookie;
960     arg.client_addr = (char*)ip;
961     arg.application_id = (char*)m_priv->m_app->getId();
962
963     shibrpc_get_session_ret_2 ret;
964     memset (&ret, 0, sizeof(ret));
965
966     // Loop on the RPC in case we lost contact the first time through
967     int retry = 1;
968     CLIENT *clnt;
969     RPC rpc;
970     do {
971         clnt = rpc->connect();
972         clnt_stat status = shibrpc_get_session_2(&arg, &ret, clnt);
973         if (status != RPC_SUCCESS) {
974             // FAILED.  Release, disconnect, and try again...
975             log.error("RPC Failure: %p (%p) (%d) %s", this, clnt, status, clnt_spcreateerror("shibrpc_get_session_2"));
976             rpc->disconnect();
977             if (retry)
978                 retry--;
979             else
980                 throw ListenerException("Failure requesting session information from listener.");
981         }
982         else {
983             // SUCCESS
984             retry = -1;
985         }
986     } while (retry>=0);
987
988     if (ret.status && *ret.status)
989         log.debug("RPC completed with exception: %s", ret.status);
990     else
991         log.debug("RPC completed successfully");
992
993     SAMLException* except=NULL;
994     if (ret.status && *ret.status) {
995         // Reconstitute exception object.
996         try { 
997             istringstream estr(ret.status);
998             except=SAMLException::getInstance(estr);
999         }
1000         catch (SAMLException& e) {
1001             log.error("caught SAML Exception while building the SAMLException: %s", e.what());
1002             log.error("XML was: %s", ret.status);
1003             clnt_freeres(clnt, (xdrproc_t)xdr_shibrpc_get_session_ret_2, (caddr_t)&ret);
1004             rpc.pool();
1005             throw FatalProfileException("An unrecoverable error occurred while accessing your session.");
1006         }
1007         catch (...) {
1008             log.error("caught unknown exception building SAMLException");
1009             log.error("XML was: %s", ret.status);
1010             clnt_freeres(clnt, (xdrproc_t)xdr_shibrpc_get_session_ret_2, (caddr_t)&ret);
1011             rpc.pool();
1012             throw;
1013         }
1014     }
1015     else {
1016         try {
1017             profile = ret.profile;
1018             provider_id = ret.provider_id;
1019         
1020             // return the Authentication Statement
1021             if (auth_statement) {
1022                 istringstream authstream(ret.auth_statement);
1023                 log.debugStream() << "trying to decode authentication statement: "
1024                     << ret.auth_statement << CategoryStream::ENDLINE;
1025                 *auth_statement = new SAMLAuthenticationStatement(authstream);
1026             }
1027     
1028             // return the unfiltered Response
1029             if (attr_response_pre) {
1030                 istringstream prestream(ret.attr_response_pre);
1031                 log.debugStream() << "trying to decode unfiltered attribute response: "
1032                     << ret.attr_response_pre << CategoryStream::ENDLINE;
1033                 *attr_response_pre = new SAMLResponse(prestream);
1034             }
1035     
1036             // return the filtered Response
1037             if (attr_response_post) {
1038                 istringstream poststream(ret.attr_response_post);
1039                 log.debugStream() << "trying to decode filtered attribute response: "
1040                     << ret.attr_response_post << CategoryStream::ENDLINE;
1041                 *attr_response_post = new SAMLResponse(poststream);
1042             }
1043         }
1044         catch (SAMLException& e) {
1045             log.error("caught SAML exception while reconstituting session objects: %s", e.what());
1046             clnt_freeres (clnt, (xdrproc_t)xdr_shibrpc_get_session_ret_2, (caddr_t)&ret);
1047             rpc.pool();
1048             throw;
1049         }
1050 #ifndef _DEBUG
1051         catch (...) {
1052             log.error("caught unknown exception while reconstituting session objects");
1053             clnt_freeres (clnt, (xdrproc_t)xdr_shibrpc_get_session_ret_2, (caddr_t)&ret);
1054             rpc.pool();
1055             throw;
1056         }
1057 #endif
1058     }
1059
1060     clnt_freeres (clnt, (xdrproc_t)xdr_shibrpc_get_session_ret_2, (caddr_t)&ret);
1061     rpc.pool();
1062     if (except) {
1063         auto_ptr<SAMLException> wrapper(except);
1064         wrapper->raise();
1065     }
1066 }
1067
1068 void ShibTarget::sessionEnd(const char* cookie) const
1069 {
1070 #ifdef _DEBUG
1071     saml::NDC ndc("sessionEnd");
1072 #endif
1073     Category& log = Category::getInstance("shibtarget.ShibTarget");
1074
1075     if (!cookie || !*cookie) {
1076         log.error("no session key provided");
1077         throw InvalidSessionException("No session key was provided.");
1078     }
1079     else if (strchr(cookie,'=')) {
1080         log.error("cookie value not extracted successfully, probably overlapping cookies across domains");
1081         throw InvalidSessionException("The session key wasn't extracted successfully from the browser cookie.");
1082     }
1083
1084     log.debug("ending session with cookie (%s)", cookie);
1085
1086     shibrpc_end_session_args_2 arg;
1087     arg.cookie = (char*)cookie;
1088
1089     shibrpc_end_session_ret_2 ret;
1090     memset (&ret, 0, sizeof(ret));
1091
1092     // Loop on the RPC in case we lost contact the first time through
1093     int retry = 1;
1094     CLIENT *clnt;
1095     RPC rpc;
1096     do {
1097         clnt = rpc->connect();
1098         clnt_stat status = shibrpc_end_session_2(&arg, &ret, clnt);
1099         if (status != RPC_SUCCESS) {
1100             // FAILED.  Release, disconnect, and try again...
1101             log.error("RPC Failure: %p (%p) (%d) %s", this, clnt, status, clnt_spcreateerror("shibrpc_end_session_2"));
1102             rpc->disconnect();
1103             if (retry)
1104                 retry--;
1105             else
1106                 throw ListenerException("Failure ending session through listener.");
1107         }
1108         else {
1109             // SUCCESS
1110             retry = -1;
1111         }
1112     } while (retry>=0);
1113
1114     if (ret.status && *ret.status)
1115         log.debug("RPC completed with exception: %s", ret.status);
1116     else
1117         log.debug("RPC completed successfully");
1118
1119     SAMLException* except=NULL;
1120     if (ret.status && *ret.status) {
1121         // Reconstitute exception object.
1122         try { 
1123             istringstream estr(ret.status);
1124             except=SAMLException::getInstance(estr);
1125         }
1126         catch (SAMLException& e) {
1127             log.error("caught SAML Exception while building the SAMLException: %s", e.what());
1128             log.error("XML was: %s", ret.status);
1129             clnt_freeres(clnt, (xdrproc_t)xdr_shibrpc_end_session_ret_2, (caddr_t)&ret);
1130             rpc.pool();
1131             throw FatalProfileException("An unrecoverable error occurred while accessing your session.");
1132         }
1133         catch (...) {
1134             log.error("caught unknown exception building SAMLException");
1135             log.error("XML was: %s", ret.status);
1136             clnt_freeres(clnt, (xdrproc_t)xdr_shibrpc_end_session_ret_2, (caddr_t)&ret);
1137             rpc.pool();
1138             throw;
1139         }
1140     }
1141
1142     clnt_freeres (clnt, (xdrproc_t)xdr_shibrpc_end_session_ret_2, (caddr_t)&ret);
1143     rpc.pool();
1144     if (except) {
1145         auto_ptr<SAMLException> wrapper(except);
1146         wrapper->raise();
1147     }
1148 }
1149
1150 /*************************************************************************
1151  * Shib Target Private implementation
1152  */
1153
1154 ShibTargetPriv::ShibTargetPriv() : m_app(NULL), m_mapper(NULL), m_conf(NULL), m_Config(NULL),
1155     m_sso_profile(PROFILE_UNSPECIFIED), m_sso_statement(NULL), m_pre_response(NULL), m_post_response(NULL) {}
1156
1157 ShibTargetPriv::~ShibTargetPriv()
1158 {
1159   delete m_sso_statement;
1160   m_sso_statement = NULL;
1161
1162   delete m_pre_response;
1163   m_pre_response = NULL;
1164   
1165   delete m_post_response;
1166   m_post_response = NULL;
1167
1168   if (m_mapper) {
1169     m_mapper->unlock();
1170     m_mapper = NULL;
1171   }
1172   if (m_conf) {
1173     m_conf->unlock();
1174     m_conf = NULL;
1175   }
1176   m_app = NULL;
1177   m_Config = NULL;
1178 }
1179
1180 void ShibTargetPriv::get_application(ShibTarget* st, const string& protocol, const string& hostname, int port, const string& uri)
1181 {
1182   if (m_app)
1183     return;
1184
1185   // XXX: Do we need to keep conf and mapper locked while we hold m_app?
1186   // TODO: No, should be able to hold the conf but release the mapper.
1187
1188   // We lock the configuration system for the duration.
1189   m_conf=m_Config->getINI();
1190   m_conf->lock();
1191     
1192   // Map request to application and content settings.
1193   m_mapper=m_conf->getRequestMapper();
1194   m_mapper->lock();
1195
1196   // Obtain the application settings from the parsed URL
1197   m_settings = m_mapper->getSettingsFromParsedURL(protocol.c_str(),hostname.c_str(),port,uri.c_str(),st);
1198
1199   // Now find the application from the URL settings
1200   pair<bool,const char*> application_id=m_settings.first->getString("applicationId");
1201   const IApplication* application=m_conf->getApplication(application_id.second);
1202   if (!application) {
1203     m_mapper->unlock();
1204     m_mapper = NULL;
1205     m_conf->unlock();
1206     m_conf = NULL;
1207     throw SAMLException("Unable to map request to application settings, check configuration.");
1208   }
1209
1210   // Store the application for later use
1211   m_app = application;
1212
1213   // Compute the target URL
1214   st->m_url = protocol + "://" + hostname;
1215   if ((protocol == "http" && port != 80) || (protocol == "https" && port != 443))
1216     st->m_url += ":" + port;
1217   st->m_url += uri;
1218 }
1219
1220 void* ShibTargetPriv::sendError(ShibTarget* st, const char* page, ShibMLP &mlp)
1221 {
1222     ShibTarget::header_t hdrs[] = {
1223         ShibTarget::header_t("Expires","01-Jan-1997 12:00:00 GMT"),
1224         ShibTarget::header_t("Cache-Control","private,no-store,no-cache")
1225         };
1226     
1227     const IPropertySet* props=m_app->getPropertySet("Errors");
1228     if (props) {
1229         pair<bool,const char*> p=props->getString(page);
1230         if (p.first) {
1231             ifstream infile(p.second);
1232             if (!infile.fail()) {
1233                 const char* res = mlp.run(infile,props);
1234                 if (res)
1235                     return st->sendPage(res, 200, "text/html", ArrayIterator<ShibTarget::header_t>(hdrs,2));
1236             }
1237         }
1238         else if (!strcmp(page,"access"))
1239             return st->sendPage("Access Denied", 403, "text/html", ArrayIterator<ShibTarget::header_t>(hdrs,2));
1240     }
1241
1242     string errstr = string("sendError could not process error template (") + page + ") for application (";
1243     errstr += m_app->getId();
1244     errstr += ")";
1245     st->log(ShibTarget::LogLevelError, errstr);
1246     return st->sendPage(
1247         "Internal Server Error. Please contact the site administrator.", 500, "text/html", ArrayIterator<ShibTarget::header_t>(hdrs,2)
1248         );
1249 }
1250
1251 const char* ShibTargetPriv::getCookie(ShibTarget* st, const string& name) const
1252 {
1253     if (m_cookieMap.empty()) {
1254         string cookies=st->getCookies();
1255
1256         string::size_type pos=0,cname,namelen,val,vallen;
1257         while (pos !=string::npos && pos < cookies.length()) {
1258             while (isspace(cookies[pos])) pos++;
1259             cname=pos;
1260             pos=cookies.find_first_of("=",pos);
1261             if (pos == string::npos)
1262                 break;
1263             namelen=pos-cname;
1264             pos++;
1265             if (pos==cookies.length())
1266                 break;
1267             val=pos;
1268             pos=cookies.find_first_of(";",pos);
1269             if (pos != string::npos) {
1270                 vallen=pos-val;
1271                 pos++;
1272                 m_cookieMap.insert(make_pair(cookies.substr(cname,namelen),cookies.substr(val,vallen)));
1273             }
1274             else
1275                 m_cookieMap.insert(make_pair(cookies.substr(cname,namelen),cookies.substr(val)));
1276         }
1277     }
1278     map<string,string>::const_iterator lookup=m_cookieMap.find(name);
1279     return (lookup==m_cookieMap.end()) ? NULL : lookup->second.c_str();
1280 }
1281
1282 // Get the session cookie name and properties for the application
1283 pair<string,const char*> ShibTargetPriv::getCookieNameProps(const char* prefix) const
1284 {
1285     static const char* defProps="; path=/";
1286     
1287     const IPropertySet* props=m_app ? m_app->getPropertySet("Sessions") : NULL;
1288     if (props) {
1289         pair<bool,const char*> p=props->getString("cookieProps");
1290         if (!p.first)
1291             p.second=defProps;
1292         pair<bool,const char*> p2=props->getString("cookieName");
1293         if (p2.first)
1294             return make_pair(string(prefix) + p2.second,p.second);
1295         return make_pair(string(prefix) + m_app->getHash(),p.second);
1296     }
1297     
1298     // Shouldn't happen, but just in case..
1299     return make_pair(prefix,defProps);
1300 }
1301
1302 const char* ShibTargetPriv::getHandlerURL(const char* resource) const
1303 {
1304     if (!m_handlerURL.empty())
1305         return m_handlerURL.c_str();
1306
1307     if (!m_app)
1308         throw ConfigurationException("Internal error in ShibTargetPriv::getHandlerURL, missing application pointer.");
1309
1310     bool ssl_only=false;
1311     const char* handler=NULL;
1312     const IPropertySet* props=m_app->getPropertySet("Sessions");
1313     if (props) {
1314         pair<bool,bool> p=props->getBool("handlerSSL");
1315         if (p.first)
1316             ssl_only=p.second;
1317         pair<bool,const char*> p2=props->getString("handlerURL");
1318         if (p2.first)
1319             handler=p2.second;
1320     }
1321     
1322     // Should never happen...
1323     if (!handler || (*handler!='/' && strncmp(handler,"http:",5) && strncmp(handler,"https:",6)))
1324         throw ConfigurationException(
1325             "Invalid handlerURL property ($1) in Application ($2)",
1326             params(2, handler ? handler : "null", m_app->getId())
1327             );
1328
1329     // The "handlerURL" property can be in one of three formats:
1330     //
1331     // 1) a full URI:       http://host/foo/bar
1332     // 2) a hostless URI:   http:///foo/bar
1333     // 3) a relative path:  /foo/bar
1334     //
1335     // #  Protocol  Host        Path
1336     // 1  handler   handler     handler
1337     // 2  handler   resource    handler
1338     // 3  resource  resource    handler
1339     //
1340     // note: if ssl_only is true, make sure the protocol is https
1341
1342     const char* path = NULL;
1343
1344     // Decide whether to use the handler or the resource for the "protocol"
1345     const char* prot;
1346     if (*handler != '/') {
1347         prot = handler;
1348     }
1349     else {
1350         prot = resource;
1351         path = handler;
1352     }
1353
1354     // break apart the "protocol" string into protocol, host, and "the rest"
1355     const char* colon=strchr(prot,':');
1356     colon += 3;
1357     const char* slash=strchr(colon,'/');
1358     if (!path)
1359         path = slash;
1360
1361     // Compute the actual protocol and store in member.
1362     if (ssl_only)
1363         m_handlerURL.assign("https://");
1364     else
1365         m_handlerURL.assign(prot, colon-prot);
1366
1367     // create the "host" from either the colon/slash or from the target string
1368     // If prot == handler then we're in either #1 or #2, else #3.
1369     // If slash == colon then we're in #2.
1370     if (prot != handler || slash == colon) {
1371         colon = strchr(resource, ':');
1372         colon += 3;      // Get past the ://
1373         slash = strchr(colon, '/');
1374     }
1375     string host(colon, slash-colon);
1376
1377     // Build the shire URL
1378     m_handlerURL+=host + path;
1379     return m_handlerURL.c_str();
1380 }
1381
1382 pair<bool,void*> ShibTargetPriv::doSessionInitiator(ShibTarget* st, const IPropertySet* handler, bool isHandler) const
1383 {
1384     string dupresource;
1385     const char* resource=NULL;
1386     const IPropertySet* ACS=NULL;
1387     
1388     if (isHandler) {
1389         // We're running as an actual handler, so check to see if we understand the binding.
1390         pair<bool,const XMLCh*> binding=handler->getXMLString("Binding");
1391         if (binding.first && XMLString::compareString(binding.second,Constants::SHIB_SESSIONINIT_PROFILE_URI))
1392             throw UnsupportedProfileException(
1393                 "Unsupported session initiator binding ($1).", params(1,handler->getString("Binding").second)
1394                 );
1395         
1396         /* 
1397          * Binding is CGI query string with:
1398          *  target      the resource to direct back to later
1399          *  acsIndex    optional index of an ACS to use on the way back in
1400          *  providerId  optional direct invocation of a specific IdP
1401          */
1402         string query=st->getArgs();
1403         CgiParse parser(query.c_str(),query.length());
1404
1405         const char* option=parser.get_value("acsIndex");
1406         if (option)
1407             ACS=m_app->getAssertionConsumerServiceByIndex(atoi(option));
1408         option=parser.get_value("providerId");
1409         
1410         resource=parser.get_value("target");
1411         if (!resource || !*resource) {
1412             pair<bool,const char*> home=m_app->getString("homeURL");
1413             if (home.first)
1414                 resource=home.second;
1415             else
1416                 throw FatalProfileException("Session initiator requires a target parameter or a homeURL application property.");
1417         }
1418         else if (!option) {
1419             dupresource=resource;
1420             resource=dupresource.c_str();
1421         }
1422         
1423         if (option) {
1424             // Here we actually use metadata to invoke the SSO service directly.
1425             // The only currently understood binding is the Shibboleth profile.
1426             Metadata m(m_app->getMetadataProviders());
1427             const IEntityDescriptor* entity=m.lookup(option);
1428             if (!entity)
1429                 throw MetadataException("Session initiator unable to locate metadata for provider ($1).", params(1,option));
1430             const IIDPSSODescriptor* role=entity->getIDPSSODescriptor(saml::XML::SAML11_PROTOCOL_ENUM);
1431             if (!role)
1432                 throw MetadataException(
1433                     "Session initiator unable to locate SAML identity provider role for provider ($1).", params(1,option)
1434                     );
1435             const IEndpointManager* SSO=role->getSingleSignOnServiceManager();
1436             const IEndpoint* ep=SSO->getEndpointByBinding(Constants::SHIB_AUTHNREQUEST_PROFILE_URI);
1437             if (!ep)
1438                 throw MetadataException(
1439                     "Session initiator unable to locate compatible SSO service for provider ($1).", params(1,option)
1440                     );
1441             auto_ptr_char dest(ep->getLocation());
1442             return ShibAuthnRequest(
1443                 st,ACS ? ACS : m_app->getDefaultAssertionConsumerService(),dest.get(),resource,m_app->getString("providerId").second
1444                 );
1445         }
1446     }
1447     else {
1448         // We're running as a "virtual handler" from within the filter.
1449         // The target resource is the current one and everything else is defaulted.
1450         resource=st->m_url.c_str();
1451     }
1452     
1453     if (!ACS) ACS=m_app->getDefaultAssertionConsumerService();
1454     
1455     // For now, we only support external session initiation via a wayfURL
1456     pair<bool,const char*> wayfURL=handler->getString("wayfURL");
1457     if (!wayfURL.first)
1458         throw ConfigurationException("Session initiator is missing wayfURL property.");
1459
1460     pair<bool,const XMLCh*> wayfBinding=handler->getXMLString("wayfBinding");
1461     if (!wayfBinding.first || !XMLString::compareString(wayfBinding.second,Constants::SHIB_AUTHNREQUEST_PROFILE_URI))
1462         // Standard Shib 1.x
1463         return ShibAuthnRequest(st,ACS,wayfURL.second,resource,m_app->getString("providerId").second);
1464     else if (!XMLString::compareString(wayfBinding.second,Constants::SHIB_LEGACY_AUTHNREQUEST_PROFILE_URI))
1465         // Shib pre-1.2
1466         return ShibAuthnRequest(st,ACS,wayfURL.second,resource,NULL);
1467     else if (!strcmp(handler->getString("wayfBinding").second,"urn:mace:shibboleth:1.0:profiles:EAuth")) {
1468         // TODO: Finalize E-Auth profile URI
1469         pair<bool,bool> localRelayState=m_conf->getPropertySet("Local")->getBool("localRelayState");
1470         if (!localRelayState.first || !localRelayState.second)
1471             throw ConfigurationException("Federal E-Authn requests cannot include relay state, so localRelayState must be enabled.");
1472
1473         // Here we store the state in a cookie.
1474         pair<string,const char*> shib_cookie=getCookieNameProps("_shibstate_");
1475         st->setCookie(shib_cookie.first,CgiParse::url_encode(resource) + shib_cookie.second);
1476         return make_pair(true, st->sendRedirect(wayfURL.second));
1477     }
1478    
1479     throw UnsupportedProfileException("Unsupported WAYF binding ($1).", params(1,handler->getString("wayfBinding").second));
1480 }
1481
1482 // Handles Shib 1.x AuthnRequest profile.
1483 pair<bool,void*> ShibTargetPriv::ShibAuthnRequest(
1484     ShibTarget* st,
1485     const IPropertySet* shire,
1486     const char* dest,
1487     const char* target,
1488     const char* providerId
1489     ) const
1490 {
1491     // Compute the ACS URL. We add the ACS location to the handler baseURL.
1492     // Legacy configs will not have an ACS specified, so no suffix will be added.
1493     string ACSloc=getHandlerURL(target);
1494     if (shire) ACSloc+=shire->getString("Location").second;
1495     
1496     char timebuf[16];
1497     sprintf(timebuf,"%u",time(NULL));
1498     string req=string(dest) + "?shire=" + CgiParse::url_encode(ACSloc.c_str()) + "&time=" + timebuf;
1499
1500     // How should the resource value be preserved?
1501     pair<bool,bool> localRelayState=m_conf->getPropertySet("Local")->getBool("localRelayState");
1502     if (!localRelayState.first || !localRelayState.second) {
1503         // The old way, just send it along.
1504         req+="&target=" + CgiParse::url_encode(target);
1505     }
1506     else {
1507         // Here we store the state in a cookie and send a fixed
1508         // value to the IdP so we can recognize it on the way back.
1509         pair<string,const char*> shib_cookie=getCookieNameProps("_shibstate_");
1510         st->setCookie(shib_cookie.first,CgiParse::url_encode(target) + shib_cookie.second);
1511         req+="&target=cookie";
1512     }
1513     
1514     // Only omitted for 1.1 style requests.
1515     if (providerId)
1516         req+="&providerId=" + CgiParse::url_encode(providerId);
1517
1518     return make_pair(true, st->sendRedirect(req));
1519 }
1520
1521 pair<bool,void*> ShibTargetPriv::doAssertionConsumer(ShibTarget* st, const IPropertySet* handler) const
1522 {
1523     int profile=0;
1524     string input,cookie,target,providerId;
1525
1526     // Right now, this only handles SAML 1.1.
1527     pair<bool,const XMLCh*> binding=handler->getXMLString("Binding");
1528     if (!binding.first || !XMLString::compareString(binding.second,SAMLBrowserProfile::BROWSER_POST)) {
1529         if (strcasecmp(st->m_method.c_str(), "POST"))
1530             throw FatalProfileException(
1531                 "SAML 1.1 Browser/POST handler does not support HTTP method ($1).", params(1,st->m_method.c_str())
1532                 );
1533         
1534         if (st->m_content_type.empty() || strcasecmp(st->m_content_type.c_str(),"application/x-www-form-urlencoded"))
1535             throw FatalProfileException(
1536                 "Blocked invalid content-type ($1) submitted to SAML 1.1 Browser/POST handler.", params(1,st->m_content_type.c_str())
1537                 );
1538         input=st->getPostData();
1539         profile|=SAML11_POST;
1540     }
1541     else if (!XMLString::compareString(binding.second,SAMLBrowserProfile::BROWSER_ARTIFACT)) {
1542         if (strcasecmp(st->m_method.c_str(), "GET"))
1543             throw FatalProfileException(
1544                 "SAML 1.1 Browser/Artifact handler does not support HTTP method ($1).", params(1,st->m_method.c_str())
1545                 );
1546         input=st->getArgs();
1547         profile|=SAML11_ARTIFACT;
1548     }
1549     
1550     if (input.empty())
1551         throw FatalProfileException("SAML 1.1 Browser Profile handler received no data from browser.");
1552             
1553     pair<bool,const char*> loc=handler->getString("Location");
1554     st->sessionNew(
1555         profile,
1556         loc.first ? m_handlerURL + loc.second : m_handlerURL,
1557         input.c_str(),
1558         st->m_remote_addr.c_str(),
1559         target,
1560         cookie,
1561         providerId
1562         );
1563
1564     st->log(ShibTarget::LogLevelDebug, string("profile processing succeeded, new session created (") + cookie + ")");
1565
1566     if (target=="default") {
1567         pair<bool,const char*> homeURL=m_app->getString("homeURL");
1568         target=homeURL.first ? homeURL.second : "/";
1569     }
1570     else if (target=="cookie") {
1571         // Pull the target value from the "relay state" cookie.
1572         pair<string,const char*> relay_cookie = getCookieNameProps("_shibstate_");
1573         const char* relay_state = getCookie(st,relay_cookie.first);
1574         if (!relay_state || !*relay_state) {
1575             // No apparent relay state value to use, so fall back on the default.
1576             pair<bool,const char*> homeURL=m_app->getString("homeURL");
1577             target=homeURL.first ? homeURL.second : "/";
1578         }
1579         else {
1580             char* rscopy=strdup(relay_state);
1581             CgiParse::url_decode(rscopy);
1582             target=rscopy;
1583             free(rscopy);
1584         }
1585     }
1586
1587     // We've got a good session, set the session cookie.
1588     pair<string,const char*> shib_cookie=getCookieNameProps("_shibsession_");
1589     st->setCookie(shib_cookie.first, cookie + shib_cookie.second);
1590
1591     const IPropertySet* sessionProps=m_app->getPropertySet("Sessions");
1592     pair<bool,bool> idpHistory=sessionProps->getBool("idpHistory");
1593     if (!idpHistory.first || idpHistory.second) {
1594         // Set an IdP history cookie locally (essentially just a CDC).
1595         CommonDomainCookie cdc(getCookie(st,CommonDomainCookie::CDCName));
1596
1597         // Either leave in memory or set an expiration.
1598         pair<bool,unsigned int> days=sessionProps->getUnsignedInt("idpHistoryDays");
1599             if (!days.first || days.second==0)
1600                 st->setCookie(CommonDomainCookie::CDCName,string(cdc.set(providerId.c_str())) + shib_cookie.second);
1601             else {
1602                 time_t now=time(NULL) + (days.second * 24 * 60 * 60);
1603 #ifdef HAVE_GMTIME_R
1604                 struct tm res;
1605                 struct tm* ptime=gmtime_r(&now,&res);
1606 #else
1607                 struct tm* ptime=gmtime(&now);
1608 #endif
1609                 char timebuf[64];
1610                 strftime(timebuf,64,"%a, %d %b %Y %H:%M:%S GMT",ptime);
1611                 st->setCookie(
1612                     CommonDomainCookie::CDCName,
1613                     string(cdc.set(providerId.c_str())) + shib_cookie.second + "; expires=" + timebuf
1614                     );
1615         }
1616     }
1617
1618     // Now redirect to the target.
1619     return make_pair(true, st->sendRedirect(target));
1620 }
1621
1622 pair<bool,void*> ShibTargetPriv::doLogout(ShibTarget* st, const IPropertySet* handler) const
1623 {
1624     pair<bool,const XMLCh*> binding=handler->getXMLString("Binding");
1625     if (!binding.first || XMLString::compareString(binding.second,Constants::SHIB_LOGOUT_PROFILE_URI)) {
1626         if (!binding.first)
1627             throw UnsupportedProfileException("Missing Logout binding.");
1628         throw UnsupportedProfileException("Unsupported Logout binding ($1).", params(1,handler->getString("Binding").second));
1629     }
1630
1631     // Recover the session key.
1632     pair<string,const char*> shib_cookie = getCookieNameProps("_shibsession_");
1633     const char* session_id = getCookie(st,shib_cookie.first);
1634     
1635     // Logout is best effort.
1636     if (session_id && *session_id) {
1637         try {
1638             st->sessionEnd(session_id);
1639         }
1640         catch (SAMLException& e) {
1641             st->log(ShibTarget::LogLevelError, string("logout processing failed with exception: ") + e.what());
1642         }
1643 #ifndef _DEBUG
1644         catch (...) {
1645             st->log(ShibTarget::LogLevelError, "logout processing failed with unknown exception");
1646         }
1647 #endif
1648         st->setCookie(shib_cookie.first,"");
1649     }
1650     
1651     string query=st->getArgs();
1652     CgiParse parser(query.c_str(),query.length());
1653
1654     const char* ret=parser.get_value("return");
1655     if (!ret)
1656         ret=handler->getString("ResponseLocation").second;
1657     if (!ret)
1658         ret=m_app->getString("homeURL").second;
1659     if (!ret)
1660         ret="/";
1661     return make_pair(true, st->sendRedirect(ret));
1662 }
1663
1664 /*************************************************************************
1665  * CGI Parser implementation
1666  */
1667
1668 CgiParse::CgiParse(const char* data, unsigned int len)
1669 {
1670     const char* pch = data;
1671     unsigned int cl = len;
1672         
1673     while (cl && pch) {
1674         char *name;
1675         char *value;
1676         value=fmakeword('&',&cl,&pch);
1677         plustospace(value);
1678         url_decode(value);
1679         name=makeword(value,'=');
1680         kvp_map[name]=value;
1681         free(name);
1682     }
1683 }
1684
1685 CgiParse::~CgiParse()
1686 {
1687     for (map<string,char*>::iterator i=kvp_map.begin(); i!=kvp_map.end(); i++)
1688         free(i->second);
1689 }
1690
1691 const char*
1692 CgiParse::get_value(const char* name) const
1693 {
1694     map<string,char*>::const_iterator i=kvp_map.find(name);
1695     if (i==kvp_map.end())
1696         return NULL;
1697     return i->second;
1698 }
1699
1700 /* Parsing routines modified from NCSA source. */
1701 char *
1702 CgiParse::makeword(char *line, char stop)
1703 {
1704     int x = 0,y;
1705     char *word = (char *) malloc(sizeof(char) * (strlen(line) + 1));
1706
1707     for(x=0;((line[x]) && (line[x] != stop));x++)
1708         word[x] = line[x];
1709
1710     word[x] = '\0';
1711     if(line[x])
1712         ++x;
1713     y=0;
1714
1715     while(line[x])
1716       line[y++] = line[x++];
1717     line[y] = '\0';
1718     return word;
1719 }
1720
1721 char *
1722 CgiParse::fmakeword(char stop, unsigned int *cl, const char** ppch)
1723 {
1724     int wsize;
1725     char *word;
1726     int ll;
1727
1728     wsize = 1024;
1729     ll=0;
1730     word = (char *) malloc(sizeof(char) * (wsize + 1));
1731
1732     while(1)
1733     {
1734         word[ll] = *((*ppch)++);
1735         if(ll==wsize-1)
1736         {
1737             word[ll+1] = '\0';
1738             wsize+=1024;
1739             word = (char *)realloc(word,sizeof(char)*(wsize+1));
1740         }
1741         --(*cl);
1742         if((word[ll] == stop) || word[ll] == EOF || (!(*cl)))
1743         {
1744             if(word[ll] != stop)
1745                 ll++;
1746             word[ll] = '\0';
1747             return word;
1748         }
1749         ++ll;
1750     }
1751 }
1752
1753 void
1754 CgiParse::plustospace(char *str)
1755 {
1756     register int x;
1757
1758     for(x=0;str[x];x++)
1759         if(str[x] == '+') str[x] = ' ';
1760 }
1761
1762 char
1763 CgiParse::x2c(char *what)
1764 {
1765     register char digit;
1766
1767     digit = (what[0] >= 'A' ? ((what[0] & 0xdf) - 'A')+10 : (what[0] - '0'));
1768     digit *= 16;
1769     digit += (what[1] >= 'A' ? ((what[1] & 0xdf) - 'A')+10 : (what[1] - '0'));
1770     return(digit);
1771 }
1772
1773 void
1774 CgiParse::url_decode(char *url)
1775 {
1776     register int x,y;
1777
1778     for(x=0,y=0;url[y];++x,++y)
1779     {
1780         if((url[x] = url[y]) == '%')
1781         {
1782             url[x] = x2c(&url[y+1]);
1783             y+=2;
1784         }
1785     }
1786     url[x] = '\0';
1787 }
1788
1789 static inline char hexchar(unsigned short s)
1790 {
1791     return (s<=9) ? ('0' + s) : ('A' + s - 10);
1792 }
1793
1794 string CgiParse::url_encode(const char* s)
1795 {
1796     static char badchars[]="\"\\+<>#%{}|^~[]`;/?:@=&";
1797
1798     string ret;
1799     for (; *s; s++) {
1800         if (strchr(badchars,*s) || *s<=0x1F || *s>=0x7F) {
1801             ret+='%';
1802         ret+=hexchar(*s >> 4);
1803         ret+=hexchar(*s & 0x0F);
1804         }
1805         else
1806             ret+=*s;
1807     }
1808     return ret;
1809 }
1810 // Subclasses may not need to override these particular virtual methods.
1811 string ShibTarget::getAuthType(void)
1812 {
1813   return string("shibboleth");
1814 }
1815 void* ShibTarget::returnDecline(void)
1816 {
1817   return NULL;
1818 }
1819 void* ShibTarget::returnOK(void)
1820 {
1821   return NULL;
1822 }
1823 HTAccessInfo* ShibTarget::getAccessInfo(void)
1824 {
1825   return NULL;
1826 }
1827 HTGroupTable* ShibTarget::getGroupTable(string &user)
1828 {
1829   return NULL;
1830 }
1831
1832 // CDC implementation
1833
1834 const char CommonDomainCookie::CDCName[] = "_saml_idp";
1835
1836 CommonDomainCookie::CommonDomainCookie(const char* cookie) : m_decoded(NULL)
1837 {
1838     if (!cookie)
1839         return;
1840         
1841     // Copy it so we can URL-decode it.
1842     char* b64=strdup(cookie);
1843     CgiParse::url_decode(b64);
1844     
1845     // Now Base64 decode it into the decoded delimited list.
1846     unsigned int len;
1847     m_decoded=Base64::decode(reinterpret_cast<XMLByte*>(b64),&len);
1848     free(b64);
1849     if (!m_decoded) {
1850         Category::getInstance("CommonDomainCookie").warn("cookie does not appear to be base64-encoded");
1851         return;
1852     }
1853     
1854     // Chop it up and save off pointers.
1855     char* ptr=reinterpret_cast<char*>(m_decoded);
1856     while (*ptr) {
1857         while (isspace(*ptr)) ptr++;
1858         m_list.push_back(ptr);
1859         while (*ptr && !isspace(*ptr)) ptr++;
1860         if (*ptr)
1861             *ptr++='\0';
1862     }
1863 }
1864
1865 CommonDomainCookie::~CommonDomainCookie()
1866 {
1867     if (m_decoded)
1868         XMLString::release(&m_decoded);
1869 }
1870
1871 const char* CommonDomainCookie::set(const char* providerId)
1872 {
1873     // First scan the list for this IdP.
1874     for (vector<const char*>::iterator i=m_list.begin(); i!=m_list.end(); i++) {
1875         if (!strcmp(providerId,*i)) {
1876             m_list.erase(i);
1877             break;
1878         }
1879     }
1880     
1881     // Append it to the end, after storing locally.
1882     m_additions.push_back(providerId);
1883     m_list.push_back(m_additions.back().c_str());
1884     
1885     // Now rebuild the delimited list.
1886     string delimited;
1887     for (vector<const char*>::const_iterator j=m_list.begin(); j!=m_list.end(); j++) {
1888         if (!delimited.empty()) delimited += ' ';
1889         delimited += *j;
1890     }
1891     
1892     // Base64 and URL encode it.
1893     unsigned int len;
1894     XMLByte* b64=Base64::encode(reinterpret_cast<const XMLByte*>(delimited.c_str()),delimited.length(),&len);
1895     XMLByte *pos, *pos2;
1896     for (pos=b64, pos2=b64; *pos2; pos2++)
1897         if (isgraph(*pos2))
1898             *pos++=*pos2;
1899     *pos=0;
1900     m_encoded=CgiParse::url_encode(reinterpret_cast<char*>(b64));
1901     XMLString::release(&b64);
1902     return m_encoded.c_str();
1903 }