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 # include <xmltooling/security/Credential.h>
37 using namespace opensaml::saml2md;
38 using namespace opensaml;
39 using namespace xmlsignature;
41 using namespace xmltooling;
46 #if defined (_MSC_VER)
47 #pragma warning( push )
48 #pragma warning( disable : 4250 )
51 class SHIBSP_DLLLOCAL Blocker : public DOMNodeFilter
54 #ifdef SHIBSP_XERCESC_SHORT_ACCEPTNODE
59 acceptNode(const DOMNode* node) const {
64 static SHIBSP_DLLLOCAL Blocker g_Blocker;
66 class SHIBSP_API StatusHandler : public AbstractHandler, public RemotedHandler
69 StatusHandler(const DOMElement* e, const char* appId);
70 virtual ~StatusHandler() {}
72 pair<bool,long> run(SPRequest& request, bool isHandler=true) const;
73 void receive(DDF& in, ostream& out);
76 pair<bool,long> processMessage(const Application& application, const HTTPRequest& httpRequest, HTTPResponse& httpResponse) const;
81 #if defined (_MSC_VER)
82 #pragma warning( pop )
85 Handler* SHIBSP_DLLLOCAL StatusHandlerFactory(const pair<const DOMElement*,const char*>& p)
87 return new StatusHandler(p.first, p.second);
90 #ifndef XMLTOOLING_NO_XMLSEC
91 vector<XSECCryptoX509*> g_NoCerts;
93 vector<string> g_NoCerts;
96 static char _x2c(const char *what)
100 digit = (what[0] >= 'A' ? ((what[0] & 0xdf) - 'A')+10 : (what[0] - '0'));
102 digit += (what[1] >= 'A' ? ((what[1] & 0xdf) - 'A')+10 : (what[1] - '0'));
106 class DummyRequest : public HTTPRequest
109 DummyRequest(const char* url) : m_parser(NULL), m_url(url), m_scheme(NULL), m_query(NULL), m_port(0) {
110 #ifdef HAVE_STRCASECMP
111 if (url && !strncasecmp(url,"http://",7)) {
115 else if (url && !strncasecmp(url,"https://",8)) {
121 if (url && !strnicmp(url,"http://",7)) {
126 else if (url && !strnicmp(url,"https://",8)) {
133 throw invalid_argument("Target parameter was not an absolute URL.");
135 m_query = strchr(url,'?');
139 const char* slash = strchr(url, '/');
140 const char* colon = strchr(url, ':');
141 if (colon && colon < slash) {
142 m_hostname.assign(url, colon-url);
143 string port(colon + 1, slash - colon);
144 m_port = atoi(port.c_str());
147 m_hostname.assign(url, slash - url);
155 else if (*slash != '%') {
160 if (!isxdigit(*slash) || !isxdigit(*(slash+1)))
161 throw invalid_argument("Bad request, contained unsupported encoded characters.");
162 m_uri += _x2c(slash);
173 const char* getRequestURL() const {
176 const char* getScheme() const {
179 const char* getHostname() const {
180 return m_hostname.c_str();
182 int getPort() const {
185 const char* getRequestURI() const {
186 return m_uri.c_str();
188 const char* getMethod() const {
191 string getContentType() const {
194 long getContentLength() const {
197 string getRemoteAddr() const {
200 string getRemoteUser() const {
203 const char* getRequestBody() const {
206 const char* getQueryString() const {
209 const char* getParameter(const char* name) const
212 m_parser=new CGIParser(*this);
214 pair<CGIParser::walker,CGIParser::walker> bounds=m_parser->getParameters(name);
215 return (bounds.first==bounds.second) ? NULL : bounds.first->second;
217 vector<const char*>::size_type getParameters(const char* name, vector<const char*>& values) const
220 m_parser=new CGIParser(*this);
222 pair<CGIParser::walker,CGIParser::walker> bounds=m_parser->getParameters(name);
223 while (bounds.first!=bounds.second) {
224 values.push_back(bounds.first->second);
227 return values.size();
229 string getHeader(const char* name) const {
233 #ifndef XMLTOOLING_NO_XMLSEC
234 std::vector<XSECCryptoX509*>&
236 std::vector<std::string>&
238 getClientCertificates() const {
243 mutable CGIParser* m_parser;
245 const char* m_scheme;
248 string m_hostname,m_uri;
252 StatusHandler::StatusHandler(const DOMElement* e, const char* appId)
253 : AbstractHandler(e, Category::getInstance(SHIBSP_LOGCAT".StatusHandler"), &g_Blocker)
255 string address(appId);
256 address += getString("Location").second;
257 setAddress(address.c_str());
258 if (SPConfig::getConfig().isEnabled(SPConfig::InProcess)) {
259 pair<bool,const char*> acl = getString("acl");
261 string aclbuf=acl.second;
263 for (unsigned int i=0; i < aclbuf.length(); i++) {
264 if (aclbuf.at(i)==' ') {
265 m_acl.insert(aclbuf.substr(j, i-j));
269 m_acl.insert(aclbuf.substr(j, aclbuf.length()-j));
274 pair<bool,long> StatusHandler::run(SPRequest& request, bool isHandler) const
276 SPConfig& conf = SPConfig::getConfig();
277 if (conf.isEnabled(SPConfig::InProcess)) {
278 if (!m_acl.empty() && m_acl.count(request.getRemoteAddr()) == 0) {
279 m_log.error("status handler request blocked from invalid address (%s)", request.getRemoteAddr().c_str());
280 istringstream msg("Status Handler Blocked");
281 return make_pair(true,request.sendResponse(msg, HTTPResponse::XMLTOOLING_HTTP_STATUS_FORBIDDEN));
285 const char* target = request.getParameter("target");
287 // RequestMap query, so handle it inproc.
288 DummyRequest dummy(target);
289 RequestMapper::Settings settings = request.getApplication().getServiceProvider().getRequestMapper()->getSettings(dummy);
290 map<string,const char*> props;
291 settings.first->getAll(props);
293 request.setContentType("text/xml");
295 msg << "<StatusHandler>";
296 msg << "<Version Xerces-C='" << XERCES_FULLVERSIONDOT
298 << "' XML-Security-C='" << XSEC_FULLVERSIONDOT
299 << "' OpenSAML-C='" << OPENSAML_FULLVERSIONDOT
301 << "' Shibboleth='" << PACKAGE_VERSION << "'/>";
302 msg << "<RequestSettings";
303 for (map<string,const char*>::const_iterator p = props.begin(); p != props.end(); ++p)
304 msg << ' ' << p->first << "='" << p->second << "'";
305 msg << '>' << target << "</RequestSettings>";
306 msg << "<Status><OK/></Status>";
307 msg << "</StatusHandler>";
308 return make_pair(true,request.sendResponse(msg));
312 if (conf.isEnabled(SPConfig::OutOfProcess)) {
313 // When out of process, we run natively and directly process the message.
314 return processMessage(request.getApplication(), request, request);
317 // When not out of process, we remote all the message processing.
318 DDF out,in = wrap(request);
319 DDFJanitor jin(in), jout(out);
320 out=request.getServiceProvider().getListenerService()->send(in);
321 return unwrap(request, out);
324 catch (XMLToolingException& ex) {
325 m_log.error("error while processing request: %s", ex.what());
326 request.setContentType("text/xml");
328 msg << "<StatusHandler>";
329 msg << "<Version Xerces-C='" << XERCES_FULLVERSIONDOT
331 << "' XML-Security-C='" << XSEC_FULLVERSIONDOT
332 << "' OpenSAML-C='" << OPENSAML_FULLVERSIONDOT
334 << "' Shibboleth='" << PACKAGE_VERSION << "'/>";
335 msg << "<Status><Exception type='" << ex.getClassName() << "'>" << ex.what() << "</Exception></Status>";
336 msg << "</StatusHandler>";
337 return make_pair(true,request.sendResponse(msg, HTTPResponse::XMLTOOLING_HTTP_STATUS_ERROR));
339 catch (exception& ex) {
340 m_log.error("error while processing request: %s", ex.what());
341 request.setContentType("text/xml");
343 msg << "<StatusHandler>";
344 msg << "<Version Xerces-C='" << XERCES_FULLVERSIONDOT
346 << "' XML-Security-C='" << XSEC_FULLVERSIONDOT
347 << "' OpenSAML-C='" << OPENSAML_FULLVERSIONDOT
349 << "' Shibboleth='" << PACKAGE_VERSION << "'/>";
350 msg << "<Status><Exception type='std::exception'>" << ex.what() << "</Exception></Status>";
351 msg << "</StatusHandler>";
352 return make_pair(true,request.sendResponse(msg, HTTPResponse::XMLTOOLING_HTTP_STATUS_ERROR));
356 void StatusHandler::receive(DDF& in, ostream& out)
359 const char* aid=in["application_id"].string();
360 const Application* app=aid ? SPConfig::getConfig().getServiceProvider()->getApplication(aid) : NULL;
362 // Something's horribly wrong.
363 m_log.error("couldn't find application (%s) for status request", aid ? aid : "(missing)");
364 throw ConfigurationException("Unable to locate application for status request, deleted?");
367 // Wrap a response shim.
369 DDFJanitor jout(ret);
370 auto_ptr<HTTPRequest> req(getRequest(in));
371 auto_ptr<HTTPResponse> resp(getResponse(ret));
373 // Since we're remoted, the result should either be a throw, a false/0 return,
374 // which we just return as an empty structure, or a response/redirect,
375 // which we capture in the facade and send back.
376 processMessage(*app, *req.get(), *resp.get());
380 pair<bool,long> StatusHandler::processMessage(
381 const Application& application, const HTTPRequest& httpRequest, HTTPResponse& httpResponse
385 m_log.debug("processing status request");
388 s << "<StatusHandler>";
389 const char* status = "<OK/>";
391 s << "<Version Xerces-C='" << XERCES_FULLVERSIONDOT
392 << "' XML-Security-C='" << XSEC_FULLVERSIONDOT
393 << "' OpenSAML-C='" << OPENSAML_FULLVERSIONDOT
394 << "' Shibboleth='" << PACKAGE_VERSION << "'/>";
396 const char* param = NULL;
400 // General configuration and status report.
402 SessionCache* sc = application.getServiceProvider().getSessionCache(false);
405 s << "<SessionCache><OK/></SessionCache>";
408 s << "<SessionCache><None/></SessionCache>";
411 catch (XMLToolingException& ex) {
412 s << "<SessionCache><Exception type='" << ex.getClassName() << "'>" << ex.what() << "</Exception></SessionCache>";
413 status = "<Partial/>";
415 catch (exception& ex) {
416 s << "<SessionCache><Exception type='std::exception'>" << ex.what() << "</Exception></SessionCache>";
417 status = "<Partial/>";
420 const PropertySet* relyingParty=NULL;
421 param=httpRequest.getParameter("entityID");
423 MetadataProvider* m = application.getMetadataProvider();
425 relyingParty = application.getRelyingParty(m->getEntityDescriptor(MetadataProviderCriteria(application, param)).first);
428 relyingParty = &application;
431 s << "<Application id='" << application.getId() << "' entityID='" << relyingParty->getString("entityID").second << "'/>";
434 vector<const Handler*> handlers;
435 application.getHandlers(handlers);
436 for (vector<const Handler*>::const_iterator h = handlers.begin(); h != handlers.end(); ++h) {
437 s << "<Handler type='" << (*h)->getType() << "' Location='" << (*h)->getString("Location").second << "'";
438 if ((*h)->getString("Binding").first)
439 s << " Binding='" << (*h)->getString("Binding").second << "'";
444 CredentialResolver* credResolver=application.getCredentialResolver();
446 Locker credLocker(credResolver);
447 CredentialCriteria cc;
448 cc.setUsage(Credential::SIGNING_CREDENTIAL);
449 pair<bool,const char*> keyName = relyingParty->getString("keyName");
451 cc.getKeyNames().insert(keyName.second);
452 vector<const Credential*> creds;
453 credResolver->resolve(creds,&cc);
454 for (vector<const Credential*>::const_iterator c = creds.begin(); c != creds.end(); ++c) {
455 KeyInfo* kinfo = (*c)->getKeyInfo();
457 auto_ptr<KeyDescriptor> kd(KeyDescriptorBuilder::buildKeyDescriptor());
458 kd->setUse(KeyDescriptor::KEYTYPE_SIGNING);
459 kd->setKeyInfo(kinfo);
464 cc.setUsage(Credential::ENCRYPTION_CREDENTIAL);
466 cc.getKeyNames().clear();
467 credResolver->resolve(creds,&cc);
468 for (vector<const Credential*>::const_iterator c = creds.begin(); c != creds.end(); ++c) {
469 KeyInfo* kinfo = (*c)->getKeyInfo();
471 auto_ptr<KeyDescriptor> kd(KeyDescriptorBuilder::buildKeyDescriptor());
472 kd->setUse(KeyDescriptor::KEYTYPE_ENCRYPTION);
473 kd->setKeyInfo(kinfo);
480 s << "<Status>" << status << "</Status></StatusHandler>";
482 httpResponse.setContentType("text/xml");
483 return make_pair(true, httpResponse.sendResponse(s));
485 return make_pair(false,0L);