2 * Copyright 2001-2007 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 <saml/version.h>
35 using namespace opensaml::saml2md;
36 using namespace opensaml;
37 using namespace xmlsignature;
39 using namespace xmltooling;
44 #if defined (_MSC_VER)
45 #pragma warning( push )
46 #pragma warning( disable : 4250 )
49 class SHIBSP_DLLLOCAL Blocker : public DOMNodeFilter
52 short acceptNode(const DOMNode* node) const {
57 static SHIBSP_DLLLOCAL Blocker g_Blocker;
59 class SHIBSP_API StatusHandler : public AbstractHandler, public RemotedHandler
62 StatusHandler(const DOMElement* e, const char* appId);
63 virtual ~StatusHandler() {}
65 pair<bool,long> run(SPRequest& request, bool isHandler=true) const;
66 void receive(DDF& in, ostream& out);
69 pair<bool,long> processMessage(const Application& application, const HTTPRequest& httpRequest, HTTPResponse& httpResponse) const;
74 #if defined (_MSC_VER)
75 #pragma warning( pop )
78 Handler* SHIBSP_DLLLOCAL StatusHandlerFactory(const pair<const DOMElement*,const char*>& p)
80 return new StatusHandler(p.first, p.second);
83 #ifndef XMLTOOLING_NO_XMLSEC
84 vector<XSECCryptoX509*> g_NoCerts;
86 vector<string> g_NoCerts;
89 static char _x2c(const char *what)
93 digit = (what[0] >= 'A' ? ((what[0] & 0xdf) - 'A')+10 : (what[0] - '0'));
95 digit += (what[1] >= 'A' ? ((what[1] & 0xdf) - 'A')+10 : (what[1] - '0'));
99 class DummyRequest : public HTTPRequest
102 DummyRequest(const char* url) : m_parser(NULL), m_url(url), m_scheme(NULL), m_query(NULL), m_port(0) {
103 #ifdef HAVE_STRCASECMP
104 if (url && !strncasecmp(url,"http://",7)) {
108 else if (url && !strncasecmp(url,"https://",8)) {
114 if (url && !strnicmp(url,"http://",7)) {
119 else if (url && !strnicmp(url,"https://",8)) {
126 throw invalid_argument("Target parameter was not an absolute URL.");
128 m_query = strchr(url,'?');
132 const char* slash = strchr(url, '/');
133 const char* colon = strchr(url, ':');
134 if (colon && colon < slash) {
135 m_hostname.assign(url, colon-url);
136 string port(colon + 1, slash - colon);
137 m_port = atoi(port.c_str());
140 m_hostname.assign(url, slash - url);
148 else if (*slash == ';') {
149 // If this is Java being stupid, skip everything up to the query string, if any.
150 if (!strncmp(slash, ";jsessionid=", 12)) {
151 if (slash = strchr(slash, '?'))
159 else if (*slash != '%') {
164 if (!isxdigit(*slash) || !isxdigit(*(slash+1)))
165 throw invalid_argument("Bad request, contained unsupported encoded characters.");
166 m_uri += _x2c(slash);
177 const char* getRequestURL() const {
180 const char* getScheme() const {
183 const char* getHostname() const {
184 return m_hostname.c_str();
186 int getPort() const {
189 const char* getRequestURI() const {
190 return m_uri.c_str();
192 const char* getMethod() const {
195 string getContentType() const {
198 long getContentLength() const {
201 string getRemoteAddr() const {
204 string getRemoteUser() const {
207 const char* getRequestBody() const {
210 const char* getQueryString() const {
213 const char* getParameter(const char* name) const
216 m_parser=new CGIParser(*this);
218 pair<CGIParser::walker,CGIParser::walker> bounds=m_parser->getParameters(name);
219 return (bounds.first==bounds.second) ? NULL : bounds.first->second;
221 vector<const char*>::size_type getParameters(const char* name, vector<const char*>& values) const
224 m_parser=new CGIParser(*this);
226 pair<CGIParser::walker,CGIParser::walker> bounds=m_parser->getParameters(name);
227 while (bounds.first!=bounds.second) {
228 values.push_back(bounds.first->second);
231 return values.size();
233 string getHeader(const char* name) const {
237 #ifndef XMLTOOLING_NO_XMLSEC
238 std::vector<XSECCryptoX509*>&
240 std::vector<std::string>&
242 getClientCertificates() const {
247 mutable CGIParser* m_parser;
249 const char* m_scheme;
252 string m_hostname,m_uri;
256 StatusHandler::StatusHandler(const DOMElement* e, const char* appId)
257 : AbstractHandler(e, Category::getInstance(SHIBSP_LOGCAT".StatusHandler"), &g_Blocker)
259 string address(appId);
260 address += getString("Location").second;
261 setAddress(address.c_str());
262 if (SPConfig::getConfig().isEnabled(SPConfig::InProcess)) {
263 pair<bool,const char*> acl = getString("acl");
265 string aclbuf=acl.second;
267 for (unsigned int i=0; i < aclbuf.length(); i++) {
268 if (aclbuf.at(i)==' ') {
269 m_acl.insert(aclbuf.substr(j, i-j));
273 m_acl.insert(aclbuf.substr(j, aclbuf.length()-j));
278 pair<bool,long> StatusHandler::run(SPRequest& request, bool isHandler) const
280 SPConfig& conf = SPConfig::getConfig();
281 if (conf.isEnabled(SPConfig::InProcess)) {
282 if (!m_acl.empty() && m_acl.count(request.getRemoteAddr()) == 0) {
283 m_log.error("status handler request blocked from invalid address (%s)", request.getRemoteAddr().c_str());
284 istringstream msg("Status Handler Blocked");
285 return make_pair(true,request.sendResponse(msg, HTTPResponse::XMLTOOLING_HTTP_STATUS_UNAUTHORIZED));
289 const char* target = request.getParameter("target");
291 // RequestMap query, so handle it inproc.
292 DummyRequest dummy(target);
293 RequestMapper::Settings settings = request.getApplication().getServiceProvider().getRequestMapper()->getSettings(dummy);
294 map<string,const char*> props;
295 settings.first->getAll(props);
297 request.setContentType("text/xml");
299 msg << "<StatusHandler>";
300 msg << "<Version Xerces-C='" << XERCES_FULLVERSIONDOT
302 << "' XML-Security-C='" << XSEC_FULLVERSIONDOT
303 << "' OpenSAML-C='" << OPENSAML_FULLVERSIONDOT
305 << "' Shibboleth='" << PACKAGE_VERSION << "'/>";
306 msg << "<RequestSettings";
307 for (map<string,const char*>::const_iterator p = props.begin(); p != props.end(); ++p)
308 msg << ' ' << p->first << "='" << p->second << "'";
309 msg << '>' << target << "</RequestSettings>";
310 msg << "<Status><OK/></Status>";
311 msg << "</StatusHandler>";
312 return make_pair(true,request.sendResponse(msg));
316 if (conf.isEnabled(SPConfig::OutOfProcess)) {
317 // When out of process, we run natively and directly process the message.
318 return processMessage(request.getApplication(), request, request);
321 // When not out of process, we remote all the message processing.
322 DDF out,in = wrap(request);
323 DDFJanitor jin(in), jout(out);
324 out=request.getServiceProvider().getListenerService()->send(in);
325 return unwrap(request, out);
328 catch (XMLToolingException& ex) {
329 m_log.error("error while processing request: %s", ex.what());
330 request.setContentType("text/xml");
332 msg << "<StatusHandler>";
333 msg << "<Version Xerces-C='" << XERCES_FULLVERSIONDOT
335 << "' XML-Security-C='" << XSEC_FULLVERSIONDOT
336 << "' OpenSAML-C='" << OPENSAML_FULLVERSIONDOT
338 << "' Shibboleth='" << PACKAGE_VERSION << "'/>";
339 msg << "<Status><Exception type='" << ex.getClassName() << "'>" << ex.what() << "</Exception></Status>";
340 msg << "</StatusHandler>";
341 return make_pair(true,request.sendResponse(msg, HTTPResponse::XMLTOOLING_HTTP_STATUS_ERROR));
343 catch (exception& ex) {
344 m_log.error("error while processing request: %s", ex.what());
345 request.setContentType("text/xml");
347 msg << "<StatusHandler>";
348 msg << "<Version Xerces-C='" << XERCES_FULLVERSIONDOT
350 << "' XML-Security-C='" << XSEC_FULLVERSIONDOT
351 << "' OpenSAML-C='" << OPENSAML_FULLVERSIONDOT
353 << "' Shibboleth='" << PACKAGE_VERSION << "'/>";
354 msg << "<Status><Exception type='std::exception'>" << ex.what() << "</Exception></Status>";
355 msg << "</StatusHandler>";
356 return make_pair(true,request.sendResponse(msg, HTTPResponse::XMLTOOLING_HTTP_STATUS_ERROR));
360 void StatusHandler::receive(DDF& in, ostream& out)
363 const char* aid=in["application_id"].string();
364 const Application* app=aid ? SPConfig::getConfig().getServiceProvider()->getApplication(aid) : NULL;
366 // Something's horribly wrong.
367 m_log.error("couldn't find application (%s) for status request", aid ? aid : "(missing)");
368 throw ConfigurationException("Unable to locate application for status request, deleted?");
371 // Wrap a response shim.
373 DDFJanitor jout(ret);
374 auto_ptr<HTTPRequest> req(getRequest(in));
375 auto_ptr<HTTPResponse> resp(getResponse(ret));
377 // Since we're remoted, the result should either be a throw, a false/0 return,
378 // which we just return as an empty structure, or a response/redirect,
379 // which we capture in the facade and send back.
380 processMessage(*app, *req.get(), *resp.get());
384 pair<bool,long> StatusHandler::processMessage(
385 const Application& application, const HTTPRequest& httpRequest, HTTPResponse& httpResponse
389 m_log.debug("processing status request");
392 s << "<StatusHandler>";
393 const char* status = "<OK/>";
395 s << "<Version Xerces-C='" << XERCES_FULLVERSIONDOT
396 << "' XML-Security-C='" << XSEC_FULLVERSIONDOT
397 << "' OpenSAML-C='" << OPENSAML_FULLVERSIONDOT
398 << "' Shibboleth='" << PACKAGE_VERSION << "'/>";
400 const char* param = NULL;
404 // General configuration and status report.
406 SessionCache* sc = application.getServiceProvider().getSessionCache(false);
409 s << "<SessionCache><OK/></SessionCache>";
412 s << "<SessionCache><None/></SessionCache>";
415 catch (XMLToolingException& ex) {
416 s << "<SessionCache><Exception type='" << ex.getClassName() << "'>" << ex.what() << "</Exception></SessionCache>";
417 status = "<Partial/>";
419 catch (exception& ex) {
420 s << "<SessionCache><Exception type='std::exception'>" << ex.what() << "</Exception></SessionCache>";
421 status = "<Partial/>";
424 const PropertySet* relyingParty=NULL;
425 param=httpRequest.getParameter("entityID");
427 MetadataProvider* m = application.getMetadataProvider();
429 relyingParty = application.getRelyingParty(m->getEntityDescriptor(MetadataProvider::Criteria(param)).first);
432 relyingParty = application.getRelyingParty(NULL);
435 s << "<Application id='" << application.getId() << "' entityID='" << relyingParty->getString("entityID").second << "'/>";
438 vector<const Handler*> handlers;
439 application.getHandlers(handlers);
440 for (vector<const Handler*>::const_iterator h = handlers.begin(); h != handlers.end(); ++h) {
441 s << "<Handler type='" << (*h)->getType() << "' Location='" << (*h)->getString("Location").second << "'";
442 if ((*h)->getString("Binding").first)
443 s << " Binding='" << (*h)->getString("Binding").second << "'";
448 CredentialResolver* credResolver=application.getCredentialResolver();
450 Locker credLocker(credResolver);
451 CredentialCriteria cc;
452 cc.setUsage(Credential::SIGNING_CREDENTIAL);
453 pair<bool,const char*> keyName = relyingParty->getString("keyName");
455 cc.getKeyNames().insert(keyName.second);
456 vector<const Credential*> creds;
457 credResolver->resolve(creds,&cc);
458 for (vector<const Credential*>::const_iterator c = creds.begin(); c != creds.end(); ++c) {
459 KeyInfo* kinfo = (*c)->getKeyInfo();
461 auto_ptr<KeyDescriptor> kd(KeyDescriptorBuilder::buildKeyDescriptor());
462 kd->setUse(KeyDescriptor::KEYTYPE_SIGNING);
463 kd->setKeyInfo(kinfo);
468 cc.setUsage(Credential::ENCRYPTION_CREDENTIAL);
470 cc.getKeyNames().clear();
471 credResolver->resolve(creds,&cc);
472 for (vector<const Credential*>::const_iterator c = creds.begin(); c != creds.end(); ++c) {
473 KeyInfo* kinfo = (*c)->getKeyInfo();
475 auto_ptr<KeyDescriptor> kd(KeyDescriptorBuilder::buildKeyDescriptor());
476 kd->setUse(KeyDescriptor::KEYTYPE_ENCRYPTION);
477 kd->setKeyInfo(kinfo);
484 s << "<Status>" << status << "</Status></StatusHandler>";
486 httpResponse.setContentType("text/xml");
487 return make_pair(true, httpResponse.sendResponse(s));
489 return make_pair(false,0L);