2 * Copyright 2001-2010 Internet2
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
20 * Handler for exposing information about the internals of the SP.
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"
32 #include <xmltooling/version.h>
33 #include <xmltooling/util/DateTime.h>
35 #ifdef HAVE_SYS_UTSNAME_H
36 # include <sys/utsname.h>
39 using namespace shibsp;
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;
51 using namespace xmltooling;
56 #if defined (_MSC_VER)
57 #pragma warning( push )
58 #pragma warning( disable : 4250 )
61 class SHIBSP_DLLLOCAL Blocker : public DOMNodeFilter
64 #ifdef SHIBSP_XERCESC_SHORT_ACCEPTNODE
69 acceptNode(const DOMNode* node) const {
74 static SHIBSP_DLLLOCAL Blocker g_Blocker;
76 class SHIBSP_API StatusHandler : public AbstractHandler, public RemotedHandler
79 StatusHandler(const DOMElement* e, const char* appId);
80 virtual ~StatusHandler() {}
82 pair<bool,long> run(SPRequest& request, bool isHandler=true) const;
83 void receive(DDF& in, ostream& out);
86 pair<bool,long> processMessage(const Application& application, const HTTPRequest& httpRequest, HTTPResponse& httpResponse) const;
87 ostream& systemInfo(ostream& os) const;
92 #if defined (_MSC_VER)
93 #pragma warning( pop )
96 Handler* SHIBSP_DLLLOCAL StatusHandlerFactory(const pair<const DOMElement*,const char*>& p)
98 return new StatusHandler(p.first, p.second);
101 #ifndef XMLTOOLING_NO_XMLSEC
102 vector<XSECCryptoX509*> g_NoCerts;
104 vector<string> g_NoCerts;
107 static char _x2c(const char *what)
111 digit = (what[0] >= 'A' ? ((what[0] & 0xdf) - 'A')+10 : (what[0] - '0'));
113 digit += (what[1] >= 'A' ? ((what[1] & 0xdf) - 'A')+10 : (what[1] - '0'));
117 class DummyRequest : public HTTPRequest
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)) {
126 else if (url && !strncasecmp(url,"https://",8)) {
132 if (url && !strnicmp(url,"http://",7)) {
137 else if (url && !strnicmp(url,"https://",8)) {
144 throw invalid_argument("Target parameter was not an absolute URL.");
146 m_query = strchr(url,'?');
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());
158 m_hostname.assign(url, slash - url);
166 else if (*slash != '%') {
171 if (!isxdigit(*slash) || !isxdigit(*(slash+1)))
172 throw invalid_argument("Bad request, contained unsupported encoded characters.");
173 m_uri += _x2c(slash);
184 const char* getRequestURL() const {
187 const char* getScheme() const {
190 const char* getHostname() const {
191 return m_hostname.c_str();
193 int getPort() const {
196 const char* getRequestURI() const {
197 return m_uri.c_str();
199 const char* getMethod() const {
202 string getContentType() const {
205 long getContentLength() const {
208 string getRemoteAddr() const {
211 string getRemoteUser() const {
214 const char* getRequestBody() const {
217 const char* getQueryString() const {
220 const char* getParameter(const char* name) const
223 m_parser=new CGIParser(*this);
225 pair<CGIParser::walker,CGIParser::walker> bounds=m_parser->getParameters(name);
226 return (bounds.first==bounds.second) ? nullptr : bounds.first->second;
228 vector<const char*>::size_type getParameters(const char* name, vector<const char*>& values) const
231 m_parser=new CGIParser(*this);
233 pair<CGIParser::walker,CGIParser::walker> bounds=m_parser->getParameters(name);
234 while (bounds.first!=bounds.second) {
235 values.push_back(bounds.first->second);
238 return values.size();
240 string getHeader(const char* name) const {
244 #ifndef XMLTOOLING_NO_XMLSEC
245 std::vector<XSECCryptoX509*>&
247 std::vector<std::string>&
249 getClientCertificates() const {
254 mutable CGIParser* m_parser;
256 const char* m_scheme;
259 string m_hostname,m_uri;
263 StatusHandler::StatusHandler(const DOMElement* e, const char* appId)
264 : AbstractHandler(e, Category::getInstance(SHIBSP_LOGCAT".StatusHandler"), &g_Blocker)
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");
272 string aclbuf=acl.second;
274 for (unsigned int i=0; i < aclbuf.length(); i++) {
275 if (aclbuf.at(i)==' ') {
276 m_acl.insert(aclbuf.substr(j, i-j));
280 m_acl.insert(aclbuf.substr(j, aclbuf.length()-j));
285 pair<bool,long> StatusHandler::run(SPRequest& request, bool isHandler) const
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));
296 const char* target = request.getParameter("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);
304 DateTime now(time(nullptr));
306 auto_ptr_char timestamp(now.getFormattedString());
307 request.setContentType("text/xml");
309 msg << "<StatusHandler time='" << timestamp.get() << "'>";
310 msg << "<Version Xerces-C='" << XERCES_FULLVERSIONDOT
311 << "' XML-Tooling-C='" << XMLTOOLING_FULLVERSIONDOT
313 << "' XML-Security-C='" << XSEC_FULLVERSIONDOT
314 << "' OpenSAML-C='" << OPENSAML_FULLVERSIONDOT
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));
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);
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);
339 catch (XMLToolingException& ex) {
340 m_log.error("error while processing request: %s", ex.what());
341 DateTime now(time(nullptr));
343 auto_ptr_char timestamp(now.getFormattedString());
344 request.setContentType("text/xml");
346 msg << "<StatusHandler time='" << timestamp.get() << "'>";
347 msg << "<Version Xerces-C='" << XERCES_FULLVERSIONDOT
348 << "' XML-Tooling-C='" << XMLTOOLING_FULLVERSIONDOT
350 << "' XML-Security-C='" << XSEC_FULLVERSIONDOT
351 << "' OpenSAML-C='" << OPENSAML_FULLVERSIONDOT
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));
358 catch (exception& ex) {
359 m_log.error("error while processing request: %s", ex.what());
360 DateTime now(time(nullptr));
362 auto_ptr_char timestamp(now.getFormattedString());
363 request.setContentType("text/xml");
365 msg << "<StatusHandler time='" << timestamp.get() << "'>";
366 msg << "<Version Xerces-C='" << XERCES_FULLVERSIONDOT
367 << "' XML-Tooling-C='" << XMLTOOLING_FULLVERSIONDOT
369 << "' XML-Security-C='" << XSEC_FULLVERSIONDOT
370 << "' OpenSAML-C='" << OPENSAML_FULLVERSIONDOT
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));
379 void StatusHandler::receive(DDF& in, ostream& out)
382 const char* aid=in["application_id"].string();
383 const Application* app=aid ? SPConfig::getConfig().getServiceProvider()->getApplication(aid) : nullptr;
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?");
390 // Wrap a response shim.
392 DDFJanitor jout(ret);
393 auto_ptr<HTTPRequest> req(getRequest(in));
394 auto_ptr<HTTPResponse> resp(getResponse(ret));
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());
403 pair<bool,long> StatusHandler::processMessage(
404 const Application& application, const HTTPRequest& httpRequest, HTTPResponse& httpResponse
408 m_log.debug("processing status request");
410 DateTime now(time(nullptr));
412 auto_ptr_char timestamp(now.getFormattedString());
415 s << "<StatusHandler time='" << timestamp.get() << "'>";
416 const char* status = "<OK/>";
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 << "'/>";
426 const char* param = nullptr;
430 // General configuration and status report.
432 SessionCache* sc = application.getServiceProvider().getSessionCache(false);
435 s << "<SessionCache><OK/></SessionCache>";
438 s << "<SessionCache><None/></SessionCache>";
441 catch (XMLToolingException& ex) {
442 s << "<SessionCache><Exception type='" << ex.getClassName() << "'>" << ex.what() << "</Exception></SessionCache>";
443 status = "<Partial/>";
445 catch (exception& ex) {
446 s << "<SessionCache><Exception type='std::exception'>" << ex.what() << "</Exception></SessionCache>";
447 status = "<Partial/>";
450 const PropertySet* relyingParty=nullptr;
451 param=httpRequest.getParameter("entityID");
453 MetadataProvider* m = application.getMetadataProvider();
455 relyingParty = application.getRelyingParty(m->getEntityDescriptor(MetadataProviderCriteria(application, param)).first);
458 relyingParty = &application;
461 s << "<Application id='" << application.getId() << "' entityID='" << relyingParty->getString("entityID").second << "'/>";
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 << "'";
474 CredentialResolver* credResolver=application.getCredentialResolver();
476 Locker credLocker(credResolver);
477 CredentialCriteria cc;
478 cc.setUsage(Credential::SIGNING_CREDENTIAL);
479 pair<bool,const char*> keyName = relyingParty->getString("keyName");
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();
487 auto_ptr<KeyDescriptor> kd(KeyDescriptorBuilder::buildKeyDescriptor());
488 kd->setUse(KeyDescriptor::KEYTYPE_SIGNING);
489 kd->setKeyInfo(kinfo);
494 cc.setUsage(Credential::ENCRYPTION_CREDENTIAL);
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();
501 auto_ptr<KeyDescriptor> kd(KeyDescriptorBuilder::buildKeyDescriptor());
502 kd->setUse(KeyDescriptor::KEYTYPE_ENCRYPTION);
503 kd->setKeyInfo(kinfo);
510 s << "<Status>" << status << "</Status></StatusHandler>";
512 httpResponse.setContentType("text/xml");
513 return make_pair(true, httpResponse.sendResponse(s));
515 return make_pair(false,0L);
520 typedef void (WINAPI *PGNSI)(LPSYSTEM_INFO);
523 ostream& StatusHandler::systemInfo(ostream& os) const
525 #if defined(HAVE_SYS_UTSNAME_H)
526 struct utsname sysinfo;
527 if (uname(&sysinfo) == 0) {
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 << "'";
542 OSVERSIONINFOEX osvi;
543 memset(&osvi, 0, sizeof(OSVERSIONINFOEX));
544 osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEX);
545 if(GetVersionEx((OSVERSIONINFO*)&osvi)) {
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'";
556 case VER_NT_DOMAIN_CONTROLLER:
557 os << " producttype='Server'";
562 memset(&si, 0, sizeof(SYSTEM_INFO));
563 PGNSI pGNSI = (PGNSI)GetProcAddress(GetModuleHandle(TEXT("kernel32.dll")), "GetNativeSystemInfo");
568 switch (si.dwProcessorType) {
569 case PROCESSOR_ARCHITECTURE_INTEL:
570 os << " arch='i386'";
572 case PROCESSOR_ARCHITECTURE_AMD64:
573 os << " arch='x86_64'";
575 case PROCESSOR_ARCHITECTURE_IA64:
576 os << " arch='IA64'";
579 os << " cpucount='" << si.dwNumberOfProcessors << "'";
582 memset(&ms, 0, sizeof(MEMORYSTATUSEX));
583 ms.dwLength = sizeof(MEMORYSTATUSEX);
584 if (GlobalMemoryStatusEx(&ms)) {
585 os << " memory='" << (ms.ullTotalPhys / (1024 * 1024)) << "M'";