e441e3cc661b18b0f8bde6783350276c8381391e
[shibboleth/cpp-sp.git] / shibsp / ServiceProvider.cpp
1 /*
2  *  Copyright 2001-2007 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  * ServiceProvider.cpp
19  * 
20  * Interface to a Shibboleth ServiceProvider instance.
21  */
22
23 #include "internal.h"
24 #include "exceptions.h"
25 #include "AccessControl.h"
26 #include "Application.h"
27 #include "ServiceProvider.h"
28 #include "SessionCache.h"
29 #include "SPRequest.h"
30 #include "attribute/Attribute.h"
31 #include "handler/SessionInitiator.h"
32 #include "util/TemplateParameters.h"
33
34 #include <fstream>
35 #include <sstream>
36 #include <xmltooling/XMLToolingConfig.h>
37 #include <xmltooling/util/NDC.h>
38 #include <xmltooling/util/URLEncoder.h>
39 #include <xmltooling/util/XMLHelper.h>
40
41 using namespace shibsp;
42 using namespace xmltooling;
43 using namespace std;
44
45 namespace shibsp {
46     SHIBSP_DLLLOCAL PluginManager<ServiceProvider,string,const DOMElement*>::Factory XMLServiceProviderFactory;
47
48     long SHIBSP_DLLLOCAL sendError(SPRequest& request, const Application* app, const char* page, TemplateParameters& tp, bool mayRedirect=true)
49     {
50         // The properties we need can be set in the RequestMap, or the Errors element.
51         bool mderror = dynamic_cast<const opensaml::saml2md::MetadataException*>(tp.getRichException())!=NULL;
52         pair<bool,const char*> redirectErrors = pair<bool,const char*>(false,NULL);
53         pair<bool,const char*> pathname = pair<bool,const char*>(false,NULL);
54         const PropertySet* props=app ? app->getPropertySet("Errors") : NULL;
55
56         try {
57             RequestMapper::Settings settings = request.getRequestSettings();
58             if (mderror)
59                 pathname = settings.first->getString("metadataError");
60             if (!pathname.first) {
61                 string pagename(page);
62                 pagename += "Error";
63                 pathname = settings.first->getString(pagename.c_str());
64             }
65             if (mayRedirect)
66                 redirectErrors = settings.first->getString("redirectErrors");
67         }
68         catch (exception& ex) {
69             request.log(SPRequest::SPError, ex.what());
70         }
71
72         if (mayRedirect) {
73             // Check for redirection on errors instead of template.
74             if (!redirectErrors.first && props)
75                 redirectErrors = props->getString("redirectErrors");
76             if (redirectErrors.first) {
77                 string loc(redirectErrors.second);
78                 loc = loc + '?' + tp.toQueryString();
79                 return request.sendRedirect(loc.c_str());
80             }
81         }
82
83         request.setContentType("text/html");
84         request.setResponseHeader("Expires","01-Jan-1997 12:00:00 GMT");
85         request.setResponseHeader("Cache-Control","private,no-store,no-cache");
86     
87         if (!pathname.first && props) {
88             if (mderror)
89                 pathname=props->getString("metadata");
90             if (!pathname.first)
91                 pathname=props->getString(page);
92         }
93         if (pathname.first) {
94             ifstream infile(pathname.second);
95             if (infile) {
96                 tp.setPropertySet(props);
97                 stringstream str;
98                 XMLToolingConfig::getConfig().getTemplateEngine()->run(infile, str, tp, tp.getRichException());
99                 return request.sendResponse(str);
100             }
101         }
102         
103         if (!strcmp(page,"access")) {
104             istringstream msg("Access Denied");
105             return request.sendResponse(msg, HTTPResponse::XMLTOOLING_HTTP_STATUS_UNAUTHORIZED);
106         }
107     
108         string errstr = string("sendError could not process error template (") + page + ")";
109         request.log(SPRequest::SPError, errstr);
110         istringstream msg("Internal Server Error. Please contact the site administrator.");
111         return request.sendError(msg);
112     }
113     
114     void SHIBSP_DLLLOCAL clearHeaders(SPRequest& request) {
115         request.clearHeader("Shib-Session-ID", "HTTP_SHIB_SESSION_ID");
116         request.clearHeader("Shib-Identity-Provider", "HTTP_SHIB_IDENTITY_PROVIDER");
117         request.clearHeader("Shib-Authentication-Method", "HTTP_SHIB_AUTHENTICATION_METHOD");
118         request.clearHeader("Shib-Authentication-Instant", "HTTP_SHIB_AUTHENTICATION_INSTANT");
119         request.clearHeader("Shib-AuthnContext-Class", "HTTP_SHIB_AUTHNCONTEXT_CLASS");
120         request.clearHeader("Shib-AuthnContext-Decl", "HTTP_SHIB_AUTHNCONTEXT_DECL");
121         request.clearHeader("Shib-Assertion-Count", "HTTP_SHIB_ASSERTION_COUNT");
122         request.clearHeader("REMOTE_USER", "HTTP_REMOTE_USER");
123         //request.clearHeader("Shib-Application-ID");   handle inside app method
124         request.getApplication().clearAttributeHeaders(request);
125     }
126 };
127
128 void SHIBSP_API shibsp::registerServiceProviders()
129 {
130     SPConfig::getConfig().ServiceProviderManager.registerFactory(XML_SERVICE_PROVIDER, XMLServiceProviderFactory);
131 }
132
133 pair<bool,long> ServiceProvider::doAuthentication(SPRequest& request, bool handler) const
134 {
135 #ifdef _DEBUG
136     xmltooling::NDC ndc("doAuthentication");
137 #endif
138
139     const Application* app=NULL;
140     string targetURL = request.getRequestURL();
141
142     try {
143         RequestMapper::Settings settings = request.getRequestSettings();
144         app = &(request.getApplication());
145
146         // If not SSL, check to see if we should block or redirect it.
147         if (!request.isSecure()) {
148             pair<bool,const char*> redirectToSSL = settings.first->getString("redirectToSSL");
149             if (redirectToSSL.first) {
150 #ifdef HAVE_STRCASECMP
151                 if (!strcasecmp("GET",request.getMethod()) || !strcasecmp("HEAD",request.getMethod())) {
152 #else
153                 if (!stricmp("GET",request.getMethod()) || !stricmp("HEAD",request.getMethod())) {
154 #endif
155                     // Compute the new target URL
156                     string redirectURL = string("https://") + request.getHostname();
157                     if (strcmp(redirectToSSL.second,"443")) {
158                         redirectURL = redirectURL + ':' + redirectToSSL.second;
159                     }
160                     redirectURL += request.getRequestURI();
161                     return make_pair(true, request.sendRedirect(redirectURL.c_str()));
162                 }
163                 else {
164                     TemplateParameters tp;
165                     tp.m_map["requestURL"] = targetURL.substr(0,targetURL.find('?'));
166                     return make_pair(true,sendError(request, app, "ssl", tp, false));
167                 }
168             }
169         }
170         
171         const char* handlerURL=request.getHandlerURL(targetURL.c_str());
172         if (!handlerURL)
173             throw ConfigurationException("Cannot determine handler from resource URL, check configuration.");
174
175         // If the request URL contains the handler base URL for this application, either dispatch
176         // directly (mainly Apache 2.0) or just pass back control.
177         if (strstr(targetURL.c_str(),handlerURL)) {
178             if (handler)
179                 return doHandler(request);
180             else
181                 return make_pair(true, request.returnOK());
182         }
183
184         // Three settings dictate how to proceed.
185         pair<bool,const char*> authType = settings.first->getString("authType");
186         pair<bool,bool> requireSession = settings.first->getBool("requireSession");
187         pair<bool,const char*> requireSessionWith = settings.first->getString("requireSessionWith");
188
189         // If no session is required AND the AuthType (an Apache-derived concept) isn't shibboleth,
190         // then we ignore this request and consider it unprotected. Apache might lie to us if
191         // ShibBasicHijack is on, but that's up to it.
192         if ((!requireSession.first || !requireSession.second) && !requireSessionWith.first &&
193 #ifdef HAVE_STRCASECMP
194                 (!authType.first || strcasecmp(authType.second,"shibboleth")))
195 #else
196                 (!authType.first || _stricmp(authType.second,"shibboleth")))
197 #endif
198             return make_pair(true,request.returnDecline());
199
200         // Fix for secadv 20050901
201         clearHeaders(request);
202
203         Session* session = NULL;
204         try {
205             session = request.getSession();
206         }
207         catch (exception& e) {
208             request.log(SPRequest::SPWarn, string("error during session lookup: ") + e.what());
209             // If it's not a retryable session failure, we throw to the outer handler for reporting.
210             if (dynamic_cast<opensaml::RetryableProfileException*>(&e)==NULL)
211                 throw;
212         }
213
214         if (!session) {
215             // No session.  Maybe that's acceptable?
216             if ((!requireSession.first || !requireSession.second) && !requireSessionWith.first)
217                 return make_pair(true,request.returnOK());
218
219             // No session, but we require one. Initiate a new session using the indicated method.
220             const Handler* initiator=NULL;
221             if (requireSessionWith.first) {
222                 initiator=app->getSessionInitiatorById(requireSessionWith.second);
223                 if (!initiator)
224                     throw ConfigurationException(
225                         "No session initiator found with id ($1), check requireSessionWith command.",
226                         params(1,requireSessionWith.second)
227                         );
228             }
229             else {
230                 initiator=app->getDefaultSessionInitiator();
231                 if (!initiator)
232                     throw ConfigurationException("No default session initiator found, check configuration.");
233             }
234
235             return initiator->run(request,false);
236         }
237
238         // We're done.  Everything is okay.  Nothing to report.  Nothing to do..
239         // Let the caller decide how to proceed.
240         request.log(SPRequest::SPDebug, "doAuthentication succeeded");
241         return make_pair(false,0L);
242     }
243     catch (exception& e) {
244         TemplateParameters tp(&e);
245         tp.m_map["requestURL"] = targetURL.substr(0,targetURL.find('?'));
246         return make_pair(true,sendError(request, app, "session", tp));
247     }
248 }
249
250 pair<bool,long> ServiceProvider::doAuthorization(SPRequest& request) const
251 {
252 #ifdef _DEBUG
253     xmltooling::NDC ndc("doAuthorization");
254 #endif
255
256     const Application* app=NULL;
257     string targetURL = request.getRequestURL();
258
259     try {
260         RequestMapper::Settings settings = request.getRequestSettings();
261         app = &(request.getApplication());
262
263         // Three settings dictate how to proceed.
264         pair<bool,const char*> authType = settings.first->getString("authType");
265         pair<bool,bool> requireSession = settings.first->getBool("requireSession");
266         pair<bool,const char*> requireSessionWith = settings.first->getString("requireSessionWith");
267
268         // If no session is required AND the AuthType (an Apache-derived concept) isn't shibboleth,
269         // then we ignore this request and consider it unprotected. Apache might lie to us if
270         // ShibBasicHijack is on, but that's up to it.
271         if ((!requireSession.first || !requireSession.second) && !requireSessionWith.first &&
272 #ifdef HAVE_STRCASECMP
273                 (!authType.first || strcasecmp(authType.second,"shibboleth")))
274 #else
275                 (!authType.first || _stricmp(authType.second,"shibboleth")))
276 #endif
277             return make_pair(true,request.returnDecline());
278
279         // Do we have an access control plugin?
280         if (settings.second) {
281             const Session* session = NULL;
282             try {
283                 session = request.getSession(false);
284             }
285             catch (exception& e) {
286                 request.log(SPRequest::SPWarn, string("unable to obtain session to pass to access control provider: ") + e.what());
287             }
288         
289             Locker acllock(settings.second);
290             switch (settings.second->authorized(request,session)) {
291                 case AccessControl::shib_acl_true:
292                     request.log(SPRequest::SPDebug, "access control provider granted access");
293                     return make_pair(true,request.returnOK());
294
295                 case AccessControl::shib_acl_false:
296                 {
297                     request.log(SPRequest::SPWarn, "access control provider denied access");
298                     TemplateParameters tp;
299                     tp.m_map["requestURL"] = targetURL;
300                     return make_pair(true,sendError(request, app, "access", tp, false));
301                 }
302
303                 default:
304                     // Use the "DECLINE" interface to signal we don't know what to do.
305                     return make_pair(true,request.returnDecline());
306             }
307         }
308         else {
309             return make_pair(true,request.returnDecline());
310         }
311     }
312     catch (exception& e) {
313         TemplateParameters tp(&e);
314         tp.m_map["requestURL"] = targetURL.substr(0,targetURL.find('?'));
315         return make_pair(true,sendError(request, app, "access", tp));
316     }
317 }
318
319 pair<bool,long> ServiceProvider::doExport(SPRequest& request, bool requireSession) const
320 {
321 #ifdef _DEBUG
322     xmltooling::NDC ndc("doExport");
323 #endif
324
325     const Application* app=NULL;
326     string targetURL = request.getRequestURL();
327
328     try {
329         RequestMapper::Settings settings = request.getRequestSettings();
330         app = &(request.getApplication());
331
332         const Session* session = NULL;
333         try {
334             session = request.getSession(false);
335         }
336         catch (exception& e) {
337             request.log(SPRequest::SPWarn, string("unable to obtain session to export to request: ") +  e.what());
338                 // If we have to have a session, then this is a fatal error.
339                 if (requireSession)
340                         throw;
341         }
342
343                 // Still no data?
344         if (!session) {
345                 if (requireSession)
346                 throw opensaml::RetryableProfileException("Unable to obtain session to export to request.");
347                 else
348                         return make_pair(false,0L);     // just bail silently
349         }
350         
351         request.setHeader("Shib-Application-ID", app->getId());
352         request.setHeader("Shib-Session-ID", session->getID());
353
354         // Export the IdP name and Authn method/context info.
355         const char* hval = session->getEntityID();
356         if (hval)
357             request.setHeader("Shib-Identity-Provider", hval);
358         hval = session->getAuthnInstant();
359         if (hval)
360             request.setHeader("Shib-Authentication-Instant", hval);
361         hval = session->getAuthnContextClassRef();
362         if (hval) {
363             request.setHeader("Shib-Authentication-Method", hval);
364             request.setHeader("Shib-AuthnContext-Class", hval);
365         }
366         hval = session->getAuthnContextDeclRef();
367         if (hval)
368             request.setHeader("Shib-AuthnContext-Decl", hval);
369         
370         // Maybe export the assertion keys.
371         pair<bool,bool> exp=settings.first->getBool("exportAssertion");
372         if (exp.first && exp.second) {
373             const PropertySet* sessions=app->getPropertySet("Sessions");
374             pair<bool,const char*> exportLocation = sessions ? sessions->getString("exportLocation") : pair<bool,const char*>(false,NULL);
375             if (!exportLocation.first)
376                 request.log(SPRequest::SPWarn, "can't export assertions without an exportLocation Sessions property");
377             else {
378                 const URLEncoder* encoder = XMLToolingConfig::getConfig().getURLEncoder();
379                 string exportName = "Shib-Assertion-00";
380                 string baseURL;
381                 if (!strncmp(exportLocation.second, "http", 4))
382                     baseURL = exportLocation.second;
383                 else
384                     baseURL = string(request.getHandlerURL(targetURL.c_str())) + exportLocation.second;
385                 baseURL = baseURL + "?key=" + session->getID() + "&ID=";
386                 const vector<const char*>& tokens = session->getAssertionIDs();
387                 vector<const char*>::size_type count = 0;
388                 for (vector<const char*>::const_iterator tokenids = tokens.begin(); tokenids!=tokens.end(); ++tokenids) {
389                     count++;
390                     *(exportName.rbegin()) = '0' + (count%10);
391                     *(++exportName.rbegin()) = '0' + (count/10);
392                     string fullURL = baseURL + encoder->encode(*tokenids);
393                     request.setHeader(exportName.c_str(), fullURL.c_str());
394                 }
395                 request.setHeader("Shib-Assertion-Count", exportName.c_str() + 15);
396             }
397         }
398
399         // Export the attributes.
400         bool remoteUserSet = false;
401         const multimap<string,const Attribute*>& attributes = session->getIndexedAttributes();
402         for (multimap<string,const Attribute*>::const_iterator a = attributes.begin(); a!=attributes.end(); ++a) {
403             const vector<string>& vals = a->second->getSerializedValues();
404
405             // See if this needs to be set as the REMOTE_USER value.
406             if (!remoteUserSet && !vals.empty() && app->getRemoteUserAttributeIds().count(a->first)) {
407                 request.setRemoteUser(vals.front().c_str());
408                 remoteUserSet = true;
409             }
410
411             // Handle the normal export case.
412             string header(request.getSecureHeader(a->first.c_str()));
413             for (vector<string>::const_iterator v = vals.begin(); v!=vals.end(); ++v) {
414                 if (!header.empty())
415                     header += ";";
416                 string::size_type pos = v->find_first_of(';',string::size_type(0));
417                 if (pos!=string::npos) {
418                     string value(*v);
419                     for (; pos != string::npos; pos = value.find_first_of(';',pos)) {
420                         value.insert(pos, "\\");
421                         pos += 2;
422                     }
423                     header += value;
424                 }
425                 else {
426                     header += (*v);
427                 }
428             }
429             request.setHeader(a->first.c_str(), header.c_str());
430         }
431
432         return make_pair(false,0L);
433     }
434     catch (exception& e) {
435         TemplateParameters tp(&e);
436         tp.m_map["requestURL"] = targetURL.substr(0,targetURL.find('?'));
437         return make_pair(true,sendError(request, app, "session", tp));
438     }
439 }
440
441 pair<bool,long> ServiceProvider::doHandler(SPRequest& request) const
442 {
443 #ifdef _DEBUG
444     xmltooling::NDC ndc("doHandler");
445 #endif
446
447     const Application* app=NULL;
448     string targetURL = request.getRequestURL();
449
450     try {
451         RequestMapper::Settings settings = request.getRequestSettings();
452         app = &(request.getApplication());
453
454         const char* handlerURL=request.getHandlerURL(targetURL.c_str());
455         if (!handlerURL)
456             throw ConfigurationException("Cannot determine handler from resource URL, check configuration.");
457
458         // Make sure we only process handler requests.
459         if (!strstr(targetURL.c_str(),handlerURL))
460             return make_pair(true, request.returnDecline());
461
462         const PropertySet* sessionProps=app->getPropertySet("Sessions");
463         if (!sessionProps)
464             throw ConfigurationException("Unable to map request to application session settings, check configuration.");
465
466         // Process incoming request.
467         pair<bool,bool> handlerSSL=sessionProps->getBool("handlerSSL");
468       
469         // Make sure this is SSL, if it should be
470         if ((!handlerSSL.first || handlerSSL.second) && !request.isSecure())
471             throw opensaml::FatalProfileException("Blocked non-SSL access to Shibboleth handler.");
472
473         // We dispatch based on our path info. We know the request URL begins with or equals the handler URL,
474         // so the path info is the next character (or null).
475         const Handler* handler=app->getHandler(targetURL.c_str() + strlen(handlerURL));
476         if (!handler)
477             throw ConfigurationException("Shibboleth handler invoked at an unconfigured location.");
478
479         pair<bool,long> hret=handler->run(request);
480
481         // Did the handler run successfully?
482         if (hret.first)
483             return hret;
484        
485         throw ConfigurationException("Configured Shibboleth handler failed to process the request.");
486     }
487     catch (exception& e) {
488         TemplateParameters tp(&e);
489         tp.m_map["requestURL"] = targetURL.substr(0,targetURL.find('?'));
490         return make_pair(true,sendError(request, app, "session", tp));
491     }
492 }