Imported Upstream version 2.2.1+dfsg
[shibboleth/sp.git] / shibsp / handler / impl / StatusHandler.cpp
1 /*
2  *  Copyright 2001-2009 Internet2
3  *
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
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
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.
15  */
16
17 /**
18  * StatusHandler.cpp
19  *
20  * Handler for exposing information about the internals of the SP.
21  */
22
23 #include "internal.h"
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"
30
31 using namespace shibsp;
32 #ifndef SHIBSP_LITE
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;
39 #endif
40 using namespace xmltooling;
41 using namespace std;
42
43 namespace shibsp {
44
45 #if defined (_MSC_VER)
46     #pragma warning( push )
47     #pragma warning( disable : 4250 )
48 #endif
49
50     class SHIBSP_DLLLOCAL Blocker : public DOMNodeFilter
51     {
52     public:
53 #ifdef SHIBSP_XERCESC_SHORT_ACCEPTNODE
54         short
55 #else
56         FilterAction
57 #endif
58         acceptNode(const DOMNode* node) const {
59             return FILTER_REJECT;
60         }
61     };
62
63     static SHIBSP_DLLLOCAL Blocker g_Blocker;
64
65     class SHIBSP_API StatusHandler : public AbstractHandler, public RemotedHandler
66     {
67     public:
68         StatusHandler(const DOMElement* e, const char* appId);
69         virtual ~StatusHandler() {}
70
71         pair<bool,long> run(SPRequest& request, bool isHandler=true) const;
72         void receive(DDF& in, ostream& out);
73
74     private:
75         pair<bool,long> processMessage(const Application& application, const HTTPRequest& httpRequest, HTTPResponse& httpResponse) const;
76
77         set<string> m_acl;
78     };
79
80 #if defined (_MSC_VER)
81     #pragma warning( pop )
82 #endif
83
84     Handler* SHIBSP_DLLLOCAL StatusHandlerFactory(const pair<const DOMElement*,const char*>& p)
85     {
86         return new StatusHandler(p.first, p.second);
87     }
88
89 #ifndef XMLTOOLING_NO_XMLSEC
90     vector<XSECCryptoX509*> g_NoCerts;
91 #else
92     vector<string> g_NoCerts;
93 #endif
94
95     static char _x2c(const char *what)
96     {
97         register char digit;
98
99         digit = (what[0] >= 'A' ? ((what[0] & 0xdf) - 'A')+10 : (what[0] - '0'));
100         digit *= 16;
101         digit += (what[1] >= 'A' ? ((what[1] & 0xdf) - 'A')+10 : (what[1] - '0'));
102         return(digit);
103     }
104
105     class DummyRequest : public HTTPRequest
106     {
107     public:
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)) {
111                 m_scheme="http";
112                 url+=7;
113             }
114             else if (url && !strncasecmp(url,"https://",8)) {
115                 m_scheme="https";
116                 url+=8;
117             }
118             else
119 #else
120             if (url && !strnicmp(url,"http://",7)) {
121                 m_scheme="http";
122                 m_port = 80;
123                 url+=7;
124             }
125             else if (url && !strnicmp(url,"https://",8)) {
126                 m_scheme="https";
127                 m_port = 443;
128                 url+=8;
129             }
130             else
131 #endif
132                 throw invalid_argument("Target parameter was not an absolute URL.");
133
134             m_query = strchr(url,'?');
135             if (m_query)
136                 m_query++;
137
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());
144             }
145             else {
146                 m_hostname.assign(url, slash - url);
147             }
148
149             while (*slash) {
150                 if (*slash == '?') {
151                     m_uri += slash;
152                     break;
153                 }
154                 else if (*slash != '%') {
155                     m_uri += *slash;
156                 }
157                 else {
158                     ++slash;
159                     if (!isxdigit(*slash) || !isxdigit(*(slash+1)))
160                         throw invalid_argument("Bad request, contained unsupported encoded characters.");
161                     m_uri += _x2c(slash);
162                     ++slash;
163                 }
164                 ++slash;
165             }
166         }
167
168         ~DummyRequest() {
169             delete m_parser;
170         }
171
172         const char* getRequestURL() const {
173             return m_url;
174         }
175         const char* getScheme() const {
176             return m_scheme;
177         }
178         const char* getHostname() const {
179             return m_hostname.c_str();
180         }
181         int getPort() const {
182             return m_port;
183         }
184         const char* getRequestURI() const {
185             return m_uri.c_str();
186         }
187         const char* getMethod() const {
188             return "GET";
189         }
190         string getContentType() const {
191             return "";
192         }
193         long getContentLength() const {
194             return 0;
195         }
196         string getRemoteAddr() const {
197             return "";
198         }
199         string getRemoteUser() const {
200             return "";
201         }
202         const char* getRequestBody() const {
203             return NULL;
204         }
205         const char* getQueryString() const {
206             return m_query;
207         }
208         const char* getParameter(const char* name) const
209         {
210             if (!m_parser)
211                 m_parser=new CGIParser(*this);
212
213             pair<CGIParser::walker,CGIParser::walker> bounds=m_parser->getParameters(name);
214             return (bounds.first==bounds.second) ? NULL : bounds.first->second;
215         }
216         vector<const char*>::size_type getParameters(const char* name, vector<const char*>& values) const
217         {
218             if (!m_parser)
219                 m_parser=new CGIParser(*this);
220
221             pair<CGIParser::walker,CGIParser::walker> bounds=m_parser->getParameters(name);
222             while (bounds.first!=bounds.second) {
223                 values.push_back(bounds.first->second);
224                 ++bounds.first;
225             }
226             return values.size();
227         }
228         string getHeader(const char* name) const {
229             return "";
230         }
231         virtual const
232 #ifndef XMLTOOLING_NO_XMLSEC
233             std::vector<XSECCryptoX509*>&
234 #else
235             std::vector<std::string>&
236 #endif
237             getClientCertificates() const {
238                 return g_NoCerts;
239         }
240
241     private:
242         mutable CGIParser* m_parser;
243         const char* m_url;
244         const char* m_scheme;
245         const char* m_query;
246         int m_port;
247         string m_hostname,m_uri;
248     };
249 };
250
251 StatusHandler::StatusHandler(const DOMElement* e, const char* appId)
252     : AbstractHandler(e, Category::getInstance(SHIBSP_LOGCAT".StatusHandler"), &g_Blocker)
253 {
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");
259         if (acl.first) {
260             string aclbuf=acl.second;
261             int j = 0;
262             for (unsigned int i=0;  i < aclbuf.length();  i++) {
263                 if (aclbuf.at(i)==' ') {
264                     m_acl.insert(aclbuf.substr(j, i-j));
265                     j = i+1;
266                 }
267             }
268             m_acl.insert(aclbuf.substr(j, aclbuf.length()-j));
269         }
270     }
271 }
272
273 pair<bool,long> StatusHandler::run(SPRequest& request, bool isHandler) const
274 {
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));
281         }
282     }
283
284     const char* target = request.getParameter("target");
285     if (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);
291
292         request.setContentType("text/xml");
293         stringstream msg;
294         msg << "<StatusHandler>";
295             msg << "<Version Xerces-C='" << XERCES_FULLVERSIONDOT
296 #ifndef SHIBSP_LITE
297                 << "' XML-Security-C='" << XSEC_FULLVERSIONDOT
298                 << "' OpenSAML-C='" << OPENSAML_FULLVERSIONDOT
299 #endif
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));
308     }
309
310     try {
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);
314         }
315         else {
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);
321         }
322     }
323     catch (XMLToolingException& ex) {
324         m_log.error("error while processing request: %s", ex.what());
325         request.setContentType("text/xml");
326         stringstream msg;
327         msg << "<StatusHandler>";
328             msg << "<Version Xerces-C='" << XERCES_FULLVERSIONDOT
329 #ifndef SHIBSP_LITE
330                 << "' XML-Security-C='" << XSEC_FULLVERSIONDOT
331                 << "' OpenSAML-C='" << OPENSAML_FULLVERSIONDOT
332 #endif
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));
337     }
338     catch (exception& ex) {
339         m_log.error("error while processing request: %s", ex.what());
340         request.setContentType("text/xml");
341         stringstream msg;
342         msg << "<StatusHandler>";
343             msg << "<Version Xerces-C='" << XERCES_FULLVERSIONDOT
344 #ifndef SHIBSP_LITE
345                 << "' XML-Security-C='" << XSEC_FULLVERSIONDOT
346                 << "' OpenSAML-C='" << OPENSAML_FULLVERSIONDOT
347 #endif
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));
352     }
353 }
354
355 void StatusHandler::receive(DDF& in, ostream& out)
356 {
357     // Find application.
358     const char* aid=in["application_id"].string();
359     const Application* app=aid ? SPConfig::getConfig().getServiceProvider()->getApplication(aid) : NULL;
360     if (!app) {
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?");
364     }
365
366     // Wrap a response shim.
367     DDF ret(NULL);
368     DDFJanitor jout(ret);
369     auto_ptr<HTTPRequest> req(getRequest(in));
370     auto_ptr<HTTPResponse> resp(getResponse(ret));
371
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());
376     out << ret;
377 }
378
379 pair<bool,long> StatusHandler::processMessage(
380     const Application& application, const HTTPRequest& httpRequest, HTTPResponse& httpResponse
381     ) const
382 {
383 #ifndef SHIBSP_LITE
384     m_log.debug("processing status request");
385
386     stringstream s;
387     s << "<StatusHandler>";
388     const char* status = "<OK/>";
389
390     s << "<Version Xerces-C='" << XERCES_FULLVERSIONDOT
391         << "' XML-Security-C='" << XSEC_FULLVERSIONDOT
392         << "' OpenSAML-C='" << OPENSAML_FULLVERSIONDOT
393         << "' Shibboleth='" << PACKAGE_VERSION << "'/>";
394
395     const char* param = NULL;
396     if (param) {
397     }
398     else {
399         // General configuration and status report.
400         try {
401             SessionCache* sc = application.getServiceProvider().getSessionCache(false);
402             if (sc) {
403                 sc->test();
404                 s << "<SessionCache><OK/></SessionCache>";
405             }
406             else {
407                 s << "<SessionCache><None/></SessionCache>";
408             }
409         }
410         catch (XMLToolingException& ex) {
411             s << "<SessionCache><Exception type='" << ex.getClassName() << "'>" << ex.what() << "</Exception></SessionCache>";
412             status = "<Partial/>";
413         }
414         catch (exception& ex) {
415             s << "<SessionCache><Exception type='std::exception'>" << ex.what() << "</Exception></SessionCache>";
416             status = "<Partial/>";
417         }
418
419         const PropertySet* relyingParty=NULL;
420         param=httpRequest.getParameter("entityID");
421         if (param) {
422             MetadataProvider* m = application.getMetadataProvider();
423             Locker mlock(m);
424             relyingParty = application.getRelyingParty(m->getEntityDescriptor(MetadataProviderCriteria(application, param)).first);
425         }
426         else {
427             relyingParty = &application;
428         }
429
430         s << "<Application id='" << application.getId() << "' entityID='" << relyingParty->getString("entityID").second << "'/>";
431
432         s << "<Handlers>";
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 << "'";
439             s << "/>";
440         }
441         s << "</Handlers>";
442
443         CredentialResolver* credResolver=application.getCredentialResolver();
444         if (credResolver) {
445             Locker credLocker(credResolver);
446             CredentialCriteria cc;
447             cc.setUsage(Credential::SIGNING_CREDENTIAL);
448             pair<bool,const char*> keyName = relyingParty->getString("keyName");
449             if (keyName.first)
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();
455                 if (kinfo) {
456                     auto_ptr<KeyDescriptor> kd(KeyDescriptorBuilder::buildKeyDescriptor());
457                     kd->setUse(KeyDescriptor::KEYTYPE_SIGNING);
458                     kd->setKeyInfo(kinfo);
459                     s << *(kd.get());
460                 }
461             }
462
463             cc.setUsage(Credential::ENCRYPTION_CREDENTIAL);
464             creds.clear();
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();
469                 if (kinfo) {
470                     auto_ptr<KeyDescriptor> kd(KeyDescriptorBuilder::buildKeyDescriptor());
471                     kd->setUse(KeyDescriptor::KEYTYPE_ENCRYPTION);
472                     kd->setKeyInfo(kinfo);
473                     s << *(kd.get());
474                 }
475             }
476         }
477     }
478
479     s << "<Status>" << status << "</Status></StatusHandler>";
480
481     httpResponse.setContentType("text/xml");
482     return make_pair(true, httpResponse.sendResponse(s));
483 #else
484     return make_pair(false,0L);
485 #endif
486 }