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