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 "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 short acceptNode(const DOMNode* node) const {
58 static SHIBSP_DLLLOCAL Blocker g_Blocker;
60 class SHIBSP_API StatusHandler : public AbstractHandler, public RemotedHandler
63 StatusHandler(const DOMElement* e, const char* appId);
64 virtual ~StatusHandler() {}
66 pair<bool,long> run(SPRequest& request, bool isHandler=true) const;
67 void receive(DDF& in, ostream& out);
70 pair<bool,long> processMessage(const Application& application, const HTTPRequest& httpRequest, HTTPResponse& httpResponse) const;
75 #if defined (_MSC_VER)
76 #pragma warning( pop )
79 Handler* SHIBSP_DLLLOCAL StatusHandlerFactory(const pair<const DOMElement*,const char*>& p)
81 return new StatusHandler(p.first, p.second);
84 #ifndef XMLTOOLING_NO_XMLSEC
85 vector<XSECCryptoX509*> g_NoCerts;
87 vector<string> g_NoCerts;
90 static char _x2c(const char *what)
94 digit = (what[0] >= 'A' ? ((what[0] & 0xdf) - 'A')+10 : (what[0] - '0'));
96 digit += (what[1] >= 'A' ? ((what[1] & 0xdf) - 'A')+10 : (what[1] - '0'));
100 class DummyRequest : public HTTPRequest
103 DummyRequest(const char* url) : m_parser(NULL), m_url(url), m_scheme(NULL), m_query(NULL), m_port(0) {
104 #ifdef HAVE_STRCASECMP
105 if (url && !strncasecmp(url,"http://",7)) {
109 else if (url && !strncasecmp(url,"https://",8)) {
115 if (url && !strnicmp(url,"http://",7)) {
120 else if (url && !strnicmp(url,"https://",8)) {
127 throw invalid_argument("Target parameter was not an absolute URL.");
129 m_query = strchr(url,'?');
133 const char* slash = strchr(url, '/');
134 const char* colon = strchr(url, ':');
135 if (colon && colon < slash) {
136 m_hostname.assign(url, colon-url);
137 string port(colon + 1, slash - colon);
138 m_port = atoi(port.c_str());
141 m_hostname.assign(url, slash - url);
149 else if (*slash == ';') {
150 // If this is Java being stupid, skip everything up to the query string, if any.
151 if (!strncmp(slash, ";jsessionid=", 12)) {
152 if (slash = strchr(slash, '?'))
160 else if (*slash != '%') {
165 if (!isxdigit(*slash) || !isxdigit(*(slash+1)))
166 throw invalid_argument("Bad request, contained unsupported encoded characters.");
167 m_uri += _x2c(slash);
178 const char* getRequestURL() const {
181 const char* getScheme() const {
184 const char* getHostname() const {
185 return m_hostname.c_str();
187 int getPort() const {
190 const char* getRequestURI() const {
191 return m_uri.c_str();
193 const char* getMethod() const {
196 string getContentType() const {
199 long getContentLength() const {
202 string getRemoteAddr() const {
205 string getRemoteUser() const {
208 const char* getRequestBody() const {
211 const char* getQueryString() const {
214 const char* getParameter(const char* name) const
217 m_parser=new CGIParser(*this);
219 pair<CGIParser::walker,CGIParser::walker> bounds=m_parser->getParameters(name);
220 return (bounds.first==bounds.second) ? NULL : bounds.first->second;
222 vector<const char*>::size_type getParameters(const char* name, vector<const char*>& values) const
225 m_parser=new CGIParser(*this);
227 pair<CGIParser::walker,CGIParser::walker> bounds=m_parser->getParameters(name);
228 while (bounds.first!=bounds.second) {
229 values.push_back(bounds.first->second);
232 return values.size();
234 string getHeader(const char* name) const {
238 #ifndef XMLTOOLING_NO_XMLSEC
239 std::vector<XSECCryptoX509*>&
241 std::vector<std::string>&
243 getClientCertificates() const {
248 mutable CGIParser* m_parser;
250 const char* m_scheme;
253 string m_hostname,m_uri;
257 StatusHandler::StatusHandler(const DOMElement* e, const char* appId)
258 : AbstractHandler(e, Category::getInstance(SHIBSP_LOGCAT".StatusHandler"), &g_Blocker)
260 string address(appId);
261 address += getString("Location").second;
262 setAddress(address.c_str());
263 if (SPConfig::getConfig().isEnabled(SPConfig::InProcess)) {
264 pair<bool,const char*> acl = getString("acl");
266 string aclbuf=acl.second;
268 for (unsigned int i=0; i < aclbuf.length(); i++) {
269 if (aclbuf.at(i)==' ') {
270 m_acl.insert(aclbuf.substr(j, i-j));
274 m_acl.insert(aclbuf.substr(j, aclbuf.length()-j));
279 pair<bool,long> StatusHandler::run(SPRequest& request, bool isHandler) const
281 SPConfig& conf = SPConfig::getConfig();
282 if (conf.isEnabled(SPConfig::InProcess)) {
283 if (!m_acl.empty() && m_acl.count(request.getRemoteAddr()) == 0) {
284 m_log.error("status handler request blocked from invalid address (%s)", request.getRemoteAddr().c_str());
285 istringstream msg("Status Handler Blocked");
286 return make_pair(true,request.sendResponse(msg, HTTPResponse::XMLTOOLING_HTTP_STATUS_UNAUTHORIZED));
290 const char* target = request.getParameter("target");
292 // RequestMap query, so handle it inproc.
293 DummyRequest dummy(target);
294 RequestMapper::Settings settings = request.getApplication().getServiceProvider().getRequestMapper()->getSettings(dummy);
295 map<string,const char*> props;
296 settings.first->getAll(props);
298 request.setContentType("text/xml");
300 msg << "<StatusHandler>";
301 msg << "<Version Xerces-C='" << XERCES_FULLVERSIONDOT
303 << "' XML-Security-C='" << XSEC_FULLVERSIONDOT
304 << "' OpenSAML-C='" << OPENSAML_FULLVERSIONDOT
306 << "' Shibboleth='" << PACKAGE_VERSION << "'/>";
307 msg << "<RequestSettings";
308 for (map<string,const char*>::const_iterator p = props.begin(); p != props.end(); ++p)
309 msg << ' ' << p->first << "='" << p->second << "'";
310 msg << '>' << target << "</RequestSettings>";
311 msg << "<Status><OK/></Status>";
312 msg << "</StatusHandler>";
313 return make_pair(true,request.sendResponse(msg));
317 if (conf.isEnabled(SPConfig::OutOfProcess)) {
318 // When out of process, we run natively and directly process the message.
319 return processMessage(request.getApplication(), request, request);
322 // When not out of process, we remote all the message processing.
323 DDF out,in = wrap(request);
324 DDFJanitor jin(in), jout(out);
325 out=request.getServiceProvider().getListenerService()->send(in);
326 return unwrap(request, out);
329 catch (XMLToolingException& ex) {
330 m_log.error("error while processing request: %s", ex.what());
331 request.setContentType("text/xml");
333 msg << "<StatusHandler>";
334 msg << "<Version Xerces-C='" << XERCES_FULLVERSIONDOT
336 << "' XML-Security-C='" << XSEC_FULLVERSIONDOT
337 << "' OpenSAML-C='" << OPENSAML_FULLVERSIONDOT
339 << "' Shibboleth='" << PACKAGE_VERSION << "'/>";
340 msg << "<Status><Exception type='" << ex.getClassName() << "'>" << ex.what() << "</Exception></Status>";
341 msg << "</StatusHandler>";
342 return make_pair(true,request.sendResponse(msg, HTTPResponse::XMLTOOLING_HTTP_STATUS_ERROR));
344 catch (exception& ex) {
345 m_log.error("error while processing request: %s", ex.what());
346 request.setContentType("text/xml");
348 msg << "<StatusHandler>";
349 msg << "<Version Xerces-C='" << XERCES_FULLVERSIONDOT
351 << "' XML-Security-C='" << XSEC_FULLVERSIONDOT
352 << "' OpenSAML-C='" << OPENSAML_FULLVERSIONDOT
354 << "' Shibboleth='" << PACKAGE_VERSION << "'/>";
355 msg << "<Status><Exception type='std::exception'>" << ex.what() << "</Exception></Status>";
356 msg << "</StatusHandler>";
357 return make_pair(true,request.sendResponse(msg, HTTPResponse::XMLTOOLING_HTTP_STATUS_ERROR));
361 void StatusHandler::receive(DDF& in, ostream& out)
364 const char* aid=in["application_id"].string();
365 const Application* app=aid ? SPConfig::getConfig().getServiceProvider()->getApplication(aid) : NULL;
367 // Something's horribly wrong.
368 m_log.error("couldn't find application (%s) for status request", aid ? aid : "(missing)");
369 throw ConfigurationException("Unable to locate application for status request, deleted?");
372 // Wrap a response shim.
374 DDFJanitor jout(ret);
375 auto_ptr<HTTPRequest> req(getRequest(in));
376 auto_ptr<HTTPResponse> resp(getResponse(ret));
378 // Since we're remoted, the result should either be a throw, a false/0 return,
379 // which we just return as an empty structure, or a response/redirect,
380 // which we capture in the facade and send back.
381 processMessage(*app, *req.get(), *resp.get());
385 pair<bool,long> StatusHandler::processMessage(
386 const Application& application, const HTTPRequest& httpRequest, HTTPResponse& httpResponse
390 m_log.debug("processing status request");
393 s << "<StatusHandler>";
394 const char* status = "<OK/>";
396 s << "<Version Xerces-C='" << XERCES_FULLVERSIONDOT
397 << "' XML-Security-C='" << XSEC_FULLVERSIONDOT
398 << "' OpenSAML-C='" << OPENSAML_FULLVERSIONDOT
399 << "' Shibboleth='" << PACKAGE_VERSION << "'/>";
401 const char* param = NULL;
405 // General configuration and status report.
407 SessionCache* sc = application.getServiceProvider().getSessionCache(false);
410 s << "<SessionCache><OK/></SessionCache>";
413 s << "<SessionCache><None/></SessionCache>";
416 catch (XMLToolingException& ex) {
417 s << "<SessionCache><Exception type='" << ex.getClassName() << "'>" << ex.what() << "</Exception></SessionCache>";
418 status = "<Partial/>";
420 catch (exception& ex) {
421 s << "<SessionCache><Exception type='std::exception'>" << ex.what() << "</Exception></SessionCache>";
422 status = "<Partial/>";
425 const PropertySet* relyingParty=NULL;
426 param=httpRequest.getParameter("entityID");
428 MetadataProvider* m = application.getMetadataProvider();
430 relyingParty = application.getRelyingParty(m->getEntityDescriptor(MetadataProviderCriteria(application, param)).first);
433 relyingParty = &application;
436 s << "<Application id='" << application.getId() << "' entityID='" << relyingParty->getString("entityID").second << "'/>";
439 vector<const Handler*> handlers;
440 application.getHandlers(handlers);
441 for (vector<const Handler*>::const_iterator h = handlers.begin(); h != handlers.end(); ++h) {
442 s << "<Handler type='" << (*h)->getType() << "' Location='" << (*h)->getString("Location").second << "'";
443 if ((*h)->getString("Binding").first)
444 s << " Binding='" << (*h)->getString("Binding").second << "'";
449 CredentialResolver* credResolver=application.getCredentialResolver();
451 Locker credLocker(credResolver);
452 CredentialCriteria cc;
453 cc.setUsage(Credential::SIGNING_CREDENTIAL);
454 pair<bool,const char*> keyName = relyingParty->getString("keyName");
456 cc.getKeyNames().insert(keyName.second);
457 vector<const Credential*> creds;
458 credResolver->resolve(creds,&cc);
459 for (vector<const Credential*>::const_iterator c = creds.begin(); c != creds.end(); ++c) {
460 KeyInfo* kinfo = (*c)->getKeyInfo();
462 auto_ptr<KeyDescriptor> kd(KeyDescriptorBuilder::buildKeyDescriptor());
463 kd->setUse(KeyDescriptor::KEYTYPE_SIGNING);
464 kd->setKeyInfo(kinfo);
469 cc.setUsage(Credential::ENCRYPTION_CREDENTIAL);
471 cc.getKeyNames().clear();
472 credResolver->resolve(creds,&cc);
473 for (vector<const Credential*>::const_iterator c = creds.begin(); c != creds.end(); ++c) {
474 KeyInfo* kinfo = (*c)->getKeyInfo();
476 auto_ptr<KeyDescriptor> kd(KeyDescriptorBuilder::buildKeyDescriptor());
477 kd->setUse(KeyDescriptor::KEYTYPE_ENCRYPTION);
478 kd->setKeyInfo(kinfo);
485 s << "<Status>" << status << "</Status></StatusHandler>";
487 httpResponse.setContentType("text/xml");
488 return make_pair(true, httpResponse.sendResponse(s));
490 return make_pair(false,0L);