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 # include <xmltooling/security/CredentialCriteria.h>
38 using namespace opensaml::saml2md;
39 using namespace opensaml;
40 using namespace xmlsignature;
42 using namespace xmltooling;
47 #if defined (_MSC_VER)
48 #pragma warning( push )
49 #pragma warning( disable : 4250 )
52 class SHIBSP_DLLLOCAL Blocker : public DOMNodeFilter
55 #ifdef SHIBSP_XERCESC_SHORT_ACCEPTNODE
60 acceptNode(const DOMNode* node) const {
65 static SHIBSP_DLLLOCAL Blocker g_Blocker;
67 class SHIBSP_API StatusHandler : public AbstractHandler, public RemotedHandler
70 StatusHandler(const DOMElement* e, const char* appId);
71 virtual ~StatusHandler() {}
73 pair<bool,long> run(SPRequest& request, bool isHandler=true) const;
74 void receive(DDF& in, ostream& out);
77 pair<bool,long> processMessage(const Application& application, const HTTPRequest& httpRequest, HTTPResponse& httpResponse) const;
82 #if defined (_MSC_VER)
83 #pragma warning( pop )
86 Handler* SHIBSP_DLLLOCAL StatusHandlerFactory(const pair<const DOMElement*,const char*>& p)
88 return new StatusHandler(p.first, p.second);
91 #ifndef XMLTOOLING_NO_XMLSEC
92 vector<XSECCryptoX509*> g_NoCerts;
94 vector<string> g_NoCerts;
97 static char _x2c(const char *what)
101 digit = (what[0] >= 'A' ? ((what[0] & 0xdf) - 'A')+10 : (what[0] - '0'));
103 digit += (what[1] >= 'A' ? ((what[1] & 0xdf) - 'A')+10 : (what[1] - '0'));
107 class DummyRequest : public HTTPRequest
110 DummyRequest(const char* url) : m_parser(NULL), m_url(url), m_scheme(NULL), m_query(NULL), m_port(0) {
111 #ifdef HAVE_STRCASECMP
112 if (url && !strncasecmp(url,"http://",7)) {
116 else if (url && !strncasecmp(url,"https://",8)) {
122 if (url && !strnicmp(url,"http://",7)) {
127 else if (url && !strnicmp(url,"https://",8)) {
134 throw invalid_argument("Target parameter was not an absolute URL.");
136 m_query = strchr(url,'?');
140 const char* slash = strchr(url, '/');
141 const char* colon = strchr(url, ':');
142 if (colon && colon < slash) {
143 m_hostname.assign(url, colon-url);
144 string port(colon + 1, slash - colon);
145 m_port = atoi(port.c_str());
148 m_hostname.assign(url, slash - url);
156 else if (*slash != '%') {
161 if (!isxdigit(*slash) || !isxdigit(*(slash+1)))
162 throw invalid_argument("Bad request, contained unsupported encoded characters.");
163 m_uri += _x2c(slash);
174 const char* getRequestURL() const {
177 const char* getScheme() const {
180 const char* getHostname() const {
181 return m_hostname.c_str();
183 int getPort() const {
186 const char* getRequestURI() const {
187 return m_uri.c_str();
189 const char* getMethod() const {
192 string getContentType() const {
195 long getContentLength() const {
198 string getRemoteAddr() const {
201 string getRemoteUser() const {
204 const char* getRequestBody() const {
207 const char* getQueryString() const {
210 const char* getParameter(const char* name) const
213 m_parser=new CGIParser(*this);
215 pair<CGIParser::walker,CGIParser::walker> bounds=m_parser->getParameters(name);
216 return (bounds.first==bounds.second) ? NULL : bounds.first->second;
218 vector<const char*>::size_type getParameters(const char* name, vector<const char*>& values) const
221 m_parser=new CGIParser(*this);
223 pair<CGIParser::walker,CGIParser::walker> bounds=m_parser->getParameters(name);
224 while (bounds.first!=bounds.second) {
225 values.push_back(bounds.first->second);
228 return values.size();
230 string getHeader(const char* name) const {
234 #ifndef XMLTOOLING_NO_XMLSEC
235 std::vector<XSECCryptoX509*>&
237 std::vector<std::string>&
239 getClientCertificates() const {
244 mutable CGIParser* m_parser;
246 const char* m_scheme;
249 string m_hostname,m_uri;
253 StatusHandler::StatusHandler(const DOMElement* e, const char* appId)
254 : AbstractHandler(e, Category::getInstance(SHIBSP_LOGCAT".StatusHandler"), &g_Blocker)
256 string address(appId);
257 address += getString("Location").second;
258 setAddress(address.c_str());
259 if (SPConfig::getConfig().isEnabled(SPConfig::InProcess)) {
260 pair<bool,const char*> acl = getString("acl");
262 string aclbuf=acl.second;
264 for (unsigned int i=0; i < aclbuf.length(); i++) {
265 if (aclbuf.at(i)==' ') {
266 m_acl.insert(aclbuf.substr(j, i-j));
270 m_acl.insert(aclbuf.substr(j, aclbuf.length()-j));
275 pair<bool,long> StatusHandler::run(SPRequest& request, bool isHandler) const
277 SPConfig& conf = SPConfig::getConfig();
278 if (conf.isEnabled(SPConfig::InProcess)) {
279 if (!m_acl.empty() && m_acl.count(request.getRemoteAddr()) == 0) {
280 m_log.error("status handler request blocked from invalid address (%s)", request.getRemoteAddr().c_str());
281 istringstream msg("Status Handler Blocked");
282 return make_pair(true,request.sendResponse(msg, HTTPResponse::XMLTOOLING_HTTP_STATUS_FORBIDDEN));
286 const char* target = request.getParameter("target");
288 // RequestMap query, so handle it inproc.
289 DummyRequest dummy(target);
290 RequestMapper::Settings settings = request.getApplication().getServiceProvider().getRequestMapper()->getSettings(dummy);
291 map<string,const char*> props;
292 settings.first->getAll(props);
294 request.setContentType("text/xml");
296 msg << "<StatusHandler>";
297 msg << "<Version Xerces-C='" << XERCES_FULLVERSIONDOT
299 << "' XML-Security-C='" << XSEC_FULLVERSIONDOT
300 << "' OpenSAML-C='" << OPENSAML_FULLVERSIONDOT
302 << "' Shibboleth='" << PACKAGE_VERSION << "'/>";
303 msg << "<RequestSettings";
304 for (map<string,const char*>::const_iterator p = props.begin(); p != props.end(); ++p)
305 msg << ' ' << p->first << "='" << p->second << "'";
306 msg << '>' << target << "</RequestSettings>";
307 msg << "<Status><OK/></Status>";
308 msg << "</StatusHandler>";
309 return make_pair(true,request.sendResponse(msg));
313 if (conf.isEnabled(SPConfig::OutOfProcess)) {
314 // When out of process, we run natively and directly process the message.
315 return processMessage(request.getApplication(), request, request);
318 // When not out of process, we remote all the message processing.
319 DDF out,in = wrap(request);
320 DDFJanitor jin(in), jout(out);
321 out=request.getServiceProvider().getListenerService()->send(in);
322 return unwrap(request, out);
325 catch (XMLToolingException& ex) {
326 m_log.error("error while processing request: %s", ex.what());
327 request.setContentType("text/xml");
329 msg << "<StatusHandler>";
330 msg << "<Version Xerces-C='" << XERCES_FULLVERSIONDOT
332 << "' XML-Security-C='" << XSEC_FULLVERSIONDOT
333 << "' OpenSAML-C='" << OPENSAML_FULLVERSIONDOT
335 << "' Shibboleth='" << PACKAGE_VERSION << "'/>";
336 msg << "<Status><Exception type='" << ex.getClassName() << "'>" << ex.what() << "</Exception></Status>";
337 msg << "</StatusHandler>";
338 return make_pair(true,request.sendResponse(msg, HTTPResponse::XMLTOOLING_HTTP_STATUS_ERROR));
340 catch (exception& ex) {
341 m_log.error("error while processing request: %s", ex.what());
342 request.setContentType("text/xml");
344 msg << "<StatusHandler>";
345 msg << "<Version Xerces-C='" << XERCES_FULLVERSIONDOT
347 << "' XML-Security-C='" << XSEC_FULLVERSIONDOT
348 << "' OpenSAML-C='" << OPENSAML_FULLVERSIONDOT
350 << "' Shibboleth='" << PACKAGE_VERSION << "'/>";
351 msg << "<Status><Exception type='std::exception'>" << ex.what() << "</Exception></Status>";
352 msg << "</StatusHandler>";
353 return make_pair(true,request.sendResponse(msg, HTTPResponse::XMLTOOLING_HTTP_STATUS_ERROR));
357 void StatusHandler::receive(DDF& in, ostream& out)
360 const char* aid=in["application_id"].string();
361 const Application* app=aid ? SPConfig::getConfig().getServiceProvider()->getApplication(aid) : NULL;
363 // Something's horribly wrong.
364 m_log.error("couldn't find application (%s) for status request", aid ? aid : "(missing)");
365 throw ConfigurationException("Unable to locate application for status request, deleted?");
368 // Wrap a response shim.
370 DDFJanitor jout(ret);
371 auto_ptr<HTTPRequest> req(getRequest(in));
372 auto_ptr<HTTPResponse> resp(getResponse(ret));
374 // Since we're remoted, the result should either be a throw, a false/0 return,
375 // which we just return as an empty structure, or a response/redirect,
376 // which we capture in the facade and send back.
377 processMessage(*app, *req.get(), *resp.get());
381 pair<bool,long> StatusHandler::processMessage(
382 const Application& application, const HTTPRequest& httpRequest, HTTPResponse& httpResponse
386 m_log.debug("processing status request");
389 s << "<StatusHandler>";
390 const char* status = "<OK/>";
392 s << "<Version Xerces-C='" << XERCES_FULLVERSIONDOT
393 << "' XML-Security-C='" << XSEC_FULLVERSIONDOT
394 << "' OpenSAML-C='" << OPENSAML_FULLVERSIONDOT
395 << "' Shibboleth='" << PACKAGE_VERSION << "'/>";
397 const char* param = NULL;
401 // General configuration and status report.
403 SessionCache* sc = application.getServiceProvider().getSessionCache(false);
406 s << "<SessionCache><OK/></SessionCache>";
409 s << "<SessionCache><None/></SessionCache>";
412 catch (XMLToolingException& ex) {
413 s << "<SessionCache><Exception type='" << ex.getClassName() << "'>" << ex.what() << "</Exception></SessionCache>";
414 status = "<Partial/>";
416 catch (exception& ex) {
417 s << "<SessionCache><Exception type='std::exception'>" << ex.what() << "</Exception></SessionCache>";
418 status = "<Partial/>";
421 const PropertySet* relyingParty=NULL;
422 param=httpRequest.getParameter("entityID");
424 MetadataProvider* m = application.getMetadataProvider();
426 relyingParty = application.getRelyingParty(m->getEntityDescriptor(MetadataProviderCriteria(application, param)).first);
429 relyingParty = &application;
432 s << "<Application id='" << application.getId() << "' entityID='" << relyingParty->getString("entityID").second << "'/>";
435 vector<const Handler*> handlers;
436 application.getHandlers(handlers);
437 for (vector<const Handler*>::const_iterator h = handlers.begin(); h != handlers.end(); ++h) {
438 s << "<Handler type='" << (*h)->getType() << "' Location='" << (*h)->getString("Location").second << "'";
439 if ((*h)->getString("Binding").first)
440 s << " Binding='" << (*h)->getString("Binding").second << "'";
445 CredentialResolver* credResolver=application.getCredentialResolver();
447 Locker credLocker(credResolver);
448 CredentialCriteria cc;
449 cc.setUsage(Credential::SIGNING_CREDENTIAL);
450 pair<bool,const char*> keyName = relyingParty->getString("keyName");
452 cc.getKeyNames().insert(keyName.second);
453 vector<const Credential*> creds;
454 credResolver->resolve(creds,&cc);
455 for (vector<const Credential*>::const_iterator c = creds.begin(); c != creds.end(); ++c) {
456 KeyInfo* kinfo = (*c)->getKeyInfo();
458 auto_ptr<KeyDescriptor> kd(KeyDescriptorBuilder::buildKeyDescriptor());
459 kd->setUse(KeyDescriptor::KEYTYPE_SIGNING);
460 kd->setKeyInfo(kinfo);
465 cc.setUsage(Credential::ENCRYPTION_CREDENTIAL);
467 cc.getKeyNames().clear();
468 credResolver->resolve(creds,&cc);
469 for (vector<const Credential*>::const_iterator c = creds.begin(); c != creds.end(); ++c) {
470 KeyInfo* kinfo = (*c)->getKeyInfo();
472 auto_ptr<KeyDescriptor> kd(KeyDescriptorBuilder::buildKeyDescriptor());
473 kd->setUse(KeyDescriptor::KEYTYPE_ENCRYPTION);
474 kd->setKeyInfo(kinfo);
481 s << "<Status>" << status << "</Status></StatusHandler>";
483 httpResponse.setContentType("text/xml");
484 return make_pair(true, httpResponse.sendResponse(s));
486 return make_pair(false,0L);