Handle getting session data properly in the different methods.
[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 <xercesc/util/Base64.hpp>
71
72 #ifndef HAVE_STRCASECMP
73 # define strcasecmp stricmp
74 #endif
75
76 using namespace std;
77 using namespace saml;
78 using namespace shibboleth;
79 using namespace shibtarget;
80 using namespace log4cpp;
81
82 namespace shibtarget {
83   class ShibTargetPriv
84   {
85   public:
86     ShibTargetPriv();
87     ~ShibTargetPriv();
88
89     // Helper functions
90     void get_application(ShibTarget* st, const string& protocol, const string& hostname, int port, const string& uri);
91     void* sendError(ShibTarget* st, const char* page, ShibMLP &mlp);
92     
93     // Handlers do the real Shibboleth work
94     pair<bool,void*> dispatch(
95         ShibTarget* st,
96         const IPropertySet* handler,
97         bool isHandler=true,
98         const char* forceType=NULL
99         ) const;
100
101   private:
102     friend class ShibTarget;
103     IRequestMapper::Settings m_settings;
104     const IApplication *m_app;
105     mutable string m_handlerURL;
106     mutable map<string,string> m_cookieMap;
107
108     ISessionCacheEntry* m_cacheEntry;
109
110     ShibTargetConfig* m_Config;
111
112     IConfig* m_conf;
113     IRequestMapper* m_mapper;
114   };
115 }
116
117
118 /*************************************************************************
119  * Shib Target implementation
120  */
121
122 ShibTarget::ShibTarget(void) : m_priv(NULL)
123 {
124   m_priv = new ShibTargetPriv();
125 }
126
127 ShibTarget::ShibTarget(const IApplication *app) : m_priv(NULL)
128 {
129   m_priv = new ShibTargetPriv();
130   m_priv->m_app = app;
131 }
132
133 ShibTarget::~ShibTarget(void)
134 {
135   if (m_priv) delete m_priv;
136 }
137
138 void ShibTarget::init(
139     const char* protocol,
140     const char* hostname,
141     int port,
142     const char* uri,
143     const char* content_type,
144     const char* remote_addr,
145     const char* method
146     )
147 {
148 #ifdef _DEBUG
149   saml::NDC ndc("init");
150 #endif
151
152   if (m_priv->m_app)
153     throw SAMLException("Request initialization occurred twice!");
154
155   if (method) m_method = method;
156   if (protocol) m_protocol = protocol;
157   if (hostname) m_hostname = hostname;
158   if (uri) m_uri = uri;
159   if (content_type) m_content_type = content_type;
160   if (remote_addr) m_remote_addr = remote_addr;
161   m_port = port;
162   m_priv->m_Config = &ShibTargetConfig::getConfig();
163   m_priv->get_application(this, protocol, hostname, port, uri);
164 }
165
166
167 // These functions implement the server-agnostic shibboleth engine
168 // The web server modules implement a subclass and then call into 
169 // these methods once they instantiate their request object.
170
171 pair<bool,void*> ShibTarget::doCheckAuthN(bool handler)
172 {
173 #ifdef _DEBUG
174     saml::NDC ndc("doCheckAuthN");
175 #endif
176
177     const char* procState = "Request Processing Error";
178     const char* targetURL = m_url.c_str();
179     ShibMLP mlp;
180
181     try {
182         if (!m_priv->m_app)
183             throw ConfigurationException("System uninitialized, application did not supply request information.");
184
185         string hURL = getHandlerURL(targetURL);
186         const char* handlerURL=hURL.c_str();
187         if (!handlerURL)
188             throw ConfigurationException("Cannot determine handler from resource URL, check configuration.");
189
190         // If the request URL contains the handler base URL for this application, either dispatch
191         // directly (mainly Apache 2.0) or just pass back control.
192         if (strstr(targetURL,handlerURL)) {
193             if (handler)
194                 return doHandler();
195             else
196                 return pair<bool,void*>(true, returnOK());
197         }
198
199         // Three settings dictate how to proceed.
200         pair<bool,const char*> authType = m_priv->m_settings.first->getString("authType");
201         pair<bool,bool> requireSession = m_priv->m_settings.first->getBool("requireSession");
202         pair<bool,const char*> requireSessionWith = m_priv->m_settings.first->getString("requireSessionWith");
203
204         // If no session is required AND the AuthType (an Apache-derived concept) isn't shibboleth,
205         // then we ignore this request and consider it unprotected. Apache might lie to us if
206         // ShibBasicHijack is on, but that's up to it.
207         if ((!requireSession.first || !requireSession.second) && !requireSessionWith.first &&
208 #ifdef HAVE_STRCASECMP
209                 (!authType.first || strcasecmp(authType.second,"shibboleth")))
210 #else
211                 (!authType.first || stricmp(authType.second,"shibboleth")))
212 #endif
213             return pair<bool,void*>(true,returnDecline());
214
215         pair<string,const char*> shib_cookie = getCookieNameProps("_shibsession_");
216         const char* session_id = getCookie(shib_cookie.first);
217         if (!session_id || !*session_id) {
218             // No session.  Maybe that's acceptable?
219             if ((!requireSession.first || !requireSession.second) && !requireSessionWith.first)
220                 return pair<bool,void*>(true,returnOK());
221
222             // No cookie, but we require a session. Initiate a new session using the indicated method.
223             procState = "Session Initiator Error";
224             const IPropertySet* initiator=NULL;
225             if (requireSessionWith.first)
226                 initiator=m_priv->m_app->getSessionInitiatorById(requireSessionWith.second);
227             if (!initiator)
228                 initiator=m_priv->m_app->getDefaultSessionInitiator();
229             
230             // Standard handler element, so we dispatch normally.
231             if (initiator)
232                 return m_priv->dispatch(this,initiator,false);
233             else {
234                 // Legacy config support maps the Sessions element to the Shib profile.
235                 auto_ptr_char binding(Constants::SHIB_SESSIONINIT_PROFILE_URI);
236                 return m_priv->dispatch(this, m_priv->m_app->getPropertySet("Sessions"), false, binding.get());
237             }
238         }
239
240         procState = "Session Processing Error";
241         try {
242             // Localized exception throw if the session isn't valid.
243             m_priv->m_conf->getListener()->sessionGet(
244                 m_priv->m_app,
245                 session_id,
246                 m_remote_addr.c_str(),
247                 &m_priv->m_cacheEntry
248                 );
249         }
250         catch (SAMLException& e) {
251             log(LogLevelError, string("session processing failed: ") + e.what());
252
253             // If no session is required, bail now.
254             if ((!requireSession.first || !requireSession.second) && !requireSessionWith.first)
255                 // Has to be OK because DECLINED will just cause Apache
256                 // to fail when it can't locate anything to process the
257                 // AuthType.  No session plus requireSession false means
258                 // do not authenticate the user at this time.
259                 return pair<bool,void*>(true, returnOK());
260
261             // Try and cast down. This should throw an exception if it fails.
262             bool retryable=false;
263             try {
264                 RetryableProfileException& trycast=dynamic_cast<RetryableProfileException&>(e);
265                 retryable=true;
266             }
267             catch (exception&) {
268             }
269             if (retryable) {
270                 // Session is invalid but we can retry -- initiate a new session.
271                 procState = "Session Initiator Error";
272                 const IPropertySet* initiator=NULL;
273                 if (requireSessionWith.first)
274                     initiator=m_priv->m_app->getSessionInitiatorById(requireSessionWith.second);
275                 if (!initiator)
276                     initiator=m_priv->m_app->getDefaultSessionInitiator();
277                 // Standard handler element, so we dispatch normally.
278                 if (initiator)
279                     return m_priv->dispatch(this,initiator,false);
280                 else {
281                     // Legacy config support maps the Sessions element to the Shib profile.
282                     auto_ptr_char binding(Constants::SHIB_SESSIONINIT_PROFILE_URI);
283                     return m_priv->dispatch(this, m_priv->m_app->getPropertySet("Sessions"), false, binding.get());
284                 }
285             }
286             throw;    // send it to the outer handler
287         }
288
289         // We're done.  Everything is okay.  Nothing to report.  Nothing to do..
290         // Let the caller decide how to proceed.
291         log(LogLevelDebug, "doCheckAuthN succeeded");
292         return pair<bool,void*>(false,NULL);
293     }
294     catch (SAMLException& e) {
295         mlp.insert(e);
296     }
297 #ifndef _DEBUG
298     catch (...) {
299         mlp.insert("errorText", "Caught an unknown exception.");
300     }
301 #endif
302
303     // If we get here then we've got an error.
304     mlp.insert("errorType", procState);
305     if (targetURL)
306         mlp.insert("requestURL", m_url.substr(0,m_url.find('?')));
307
308     return pair<bool,void*>(true,m_priv->sendError(this,"session", mlp));
309 }
310
311 pair<bool,void*> ShibTarget::doHandler(void)
312 {
313 #ifdef _DEBUG
314     saml::NDC ndc("doHandler");
315 #endif
316
317     const char* procState = "Shibboleth Handler Error";
318     const char* targetURL = m_url.c_str();
319     ShibMLP mlp;
320
321     try {
322         if (!m_priv->m_app)
323             throw ConfigurationException("System uninitialized, application did not supply request information.");
324
325         string hURL = getHandlerURL(targetURL);
326         const char* handlerURL=hURL.c_str();
327         if (!handlerURL)
328             throw ConfigurationException("Cannot determine handler from resource URL, check configuration.");
329
330         // Make sure we only process handler requests.
331         if (!strstr(targetURL,handlerURL))
332             return pair<bool,void*>(true, returnDecline());
333
334         const IPropertySet* sessionProps=m_priv->m_app->getPropertySet("Sessions");
335         if (!sessionProps)
336             throw ConfigurationException("Unable to map request to application session settings, check configuration.");
337
338         // Process incoming request.
339         pair<bool,bool> handlerSSL=sessionProps->getBool("handlerSSL");
340       
341         // Make sure this is SSL, if it should be
342         if ((!handlerSSL.first || handlerSSL.second) && m_protocol != "https")
343             throw FatalProfileException("Blocked non-SSL access to Shibboleth handler.");
344
345         // We dispatch based on our path info. We know the request URL begins with or equals the handler URL,
346         // so the path info is the next character (or null).
347         const IPropertySet* handler=m_priv->m_app->getHandlerConfig(targetURL + strlen(handlerURL));
348         if (handler) {
349             if (saml::XML::isElementNamed(handler->getElement(),shibtarget::XML::SAML2META_NS,SHIBT_L(AssertionConsumerService))) {
350                 procState = "Session Creation Error";
351                 return m_priv->dispatch(this,handler);
352             }
353             else if (saml::XML::isElementNamed(handler->getElement(),shibtarget::XML::SHIBTARGET_NS,SHIBT_L(SessionInitiator))) {
354                 procState = "Session Initiator Error";
355                 return m_priv->dispatch(this,handler);
356             }
357             else if (saml::XML::isElementNamed(handler->getElement(),shibtarget::XML::SAML2META_NS,SHIBT_L(SingleLogoutService))) {
358                 procState = "Session Termination Error";
359                 return m_priv->dispatch(this,handler);
360             }
361             else if (saml::XML::isElementNamed(handler->getElement(),shibtarget::XML::SHIBTARGET_NS,SHIBT_L(DiagnosticService))) {
362                 procState = "Diagnostics Error";
363                 return m_priv->dispatch(this,handler);
364             }
365             else {
366                 procState = "Extension Service Error";
367                 return m_priv->dispatch(this,handler);
368             }
369         }
370         
371         if (strlen(targetURL)>strlen(handlerURL) && targetURL[strlen(handlerURL)]!='?')
372             throw SAMLException("Shibboleth handler invoked at an unconfigured location.");
373         
374         // This is a legacy direct execution of the handler (the old shireURL).
375         // If this is a GET, we see if it's a lazy session request, otherwise
376         // assume it's a SAML 1.x POST profile response and process it.
377         if (!strcasecmp(m_method.c_str(), "GET")) {
378             procState = "Session Initiator Error";
379             auto_ptr_char binding(Constants::SHIB_SESSIONINIT_PROFILE_URI);
380             return m_priv->dispatch(this, sessionProps, true, binding.get());
381         }
382         
383         procState = "Session Creation Error";
384         auto_ptr_char binding(SAMLBrowserProfile::BROWSER_POST);
385         return m_priv->dispatch(this, sessionProps, true, binding.get());
386     }
387     catch (MetadataException& e) {
388         mlp.insert(e);
389         // See if a metadata error page is installed.
390         const IPropertySet* props=m_priv->m_app->getPropertySet("Errors");
391         if (props) {
392             pair<bool,const char*> p=props->getString("metadata");
393             if (p.first) {
394                 mlp.insert("errorType", procState);
395                 if (targetURL)
396                     mlp.insert("requestURL", targetURL);
397                 return make_pair(true,m_priv->sendError(this,"metadata", mlp));
398             }
399         }
400     }
401     catch (SAMLException& e) {
402         mlp.insert(e);
403     }
404 #ifndef _DEBUG
405     catch (...) {
406         mlp.insert("errorText", "Caught an unknown exception.");
407     }
408 #endif
409
410     // If we get here then we've got an error.
411     mlp.insert("errorType", procState);
412
413     if (targetURL)
414         mlp.insert("requestURL", m_url.substr(0,m_url.find('?')));
415
416     return make_pair(true,m_priv->sendError(this,"session", mlp));
417 }
418
419 pair<bool,void*> ShibTarget::doCheckAuthZ(void)
420 {
421 #ifdef _DEBUG
422     saml::NDC ndc("doCheckAuthZ");
423 #endif
424
425     ShibMLP mlp;
426     const char* procState = "Authorization Processing Error";
427     const char* targetURL = m_url.c_str();
428
429     try {
430         if (!m_priv->m_app)
431             throw ConfigurationException("System uninitialized, application did not supply request information.");
432
433         // Three settings dictate how to proceed.
434         pair<bool,const char*> authType = m_priv->m_settings.first->getString("authType");
435         pair<bool,bool> requireSession = m_priv->m_settings.first->getBool("requireSession");
436         pair<bool,const char*> requireSessionWith = m_priv->m_settings.first->getString("requireSessionWith");
437
438         // If no session is required AND the AuthType (an Apache-derived concept) isn't shibboleth,
439         // then we ignore this request and consider it unprotected. Apache might lie to us if
440         // ShibBasicHijack is on, but that's up to it.
441         if ((!requireSession.first || !requireSession.second) && !requireSessionWith.first &&
442 #ifdef HAVE_STRCASECMP
443                 (!authType.first || strcasecmp(authType.second,"shibboleth")))
444 #else
445                 (!authType.first || stricmp(authType.second,"shibboleth")))
446 #endif
447             return pair<bool,void*>(true,returnDecline());
448
449         // Do we have an access control plugin?
450         if (m_priv->m_settings.second) {
451                 
452                 if (!m_priv->m_cacheEntry) {
453                     // No data yet, so we may need to try and get the session.
454                         pair<string,const char*> shib_cookie=getCookieNameProps("_shibsession_");
455                         const char *session_id = getCookie(shib_cookie.first);
456                     try {
457                                 if (session_id && *session_id) {
458                                     m_priv->m_conf->getListener()->sessionGet(
459                                         m_priv->m_app,
460                                         session_id,
461                                         m_remote_addr.c_str(),
462                                         &m_priv->m_cacheEntry
463                                         );
464                                 }
465                     }
466                     catch (SAMLException&) {
467                         log(LogLevelError, "doCheckAuthZ: unable to obtain session information to pass to access control provider");
468                     }
469                 }
470         
471             Locker acllock(m_priv->m_settings.second);
472             if (m_priv->m_settings.second->authorized(this,m_priv->m_cacheEntry)) {
473                 // Let the caller decide how to proceed.
474                 log(LogLevelDebug, "doCheckAuthZ: access control provider granted access");
475                 return pair<bool,void*>(false,NULL);
476             }
477             else {
478                 log(LogLevelWarn, "doCheckAuthZ: access control provider denied access");
479                 if (targetURL)
480                     mlp.insert("requestURL", targetURL);
481                 return make_pair(true,m_priv->sendError(this, "access", mlp));
482             }
483         }
484         else
485             return make_pair(true,returnDecline());
486     }
487     catch (SAMLException& e) {
488         mlp.insert(e);
489     }
490 #ifndef _DEBUG
491     catch (...) {
492         mlp.insert("errorText", "Caught an unknown exception.");
493     }
494 #endif
495
496     // If we get here then we've got an error.
497     mlp.insert("errorType", procState);
498
499     if (targetURL)
500         mlp.insert("requestURL", m_url.substr(0,m_url.find('?')));
501
502     return make_pair(true,m_priv->sendError(this, "access", mlp));
503 }
504
505 pair<bool,void*> ShibTarget::doExportAssertions(bool requireSession)
506 {
507 #ifdef _DEBUG
508     saml::NDC ndc("doExportAssertions");
509 #endif
510
511     ShibMLP mlp;
512     const char* procState = "Attribute Processing Error";
513     const char* targetURL = m_url.c_str();
514
515     try {
516         if (!m_priv->m_app)
517             throw ConfigurationException("System uninitialized, application did not supply request information.");
518
519         if (!m_priv->m_cacheEntry) {
520             // No data yet, so we need to get the session. This can only happen
521             // if the call to doCheckAuthn doesn't happen in the same object lifetime.
522                 pair<string,const char*> shib_cookie=getCookieNameProps("_shibsession_");
523                 const char *session_id = getCookie(shib_cookie.first);
524             try {
525                         if (session_id && *session_id) {
526                             m_priv->m_conf->getListener()->sessionGet(
527                                 m_priv->m_app,
528                                 session_id,
529                                 m_remote_addr.c_str(),
530                                 &m_priv->m_cacheEntry
531                                 );
532                         }
533             }
534             catch (SAMLException&) {
535                 log(LogLevelError, "unable to obtain session information to export into request headers");
536                 // If we have to have a session, then this is a fatal error.
537                 if (requireSession)
538                         throw;
539             }
540         }
541
542                 // Still no data?
543         if (!m_priv->m_cacheEntry) {
544                 if (requireSession)
545                         throw InvalidSessionException("Unable to obtain session information for request.");
546                 else
547                         return pair<bool,void*>(false,NULL);    // just bail silently
548         }
549
550         // Get the AAP providers, which contain the attribute policy info.
551         Iterator<IAAP*> provs=m_priv->m_app->getAAPProviders();
552
553         // Clear out the list of mapped attributes
554         while (provs.hasNext()) {
555             IAAP* aap=provs.next();
556             Locker locker(aap);
557             Iterator<const IAttributeRule*> rules=aap->getAttributeRules();
558             while (rules.hasNext()) {
559                 const char* header=rules.next()->getHeader();
560                 if (header)
561                     clearHeader(header);
562             }
563         }
564         
565         ISessionCacheEntry::CachedResponse cr=m_priv->m_cacheEntry->getResponse();
566
567         // Maybe export the response.
568         clearHeader("Shib-Attributes");
569         pair<bool,bool> exp=m_priv->m_settings.first->getBool("exportAssertion");
570         if (exp.first && exp.second && cr.unfiltered) {
571             ostringstream os;
572             os << *cr.unfiltered;
573             unsigned int outlen;
574             XMLByte* serialized = Base64::encode(reinterpret_cast<XMLByte*>((char*)os.str().c_str()), os.str().length(), &outlen);
575             XMLByte *pos, *pos2;
576             for (pos=serialized, pos2=serialized; *pos2; pos2++)
577                 if (isgraph(*pos2))
578                     *pos++=*pos2;
579             *pos=0;
580             setHeader("Shib-Attributes", reinterpret_cast<char*>(serialized));
581             XMLString::release(&serialized);
582         }
583     
584         // Export the SAML AuthnMethod and the origin site name, and possibly the NameIdentifier.
585         clearHeader("Shib-Origin-Site");
586         clearHeader("Shib-Identity-Provider");
587         clearHeader("Shib-Authentication-Method");
588         clearHeader("Shib-NameIdentifier-Format");
589         setHeader("Shib-Origin-Site", m_priv->m_cacheEntry->getProviderId());
590         setHeader("Shib-Identity-Provider", m_priv->m_cacheEntry->getProviderId());
591         auto_ptr_char am(m_priv->m_cacheEntry->getAuthnStatement()->getAuthMethod());
592         setHeader("Shib-Authentication-Method", am.get());
593         
594         // Export NameID?
595         provs.reset();
596         while (provs.hasNext()) {
597             IAAP* aap=provs.next();
598             Locker locker(aap);
599             const IAttributeRule* rule=aap->lookup(
600                 m_priv->m_cacheEntry->getAuthnStatement()->getSubject()->getNameIdentifier()->getFormat()
601                 );
602             if (rule && rule->getHeader()) {
603                 auto_ptr_char form(m_priv->m_cacheEntry->getAuthnStatement()->getSubject()->getNameIdentifier()->getFormat());
604                 auto_ptr_char nameid(m_priv->m_cacheEntry->getAuthnStatement()->getSubject()->getNameIdentifier()->getName());
605                 setHeader("Shib-NameIdentifier-Format", form.get());
606                 if (!strcmp(rule->getHeader(),"REMOTE_USER"))
607                     setRemoteUser(nameid.get());
608                 else
609                     setHeader(rule->getHeader(), nameid.get());
610             }
611         }
612         
613         clearHeader("Shib-Application-ID");
614         setHeader("Shib-Application-ID", m_priv->m_app->getId());
615     
616         // Export the attributes.
617         Iterator<SAMLAssertion*> a_iter(cr.filtered ? cr.filtered->getAssertions() : EMPTY(SAMLAssertion*));
618         while (a_iter.hasNext()) {
619             SAMLAssertion* assert=a_iter.next();
620             Iterator<SAMLStatement*> statements=assert->getStatements();
621             while (statements.hasNext()) {
622                 SAMLAttributeStatement* astate=dynamic_cast<SAMLAttributeStatement*>(statements.next());
623                 if (!astate)
624                     continue;
625                 Iterator<SAMLAttribute*> attrs=astate->getAttributes();
626                 while (attrs.hasNext()) {
627                     SAMLAttribute* attr=attrs.next();
628             
629                     // Are we supposed to export it?
630                     provs.reset();
631                     while (provs.hasNext()) {
632                         IAAP* aap=provs.next();
633                         Locker locker(aap);
634                         const IAttributeRule* rule=aap->lookup(attr->getName(),attr->getNamespace());
635                         if (!rule || !rule->getHeader())
636                             continue;
637                     
638                         Iterator<string> vals=attr->getSingleByteValues();
639                         if (!strcmp(rule->getHeader(),"REMOTE_USER") && vals.hasNext())
640                             setRemoteUser(vals.next());
641                         else {
642                             int it=0;
643                             string header = getHeader(rule->getHeader());
644                             if (!header.empty())
645                                 it++;
646                             for (; vals.hasNext(); it++) {
647                                 string value = vals.next();
648                                 for (string::size_type pos = value.find_first_of(";", string::size_type(0));
649                                         pos != string::npos;
650                                         pos = value.find_first_of(";", pos)) {
651                                     value.insert(pos, "\\");
652                                     pos += 2;
653                                 }
654                                 if (it)
655                                     header += ";";
656                                 header += value;
657                             }
658                             setHeader(rule->getHeader(), header);
659                         }
660                     }
661                 }
662             }
663         }
664     
665         return pair<bool,void*>(false,NULL);
666     }
667     catch (SAMLException& e) {
668         mlp.insert(e);
669     }
670 #ifndef _DEBUG
671     catch (...) {
672         mlp.insert("errorText", "Caught an unknown exception.");
673     }
674 #endif
675
676     // If we get here then we've got an error.
677     mlp.insert("errorType", procState);
678
679     if (targetURL)
680         mlp.insert("requestURL", m_url.substr(0,m_url.find('?')));
681
682     return make_pair(true,m_priv->sendError(this, "rm", mlp));
683 }
684
685 const char* ShibTarget::getCookie(const string& name) const
686 {
687     if (m_priv->m_cookieMap.empty()) {
688         string cookies=getCookies();
689
690         string::size_type pos=0,cname,namelen,val,vallen;
691         while (pos !=string::npos && pos < cookies.length()) {
692             while (isspace(cookies[pos])) pos++;
693             cname=pos;
694             pos=cookies.find_first_of("=",pos);
695             if (pos == string::npos)
696                 break;
697             namelen=pos-cname;
698             pos++;
699             if (pos==cookies.length())
700                 break;
701             val=pos;
702             pos=cookies.find_first_of(";",pos);
703             if (pos != string::npos) {
704                 vallen=pos-val;
705                 pos++;
706                 m_priv->m_cookieMap.insert(make_pair(cookies.substr(cname,namelen),cookies.substr(val,vallen)));
707             }
708             else
709                 m_priv->m_cookieMap.insert(make_pair(cookies.substr(cname,namelen),cookies.substr(val)));
710         }
711     }
712     map<string,string>::const_iterator lookup=m_priv->m_cookieMap.find(name);
713     return (lookup==m_priv->m_cookieMap.end()) ? NULL : lookup->second.c_str();
714 }
715
716 pair<string,const char*> ShibTarget::getCookieNameProps(const char* prefix) const
717 {
718     static const char* defProps="; path=/";
719     
720     const IPropertySet* props=m_priv->m_app ? m_priv->m_app->getPropertySet("Sessions") : NULL;
721     if (props) {
722         pair<bool,const char*> p=props->getString("cookieProps");
723         if (!p.first)
724             p.second=defProps;
725         pair<bool,const char*> p2=props->getString("cookieName");
726         if (p2.first)
727             return make_pair(string(prefix) + p2.second,p.second);
728         return make_pair(string(prefix) + m_priv->m_app->getHash(),p.second);
729     }
730     
731     // Shouldn't happen, but just in case..
732     return make_pair(prefix,defProps);
733 }
734
735 string ShibTarget::getHandlerURL(const char* resource) const
736 {
737     if (!m_priv->m_handlerURL.empty() && resource && !strcmp(getRequestURL(),resource))
738         return m_priv->m_handlerURL;
739         
740     if (!m_priv->m_app)
741         throw ConfigurationException("Internal error in ShibTargetPriv::getHandlerURL, missing application pointer.");
742
743     bool ssl_only=false;
744     const char* handler=NULL;
745     const IPropertySet* props=m_priv->m_app->getPropertySet("Sessions");
746     if (props) {
747         pair<bool,bool> p=props->getBool("handlerSSL");
748         if (p.first)
749             ssl_only=p.second;
750         pair<bool,const char*> p2=props->getString("handlerURL");
751         if (p2.first)
752             handler=p2.second;
753     }
754     
755     // Should never happen...
756     if (!handler || (*handler!='/' && strncmp(handler,"http:",5) && strncmp(handler,"https:",6)))
757         throw ConfigurationException(
758             "Invalid handlerURL property ($1) in Application ($2)",
759             params(2, handler ? handler : "null", m_priv->m_app->getId())
760             );
761
762     // The "handlerURL" property can be in one of three formats:
763     //
764     // 1) a full URI:       http://host/foo/bar
765     // 2) a hostless URI:   http:///foo/bar
766     // 3) a relative path:  /foo/bar
767     //
768     // #  Protocol  Host        Path
769     // 1  handler   handler     handler
770     // 2  handler   resource    handler
771     // 3  resource  resource    handler
772     //
773     // note: if ssl_only is true, make sure the protocol is https
774
775     const char* path = NULL;
776
777     // Decide whether to use the handler or the resource for the "protocol"
778     const char* prot;
779     if (*handler != '/') {
780         prot = handler;
781     }
782     else {
783         prot = resource;
784         path = handler;
785     }
786
787     // break apart the "protocol" string into protocol, host, and "the rest"
788     const char* colon=strchr(prot,':');
789     colon += 3;
790     const char* slash=strchr(colon,'/');
791     if (!path)
792         path = slash;
793
794     // Compute the actual protocol and store in member.
795     if (ssl_only)
796         m_priv->m_handlerURL.assign("https://");
797     else
798         m_priv->m_handlerURL.assign(prot, colon-prot);
799
800     // create the "host" from either the colon/slash or from the target string
801     // If prot == handler then we're in either #1 or #2, else #3.
802     // If slash == colon then we're in #2.
803     if (prot != handler || slash == colon) {
804         colon = strchr(resource, ':');
805         colon += 3;      // Get past the ://
806         slash = strchr(colon, '/');
807     }
808     string host(colon, slash-colon);
809
810     // Build the handler URL
811     m_priv->m_handlerURL+=host + path;
812     return m_priv->m_handlerURL;
813 }
814
815 void ShibTarget::log(ShibLogLevel level, const string& msg)
816 {
817     Category::getInstance("shibtarget.ShibTarget").log(
818         (level == LogLevelDebug ? Priority::DEBUG :
819         (level == LogLevelInfo ? Priority::INFO :
820         (level == LogLevelWarn ? Priority::WARN : Priority::ERROR))),
821         msg
822     );
823 }
824
825 const IApplication* ShibTarget::getApplication() const
826 {
827     return m_priv->m_app;
828 }
829
830 const IConfig* ShibTarget::getConfig() const
831 {
832     return m_priv->m_conf;
833 }
834
835 void* ShibTarget::returnDecline(void)
836 {
837     return NULL;
838 }
839
840 void* ShibTarget::returnOK(void)
841 {
842     return NULL;
843 }
844
845
846 /*************************************************************************
847  * Shib Target Private implementation
848  */
849
850 ShibTargetPriv::ShibTargetPriv() : m_app(NULL), m_mapper(NULL), m_conf(NULL), m_Config(NULL), m_cacheEntry(NULL) {}
851
852 ShibTargetPriv::~ShibTargetPriv()
853 {
854     if (m_cacheEntry) {
855         m_cacheEntry->unlock();
856         m_cacheEntry = NULL;
857     }
858
859     if (m_mapper) {
860         m_mapper->unlock();
861         m_mapper = NULL;
862     }
863     
864     if (m_conf) {
865         m_conf->unlock();
866         m_conf = NULL;
867     }
868
869     m_app = NULL;
870     m_Config = NULL;
871 }
872
873 void ShibTargetPriv::get_application(ShibTarget* st, const string& protocol, const string& hostname, int port, const string& uri)
874 {
875   if (m_app)
876     return;
877
878   // XXX: Do we need to keep conf and mapper locked while we hold m_app?
879   // TODO: No, should be able to hold the conf but release the mapper.
880
881   // We lock the configuration system for the duration.
882   m_conf=m_Config->getINI();
883   m_conf->lock();
884     
885   // Map request to application and content settings.
886   m_mapper=m_conf->getRequestMapper();
887   m_mapper->lock();
888
889   // Obtain the application settings from the parsed URL
890   m_settings = m_mapper->getSettings(st);
891
892   // Now find the application from the URL settings
893   pair<bool,const char*> application_id=m_settings.first->getString("applicationId");
894   m_app=m_conf->getApplication(application_id.second);
895   if (!m_app) {
896     m_mapper->unlock();
897     m_mapper = NULL;
898     m_conf->unlock();
899     m_conf = NULL;
900     throw ConfigurationException("Unable to map request to application settings, check configuration.");
901   }
902
903   // Compute the full target URL
904   st->m_url = protocol + "://" + hostname;
905   if ((protocol == "http" && port != 80) || (protocol == "https" && port != 443))
906     st->m_url += ":" + port;
907   st->m_url += uri;
908 }
909
910 void* ShibTargetPriv::sendError(ShibTarget* st, const char* page, ShibMLP &mlp)
911 {
912     ShibTarget::header_t hdrs[] = {
913         ShibTarget::header_t("Expires","01-Jan-1997 12:00:00 GMT"),
914         ShibTarget::header_t("Cache-Control","private,no-store,no-cache")
915         };
916     
917     const IPropertySet* props=m_app->getPropertySet("Errors");
918     if (props) {
919         pair<bool,const char*> p=props->getString(page);
920         if (p.first) {
921             ifstream infile(p.second);
922             if (!infile.fail()) {
923                 const char* res = mlp.run(infile,props);
924                 if (res)
925                     return st->sendPage(res, 200, "text/html", ArrayIterator<ShibTarget::header_t>(hdrs,2));
926             }
927         }
928         else if (!strcmp(page,"access"))
929             return st->sendPage("Access Denied", 403, "text/html", ArrayIterator<ShibTarget::header_t>(hdrs,2));
930     }
931
932     string errstr = string("sendError could not process error template (") + page + ") for application (";
933     errstr += m_app->getId();
934     errstr += ")";
935     st->log(ShibTarget::LogLevelError, errstr);
936     return st->sendPage(
937         "Internal Server Error. Please contact the site administrator.", 500, "text/html", ArrayIterator<ShibTarget::header_t>(hdrs,2)
938         );
939 }
940
941 pair<bool,void*> ShibTargetPriv::dispatch(
942     ShibTarget* st,
943     const IPropertySet* config,
944     bool isHandler,
945     const char* forceType
946     ) const
947 {
948     pair<bool,const char*> binding=forceType ? make_pair(true,forceType) : config->getString("Binding");
949     if (binding.first) {
950         auto_ptr<IPlugIn> plugin(SAMLConfig::getConfig().getPlugMgr().newPlugin(binding.second,config->getElement()));
951         IHandler* handler=dynamic_cast<IHandler*>(plugin.get());
952         if (!handler)
953             throw UnsupportedProfileException(
954                 "Plugin for binding ($1) does not implement IHandler interface.",params(1,binding.second)
955                 );
956         return handler->run(st,config,isHandler);
957     }
958     throw UnsupportedProfileException("Handler element is missing Binding attribute to determine what handler to run.");
959 }