2 * Copyright 2001-2009 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 "handler/AbstractHandler.h"
28 #include "handler/RemotedHandler.h"
29 #include "util/CGIParser.h"
31 using namespace shibsp;
33 # include "SessionCache.h"
34 # include "metadata/MetadataProviderCriteria.h"
35 # include <saml/version.h>
36 using namespace opensaml::saml2md;
37 using namespace opensaml;
38 using namespace xmlsignature;
40 using namespace xmltooling;
45 #if defined (_MSC_VER)
46 #pragma warning( push )
47 #pragma warning( disable : 4250 )
50 class SHIBSP_DLLLOCAL Blocker : public DOMNodeFilter
53 #ifdef SHIBSP_XERCESC_SHORT_ACCEPTNODE
58 acceptNode(const DOMNode* node) const {
63 static SHIBSP_DLLLOCAL Blocker g_Blocker;
65 class SHIBSP_API StatusHandler : public AbstractHandler, public RemotedHandler
68 StatusHandler(const DOMElement* e, const char* appId);
69 virtual ~StatusHandler() {}
71 pair<bool,long> run(SPRequest& request, bool isHandler=true) const;
72 void receive(DDF& in, ostream& out);
75 pair<bool,long> processMessage(const Application& application, const HTTPRequest& httpRequest, HTTPResponse& httpResponse) const;
80 #if defined (_MSC_VER)
81 #pragma warning( pop )
84 Handler* SHIBSP_DLLLOCAL StatusHandlerFactory(const pair<const DOMElement*,const char*>& p)
86 return new StatusHandler(p.first, p.second);
89 #ifndef XMLTOOLING_NO_XMLSEC
90 vector<XSECCryptoX509*> g_NoCerts;
92 vector<string> g_NoCerts;
95 static char _x2c(const char *what)
99 digit = (what[0] >= 'A' ? ((what[0] & 0xdf) - 'A')+10 : (what[0] - '0'));
101 digit += (what[1] >= 'A' ? ((what[1] & 0xdf) - 'A')+10 : (what[1] - '0'));
105 class DummyRequest : public HTTPRequest
108 DummyRequest(const char* url) : m_parser(NULL), m_url(url), m_scheme(NULL), m_query(NULL), m_port(0) {
109 #ifdef HAVE_STRCASECMP
110 if (url && !strncasecmp(url,"http://",7)) {
114 else if (url && !strncasecmp(url,"https://",8)) {
120 if (url && !strnicmp(url,"http://",7)) {
125 else if (url && !strnicmp(url,"https://",8)) {
132 throw invalid_argument("Target parameter was not an absolute URL.");
134 m_query = strchr(url,'?');
138 const char* slash = strchr(url, '/');
139 const char* colon = strchr(url, ':');
140 if (colon && colon < slash) {
141 m_hostname.assign(url, colon-url);
142 string port(colon + 1, slash - colon);
143 m_port = atoi(port.c_str());
146 m_hostname.assign(url, slash - url);
154 else if (*slash != '%') {
159 if (!isxdigit(*slash) || !isxdigit(*(slash+1)))
160 throw invalid_argument("Bad request, contained unsupported encoded characters.");
161 m_uri += _x2c(slash);
172 const char* getRequestURL() const {
175 const char* getScheme() const {
178 const char* getHostname() const {
179 return m_hostname.c_str();
181 int getPort() const {
184 const char* getRequestURI() const {
185 return m_uri.c_str();
187 const char* getMethod() const {
190 string getContentType() const {
193 long getContentLength() const {
196 string getRemoteAddr() const {
199 string getRemoteUser() const {
202 const char* getRequestBody() const {
205 const char* getQueryString() const {
208 const char* getParameter(const char* name) const
211 m_parser=new CGIParser(*this);
213 pair<CGIParser::walker,CGIParser::walker> bounds=m_parser->getParameters(name);
214 return (bounds.first==bounds.second) ? NULL : bounds.first->second;
216 vector<const char*>::size_type getParameters(const char* name, vector<const char*>& values) const
219 m_parser=new CGIParser(*this);
221 pair<CGIParser::walker,CGIParser::walker> bounds=m_parser->getParameters(name);
222 while (bounds.first!=bounds.second) {
223 values.push_back(bounds.first->second);
226 return values.size();
228 string getHeader(const char* name) const {
232 #ifndef XMLTOOLING_NO_XMLSEC
233 std::vector<XSECCryptoX509*>&
235 std::vector<std::string>&
237 getClientCertificates() const {
242 mutable CGIParser* m_parser;
244 const char* m_scheme;
247 string m_hostname,m_uri;
251 StatusHandler::StatusHandler(const DOMElement* e, const char* appId)
252 : AbstractHandler(e, Category::getInstance(SHIBSP_LOGCAT".StatusHandler"), &g_Blocker)
254 string address(appId);
255 address += getString("Location").second;
256 setAddress(address.c_str());
257 if (SPConfig::getConfig().isEnabled(SPConfig::InProcess)) {
258 pair<bool,const char*> acl = getString("acl");
260 string aclbuf=acl.second;
262 for (unsigned int i=0; i < aclbuf.length(); i++) {
263 if (aclbuf.at(i)==' ') {
264 m_acl.insert(aclbuf.substr(j, i-j));
268 m_acl.insert(aclbuf.substr(j, aclbuf.length()-j));
273 pair<bool,long> StatusHandler::run(SPRequest& request, bool isHandler) const
275 SPConfig& conf = SPConfig::getConfig();
276 if (conf.isEnabled(SPConfig::InProcess)) {
277 if (!m_acl.empty() && m_acl.count(request.getRemoteAddr()) == 0) {
278 m_log.error("status handler request blocked from invalid address (%s)", request.getRemoteAddr().c_str());
279 istringstream msg("Status Handler Blocked");
280 return make_pair(true,request.sendResponse(msg, HTTPResponse::XMLTOOLING_HTTP_STATUS_FORBIDDEN));
284 const char* target = request.getParameter("target");
286 // RequestMap query, so handle it inproc.
287 DummyRequest dummy(target);
288 RequestMapper::Settings settings = request.getApplication().getServiceProvider().getRequestMapper()->getSettings(dummy);
289 map<string,const char*> props;
290 settings.first->getAll(props);
292 request.setContentType("text/xml");
294 msg << "<StatusHandler>";
295 msg << "<Version Xerces-C='" << XERCES_FULLVERSIONDOT
297 << "' XML-Security-C='" << XSEC_FULLVERSIONDOT
298 << "' OpenSAML-C='" << OPENSAML_FULLVERSIONDOT
300 << "' Shibboleth='" << PACKAGE_VERSION << "'/>";
301 msg << "<RequestSettings";
302 for (map<string,const char*>::const_iterator p = props.begin(); p != props.end(); ++p)
303 msg << ' ' << p->first << "='" << p->second << "'";
304 msg << '>' << target << "</RequestSettings>";
305 msg << "<Status><OK/></Status>";
306 msg << "</StatusHandler>";
307 return make_pair(true,request.sendResponse(msg));
311 if (conf.isEnabled(SPConfig::OutOfProcess)) {
312 // When out of process, we run natively and directly process the message.
313 return processMessage(request.getApplication(), request, request);
316 // When not out of process, we remote all the message processing.
317 DDF out,in = wrap(request);
318 DDFJanitor jin(in), jout(out);
319 out=request.getServiceProvider().getListenerService()->send(in);
320 return unwrap(request, out);
323 catch (XMLToolingException& ex) {
324 m_log.error("error while processing request: %s", ex.what());
325 request.setContentType("text/xml");
327 msg << "<StatusHandler>";
328 msg << "<Version Xerces-C='" << XERCES_FULLVERSIONDOT
330 << "' XML-Security-C='" << XSEC_FULLVERSIONDOT
331 << "' OpenSAML-C='" << OPENSAML_FULLVERSIONDOT
333 << "' Shibboleth='" << PACKAGE_VERSION << "'/>";
334 msg << "<Status><Exception type='" << ex.getClassName() << "'>" << ex.what() << "</Exception></Status>";
335 msg << "</StatusHandler>";
336 return make_pair(true,request.sendResponse(msg, HTTPResponse::XMLTOOLING_HTTP_STATUS_ERROR));
338 catch (exception& ex) {
339 m_log.error("error while processing request: %s", ex.what());
340 request.setContentType("text/xml");
342 msg << "<StatusHandler>";
343 msg << "<Version Xerces-C='" << XERCES_FULLVERSIONDOT
345 << "' XML-Security-C='" << XSEC_FULLVERSIONDOT
346 << "' OpenSAML-C='" << OPENSAML_FULLVERSIONDOT
348 << "' Shibboleth='" << PACKAGE_VERSION << "'/>";
349 msg << "<Status><Exception type='std::exception'>" << ex.what() << "</Exception></Status>";
350 msg << "</StatusHandler>";
351 return make_pair(true,request.sendResponse(msg, HTTPResponse::XMLTOOLING_HTTP_STATUS_ERROR));
355 void StatusHandler::receive(DDF& in, ostream& out)
358 const char* aid=in["application_id"].string();
359 const Application* app=aid ? SPConfig::getConfig().getServiceProvider()->getApplication(aid) : NULL;
361 // Something's horribly wrong.
362 m_log.error("couldn't find application (%s) for status request", aid ? aid : "(missing)");
363 throw ConfigurationException("Unable to locate application for status request, deleted?");
366 // Wrap a response shim.
368 DDFJanitor jout(ret);
369 auto_ptr<HTTPRequest> req(getRequest(in));
370 auto_ptr<HTTPResponse> resp(getResponse(ret));
372 // Since we're remoted, the result should either be a throw, a false/0 return,
373 // which we just return as an empty structure, or a response/redirect,
374 // which we capture in the facade and send back.
375 processMessage(*app, *req.get(), *resp.get());
379 pair<bool,long> StatusHandler::processMessage(
380 const Application& application, const HTTPRequest& httpRequest, HTTPResponse& httpResponse
384 m_log.debug("processing status request");
387 s << "<StatusHandler>";
388 const char* status = "<OK/>";
390 s << "<Version Xerces-C='" << XERCES_FULLVERSIONDOT
391 << "' XML-Security-C='" << XSEC_FULLVERSIONDOT
392 << "' OpenSAML-C='" << OPENSAML_FULLVERSIONDOT
393 << "' Shibboleth='" << PACKAGE_VERSION << "'/>";
395 const char* param = NULL;
399 // General configuration and status report.
401 SessionCache* sc = application.getServiceProvider().getSessionCache(false);
404 s << "<SessionCache><OK/></SessionCache>";
407 s << "<SessionCache><None/></SessionCache>";
410 catch (XMLToolingException& ex) {
411 s << "<SessionCache><Exception type='" << ex.getClassName() << "'>" << ex.what() << "</Exception></SessionCache>";
412 status = "<Partial/>";
414 catch (exception& ex) {
415 s << "<SessionCache><Exception type='std::exception'>" << ex.what() << "</Exception></SessionCache>";
416 status = "<Partial/>";
419 const PropertySet* relyingParty=NULL;
420 param=httpRequest.getParameter("entityID");
422 MetadataProvider* m = application.getMetadataProvider();
424 relyingParty = application.getRelyingParty(m->getEntityDescriptor(MetadataProviderCriteria(application, param)).first);
427 relyingParty = &application;
430 s << "<Application id='" << application.getId() << "' entityID='" << relyingParty->getString("entityID").second << "'/>";
433 vector<const Handler*> handlers;
434 application.getHandlers(handlers);
435 for (vector<const Handler*>::const_iterator h = handlers.begin(); h != handlers.end(); ++h) {
436 s << "<Handler type='" << (*h)->getType() << "' Location='" << (*h)->getString("Location").second << "'";
437 if ((*h)->getString("Binding").first)
438 s << " Binding='" << (*h)->getString("Binding").second << "'";
443 CredentialResolver* credResolver=application.getCredentialResolver();
445 Locker credLocker(credResolver);
446 CredentialCriteria cc;
447 cc.setUsage(Credential::SIGNING_CREDENTIAL);
448 pair<bool,const char*> keyName = relyingParty->getString("keyName");
450 cc.getKeyNames().insert(keyName.second);
451 vector<const Credential*> creds;
452 credResolver->resolve(creds,&cc);
453 for (vector<const Credential*>::const_iterator c = creds.begin(); c != creds.end(); ++c) {
454 KeyInfo* kinfo = (*c)->getKeyInfo();
456 auto_ptr<KeyDescriptor> kd(KeyDescriptorBuilder::buildKeyDescriptor());
457 kd->setUse(KeyDescriptor::KEYTYPE_SIGNING);
458 kd->setKeyInfo(kinfo);
463 cc.setUsage(Credential::ENCRYPTION_CREDENTIAL);
465 cc.getKeyNames().clear();
466 credResolver->resolve(creds,&cc);
467 for (vector<const Credential*>::const_iterator c = creds.begin(); c != creds.end(); ++c) {
468 KeyInfo* kinfo = (*c)->getKeyInfo();
470 auto_ptr<KeyDescriptor> kd(KeyDescriptorBuilder::buildKeyDescriptor());
471 kd->setUse(KeyDescriptor::KEYTYPE_ENCRYPTION);
472 kd->setKeyInfo(kinfo);
479 s << "<Status>" << status << "</Status></StatusHandler>";
481 httpResponse.setContentType("text/xml");
482 return make_pair(true, httpResponse.sendResponse(s));
484 return make_pair(false,0L);