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