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/IPRange.h"
35 #include "util/CGIParser.h"
37 #include <boost/bind.hpp>
38 #include <boost/iterator/indirect_iterator.hpp>
39 #include <boost/scoped_ptr.hpp>
40 #include <boost/algorithm/string.hpp>
41 #include <xmltooling/version.h>
42 #include <xmltooling/util/DateTime.h>
44 #ifdef HAVE_SYS_UTSNAME_H
45 # include <sys/utsname.h>
48 using namespace shibsp;
50 # include "SessionCache.h"
51 # include "metadata/MetadataProviderCriteria.h"
52 # include <saml/version.h>
53 # include <saml/saml2/metadata/Metadata.h>
54 # include <xmltooling/security/Credential.h>
55 # include <xmltooling/security/CredentialCriteria.h>
56 using namespace opensaml::saml2md;
57 using namespace opensaml;
58 using namespace xmlsignature;
60 using namespace xmltooling;
61 using namespace boost;
66 #if defined (_MSC_VER)
67 #pragma warning( push )
68 #pragma warning( disable : 4250 )
71 class SHIBSP_DLLLOCAL Blocker : public DOMNodeFilter
74 #ifdef SHIBSP_XERCESC_SHORT_ACCEPTNODE
79 acceptNode(const DOMNode* node) const {
84 static SHIBSP_DLLLOCAL Blocker g_Blocker;
86 class SHIBSP_API StatusHandler : public AbstractHandler, public RemotedHandler
89 StatusHandler(const DOMElement* e, const char* appId);
90 virtual ~StatusHandler() {}
92 pair<bool,long> run(SPRequest& request, bool isHandler=true) const;
93 void receive(DDF& in, ostream& out);
96 pair<bool,long> processMessage(const Application& application, const HTTPRequest& httpRequest, HTTPResponse& httpResponse) const;
97 ostream& systemInfo(ostream& os) const;
98 void parseACL(const string& acl) {
100 m_acl.push_back(IPRange::parseCIDRBlock(acl.c_str()));
102 catch (std::exception& ex) {
103 m_log.error("invalid CIDR block (%s): %s", acl.c_str(), ex.what());
107 vector<IPRange> m_acl;
110 #if defined (_MSC_VER)
111 #pragma warning( pop )
114 Handler* SHIBSP_DLLLOCAL StatusHandlerFactory(const pair<const DOMElement*,const char*>& p)
116 return new StatusHandler(p.first, p.second);
119 #ifndef XMLTOOLING_NO_XMLSEC
120 vector<XSECCryptoX509*> g_NoCerts;
122 vector<string> g_NoCerts;
125 static char _x2c(const char *what)
129 digit = (what[0] >= 'A' ? ((what[0] & 0xdf) - 'A')+10 : (what[0] - '0'));
131 digit += (what[1] >= 'A' ? ((what[1] & 0xdf) - 'A')+10 : (what[1] - '0'));
135 class DummyRequest : public HTTPRequest
138 DummyRequest(const char* url) : m_parser(nullptr), m_url(url), m_scheme(nullptr), m_query(nullptr), m_port(0) {
139 #ifdef HAVE_STRCASECMP
140 if (url && !strncasecmp(url,"http://", 7)) {
145 else if (url && !strncasecmp(url,"https://", 8)) {
152 if (url && !strnicmp(url,"http://", 7)) {
157 else if (url && !strnicmp(url,"https://", 8)) {
164 throw invalid_argument("Target parameter was not an absolute URL.");
166 m_query = strchr(url,'?');
170 const char* slash = strchr(url, '/');
171 const char* colon = strchr(url, ':');
172 if (colon && colon < slash) {
173 m_hostname.assign(url, colon-url);
174 string port(colon + 1, slash - colon);
175 m_port = atoi(port.c_str());
178 m_hostname.assign(url, slash - url);
186 else if (*slash != '%') {
191 if (!isxdigit(*slash) || !isxdigit(*(slash+1)))
192 throw invalid_argument("Bad request, contained unsupported encoded characters.");
193 m_uri += _x2c(slash);
200 virtual ~DummyRequest() {}
202 const char* getRequestURL() const {
205 const char* getScheme() const {
208 const char* getHostname() const {
209 return m_hostname.c_str();
211 int getPort() const {
214 const char* getRequestURI() const {
215 return m_uri.c_str();
217 const char* getMethod() const {
220 string getContentType() const {
223 long getContentLength() const {
226 string getRemoteAddr() const {
229 string getRemoteUser() const {
232 const char* getRequestBody() const {
235 const char* getQueryString() const {
238 const char* getParameter(const char* name) const
241 m_parser.reset(new CGIParser(*this));
243 pair<CGIParser::walker,CGIParser::walker> bounds = m_parser->getParameters(name);
244 return (bounds.first == bounds.second) ? nullptr : bounds.first->second;
246 vector<const char*>::size_type getParameters(const char* name, vector<const char*>& values) const
249 m_parser.reset(new CGIParser(*this));
251 pair<CGIParser::walker,CGIParser::walker> bounds = m_parser->getParameters(name);
252 while (bounds.first != bounds.second) {
253 values.push_back(bounds.first->second);
256 return values.size();
258 string getHeader(const char* name) const {
262 #ifndef XMLTOOLING_NO_XMLSEC
263 std::vector<XSECCryptoX509*>&
265 std::vector<std::string>&
267 getClientCertificates() const {
272 mutable scoped_ptr<CGIParser> m_parser;
274 const char* m_scheme;
277 string m_hostname,m_uri;
281 StatusHandler::StatusHandler(const DOMElement* e, const char* appId)
282 : AbstractHandler(e, Category::getInstance(SHIBSP_LOGCAT".StatusHandler"), &g_Blocker)
284 if (SPConfig::getConfig().isEnabled(SPConfig::InProcess)) {
285 pair<bool,const char*> acl = getString("acl");
287 string aclbuf=acl.second;
288 vector<string> aclarray;
289 split(aclarray, aclbuf, is_space(), algorithm::token_compress_on);
290 for_each(aclarray.begin(), aclarray.end(), boost::bind(&StatusHandler::parseACL, this, _1));
292 m_log.warn("invalid CIDR range(s) in Status handler acl property, allowing 127.0.0.1 as a fall back");
293 m_acl.push_back(IPRange::parseCIDRBlock("127.0.0.1"));
298 string address(appId);
299 address += getString("Location").second;
300 setAddress(address.c_str());
303 pair<bool,long> StatusHandler::run(SPRequest& request, bool isHandler) const
305 SPConfig& conf = SPConfig::getConfig();
306 if (conf.isEnabled(SPConfig::InProcess) && !m_acl.empty()) {
307 static bool (IPRange::* contains)(const char*) const = &IPRange::contains;
308 if (find_if(m_acl.begin(), m_acl.end(), boost::bind(contains, _1, request.getRemoteAddr().c_str())) == m_acl.end()) {
309 m_log.error("status handler request blocked from invalid address (%s)", request.getRemoteAddr().c_str());
310 istringstream msg("Status Handler Blocked");
311 return make_pair(true,request.sendResponse(msg, HTTPResponse::XMLTOOLING_HTTP_STATUS_FORBIDDEN));
315 const char* target = request.getParameter("target");
317 // RequestMap query, so handle it inproc.
318 DummyRequest dummy(target);
319 RequestMapper::Settings settings = request.getApplication().getServiceProvider().getRequestMapper()->getSettings(dummy);
320 map<string,const char*> props;
321 settings.first->getAll(props);
323 DateTime now(time(nullptr));
325 auto_ptr_char timestamp(now.getFormattedString());
326 request.setContentType("text/xml");
328 msg << "<StatusHandler time='" << timestamp.get() << "'>";
329 msg << "<Version Xerces-C='" << XERCES_FULLVERSIONDOT
330 << "' XML-Tooling-C='" << gXMLToolingDotVersionStr
332 << "' XML-Security-C='" << XSEC_FULLVERSIONDOT
333 << "' OpenSAML-C='" << gOpenSAMLDotVersionStr
335 << "' Shibboleth='" << PACKAGE_VERSION << "'/>";
336 systemInfo(msg) << "<RequestSettings";
337 for (map<string,const char*>::const_iterator p = props.begin(); p != props.end(); ++p)
338 msg << ' ' << p->first << "='" << p->second << "'";
339 msg << '>' << target << "</RequestSettings>";
340 msg << "<Status><OK/></Status>";
341 msg << "</StatusHandler>";
342 return make_pair(true, request.sendResponse(msg));
346 if (conf.isEnabled(SPConfig::OutOfProcess)) {
347 // When out of process, we run natively and directly process the message.
348 return processMessage(request.getApplication(), request, request);
351 // When not out of process, we remote all the message processing.
352 DDF out,in = wrap(request);
353 DDFJanitor jin(in), jout(out);
354 out=request.getServiceProvider().getListenerService()->send(in);
355 return unwrap(request, out);
358 catch (XMLToolingException& 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='" << gXMLToolingDotVersionStr
369 << "' XML-Security-C='" << XSEC_FULLVERSIONDOT
370 << "' OpenSAML-C='" << gOpenSAMLDotVersionStr
372 << "' Shibboleth='" << PACKAGE_VERSION << "'/>";
373 systemInfo(msg) << "<Status><Exception type='" << ex.getClassName() << "'>" << ex.what() << "</Exception></Status>";
374 msg << "</StatusHandler>";
375 return make_pair(true, request.sendResponse(msg, HTTPResponse::XMLTOOLING_HTTP_STATUS_ERROR));
377 catch (std::exception& ex) {
378 m_log.error("error while processing request: %s", ex.what());
379 DateTime now(time(nullptr));
381 auto_ptr_char timestamp(now.getFormattedString());
382 request.setContentType("text/xml");
384 msg << "<StatusHandler time='" << timestamp.get() << "'>";
385 msg << "<Version Xerces-C='" << XERCES_FULLVERSIONDOT
386 << "' XML-Tooling-C='" << gXMLToolingDotVersionStr
388 << "' XML-Security-C='" << XSEC_FULLVERSIONDOT
389 << "' OpenSAML-C='" << gOpenSAMLDotVersionStr
391 << "' Shibboleth='" << PACKAGE_VERSION << "'/>";
392 systemInfo(msg) << "<Status><Exception type='std::exception'>" << ex.what() << "</Exception></Status>";
393 msg << "</StatusHandler>";
394 return make_pair(true, request.sendResponse(msg, HTTPResponse::XMLTOOLING_HTTP_STATUS_ERROR));
398 void StatusHandler::receive(DDF& in, ostream& out)
401 const char* aid = in["application_id"].string();
402 const Application* app = aid ? SPConfig::getConfig().getServiceProvider()->getApplication(aid) : nullptr;
404 // Something's horribly wrong.
405 m_log.error("couldn't find application (%s) for status request", aid ? aid : "(missing)");
406 throw ConfigurationException("Unable to locate application for status request, deleted?");
409 // Wrap a response shim.
411 DDFJanitor jout(ret);
412 scoped_ptr<HTTPRequest> req(getRequest(in));
413 scoped_ptr<HTTPResponse> resp(getResponse(ret));
415 // Since we're remoted, the result should either be a throw, a false/0 return,
416 // which we just return as an empty structure, or a response/redirect,
417 // which we capture in the facade and send back.
418 processMessage(*app, *req, *resp);
422 pair<bool,long> StatusHandler::processMessage(
423 const Application& application, const HTTPRequest& httpRequest, HTTPResponse& httpResponse
427 m_log.debug("processing status request");
429 DateTime now(time(nullptr));
431 auto_ptr_char timestamp(now.getFormattedString());
434 s << "<StatusHandler time='" << timestamp.get() << "'>";
435 const char* status = "<OK/>";
437 s << "<Version Xerces-C='" << XERCES_FULLVERSIONDOT
438 << "' XML-Tooling-C='" << gXMLToolingDotVersionStr
439 << "' XML-Security-C='" << XSEC_FULLVERSIONDOT
440 << "' OpenSAML-C='" << gOpenSAMLDotVersionStr
441 << "' Shibboleth='" << PACKAGE_VERSION << "'/>";
445 const char* param = nullptr;
449 // General configuration and status report.
451 SessionCache* sc = application.getServiceProvider().getSessionCache(false);
454 s << "<SessionCache><OK/></SessionCache>";
457 s << "<SessionCache><None/></SessionCache>";
460 catch (XMLToolingException& ex) {
461 s << "<SessionCache><Exception type='" << ex.getClassName() << "'>" << ex.what() << "</Exception></SessionCache>";
462 status = "<Partial/>";
464 catch (std::exception& ex) {
465 s << "<SessionCache><Exception type='std::exception'>" << ex.what() << "</Exception></SessionCache>";
466 status = "<Partial/>";
469 MetadataProvider* m = application.getMetadataProvider();
472 const PropertySet* relyingParty = nullptr;
473 param=httpRequest.getParameter("entityID");
475 relyingParty = application.getRelyingParty(m->getEntityDescriptor(MetadataProviderCriteria(application, param)).first);
477 relyingParty = &application;
479 s << "<Application id='" << application.getId() << "' entityID='" << relyingParty->getString("entityID").second << "'/>";
484 vector<const Handler*> handlers;
485 application.getHandlers(handlers);
486 for (indirect_iterator<vector<const Handler*>::const_iterator> h = make_indirect_iterator(handlers.begin());
487 h != make_indirect_iterator(handlers.end()); ++h) {
488 s << "<Handler type='" << h->getType() << "' Location='" << h->getString("Location").second << "'";
489 if (h->getString("Binding").first)
490 s << " Binding='" << h->getString("Binding").second << "'";
495 CredentialResolver* credResolver = application.getCredentialResolver();
497 Locker credLocker(credResolver);
498 CredentialCriteria cc;
499 cc.setUsage(Credential::SIGNING_CREDENTIAL);
500 pair<bool,const char*> keyName = relyingParty->getString("keyName");
502 cc.getKeyNames().insert(keyName.second);
503 vector<const Credential*> creds;
504 credResolver->resolve(creds, &cc);
505 for (vector<const Credential*>::const_iterator c = creds.begin(); c != creds.end(); ++c) {
506 KeyInfo* kinfo = (*c)->getKeyInfo();
508 scoped_ptr<KeyDescriptor> kd(KeyDescriptorBuilder::buildKeyDescriptor());
509 kd->setUse(KeyDescriptor::KEYTYPE_SIGNING);
510 kd->setKeyInfo(kinfo);
515 cc.setUsage(Credential::ENCRYPTION_CREDENTIAL);
517 cc.getKeyNames().clear();
518 credResolver->resolve(creds, &cc);
519 for (vector<const Credential*>::const_iterator c = creds.begin(); c != creds.end(); ++c) {
520 KeyInfo* kinfo = (*c)->getKeyInfo();
522 scoped_ptr<KeyDescriptor> kd(KeyDescriptorBuilder::buildKeyDescriptor());
523 kd->setUse(KeyDescriptor::KEYTYPE_ENCRYPTION);
524 kd->setKeyInfo(kinfo);
531 s << "<Status>" << status << "</Status></StatusHandler>";
533 httpResponse.setContentType("text/xml");
534 return make_pair(true, httpResponse.sendResponse(s));
536 return make_pair(false, 0L);
541 typedef void (WINAPI *PGNSI)(LPSYSTEM_INFO);
544 ostream& StatusHandler::systemInfo(ostream& os) const
546 #if defined(HAVE_SYS_UTSNAME_H)
547 struct utsname sysinfo;
548 if (uname(&sysinfo) == 0) {
550 if (*sysinfo.sysname)
551 os << " sysname='" << sysinfo.sysname << "'";
552 if (*sysinfo.nodename)
553 os << " nodename='" << sysinfo.nodename << "'";
554 if (*sysinfo.release)
555 os << " release='" << sysinfo.release << "'";
556 if (*sysinfo.version)
557 os << " version='" << sysinfo.version << "'";
558 if (*sysinfo.machine)
559 os << " machine='" << sysinfo.machine << "'";
563 OSVERSIONINFOEX osvi;
564 memset(&osvi, 0, sizeof(OSVERSIONINFOEX));
565 osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEX);
566 if(GetVersionEx((OSVERSIONINFO*)&osvi)) {
568 << " version='" << osvi.dwMajorVersion << "." << osvi.dwMinorVersion << "'"
569 << " build='" << osvi.dwBuildNumber << "'";
570 if (osvi.wServicePackMajor > 0)
571 os << " servicepack='" << osvi.wServicePackMajor << "." << osvi.wServicePackMinor << "'";
572 switch (osvi.wProductType) {
573 case VER_NT_WORKSTATION:
574 os << " producttype='Workstation'";
577 case VER_NT_DOMAIN_CONTROLLER:
578 os << " producttype='Server'";
583 memset(&si, 0, sizeof(SYSTEM_INFO));
584 PGNSI pGNSI = (PGNSI)GetProcAddress(GetModuleHandle(TEXT("kernel32.dll")), "GetNativeSystemInfo");
589 switch (si.dwProcessorType) {
590 case PROCESSOR_ARCHITECTURE_INTEL:
591 os << " arch='i386'";
593 case PROCESSOR_ARCHITECTURE_AMD64:
594 os << " arch='x86_64'";
596 case PROCESSOR_ARCHITECTURE_IA64:
597 os << " arch='IA64'";
600 os << " cpucount='" << si.dwNumberOfProcessors << "'";
603 memset(&ms, 0, sizeof(MEMORYSTATUSEX));
604 ms.dwLength = sizeof(MEMORYSTATUSEX);
605 if (GlobalMemoryStatusEx(&ms)) {
606 os << " memory='" << (ms.ullTotalPhys / (1024 * 1024)) << "M'";