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.
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
12 * http://www.apache.org/licenses/LICENSE-2.0
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.
24 * Handler for exposing information about the internals of the SP.
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"
36 #include <xmltooling/version.h>
37 #include <xmltooling/util/DateTime.h>
39 #ifdef HAVE_SYS_UTSNAME_H
40 # include <sys/utsname.h>
43 using namespace shibsp;
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;
55 using namespace xmltooling;
60 #if defined (_MSC_VER)
61 #pragma warning( push )
62 #pragma warning( disable : 4250 )
65 class SHIBSP_DLLLOCAL Blocker : public DOMNodeFilter
68 #ifdef SHIBSP_XERCESC_SHORT_ACCEPTNODE
73 acceptNode(const DOMNode* node) const {
78 static SHIBSP_DLLLOCAL Blocker g_Blocker;
80 class SHIBSP_API StatusHandler : public AbstractHandler, public RemotedHandler
83 StatusHandler(const DOMElement* e, const char* appId);
84 virtual ~StatusHandler() {}
86 pair<bool,long> run(SPRequest& request, bool isHandler=true) const;
87 void receive(DDF& in, ostream& out);
90 pair<bool,long> processMessage(const Application& application, const HTTPRequest& httpRequest, HTTPResponse& httpResponse) const;
91 ostream& systemInfo(ostream& os) const;
96 #if defined (_MSC_VER)
97 #pragma warning( pop )
100 Handler* SHIBSP_DLLLOCAL StatusHandlerFactory(const pair<const DOMElement*,const char*>& p)
102 return new StatusHandler(p.first, p.second);
105 #ifndef XMLTOOLING_NO_XMLSEC
106 vector<XSECCryptoX509*> g_NoCerts;
108 vector<string> g_NoCerts;
111 static char _x2c(const char *what)
115 digit = (what[0] >= 'A' ? ((what[0] & 0xdf) - 'A')+10 : (what[0] - '0'));
117 digit += (what[1] >= 'A' ? ((what[1] & 0xdf) - 'A')+10 : (what[1] - '0'));
121 class DummyRequest : public HTTPRequest
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)) {
130 else if (url && !strncasecmp(url,"https://",8)) {
136 if (url && !strnicmp(url,"http://",7)) {
141 else if (url && !strnicmp(url,"https://",8)) {
148 throw invalid_argument("Target parameter was not an absolute URL.");
150 m_query = strchr(url,'?');
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());
162 m_hostname.assign(url, slash - url);
170 else if (*slash != '%') {
175 if (!isxdigit(*slash) || !isxdigit(*(slash+1)))
176 throw invalid_argument("Bad request, contained unsupported encoded characters.");
177 m_uri += _x2c(slash);
184 virtual ~DummyRequest() {
188 const char* getRequestURL() const {
191 const char* getScheme() const {
194 const char* getHostname() const {
195 return m_hostname.c_str();
197 int getPort() const {
200 const char* getRequestURI() const {
201 return m_uri.c_str();
203 const char* getMethod() const {
206 string getContentType() const {
209 long getContentLength() const {
212 string getRemoteAddr() const {
215 string getRemoteUser() const {
218 const char* getRequestBody() const {
221 const char* getQueryString() const {
224 const char* getParameter(const char* name) const
227 m_parser=new CGIParser(*this);
229 pair<CGIParser::walker,CGIParser::walker> bounds=m_parser->getParameters(name);
230 return (bounds.first==bounds.second) ? nullptr : bounds.first->second;
232 vector<const char*>::size_type getParameters(const char* name, vector<const char*>& values) const
235 m_parser=new CGIParser(*this);
237 pair<CGIParser::walker,CGIParser::walker> bounds=m_parser->getParameters(name);
238 while (bounds.first!=bounds.second) {
239 values.push_back(bounds.first->second);
242 return values.size();
244 string getHeader(const char* name) const {
248 #ifndef XMLTOOLING_NO_XMLSEC
249 std::vector<XSECCryptoX509*>&
251 std::vector<std::string>&
253 getClientCertificates() const {
258 mutable CGIParser* m_parser;
260 const char* m_scheme;
263 string m_hostname,m_uri;
267 StatusHandler::StatusHandler(const DOMElement* e, const char* appId)
268 : AbstractHandler(e, Category::getInstance(SHIBSP_LOGCAT".StatusHandler"), &g_Blocker)
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");
276 string aclbuf=acl.second;
278 for (unsigned int i=0; i < aclbuf.length(); i++) {
279 if (aclbuf.at(i)==' ') {
280 m_acl.insert(aclbuf.substr(j, i-j));
284 m_acl.insert(aclbuf.substr(j, aclbuf.length()-j));
289 pair<bool,long> StatusHandler::run(SPRequest& request, bool isHandler) const
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));
300 const char* target = request.getParameter("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);
308 DateTime now(time(nullptr));
310 auto_ptr_char timestamp(now.getFormattedString());
311 request.setContentType("text/xml");
313 msg << "<StatusHandler time='" << timestamp.get() << "'>";
314 msg << "<Version Xerces-C='" << XERCES_FULLVERSIONDOT
315 << "' XML-Tooling-C='" << gXMLToolingDotVersionStr
317 << "' XML-Security-C='" << XSEC_FULLVERSIONDOT
318 << "' OpenSAML-C='" << gOpenSAMLDotVersionStr
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));
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);
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);
343 catch (XMLToolingException& ex) {
344 m_log.error("error while processing request: %s", ex.what());
345 DateTime now(time(nullptr));
347 auto_ptr_char timestamp(now.getFormattedString());
348 request.setContentType("text/xml");
350 msg << "<StatusHandler time='" << timestamp.get() << "'>";
351 msg << "<Version Xerces-C='" << XERCES_FULLVERSIONDOT
352 << "' XML-Tooling-C='" << gXMLToolingDotVersionStr
354 << "' XML-Security-C='" << XSEC_FULLVERSIONDOT
355 << "' OpenSAML-C='" << gOpenSAMLDotVersionStr
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));
362 catch (exception& ex) {
363 m_log.error("error while processing request: %s", ex.what());
364 DateTime now(time(nullptr));
366 auto_ptr_char timestamp(now.getFormattedString());
367 request.setContentType("text/xml");
369 msg << "<StatusHandler time='" << timestamp.get() << "'>";
370 msg << "<Version Xerces-C='" << XERCES_FULLVERSIONDOT
371 << "' XML-Tooling-C='" << gXMLToolingDotVersionStr
373 << "' XML-Security-C='" << XSEC_FULLVERSIONDOT
374 << "' OpenSAML-C='" << gOpenSAMLDotVersionStr
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));
383 void StatusHandler::receive(DDF& in, ostream& out)
386 const char* aid=in["application_id"].string();
387 const Application* app=aid ? SPConfig::getConfig().getServiceProvider()->getApplication(aid) : nullptr;
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?");
394 // Wrap a response shim.
396 DDFJanitor jout(ret);
397 auto_ptr<HTTPRequest> req(getRequest(in));
398 auto_ptr<HTTPResponse> resp(getResponse(ret));
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());
407 pair<bool,long> StatusHandler::processMessage(
408 const Application& application, const HTTPRequest& httpRequest, HTTPResponse& httpResponse
412 m_log.debug("processing status request");
414 DateTime now(time(nullptr));
416 auto_ptr_char timestamp(now.getFormattedString());
419 s << "<StatusHandler time='" << timestamp.get() << "'>";
420 const char* status = "<OK/>";
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 << "'/>";
430 const char* param = nullptr;
434 // General configuration and status report.
436 SessionCache* sc = application.getServiceProvider().getSessionCache(false);
439 s << "<SessionCache><OK/></SessionCache>";
442 s << "<SessionCache><None/></SessionCache>";
445 catch (XMLToolingException& ex) {
446 s << "<SessionCache><Exception type='" << ex.getClassName() << "'>" << ex.what() << "</Exception></SessionCache>";
447 status = "<Partial/>";
449 catch (exception& ex) {
450 s << "<SessionCache><Exception type='std::exception'>" << ex.what() << "</Exception></SessionCache>";
451 status = "<Partial/>";
454 MetadataProvider* m = application.getMetadataProvider();
457 const PropertySet* relyingParty=nullptr;
458 param=httpRequest.getParameter("entityID");
460 relyingParty = application.getRelyingParty(m->getEntityDescriptor(MetadataProviderCriteria(application, param)).first);
462 relyingParty = &application;
464 s << "<Application id='" << application.getId() << "' entityID='" << relyingParty->getString("entityID").second << "'/>";
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 << "'";
479 CredentialResolver* credResolver=application.getCredentialResolver();
481 Locker credLocker(credResolver);
482 CredentialCriteria cc;
483 cc.setUsage(Credential::SIGNING_CREDENTIAL);
484 pair<bool,const char*> keyName = relyingParty->getString("keyName");
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();
492 auto_ptr<KeyDescriptor> kd(KeyDescriptorBuilder::buildKeyDescriptor());
493 kd->setUse(KeyDescriptor::KEYTYPE_SIGNING);
494 kd->setKeyInfo(kinfo);
499 cc.setUsage(Credential::ENCRYPTION_CREDENTIAL);
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();
506 auto_ptr<KeyDescriptor> kd(KeyDescriptorBuilder::buildKeyDescriptor());
507 kd->setUse(KeyDescriptor::KEYTYPE_ENCRYPTION);
508 kd->setKeyInfo(kinfo);
515 s << "<Status>" << status << "</Status></StatusHandler>";
517 httpResponse.setContentType("text/xml");
518 return make_pair(true, httpResponse.sendResponse(s));
520 return make_pair(false,0L);
525 typedef void (WINAPI *PGNSI)(LPSYSTEM_INFO);
528 ostream& StatusHandler::systemInfo(ostream& os) const
530 #if defined(HAVE_SYS_UTSNAME_H)
531 struct utsname sysinfo;
532 if (uname(&sysinfo) == 0) {
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 << "'";
547 OSVERSIONINFOEX osvi;
548 memset(&osvi, 0, sizeof(OSVERSIONINFOEX));
549 osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEX);
550 if(GetVersionEx((OSVERSIONINFO*)&osvi)) {
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'";
561 case VER_NT_DOMAIN_CONTROLLER:
562 os << " producttype='Server'";
567 memset(&si, 0, sizeof(SYSTEM_INFO));
568 PGNSI pGNSI = (PGNSI)GetProcAddress(GetModuleHandle(TEXT("kernel32.dll")), "GetNativeSystemInfo");
573 switch (si.dwProcessorType) {
574 case PROCESSOR_ARCHITECTURE_INTEL:
575 os << " arch='i386'";
577 case PROCESSOR_ARCHITECTURE_AMD64:
578 os << " arch='x86_64'";
580 case PROCESSOR_ARCHITECTURE_IA64:
581 os << " arch='IA64'";
584 os << " cpucount='" << si.dwNumberOfProcessors << "'";
587 memset(&ms, 0, sizeof(MEMORYSTATUSEX));
588 ms.dwLength = sizeof(MEMORYSTATUSEX);
589 if (GlobalMemoryStatusEx(&ms)) {
590 os << " memory='" << (ms.ullTotalPhys / (1024 * 1024)) << "M'";