41e9f1fdddc2e49d6614d983ae02e9af641c7fed
[shibboleth/sp.git] / shibsp / handler / impl / StatusHandler.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  * StatusHandler.cpp
19  * 
20  * Handler for exposing information about the internals of the SP.
21  */
22
23 #include "internal.h"
24 #include "Application.h"
25 #include "exceptions.h"
26 #include "ServiceProvider.h"
27 #include "handler/AbstractHandler.h"
28 #include "handler/RemotedHandler.h"
29 #include "util/CGIParser.h"
30
31 using namespace shibsp;
32 #ifndef SHIBSP_LITE
33 # include "SessionCache.h"
34 # include "metadata/MetadataProviderCriteria.h"
35 # include <saml/version.h>
36 using namespace opensaml::saml2md;
37 using namespace opensaml;
38 using namespace xmlsignature;
39 #endif
40 using namespace xmltooling;
41 using namespace std;
42
43 namespace shibsp {
44
45 #if defined (_MSC_VER)
46     #pragma warning( push )
47     #pragma warning( disable : 4250 )
48 #endif
49
50     class SHIBSP_DLLLOCAL Blocker : public DOMNodeFilter
51     {
52     public:
53         short acceptNode(const DOMNode* node) const {
54             return FILTER_REJECT;
55         }
56     };
57
58     static SHIBSP_DLLLOCAL Blocker g_Blocker;
59
60     class SHIBSP_API StatusHandler : public AbstractHandler, public RemotedHandler
61     {
62     public:
63         StatusHandler(const DOMElement* e, const char* appId);
64         virtual ~StatusHandler() {}
65
66         pair<bool,long> run(SPRequest& request, bool isHandler=true) const;
67         void receive(DDF& in, ostream& out);
68
69     private:
70         pair<bool,long> processMessage(const Application& application, const HTTPRequest& httpRequest, HTTPResponse& httpResponse) const;
71
72         set<string> m_acl;
73     };
74
75 #if defined (_MSC_VER)
76     #pragma warning( pop )
77 #endif
78
79     Handler* SHIBSP_DLLLOCAL StatusHandlerFactory(const pair<const DOMElement*,const char*>& p)
80     {
81         return new StatusHandler(p.first, p.second);
82     }
83
84 #ifndef XMLTOOLING_NO_XMLSEC
85     vector<XSECCryptoX509*> g_NoCerts;
86 #else
87     vector<string> g_NoCerts;
88 #endif
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     class DummyRequest : public HTTPRequest
101     {
102     public:
103         DummyRequest(const char* url) : m_parser(NULL), m_url(url), m_scheme(NULL), m_query(NULL), m_port(0) {
104 #ifdef HAVE_STRCASECMP
105             if (url && !strncasecmp(url,"http://",7)) {
106                 m_scheme="http";
107                 url+=7;
108             }
109             else if (url && !strncasecmp(url,"https://",8)) {
110                 m_scheme="https";
111                 url+=8;
112             }
113             else
114 #else
115             if (url && !strnicmp(url,"http://",7)) {
116                 m_scheme="http";
117                 m_port = 80;
118                 url+=7;
119             }
120             else if (url && !strnicmp(url,"https://",8)) {
121                 m_scheme="https";
122                 m_port = 443;
123                 url+=8;
124             }
125             else
126 #endif
127                 throw invalid_argument("Target parameter was not an absolute URL.");
128
129             m_query = strchr(url,'?');
130             if (m_query)
131                 m_query++;
132
133             const char* slash = strchr(url, '/');
134             const char* colon = strchr(url, ':');
135             if (colon && colon < slash) {
136                 m_hostname.assign(url, colon-url);
137                 string port(colon + 1, slash - colon);
138                 m_port = atoi(port.c_str());
139             }
140             else {
141                 m_hostname.assign(url, slash - url);
142             }
143
144             while (*slash) {
145                 if (*slash == '?') {
146                     m_uri += slash;
147                     break;
148                 }
149                 else if (*slash == ';') {
150                     // If this is Java being stupid, skip everything up to the query string, if any.
151                     if (!strncmp(slash, ";jsessionid=", 12)) {
152                         if (slash = strchr(slash, '?'))
153                             m_uri += slash;
154                         break;
155                     }
156                     else {
157                         m_uri += *slash;
158                     }
159                 }
160                 else if (*slash != '%') {
161                     m_uri += *slash;
162                 }
163                 else {
164                     ++slash;
165                     if (!isxdigit(*slash) || !isxdigit(*(slash+1)))
166                         throw invalid_argument("Bad request, contained unsupported encoded characters.");
167                     m_uri += _x2c(slash);
168                     ++slash;
169                 }
170                 ++slash;
171             }
172         }
173
174         ~DummyRequest() {
175             delete m_parser;
176         }
177
178         const char* getRequestURL() const {
179             return m_url;
180         }
181         const char* getScheme() const {
182             return m_scheme;
183         }
184         const char* getHostname() const {
185             return m_hostname.c_str();
186         }
187         int getPort() const {
188             return m_port;
189         }
190         const char* getRequestURI() const {
191             return m_uri.c_str();
192         }
193         const char* getMethod() const {
194             return "GET";
195         }
196         string getContentType() const {
197             return "";
198         }
199         long getContentLength() const {
200             return 0;
201         }
202         string getRemoteAddr() const {
203             return "";
204         }
205         string getRemoteUser() const {
206             return "";
207         }
208         const char* getRequestBody() const {
209             return NULL;
210         }
211         const char* getQueryString() const {
212             return m_query;
213         }
214         const char* getParameter(const char* name) const
215         {
216             if (!m_parser)
217                 m_parser=new CGIParser(*this);
218             
219             pair<CGIParser::walker,CGIParser::walker> bounds=m_parser->getParameters(name);
220             return (bounds.first==bounds.second) ? NULL : bounds.first->second;
221         }
222         vector<const char*>::size_type getParameters(const char* name, vector<const char*>& values) const
223         {
224             if (!m_parser)
225                 m_parser=new CGIParser(*this);
226
227             pair<CGIParser::walker,CGIParser::walker> bounds=m_parser->getParameters(name);
228             while (bounds.first!=bounds.second) {
229                 values.push_back(bounds.first->second);
230                 ++bounds.first;
231             }
232             return values.size();
233         }
234         string getHeader(const char* name) const {
235             return "";
236         }
237         virtual const
238 #ifndef XMLTOOLING_NO_XMLSEC
239             std::vector<XSECCryptoX509*>&
240 #else
241             std::vector<std::string>& 
242 #endif
243             getClientCertificates() const {
244                 return g_NoCerts;
245         }
246
247     private:
248         mutable CGIParser* m_parser;
249         const char* m_url;
250         const char* m_scheme;
251         const char* m_query;
252         int m_port;
253         string m_hostname,m_uri;
254     };
255 };
256
257 StatusHandler::StatusHandler(const DOMElement* e, const char* appId)
258     : AbstractHandler(e, Category::getInstance(SHIBSP_LOGCAT".StatusHandler"), &g_Blocker)
259 {
260     string address(appId);
261     address += getString("Location").second;
262     setAddress(address.c_str());
263     if (SPConfig::getConfig().isEnabled(SPConfig::InProcess)) {
264         pair<bool,const char*> acl = getString("acl");
265         if (acl.first) {
266             string aclbuf=acl.second;
267             int j = 0;
268             for (unsigned int i=0;  i < aclbuf.length();  i++) {
269                 if (aclbuf.at(i)==' ') {
270                     m_acl.insert(aclbuf.substr(j, i-j));
271                     j = i+1;
272                 }
273             }
274             m_acl.insert(aclbuf.substr(j, aclbuf.length()-j));
275         }
276     }
277 }
278
279 pair<bool,long> StatusHandler::run(SPRequest& request, bool isHandler) const
280 {
281     SPConfig& conf = SPConfig::getConfig();
282     if (conf.isEnabled(SPConfig::InProcess)) {
283         if (!m_acl.empty() && m_acl.count(request.getRemoteAddr()) == 0) {
284             m_log.error("status handler request blocked from invalid address (%s)", request.getRemoteAddr().c_str());
285             istringstream msg("Status Handler Blocked");
286             return make_pair(true,request.sendResponse(msg, HTTPResponse::XMLTOOLING_HTTP_STATUS_UNAUTHORIZED));
287         }
288     }
289
290     const char* target = request.getParameter("target");
291     if (target) {
292         // RequestMap query, so handle it inproc.
293         DummyRequest dummy(target);
294         RequestMapper::Settings settings = request.getApplication().getServiceProvider().getRequestMapper()->getSettings(dummy);
295         map<string,const char*> props;
296         settings.first->getAll(props);
297
298         request.setContentType("text/xml");
299         stringstream msg;
300         msg << "<StatusHandler>";
301             msg << "<Version Xerces-C='" << XERCES_FULLVERSIONDOT
302 #ifndef SHIBSP_LITE
303                 << "' XML-Security-C='" << XSEC_FULLVERSIONDOT
304                 << "' OpenSAML-C='" << OPENSAML_FULLVERSIONDOT
305 #endif
306                 << "' Shibboleth='" << PACKAGE_VERSION << "'/>";
307             msg << "<RequestSettings";
308             for (map<string,const char*>::const_iterator p = props.begin(); p != props.end(); ++p)
309                 msg << ' ' << p->first << "='" << p->second << "'";
310             msg << '>' << target << "</RequestSettings>";
311             msg << "<Status><OK/></Status>";
312         msg << "</StatusHandler>";
313         return make_pair(true,request.sendResponse(msg));
314     }
315     
316     try {
317         if (conf.isEnabled(SPConfig::OutOfProcess)) {
318             // When out of process, we run natively and directly process the message.
319             return processMessage(request.getApplication(), request, request);
320         }
321         else {
322             // When not out of process, we remote all the message processing.
323             DDF out,in = wrap(request);
324             DDFJanitor jin(in), jout(out);            
325             out=request.getServiceProvider().getListenerService()->send(in);
326             return unwrap(request, out);
327         }
328     }
329     catch (XMLToolingException& ex) {
330         m_log.error("error while processing request: %s", ex.what());
331         request.setContentType("text/xml");
332         stringstream msg;
333         msg << "<StatusHandler>";
334             msg << "<Version Xerces-C='" << XERCES_FULLVERSIONDOT
335 #ifndef SHIBSP_LITE
336                 << "' XML-Security-C='" << XSEC_FULLVERSIONDOT
337                 << "' OpenSAML-C='" << OPENSAML_FULLVERSIONDOT
338 #endif
339                 << "' Shibboleth='" << PACKAGE_VERSION << "'/>";
340             msg << "<Status><Exception type='" << ex.getClassName() << "'>" << ex.what() << "</Exception></Status>";
341         msg << "</StatusHandler>";
342         return make_pair(true,request.sendResponse(msg, HTTPResponse::XMLTOOLING_HTTP_STATUS_ERROR));
343     }
344     catch (exception& ex) {
345         m_log.error("error while processing request: %s", ex.what());
346         request.setContentType("text/xml");
347         stringstream msg;
348         msg << "<StatusHandler>";
349             msg << "<Version Xerces-C='" << XERCES_FULLVERSIONDOT
350 #ifndef SHIBSP_LITE
351                 << "' XML-Security-C='" << XSEC_FULLVERSIONDOT
352                 << "' OpenSAML-C='" << OPENSAML_FULLVERSIONDOT
353 #endif
354                 << "' Shibboleth='" << PACKAGE_VERSION << "'/>";
355             msg << "<Status><Exception type='std::exception'>" << ex.what() << "</Exception></Status>";
356         msg << "</StatusHandler>";
357         return make_pair(true,request.sendResponse(msg, HTTPResponse::XMLTOOLING_HTTP_STATUS_ERROR));
358     }
359 }
360
361 void StatusHandler::receive(DDF& in, ostream& out)
362 {
363     // Find application.
364     const char* aid=in["application_id"].string();
365     const Application* app=aid ? SPConfig::getConfig().getServiceProvider()->getApplication(aid) : NULL;
366     if (!app) {
367         // Something's horribly wrong.
368         m_log.error("couldn't find application (%s) for status request", aid ? aid : "(missing)");
369         throw ConfigurationException("Unable to locate application for status request, deleted?");
370     }
371     
372     // Wrap a response shim.
373     DDF ret(NULL);
374     DDFJanitor jout(ret);
375     auto_ptr<HTTPRequest> req(getRequest(in));
376     auto_ptr<HTTPResponse> resp(getResponse(ret));
377         
378     // Since we're remoted, the result should either be a throw, a false/0 return,
379     // which we just return as an empty structure, or a response/redirect,
380     // which we capture in the facade and send back.
381     processMessage(*app, *req.get(), *resp.get());
382     out << ret;
383 }
384
385 pair<bool,long> StatusHandler::processMessage(
386     const Application& application, const HTTPRequest& httpRequest, HTTPResponse& httpResponse
387     ) const
388 {
389 #ifndef SHIBSP_LITE
390     m_log.debug("processing status request");
391
392     stringstream s;
393     s << "<StatusHandler>";
394     const char* status = "<OK/>";
395
396     s << "<Version Xerces-C='" << XERCES_FULLVERSIONDOT
397         << "' XML-Security-C='" << XSEC_FULLVERSIONDOT
398         << "' OpenSAML-C='" << OPENSAML_FULLVERSIONDOT
399         << "' Shibboleth='" << PACKAGE_VERSION << "'/>";
400
401     const char* param = NULL;
402     if (param) {
403     }
404     else {
405         // General configuration and status report.
406         try {
407             SessionCache* sc = application.getServiceProvider().getSessionCache(false);
408             if (sc) {
409                 sc->test();
410                 s << "<SessionCache><OK/></SessionCache>";
411             }
412             else {
413                 s << "<SessionCache><None/></SessionCache>";
414             }
415         }
416         catch (XMLToolingException& ex) {
417             s << "<SessionCache><Exception type='" << ex.getClassName() << "'>" << ex.what() << "</Exception></SessionCache>";
418             status = "<Partial/>";
419         }
420         catch (exception& ex) {
421             s << "<SessionCache><Exception type='std::exception'>" << ex.what() << "</Exception></SessionCache>";
422             status = "<Partial/>";
423         }
424
425         const PropertySet* relyingParty=NULL;
426         param=httpRequest.getParameter("entityID");
427         if (param) {
428             MetadataProvider* m = application.getMetadataProvider();
429             Locker mlock(m);
430             relyingParty = application.getRelyingParty(m->getEntityDescriptor(MetadataProviderCriteria(application, param)).first);
431         }
432         else {
433             relyingParty = &application;
434         }
435
436         s << "<Application id='" << application.getId() << "' entityID='" << relyingParty->getString("entityID").second << "'/>";
437
438         s << "<Handlers>";
439         vector<const Handler*> handlers;
440         application.getHandlers(handlers);
441         for (vector<const Handler*>::const_iterator h = handlers.begin(); h != handlers.end(); ++h) {
442             s << "<Handler type='" << (*h)->getType() << "' Location='" << (*h)->getString("Location").second << "'";
443             if ((*h)->getString("Binding").first)
444                 s << " Binding='" << (*h)->getString("Binding").second << "'";
445             s << "/>";
446         }
447         s << "</Handlers>";
448
449         CredentialResolver* credResolver=application.getCredentialResolver();
450         if (credResolver) {
451             Locker credLocker(credResolver);
452             CredentialCriteria cc;
453             cc.setUsage(Credential::SIGNING_CREDENTIAL);
454             pair<bool,const char*> keyName = relyingParty->getString("keyName");
455             if (keyName.first)
456                 cc.getKeyNames().insert(keyName.second);
457             vector<const Credential*> creds;
458             credResolver->resolve(creds,&cc);
459             for (vector<const Credential*>::const_iterator c = creds.begin(); c != creds.end(); ++c) {
460                 KeyInfo* kinfo = (*c)->getKeyInfo();
461                 if (kinfo) {
462                     auto_ptr<KeyDescriptor> kd(KeyDescriptorBuilder::buildKeyDescriptor());
463                     kd->setUse(KeyDescriptor::KEYTYPE_SIGNING);
464                     kd->setKeyInfo(kinfo);
465                     s << *(kd.get());
466                 }
467             }
468
469             cc.setUsage(Credential::ENCRYPTION_CREDENTIAL);
470             creds.clear();
471             cc.getKeyNames().clear();
472             credResolver->resolve(creds,&cc);
473             for (vector<const Credential*>::const_iterator c = creds.begin(); c != creds.end(); ++c) {
474                 KeyInfo* kinfo = (*c)->getKeyInfo();
475                 if (kinfo) {
476                     auto_ptr<KeyDescriptor> kd(KeyDescriptorBuilder::buildKeyDescriptor());
477                     kd->setUse(KeyDescriptor::KEYTYPE_ENCRYPTION);
478                     kd->setKeyInfo(kinfo);
479                     s << *(kd.get());
480                 }
481             }
482         }
483     }
484
485     s << "<Status>" << status << "</Status></StatusHandler>";
486
487     httpResponse.setContentType("text/xml");
488     return make_pair(true, httpResponse.sendResponse(s));
489 #else
490     return make_pair(false,0L);
491 #endif
492 }