2 * Licensed to UCAID under one or more contributor license agreements.
3 * See the NOTICE file distributed with this work for additional information
4 * regarding copyright ownership. The ASF licenses this file to you under
5 * the Apache License, Version 2.0 (the "License"); you may not use this
6 * file except in compliance with the License. You may obtain a copy of the
9 * http://www.apache.org/licenses/LICENSE-2.0
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
21 * Handler for exposing information about the internals of the SP.
25 #include "Application.h"
26 #include "exceptions.h"
27 #include "ServiceProvider.h"
28 #include "SPRequest.h"
29 #include "handler/AbstractHandler.h"
30 #include "handler/RemotedHandler.h"
31 #include "util/CGIParser.h"
33 #include <xmltooling/version.h>
34 #include <xmltooling/util/DateTime.h>
36 #ifdef HAVE_SYS_UTSNAME_H
37 # include <sys/utsname.h>
40 using namespace shibsp;
42 # include "SessionCache.h"
43 # include "metadata/MetadataProviderCriteria.h"
44 # include <saml/version.h>
45 # include <saml/saml2/metadata/Metadata.h>
46 # include <xmltooling/security/Credential.h>
47 # include <xmltooling/security/CredentialCriteria.h>
48 using namespace opensaml::saml2md;
49 using namespace opensaml;
50 using namespace xmlsignature;
52 using namespace xmltooling;
57 #if defined (_MSC_VER)
58 #pragma warning( push )
59 #pragma warning( disable : 4250 )
62 class SHIBSP_DLLLOCAL Blocker : public DOMNodeFilter
65 #ifdef SHIBSP_XERCESC_SHORT_ACCEPTNODE
70 acceptNode(const DOMNode* node) const {
75 static SHIBSP_DLLLOCAL Blocker g_Blocker;
77 class SHIBSP_API StatusHandler : public AbstractHandler, public RemotedHandler
80 StatusHandler(const DOMElement* e, const char* appId);
81 virtual ~StatusHandler() {}
83 pair<bool,long> run(SPRequest& request, bool isHandler=true) const;
84 void receive(DDF& in, ostream& out);
87 pair<bool,long> processMessage(const Application& application, const HTTPRequest& httpRequest, HTTPResponse& httpResponse) const;
88 ostream& systemInfo(ostream& os) const;
93 #if defined (_MSC_VER)
94 #pragma warning( pop )
97 Handler* SHIBSP_DLLLOCAL StatusHandlerFactory(const pair<const DOMElement*,const char*>& p)
99 return new StatusHandler(p.first, p.second);
102 #ifndef XMLTOOLING_NO_XMLSEC
103 vector<XSECCryptoX509*> g_NoCerts;
105 vector<string> g_NoCerts;
108 static char _x2c(const char *what)
112 digit = (what[0] >= 'A' ? ((what[0] & 0xdf) - 'A')+10 : (what[0] - '0'));
114 digit += (what[1] >= 'A' ? ((what[1] & 0xdf) - 'A')+10 : (what[1] - '0'));
118 class DummyRequest : public HTTPRequest
121 DummyRequest(const char* url) : m_parser(nullptr), m_url(url), m_scheme(nullptr), m_query(nullptr), m_port(0) {
122 #ifdef HAVE_STRCASECMP
123 if (url && !strncasecmp(url,"http://",7)) {
127 else if (url && !strncasecmp(url,"https://",8)) {
133 if (url && !strnicmp(url,"http://",7)) {
138 else if (url && !strnicmp(url,"https://",8)) {
145 throw invalid_argument("Target parameter was not an absolute URL.");
147 m_query = strchr(url,'?');
151 const char* slash = strchr(url, '/');
152 const char* colon = strchr(url, ':');
153 if (colon && colon < slash) {
154 m_hostname.assign(url, colon-url);
155 string port(colon + 1, slash - colon);
156 m_port = atoi(port.c_str());
159 m_hostname.assign(url, slash - url);
167 else if (*slash != '%') {
172 if (!isxdigit(*slash) || !isxdigit(*(slash+1)))
173 throw invalid_argument("Bad request, contained unsupported encoded characters.");
174 m_uri += _x2c(slash);
185 const char* getRequestURL() const {
188 const char* getScheme() const {
191 const char* getHostname() const {
192 return m_hostname.c_str();
194 int getPort() const {
197 const char* getRequestURI() const {
198 return m_uri.c_str();
200 const char* getMethod() const {
203 string getContentType() const {
206 long getContentLength() const {
209 string getRemoteAddr() const {
212 string getRemoteUser() const {
215 const char* getRequestBody() const {
218 const char* getQueryString() const {
221 const char* getParameter(const char* name) const
224 m_parser=new CGIParser(*this);
226 pair<CGIParser::walker,CGIParser::walker> bounds=m_parser->getParameters(name);
227 return (bounds.first==bounds.second) ? nullptr : bounds.first->second;
229 vector<const char*>::size_type getParameters(const char* name, vector<const char*>& values) const
232 m_parser=new CGIParser(*this);
234 pair<CGIParser::walker,CGIParser::walker> bounds=m_parser->getParameters(name);
235 while (bounds.first!=bounds.second) {
236 values.push_back(bounds.first->second);
239 return values.size();
241 string getHeader(const char* name) const {
245 #ifndef XMLTOOLING_NO_XMLSEC
246 std::vector<XSECCryptoX509*>&
248 std::vector<std::string>&
250 getClientCertificates() const {
255 mutable CGIParser* m_parser;
257 const char* m_scheme;
260 string m_hostname,m_uri;
264 StatusHandler::StatusHandler(const DOMElement* e, const char* appId)
265 : AbstractHandler(e, Category::getInstance(SHIBSP_LOGCAT".StatusHandler"), &g_Blocker)
267 string address(appId);
268 address += getString("Location").second;
269 setAddress(address.c_str());
270 if (SPConfig::getConfig().isEnabled(SPConfig::InProcess)) {
271 pair<bool,const char*> acl = getString("acl");
273 string aclbuf=acl.second;
275 for (unsigned int i=0; i < aclbuf.length(); i++) {
276 if (aclbuf.at(i)==' ') {
277 m_acl.insert(aclbuf.substr(j, i-j));
281 m_acl.insert(aclbuf.substr(j, aclbuf.length()-j));
286 pair<bool,long> StatusHandler::run(SPRequest& request, bool isHandler) const
288 SPConfig& conf = SPConfig::getConfig();
289 if (conf.isEnabled(SPConfig::InProcess)) {
290 if (!m_acl.empty() && m_acl.count(request.getRemoteAddr()) == 0) {
291 m_log.error("status handler request blocked from invalid address (%s)", request.getRemoteAddr().c_str());
292 istringstream msg("Status Handler Blocked");
293 return make_pair(true,request.sendResponse(msg, HTTPResponse::XMLTOOLING_HTTP_STATUS_FORBIDDEN));
297 const char* target = request.getParameter("target");
299 // RequestMap query, so handle it inproc.
300 DummyRequest dummy(target);
301 RequestMapper::Settings settings = request.getApplication().getServiceProvider().getRequestMapper()->getSettings(dummy);
302 map<string,const char*> props;
303 settings.first->getAll(props);
305 DateTime now(time(nullptr));
307 auto_ptr_char timestamp(now.getFormattedString());
308 request.setContentType("text/xml");
310 msg << "<StatusHandler time='" << timestamp.get() << "'>";
311 msg << "<Version Xerces-C='" << XERCES_FULLVERSIONDOT
312 << "' XML-Tooling-C='" << gXMLToolingDotVersionStr
314 << "' XML-Security-C='" << XSEC_FULLVERSIONDOT
315 << "' OpenSAML-C='" << gOpenSAMLDotVersionStr
317 << "' Shibboleth='" << PACKAGE_VERSION << "'/>";
318 systemInfo(msg) << "<RequestSettings";
319 for (map<string,const char*>::const_iterator p = props.begin(); p != props.end(); ++p)
320 msg << ' ' << p->first << "='" << p->second << "'";
321 msg << '>' << target << "</RequestSettings>";
322 msg << "<Status><OK/></Status>";
323 msg << "</StatusHandler>";
324 return make_pair(true,request.sendResponse(msg));
328 if (conf.isEnabled(SPConfig::OutOfProcess)) {
329 // When out of process, we run natively and directly process the message.
330 return processMessage(request.getApplication(), request, request);
333 // When not out of process, we remote all the message processing.
334 DDF out,in = wrap(request);
335 DDFJanitor jin(in), jout(out);
336 out=request.getServiceProvider().getListenerService()->send(in);
337 return unwrap(request, out);
340 catch (XMLToolingException& ex) {
341 m_log.error("error while processing request: %s", ex.what());
342 DateTime now(time(nullptr));
344 auto_ptr_char timestamp(now.getFormattedString());
345 request.setContentType("text/xml");
347 msg << "<StatusHandler time='" << timestamp.get() << "'>";
348 msg << "<Version Xerces-C='" << XERCES_FULLVERSIONDOT
349 << "' XML-Tooling-C='" << gXMLToolingDotVersionStr
351 << "' XML-Security-C='" << XSEC_FULLVERSIONDOT
352 << "' OpenSAML-C='" << gOpenSAMLDotVersionStr
354 << "' Shibboleth='" << PACKAGE_VERSION << "'/>";
355 systemInfo(msg) << "<Status><Exception type='" << ex.getClassName() << "'>" << ex.what() << "</Exception></Status>";
356 msg << "</StatusHandler>";
357 return make_pair(true,request.sendResponse(msg, HTTPResponse::XMLTOOLING_HTTP_STATUS_ERROR));
359 catch (exception& ex) {
360 m_log.error("error while processing request: %s", ex.what());
361 DateTime now(time(nullptr));
363 auto_ptr_char timestamp(now.getFormattedString());
364 request.setContentType("text/xml");
366 msg << "<StatusHandler time='" << timestamp.get() << "'>";
367 msg << "<Version Xerces-C='" << XERCES_FULLVERSIONDOT
368 << "' XML-Tooling-C='" << gXMLToolingDotVersionStr
370 << "' XML-Security-C='" << XSEC_FULLVERSIONDOT
371 << "' OpenSAML-C='" << gOpenSAMLDotVersionStr
373 << "' Shibboleth='" << PACKAGE_VERSION << "'/>";
374 systemInfo(msg) << "<Status><Exception type='std::exception'>" << ex.what() << "</Exception></Status>";
375 msg << "</StatusHandler>";
376 return make_pair(true,request.sendResponse(msg, HTTPResponse::XMLTOOLING_HTTP_STATUS_ERROR));
380 void StatusHandler::receive(DDF& in, ostream& out)
383 const char* aid=in["application_id"].string();
384 const Application* app=aid ? SPConfig::getConfig().getServiceProvider()->getApplication(aid) : nullptr;
386 // Something's horribly wrong.
387 m_log.error("couldn't find application (%s) for status request", aid ? aid : "(missing)");
388 throw ConfigurationException("Unable to locate application for status request, deleted?");
391 // Wrap a response shim.
393 DDFJanitor jout(ret);
394 auto_ptr<HTTPRequest> req(getRequest(in));
395 auto_ptr<HTTPResponse> resp(getResponse(ret));
397 // Since we're remoted, the result should either be a throw, a false/0 return,
398 // which we just return as an empty structure, or a response/redirect,
399 // which we capture in the facade and send back.
400 processMessage(*app, *req.get(), *resp.get());
404 pair<bool,long> StatusHandler::processMessage(
405 const Application& application, const HTTPRequest& httpRequest, HTTPResponse& httpResponse
409 m_log.debug("processing status request");
411 DateTime now(time(nullptr));
413 auto_ptr_char timestamp(now.getFormattedString());
416 s << "<StatusHandler time='" << timestamp.get() << "'>";
417 const char* status = "<OK/>";
419 s << "<Version Xerces-C='" << XERCES_FULLVERSIONDOT
420 << "' XML-Tooling-C='" << gXMLToolingDotVersionStr
421 << "' XML-Security-C='" << XSEC_FULLVERSIONDOT
422 << "' OpenSAML-C='" << gOpenSAMLDotVersionStr
423 << "' Shibboleth='" << PACKAGE_VERSION << "'/>";
427 const char* param = nullptr;
431 // General configuration and status report.
433 SessionCache* sc = application.getServiceProvider().getSessionCache(false);
436 s << "<SessionCache><OK/></SessionCache>";
439 s << "<SessionCache><None/></SessionCache>";
442 catch (XMLToolingException& ex) {
443 s << "<SessionCache><Exception type='" << ex.getClassName() << "'>" << ex.what() << "</Exception></SessionCache>";
444 status = "<Partial/>";
446 catch (exception& ex) {
447 s << "<SessionCache><Exception type='std::exception'>" << ex.what() << "</Exception></SessionCache>";
448 status = "<Partial/>";
451 const PropertySet* relyingParty=nullptr;
452 param=httpRequest.getParameter("entityID");
454 MetadataProvider* m = application.getMetadataProvider();
456 relyingParty = application.getRelyingParty(m->getEntityDescriptor(MetadataProviderCriteria(application, param)).first);
459 relyingParty = &application;
462 s << "<Application id='" << application.getId() << "' entityID='" << relyingParty->getString("entityID").second << "'/>";
465 vector<const Handler*> handlers;
466 application.getHandlers(handlers);
467 for (vector<const Handler*>::const_iterator h = handlers.begin(); h != handlers.end(); ++h) {
468 s << "<Handler type='" << (*h)->getType() << "' Location='" << (*h)->getString("Location").second << "'";
469 if ((*h)->getString("Binding").first)
470 s << " Binding='" << (*h)->getString("Binding").second << "'";
475 CredentialResolver* credResolver=application.getCredentialResolver();
477 Locker credLocker(credResolver);
478 CredentialCriteria cc;
479 cc.setUsage(Credential::SIGNING_CREDENTIAL);
480 pair<bool,const char*> keyName = relyingParty->getString("keyName");
482 cc.getKeyNames().insert(keyName.second);
483 vector<const Credential*> creds;
484 credResolver->resolve(creds,&cc);
485 for (vector<const Credential*>::const_iterator c = creds.begin(); c != creds.end(); ++c) {
486 KeyInfo* kinfo = (*c)->getKeyInfo();
488 auto_ptr<KeyDescriptor> kd(KeyDescriptorBuilder::buildKeyDescriptor());
489 kd->setUse(KeyDescriptor::KEYTYPE_SIGNING);
490 kd->setKeyInfo(kinfo);
495 cc.setUsage(Credential::ENCRYPTION_CREDENTIAL);
497 cc.getKeyNames().clear();
498 credResolver->resolve(creds,&cc);
499 for (vector<const Credential*>::const_iterator c = creds.begin(); c != creds.end(); ++c) {
500 KeyInfo* kinfo = (*c)->getKeyInfo();
502 auto_ptr<KeyDescriptor> kd(KeyDescriptorBuilder::buildKeyDescriptor());
503 kd->setUse(KeyDescriptor::KEYTYPE_ENCRYPTION);
504 kd->setKeyInfo(kinfo);
511 s << "<Status>" << status << "</Status></StatusHandler>";
513 httpResponse.setContentType("text/xml");
514 return make_pair(true, httpResponse.sendResponse(s));
516 return make_pair(false,0L);
521 typedef void (WINAPI *PGNSI)(LPSYSTEM_INFO);
524 ostream& StatusHandler::systemInfo(ostream& os) const
526 #if defined(HAVE_SYS_UTSNAME_H)
527 struct utsname sysinfo;
528 if (uname(&sysinfo) == 0) {
530 if (*sysinfo.sysname)
531 os << " sysname='" << sysinfo.sysname << "'";
532 if (*sysinfo.nodename)
533 os << " nodename='" << sysinfo.nodename << "'";
534 if (*sysinfo.release)
535 os << " release='" << sysinfo.release << "'";
536 if (*sysinfo.version)
537 os << " version='" << sysinfo.version << "'";
538 if (*sysinfo.machine)
539 os << " machine='" << sysinfo.machine << "'";
543 OSVERSIONINFOEX osvi;
544 memset(&osvi, 0, sizeof(OSVERSIONINFOEX));
545 osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEX);
546 if(GetVersionEx((OSVERSIONINFO*)&osvi)) {
548 << " version='" << osvi.dwMajorVersion << "." << osvi.dwMinorVersion << "'"
549 << " build='" << osvi.dwBuildNumber << "'";
550 if (osvi.wServicePackMajor > 0)
551 os << " servicepack='" << osvi.wServicePackMajor << "." << osvi.wServicePackMinor << "'";
552 switch (osvi.wProductType) {
553 case VER_NT_WORKSTATION:
554 os << " producttype='Workstation'";
557 case VER_NT_DOMAIN_CONTROLLER:
558 os << " producttype='Server'";
563 memset(&si, 0, sizeof(SYSTEM_INFO));
564 PGNSI pGNSI = (PGNSI)GetProcAddress(GetModuleHandle(TEXT("kernel32.dll")), "GetNativeSystemInfo");
569 switch (si.dwProcessorType) {
570 case PROCESSOR_ARCHITECTURE_INTEL:
571 os << " arch='i386'";
573 case PROCESSOR_ARCHITECTURE_AMD64:
574 os << " arch='x86_64'";
576 case PROCESSOR_ARCHITECTURE_IA64:
577 os << " arch='IA64'";
580 os << " cpucount='" << si.dwNumberOfProcessors << "'";
583 memset(&ms, 0, sizeof(MEMORYSTATUSEX));
584 ms.dwLength = sizeof(MEMORYSTATUSEX);
585 if (GlobalMemoryStatusEx(&ms)) {
586 os << " memory='" << (ms.ullTotalPhys / (1024 * 1024)) << "M'";