2 * Copyright 2001-2010 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 * Base class for handlers that need SP request/response layer to be remoted.
24 #include "exceptions.h"
25 #include "Application.h"
26 #include "GSSRequest.h"
27 #include "ServiceProvider.h"
28 #include "SPRequest.h"
29 #include "handler/RemotedHandler.h"
32 #include <xmltooling/unicode.h>
33 #include <xercesc/util/Base64.hpp>
36 # include "util/CGIParser.h"
37 # include <xsec/enc/OpenSSL/OpenSSLCryptoX509.hpp>
38 # include <xsec/enc/XSECCryptoException.hpp>
39 # include <xsec/framework/XSECException.hpp>
40 # include <xsec/framework/XSECProvider.hpp>
43 using namespace shibsp;
44 using namespace opensaml;
45 using namespace xmltooling;
46 using namespace xercesc;
51 class SHIBSP_DLLLOCAL RemotedRequest :
53 public virtual GSSRequest,
55 public virtual HTTPRequest
58 mutable CGIParser* m_parser;
59 mutable vector<XSECCryptoX509*> m_certs;
61 mutable gss_ctx_id_t m_gss;
64 RemotedRequest(DDF& input) : m_input(input), m_parser(nullptr)
66 , m_ctx(GSS_C_NO_CONTEXT)
71 virtual ~RemotedRequest() {
72 for_each(m_certs.begin(), m_certs.end(), xmltooling::cleanup<XSECCryptoX509>());
75 if (m_ctx != GSS_C_NO_CONTEXT) {
77 gss_delete_sec_context(&minor, &m_ctx, GSS_C_NO_BUFFER);
83 const char* getScheme() const {
84 return m_input["scheme"].string();
86 const char* getHostname() const {
87 return m_input["hostname"].string();
90 return m_input["port"].integer();
92 std::string getContentType() const {
93 DDF s = m_input["content_type"];
94 return s.string() ? s.string() : "";
96 long getContentLength() const {
97 return m_input["content_length"].integer();
99 const char* getRequestBody() const {
100 return m_input["body"].string();
103 const char* getParameter(const char* name) const;
104 std::vector<const char*>::size_type getParameters(const char* name, std::vector<const char*>& values) const;
106 std::string getRemoteUser() const {
107 DDF s = m_input["remote_user"];
108 return s.string() ? s.string() : "";
110 std::string getRemoteAddr() const {
111 DDF s = m_input["client_addr"];
112 return s.string() ? s.string() : "";
115 const std::vector<XSECCryptoX509*>& getClientCertificates() const;
119 gss_ctx_id_t getGSSContext() const;
123 const char* getMethod() const {
124 return m_input["method"].string();
126 const char* getRequestURI() const {
127 return m_input["uri"].string();
129 const char* getRequestURL() const {
130 return m_input["url"].string();
132 const char* getQueryString() const {
133 return m_input["query"].string();
135 std::string getHeader(const char* name) const {
136 DDF s = m_input["headers"][name];
137 return s.string() ? s.string() : "";
141 class SHIBSP_DLLLOCAL RemotedResponse : public virtual HTTPResponse
145 RemotedResponse(DDF& output) : m_output(output) {}
146 virtual ~RemotedResponse() {}
149 long sendResponse(std::istream& inputStream, long status);
152 void setResponseHeader(const char* name, const char* value);
153 long sendRedirect(const char* url);
157 const char* RemotedRequest::getParameter(const char* name) const
160 m_parser=new CGIParser(*this);
162 pair<CGIParser::walker,CGIParser::walker> bounds=m_parser->getParameters(name);
163 return (bounds.first==bounds.second) ? nullptr : bounds.first->second;
166 std::vector<const char*>::size_type RemotedRequest::getParameters(const char* name, std::vector<const char*>& values) const
169 m_parser=new CGIParser(*this);
171 pair<CGIParser::walker,CGIParser::walker> bounds=m_parser->getParameters(name);
172 while (bounds.first!=bounds.second) {
173 values.push_back(bounds.first->second);
176 return values.size();
179 const std::vector<XSECCryptoX509*>& RemotedRequest::getClientCertificates() const
181 if (m_certs.empty()) {
182 DDF certs = m_input["certificates"];
183 DDF cert = certs.first();
184 while (cert.string()) {
186 auto_ptr<XSECCryptoX509> x509(XSECPlatformUtils::g_cryptoProvider->X509());
187 if (strstr(cert.string(), "BEGIN"))
188 x509->loadX509PEM(cert.string(), cert.strlen());
190 x509->loadX509Base64Bin(cert.string(), cert.strlen());
191 m_certs.push_back(x509.release());
193 catch(XSECException& e) {
194 auto_ptr_char temp(e.getMsg());
195 Category::getInstance(SHIBSP_LOGCAT".SPRequest").error("XML-Security exception loading client certificate: %s", temp.get());
197 catch(XSECCryptoException& e) {
198 Category::getInstance(SHIBSP_LOGCAT".SPRequest").error("XML-Security exception loading client certificate: %s", e.getMsg());
207 gss_ctx_id_t RemotedRequest::getGSSContext() const
209 if (m_ctx == GSS_C_NO_CONTEXT) {
210 const char* encoded = m_input["gss_context"];
213 XMLByte* decoded=Base64::decode(reinterpret_cast<const XMLByte*>(encoded), &x);
215 gss_buffer_desc importbuf;
216 importbuf.length = x;
217 importbuf.data = decoded;
219 OM_uint32 major = gss_import_sec_context(&minor, &importbuf, &m_ctx);
220 if (major != GSS_S_COMPLETE)
221 m_ctx = GSS_C_NO_CONTEXT;
222 #ifdef SHIBSP_XERCESC_HAS_XMLBYTE_RELEASE
223 XMLString::release(&decoded);
225 XMLString::release((char**)&decoded);
234 long RemotedResponse::sendResponse(std::istream& in, long status)
240 msg.append(buf,in.gcount());
242 if (!m_output.isstruct())
243 m_output.structure();
244 m_output.addmember("response.data").string(msg.c_str());
245 m_output.addmember("response.status").integer(status);
249 void RemotedResponse::setResponseHeader(const char* name, const char* value)
251 if (!m_output.isstruct())
252 m_output.structure();
253 DDF hdrs = m_output["headers"];
255 hdrs = m_output.addmember("headers").list();
256 DDF h = DDF(name).string(value);
260 long RemotedResponse::sendRedirect(const char* url)
262 if (!m_output.isstruct())
263 m_output.structure();
264 m_output.addmember("redirect").unsafe_string(url);
265 return HTTPResponse::XMLTOOLING_HTTP_STATUS_MOVED;
270 void RemotedHandler::setAddress(const char* address)
272 if (!m_address.empty())
273 throw ConfigurationException("Cannot register a remoting address twice for the same Handler.");
275 SPConfig& conf = SPConfig::getConfig();
276 if (!conf.isEnabled(SPConfig::InProcess)) {
277 ListenerService* listener = conf.getServiceProvider()->getListenerService(false);
279 listener->regListener(m_address.c_str(),this);
281 Category::getInstance(SHIBSP_LOGCAT".Handler").info("no ListenerService available, handler remoting disabled");
285 RemotedHandler::RemotedHandler()
289 RemotedHandler::~RemotedHandler()
291 SPConfig& conf = SPConfig::getConfig();
292 ListenerService* listener=conf.getServiceProvider()->getListenerService(false);
293 if (listener && conf.isEnabled(SPConfig::OutOfProcess) && !conf.isEnabled(SPConfig::InProcess))
294 listener->unregListener(m_address.c_str(),this);
297 DDF RemotedHandler::wrap(const SPRequest& request, const vector<string>* headers, bool certs) const
299 DDF in = DDF(m_address.c_str()).structure();
300 in.addmember("application_id").string(request.getApplication().getId());
301 in.addmember("scheme").string(request.getScheme());
302 in.addmember("hostname").unsafe_string(request.getHostname());
303 in.addmember("port").integer(request.getPort());
304 in.addmember("content_type").string(request.getContentType().c_str());
305 in.addmember("content_length").integer(request.getContentLength());
306 in.addmember("body").string(request.getRequestBody());
307 in.addmember("remote_user").string(request.getRemoteUser().c_str());
308 in.addmember("client_addr").string(request.getRemoteAddr().c_str());
309 in.addmember("method").string(request.getMethod());
310 in.addmember("uri").unsafe_string(request.getRequestURI());
311 in.addmember("url").unsafe_string(request.getRequestURL());
312 in.addmember("query").string(request.getQueryString());
316 DDF hin = in.addmember("headers").structure();
317 for (vector<string>::const_iterator h = headers->begin(); h!=headers->end(); ++h) {
318 hdr = request.getHeader(h->c_str());
320 hin.addmember(h->c_str()).unsafe_string(hdr.c_str());
326 const vector<XSECCryptoX509*>& xvec = request.getClientCertificates();
328 DDF clist = in.addmember("certificates").list();
329 for (vector<XSECCryptoX509*>::const_iterator x = xvec.begin(); x!=xvec.end(); ++x) {
330 DDF x509 = DDF(nullptr).string((*x)->getDEREncodingSB().rawCharBuffer());
335 const vector<string>& xvec = request.getClientCertificates();
337 DDF clist = in.addmember("certificates").list();
338 for (vector<string>::const_iterator x = xvec.begin(); x!=xvec.end(); ++x) {
339 DDF x509 = DDF(nullptr).string(x->c_str());
347 const GSSRequest* gss = dynamic_cast<const GSSRequest*>(&request);
349 gss_ctx_id_t ctx = gss->getGSSContext();
350 if (ctx != GSS_C_NO_CONTEXT) {
352 gss_buffer_desc contextbuf;
353 contextbuf.length = 0;
354 contextbuf.value = nullptr;
355 OM_uint32 major = gss_export_sec_context(&minor, &ctx, &contextbuf);
356 if (major == GSS_S_COMPLETE) {
358 XMLByte* out=Base64::encode(reinterpret_cast<const XMLByte*>(contextbuf.value), contextbuf.length, &len);
361 ctx.append(reinterpret_cast<char*>(out), len);
362 #ifdef SHIBSP_XERCESC_HAS_XMLBYTE_RELEASE
363 XMLString::release(&out);
365 XMLString::release((char**)&out);
367 in.addmember("gss_context").string(ctx.c_str());
370 request.log(SPRequest::SPError, "error while base64-encoding GSS context");
374 request.log(SPRequest::SPError, "error while exporting GSS context");
383 pair<bool,long> RemotedHandler::unwrap(SPRequest& request, DDF& out) const
385 DDF h = out["headers"];
387 while (hdr.isstring()) {
388 #ifdef HAVE_STRCASECMP
389 if (!strcasecmp(hdr.name(), "Content-Type"))
391 if (!stricmp(hdr.name(), "Content-Type"))
393 request.setContentType(hdr.string());
395 request.setResponseHeader(hdr.name(), hdr.string());
400 return make_pair(true, request.sendRedirect(h.string()));
403 istringstream s(h["data"].string());
404 return make_pair(true, request.sendResponse(s, h["status"].integer()));
406 return make_pair(false,0L);
409 HTTPRequest* RemotedHandler::getRequest(DDF& in) const
412 return new RemotedRequest(in);
414 throw ConfigurationException("Cannot process message using lite version of shibsp library.");
418 HTTPResponse* RemotedHandler::getResponse(DDF& out) const
421 return new RemotedResponse(out);
423 throw ConfigurationException("Cannot process message using lite version of shibsp library.");