https://issues.shibboleth.net/jira/browse/SSPCPP-362
[shibboleth/cpp-sp.git] / shibsp / handler / impl / StatusHandler.cpp
1 /**
2  * Licensed to the University Corporation for Advanced Internet
3  * Development, Inc. (UCAID) under one or more contributor license
4  * agreements. See the NOTICE file distributed with this work for
5  * additional information regarding copyright ownership.
6  *
7  * UCAID licenses this file to you under the Apache License,
8  * Version 2.0 (the "License"); you may not use this file except
9  * in compliance with the License. You may obtain a copy of the
10  * License at
11  *
12  * http://www.apache.org/licenses/LICENSE-2.0
13  *
14  * Unless required by applicable law or agreed to in writing,
15  * software distributed under the License is distributed on an
16  * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
17  * either express or implied. See the License for the specific
18  * language governing permissions and limitations under the License.
19  */
20
21 /**
22  * StatusHandler.cpp
23  *
24  * Handler for exposing information about the internals of the SP.
25  */
26
27 #include "internal.h"
28 #include "Application.h"
29 #include "exceptions.h"
30 #include "ServiceProvider.h"
31 #include "SPRequest.h"
32 #include "handler/AbstractHandler.h"
33 #include "handler/RemotedHandler.h"
34 #include "util/CGIParser.h"
35
36 #include <xmltooling/version.h>
37 #include <xmltooling/util/DateTime.h>
38
39 #ifdef HAVE_SYS_UTSNAME_H
40 # include <sys/utsname.h>
41 #endif
42
43 using namespace shibsp;
44 #ifndef SHIBSP_LITE
45 # include "SessionCache.h"
46 # include "metadata/MetadataProviderCriteria.h"
47 # include <saml/version.h>
48 # include <saml/saml2/metadata/Metadata.h>
49 # include <xmltooling/security/Credential.h>
50 # include <xmltooling/security/CredentialCriteria.h>
51 using namespace opensaml::saml2md;
52 using namespace opensaml;
53 using namespace xmlsignature;
54 #endif
55 using namespace xmltooling;
56 using namespace std;
57
58 namespace shibsp {
59
60 #if defined (_MSC_VER)
61     #pragma warning( push )
62     #pragma warning( disable : 4250 )
63 #endif
64
65     class SHIBSP_DLLLOCAL Blocker : public DOMNodeFilter
66     {
67     public:
68 #ifdef SHIBSP_XERCESC_SHORT_ACCEPTNODE
69         short
70 #else
71         FilterAction
72 #endif
73         acceptNode(const DOMNode* node) const {
74             return FILTER_REJECT;
75         }
76     };
77
78     static SHIBSP_DLLLOCAL Blocker g_Blocker;
79
80     class SHIBSP_API StatusHandler : public AbstractHandler, public RemotedHandler
81     {
82     public:
83         StatusHandler(const DOMElement* e, const char* appId);
84         virtual ~StatusHandler() {}
85
86         pair<bool,long> run(SPRequest& request, bool isHandler=true) const;
87         void receive(DDF& in, ostream& out);
88
89     private:
90         pair<bool,long> processMessage(const Application& application, const HTTPRequest& httpRequest, HTTPResponse& httpResponse) const;
91         ostream& systemInfo(ostream& os) const;
92
93         set<string> m_acl;
94     };
95
96 #if defined (_MSC_VER)
97     #pragma warning( pop )
98 #endif
99
100     Handler* SHIBSP_DLLLOCAL StatusHandlerFactory(const pair<const DOMElement*,const char*>& p)
101     {
102         return new StatusHandler(p.first, p.second);
103     }
104
105 #ifndef XMLTOOLING_NO_XMLSEC
106     vector<XSECCryptoX509*> g_NoCerts;
107 #else
108     vector<string> g_NoCerts;
109 #endif
110
111     static char _x2c(const char *what)
112     {
113         register char digit;
114
115         digit = (what[0] >= 'A' ? ((what[0] & 0xdf) - 'A')+10 : (what[0] - '0'));
116         digit *= 16;
117         digit += (what[1] >= 'A' ? ((what[1] & 0xdf) - 'A')+10 : (what[1] - '0'));
118         return(digit);
119     }
120
121     class DummyRequest : public HTTPRequest
122     {
123     public:
124         DummyRequest(const char* url) : m_parser(nullptr), m_url(url), m_scheme(nullptr), m_query(nullptr), m_port(0) {
125 #ifdef HAVE_STRCASECMP
126             if (url && !strncasecmp(url,"http://",7)) {
127                 m_scheme="http";
128                 url+=7;
129             }
130             else if (url && !strncasecmp(url,"https://",8)) {
131                 m_scheme="https";
132                 url+=8;
133             }
134             else
135 #else
136             if (url && !strnicmp(url,"http://",7)) {
137                 m_scheme="http";
138                 m_port = 80;
139                 url+=7;
140             }
141             else if (url && !strnicmp(url,"https://",8)) {
142                 m_scheme="https";
143                 m_port = 443;
144                 url+=8;
145             }
146             else
147 #endif
148                 throw invalid_argument("Target parameter was not an absolute URL.");
149
150             m_query = strchr(url,'?');
151             if (m_query)
152                 m_query++;
153
154             const char* slash = strchr(url, '/');
155             const char* colon = strchr(url, ':');
156             if (colon && colon < slash) {
157                 m_hostname.assign(url, colon-url);
158                 string port(colon + 1, slash - colon);
159                 m_port = atoi(port.c_str());
160             }
161             else {
162                 m_hostname.assign(url, slash - url);
163             }
164
165             while (*slash) {
166                 if (*slash == '?') {
167                     m_uri += slash;
168                     break;
169                 }
170                 else if (*slash != '%') {
171                     m_uri += *slash;
172                 }
173                 else {
174                     ++slash;
175                     if (!isxdigit(*slash) || !isxdigit(*(slash+1)))
176                         throw invalid_argument("Bad request, contained unsupported encoded characters.");
177                     m_uri += _x2c(slash);
178                     ++slash;
179                 }
180                 ++slash;
181             }
182         }
183
184         virtual ~DummyRequest() {
185             delete m_parser;
186         }
187
188         const char* getRequestURL() const {
189             return m_url;
190         }
191         const char* getScheme() const {
192             return m_scheme;
193         }
194         const char* getHostname() const {
195             return m_hostname.c_str();
196         }
197         int getPort() const {
198             return m_port;
199         }
200         const char* getRequestURI() const {
201             return m_uri.c_str();
202         }
203         const char* getMethod() const {
204             return "GET";
205         }
206         string getContentType() const {
207             return "";
208         }
209         long getContentLength() const {
210             return 0;
211         }
212         string getRemoteAddr() const {
213             return "";
214         }
215         string getRemoteUser() const {
216             return "";
217         }
218         const char* getRequestBody() const {
219             return nullptr;
220         }
221         const char* getQueryString() const {
222             return m_query;
223         }
224         const char* getParameter(const char* name) const
225         {
226             if (!m_parser)
227                 m_parser=new CGIParser(*this);
228
229             pair<CGIParser::walker,CGIParser::walker> bounds=m_parser->getParameters(name);
230             return (bounds.first==bounds.second) ? nullptr : bounds.first->second;
231         }
232         vector<const char*>::size_type getParameters(const char* name, vector<const char*>& values) const
233         {
234             if (!m_parser)
235                 m_parser=new CGIParser(*this);
236
237             pair<CGIParser::walker,CGIParser::walker> bounds=m_parser->getParameters(name);
238             while (bounds.first!=bounds.second) {
239                 values.push_back(bounds.first->second);
240                 ++bounds.first;
241             }
242             return values.size();
243         }
244         string getHeader(const char* name) const {
245             return "";
246         }
247         virtual const
248 #ifndef XMLTOOLING_NO_XMLSEC
249             std::vector<XSECCryptoX509*>&
250 #else
251             std::vector<std::string>&
252 #endif
253             getClientCertificates() const {
254                 return g_NoCerts;
255         }
256
257     private:
258         mutable CGIParser* m_parser;
259         const char* m_url;
260         const char* m_scheme;
261         const char* m_query;
262         int m_port;
263         string m_hostname,m_uri;
264     };
265 };
266
267 StatusHandler::StatusHandler(const DOMElement* e, const char* appId)
268     : AbstractHandler(e, Category::getInstance(SHIBSP_LOGCAT".StatusHandler"), &g_Blocker)
269 {
270     string address(appId);
271     address += getString("Location").second;
272     setAddress(address.c_str());
273     if (SPConfig::getConfig().isEnabled(SPConfig::InProcess)) {
274         pair<bool,const char*> acl = getString("acl");
275         if (acl.first) {
276             string aclbuf=acl.second;
277             int j = 0;
278             for (unsigned int i=0;  i < aclbuf.length();  i++) {
279                 if (aclbuf.at(i)==' ') {
280                     m_acl.insert(aclbuf.substr(j, i-j));
281                     j = i+1;
282                 }
283             }
284             m_acl.insert(aclbuf.substr(j, aclbuf.length()-j));
285         }
286     }
287 }
288
289 pair<bool,long> StatusHandler::run(SPRequest& request, bool isHandler) const
290 {
291     SPConfig& conf = SPConfig::getConfig();
292     if (conf.isEnabled(SPConfig::InProcess)) {
293         if (!m_acl.empty() && m_acl.count(request.getRemoteAddr()) == 0) {
294             m_log.error("status handler request blocked from invalid address (%s)", request.getRemoteAddr().c_str());
295             istringstream msg("Status Handler Blocked");
296             return make_pair(true,request.sendResponse(msg, HTTPResponse::XMLTOOLING_HTTP_STATUS_FORBIDDEN));
297         }
298     }
299
300     const char* target = request.getParameter("target");
301     if (target) {
302         // RequestMap query, so handle it inproc.
303         DummyRequest dummy(target);
304         RequestMapper::Settings settings = request.getApplication().getServiceProvider().getRequestMapper()->getSettings(dummy);
305         map<string,const char*> props;
306         settings.first->getAll(props);
307
308         DateTime now(time(nullptr));
309         now.parseDateTime();
310         auto_ptr_char timestamp(now.getFormattedString());
311         request.setContentType("text/xml");
312         stringstream msg;
313         msg << "<StatusHandler time='" << timestamp.get() << "'>";
314             msg << "<Version Xerces-C='" << XERCES_FULLVERSIONDOT
315                 << "' XML-Tooling-C='" << gXMLToolingDotVersionStr
316 #ifndef SHIBSP_LITE
317                 << "' XML-Security-C='" << XSEC_FULLVERSIONDOT
318                 << "' OpenSAML-C='" << gOpenSAMLDotVersionStr
319 #endif
320                 << "' Shibboleth='" << PACKAGE_VERSION << "'/>";
321             systemInfo(msg) << "<RequestSettings";
322             for (map<string,const char*>::const_iterator p = props.begin(); p != props.end(); ++p)
323                 msg << ' ' << p->first << "='" << p->second << "'";
324             msg << '>' << target << "</RequestSettings>";
325             msg << "<Status><OK/></Status>";
326         msg << "</StatusHandler>";
327         return make_pair(true,request.sendResponse(msg));
328     }
329
330     try {
331         if (conf.isEnabled(SPConfig::OutOfProcess)) {
332             // When out of process, we run natively and directly process the message.
333             return processMessage(request.getApplication(), request, request);
334         }
335         else {
336             // When not out of process, we remote all the message processing.
337             DDF out,in = wrap(request);
338             DDFJanitor jin(in), jout(out);
339             out=request.getServiceProvider().getListenerService()->send(in);
340             return unwrap(request, out);
341         }
342     }
343     catch (XMLToolingException& ex) {
344         m_log.error("error while processing request: %s", ex.what());
345         DateTime now(time(nullptr));
346         now.parseDateTime();
347         auto_ptr_char timestamp(now.getFormattedString());
348         request.setContentType("text/xml");
349         stringstream msg;
350         msg << "<StatusHandler time='" << timestamp.get() << "'>";
351             msg << "<Version Xerces-C='" << XERCES_FULLVERSIONDOT
352                 << "' XML-Tooling-C='" << gXMLToolingDotVersionStr
353 #ifndef SHIBSP_LITE
354                 << "' XML-Security-C='" << XSEC_FULLVERSIONDOT
355                 << "' OpenSAML-C='" << gOpenSAMLDotVersionStr
356 #endif
357                 << "' Shibboleth='" << PACKAGE_VERSION << "'/>";
358             systemInfo(msg) << "<Status><Exception type='" << ex.getClassName() << "'>" << ex.what() << "</Exception></Status>";
359         msg << "</StatusHandler>";
360         return make_pair(true,request.sendResponse(msg, HTTPResponse::XMLTOOLING_HTTP_STATUS_ERROR));
361     }
362     catch (exception& ex) {
363         m_log.error("error while processing request: %s", ex.what());
364         DateTime now(time(nullptr));
365         now.parseDateTime();
366         auto_ptr_char timestamp(now.getFormattedString());
367         request.setContentType("text/xml");
368         stringstream msg;
369         msg << "<StatusHandler time='" << timestamp.get() << "'>";
370             msg << "<Version Xerces-C='" << XERCES_FULLVERSIONDOT
371                 << "' XML-Tooling-C='" << gXMLToolingDotVersionStr
372 #ifndef SHIBSP_LITE
373                 << "' XML-Security-C='" << XSEC_FULLVERSIONDOT
374                 << "' OpenSAML-C='" << gOpenSAMLDotVersionStr
375 #endif
376                 << "' Shibboleth='" << PACKAGE_VERSION << "'/>";
377             systemInfo(msg) << "<Status><Exception type='std::exception'>" << ex.what() << "</Exception></Status>";
378         msg << "</StatusHandler>";
379         return make_pair(true,request.sendResponse(msg, HTTPResponse::XMLTOOLING_HTTP_STATUS_ERROR));
380     }
381 }
382
383 void StatusHandler::receive(DDF& in, ostream& out)
384 {
385     // Find application.
386     const char* aid=in["application_id"].string();
387     const Application* app=aid ? SPConfig::getConfig().getServiceProvider()->getApplication(aid) : nullptr;
388     if (!app) {
389         // Something's horribly wrong.
390         m_log.error("couldn't find application (%s) for status request", aid ? aid : "(missing)");
391         throw ConfigurationException("Unable to locate application for status request, deleted?");
392     }
393
394     // Wrap a response shim.
395     DDF ret(nullptr);
396     DDFJanitor jout(ret);
397     auto_ptr<HTTPRequest> req(getRequest(in));
398     auto_ptr<HTTPResponse> resp(getResponse(ret));
399
400     // Since we're remoted, the result should either be a throw, a false/0 return,
401     // which we just return as an empty structure, or a response/redirect,
402     // which we capture in the facade and send back.
403     processMessage(*app, *req.get(), *resp.get());
404     out << ret;
405 }
406
407 pair<bool,long> StatusHandler::processMessage(
408     const Application& application, const HTTPRequest& httpRequest, HTTPResponse& httpResponse
409     ) const
410 {
411 #ifndef SHIBSP_LITE
412     m_log.debug("processing status request");
413
414     DateTime now(time(nullptr));
415     now.parseDateTime();
416     auto_ptr_char timestamp(now.getFormattedString());
417
418     stringstream s;
419     s << "<StatusHandler time='" << timestamp.get() << "'>";
420     const char* status = "<OK/>";
421
422     s << "<Version Xerces-C='" << XERCES_FULLVERSIONDOT
423         << "' XML-Tooling-C='" << gXMLToolingDotVersionStr
424         << "' XML-Security-C='" << XSEC_FULLVERSIONDOT
425         << "' OpenSAML-C='" << gOpenSAMLDotVersionStr
426         << "' Shibboleth='" << PACKAGE_VERSION << "'/>";
427
428     systemInfo(s);
429
430     const char* param = nullptr;
431     if (param) {
432     }
433     else {
434         // General configuration and status report.
435         try {
436             SessionCache* sc = application.getServiceProvider().getSessionCache(false);
437             if (sc) {
438                 sc->test();
439                 s << "<SessionCache><OK/></SessionCache>";
440             }
441             else {
442                 s << "<SessionCache><None/></SessionCache>";
443             }
444         }
445         catch (XMLToolingException& ex) {
446             s << "<SessionCache><Exception type='" << ex.getClassName() << "'>" << ex.what() << "</Exception></SessionCache>";
447             status = "<Partial/>";
448         }
449         catch (exception& ex) {
450             s << "<SessionCache><Exception type='std::exception'>" << ex.what() << "</Exception></SessionCache>";
451             status = "<Partial/>";
452         }
453
454         MetadataProvider* m = application.getMetadataProvider();
455         Locker mlock(m);
456
457         const PropertySet* relyingParty=nullptr;
458         param=httpRequest.getParameter("entityID");
459         if (param)
460             relyingParty = application.getRelyingParty(m->getEntityDescriptor(MetadataProviderCriteria(application, param)).first);
461         else
462             relyingParty = &application;
463
464         s << "<Application id='" << application.getId() << "' entityID='" << relyingParty->getString("entityID").second << "'/>";
465
466         m->outputStatus(s);
467
468         s << "<Handlers>";
469         vector<const Handler*> handlers;
470         application.getHandlers(handlers);
471         for (vector<const Handler*>::const_iterator h = handlers.begin(); h != handlers.end(); ++h) {
472             s << "<Handler type='" << (*h)->getType() << "' Location='" << (*h)->getString("Location").second << "'";
473             if ((*h)->getString("Binding").first)
474                 s << " Binding='" << (*h)->getString("Binding").second << "'";
475             s << "/>";
476         }
477         s << "</Handlers>";
478
479         CredentialResolver* credResolver=application.getCredentialResolver();
480         if (credResolver) {
481             Locker credLocker(credResolver);
482             CredentialCriteria cc;
483             cc.setUsage(Credential::SIGNING_CREDENTIAL);
484             pair<bool,const char*> keyName = relyingParty->getString("keyName");
485             if (keyName.first)
486                 cc.getKeyNames().insert(keyName.second);
487             vector<const Credential*> creds;
488             credResolver->resolve(creds,&cc);
489             for (vector<const Credential*>::const_iterator c = creds.begin(); c != creds.end(); ++c) {
490                 KeyInfo* kinfo = (*c)->getKeyInfo();
491                 if (kinfo) {
492                     auto_ptr<KeyDescriptor> kd(KeyDescriptorBuilder::buildKeyDescriptor());
493                     kd->setUse(KeyDescriptor::KEYTYPE_SIGNING);
494                     kd->setKeyInfo(kinfo);
495                     s << *(kd.get());
496                 }
497             }
498
499             cc.setUsage(Credential::ENCRYPTION_CREDENTIAL);
500             creds.clear();
501             cc.getKeyNames().clear();
502             credResolver->resolve(creds,&cc);
503             for (vector<const Credential*>::const_iterator c = creds.begin(); c != creds.end(); ++c) {
504                 KeyInfo* kinfo = (*c)->getKeyInfo();
505                 if (kinfo) {
506                     auto_ptr<KeyDescriptor> kd(KeyDescriptorBuilder::buildKeyDescriptor());
507                     kd->setUse(KeyDescriptor::KEYTYPE_ENCRYPTION);
508                     kd->setKeyInfo(kinfo);
509                     s << *(kd.get());
510                 }
511             }
512         }
513     }
514
515     s << "<Status>" << status << "</Status></StatusHandler>";
516
517     httpResponse.setContentType("text/xml");
518     return make_pair(true, httpResponse.sendResponse(s));
519 #else
520     return make_pair(false,0L);
521 #endif
522 }
523
524 #ifdef WIN32
525 typedef void (WINAPI *PGNSI)(LPSYSTEM_INFO);
526 #endif
527
528 ostream& StatusHandler::systemInfo(ostream& os) const
529 {
530 #if defined(HAVE_SYS_UTSNAME_H)
531     struct utsname sysinfo;
532     if (uname(&sysinfo) == 0) {
533         os << "<NonWindows";
534         if (*sysinfo.sysname)
535             os << " sysname='" << sysinfo.sysname << "'";
536         if (*sysinfo.nodename)
537             os << " nodename='" << sysinfo.nodename << "'";
538         if (*sysinfo.release)
539             os << " release='" << sysinfo.release << "'";
540         if (*sysinfo.version)
541             os << " version='" << sysinfo.version << "'";
542         if (*sysinfo.machine)
543             os << " machine='" << sysinfo.machine << "'";
544         os << "/>";
545     }
546 #elif defined(WIN32)
547     OSVERSIONINFOEX osvi;
548     memset(&osvi, 0, sizeof(OSVERSIONINFOEX));
549     osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEX);
550     if(GetVersionEx((OSVERSIONINFO*)&osvi)) {
551         os << "<Windows"
552            << " version='" << osvi.dwMajorVersion << "." << osvi.dwMinorVersion << "'"
553            << " build='" << osvi.dwBuildNumber << "'";
554         if (osvi.wServicePackMajor > 0)
555             os << " servicepack='" << osvi.wServicePackMajor << "." << osvi.wServicePackMinor << "'";
556         switch (osvi.wProductType) {
557             case VER_NT_WORKSTATION:
558                 os << " producttype='Workstation'";
559                 break;
560             case VER_NT_SERVER:
561             case VER_NT_DOMAIN_CONTROLLER:
562                 os << " producttype='Server'";
563                 break;
564         }
565
566         SYSTEM_INFO si;
567         memset(&si, 0, sizeof(SYSTEM_INFO));
568         PGNSI pGNSI = (PGNSI)GetProcAddress(GetModuleHandle(TEXT("kernel32.dll")), "GetNativeSystemInfo");
569         if(pGNSI)
570             pGNSI(&si);
571         else
572             GetSystemInfo(&si);
573         switch (si.dwProcessorType) {
574             case PROCESSOR_ARCHITECTURE_INTEL:
575                 os << " arch='i386'";
576                 break;
577             case PROCESSOR_ARCHITECTURE_AMD64:
578                 os << " arch='x86_64'";
579                 break;
580             case PROCESSOR_ARCHITECTURE_IA64:
581                 os << " arch='IA64'";
582                 break;
583         }
584         os << " cpucount='" << si.dwNumberOfProcessors << "'";
585
586         MEMORYSTATUSEX ms;
587         memset(&ms, 0, sizeof(MEMORYSTATUSEX));
588         ms.dwLength = sizeof(MEMORYSTATUSEX);
589         if (GlobalMemoryStatusEx(&ms)) {
590             os << " memory='" << (ms.ullTotalPhys / (1024 * 1024)) << "M'";
591         }
592
593         os << "/>";
594     }
595 #endif
596     return os;
597 }