Support for GSS-API contexts attached to requests.
[shibboleth/sp.git] / shibsp / handler / impl / RemotedHandler.cpp
1 /*
2  *  Copyright 2001-2010 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  * RemotedHandler.cpp
19  * 
20  * Base class for handlers that need SP request/response layer to be remoted. 
21  */
22
23 #include "internal.h"
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"
30
31 #include <algorithm>
32 #include <xmltooling/unicode.h>
33 #include <xercesc/util/Base64.hpp>
34
35 #ifndef SHIBSP_LITE
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>
41 #endif
42
43 using namespace shibsp;
44 using namespace opensaml;
45 using namespace xmltooling;
46 using namespace xercesc;
47 using namespace std;
48
49 #ifndef SHIBSP_LITE
50 namespace shibsp {
51     class SHIBSP_DLLLOCAL RemotedRequest : 
52 #ifdef HAVE_GSSAPI
53         public virtual GSSRequest,
54 #endif
55         public virtual HTTPRequest
56     {
57         DDF& m_input;
58         mutable CGIParser* m_parser;
59         mutable vector<XSECCryptoX509*> m_certs;
60 #ifdef HAVE_GSSAPI
61         mutable gss_ctx_id_t m_gss;
62 #endif
63     public:
64         RemotedRequest(DDF& input) : m_input(input), m_parser(nullptr)
65 #ifdef HAVE_GSSAPI
66             , m_ctx(GSS_C_NO_CONTEXT)
67 #endif
68         {
69         }
70
71         virtual ~RemotedRequest() {
72             for_each(m_certs.begin(), m_certs.end(), xmltooling::cleanup<XSECCryptoX509>());
73             delete m_parser;
74 #ifdef HAVE_GSSAPI
75             if (m_ctx != GSS_C_NO_CONTEXT) {
76                 OM_uint32 minor;
77                 gss_delete_sec_context(&minor, &m_ctx, GSS_C_NO_BUFFER);
78             }
79 #endif
80         }
81
82         // GenericRequest
83         const char* getScheme() const {
84             return m_input["scheme"].string();
85         }
86         const char* getHostname() const {
87             return m_input["hostname"].string();
88         }
89         int getPort() const {
90             return m_input["port"].integer();
91         }
92         std::string getContentType() const {
93             DDF s = m_input["content_type"];
94             return s.string() ? s.string() : "";
95         }
96         long getContentLength() const {
97             return m_input["content_length"].integer();
98         }
99         const char* getRequestBody() const {
100             return m_input["body"].string();
101         }
102
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;
105         
106         std::string getRemoteUser() const {
107             DDF s = m_input["remote_user"];
108             return s.string() ? s.string() : "";
109         }
110         std::string getRemoteAddr() const {
111             DDF s = m_input["client_addr"];
112             return s.string() ? s.string() : "";
113         }
114
115         const std::vector<XSECCryptoX509*>& getClientCertificates() const;
116         
117 #ifdef HAVE_GSSAPI
118         // GSSRequest
119         gss_ctx_id_t getGSSContext() const;
120 #endif
121
122         // HTTPRequest
123         const char* getMethod() const {
124             return m_input["method"].string();
125         }
126         const char* getRequestURI() const {
127             return m_input["uri"].string();
128         }
129         const char* getRequestURL() const {
130             return m_input["url"].string();
131         }
132         const char* getQueryString() const {
133             return m_input["query"].string();
134         }
135         std::string getHeader(const char* name) const {
136             DDF s = m_input["headers"][name];
137             return s.string() ? s.string() : "";
138         }
139     };
140
141     class SHIBSP_DLLLOCAL RemotedResponse : public virtual HTTPResponse 
142     {
143         DDF& m_output;
144     public:
145         RemotedResponse(DDF& output) : m_output(output) {}
146         virtual ~RemotedResponse() {}
147        
148         // GenericResponse
149         long sendResponse(std::istream& inputStream, long status);
150         
151         // HTTPResponse
152         void setResponseHeader(const char* name, const char* value);
153         long sendRedirect(const char* url);
154     };
155 }
156
157 const char* RemotedRequest::getParameter(const char* name) const
158 {
159     if (!m_parser)
160         m_parser=new CGIParser(*this);
161     
162     pair<CGIParser::walker,CGIParser::walker> bounds=m_parser->getParameters(name);
163     return (bounds.first==bounds.second) ? nullptr : bounds.first->second;
164 }
165
166 std::vector<const char*>::size_type RemotedRequest::getParameters(const char* name, std::vector<const char*>& values) const
167 {
168     if (!m_parser)
169         m_parser=new CGIParser(*this);
170
171     pair<CGIParser::walker,CGIParser::walker> bounds=m_parser->getParameters(name);
172     while (bounds.first!=bounds.second) {
173         values.push_back(bounds.first->second);
174         ++bounds.first;
175     }
176     return values.size();
177 }
178
179 const std::vector<XSECCryptoX509*>& RemotedRequest::getClientCertificates() const
180 {
181     if (m_certs.empty()) {
182         DDF certs = m_input["certificates"];
183         DDF cert = certs.first();
184         while (cert.string()) {
185             try {
186                 auto_ptr<XSECCryptoX509> x509(XSECPlatformUtils::g_cryptoProvider->X509());
187                 if (strstr(cert.string(), "BEGIN"))
188                     x509->loadX509PEM(cert.string(), cert.strlen());
189                 else
190                     x509->loadX509Base64Bin(cert.string(), cert.strlen());
191                 m_certs.push_back(x509.release());
192             }
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());
196             }
197             catch(XSECCryptoException& e) {
198                 Category::getInstance(SHIBSP_LOGCAT".SPRequest").error("XML-Security exception loading client certificate: %s", e.getMsg());
199             }
200             cert = certs.next();
201         }
202     }
203     return m_certs;
204 }
205
206 #ifdef HAVE_GSSAPI
207 gss_ctx_id_t RemotedRequest::getGSSContext() const
208 {
209     if (m_ctx == GSS_C_NO_CONTEXT) {
210         const char* encoded = m_input["gss_context"];
211         if (encoded) {
212             xsecsize_t x;
213             XMLByte* decoded=Base64::decode(reinterpret_cast<const XMLByte*>(encoded), &x);
214             if (decoded) {
215                 gss_buffer_desc importbuf;
216                 importbuf.length = x;
217                 importbuf.data = decoded;
218                 OM_uint32 minor;
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);
224 #else
225                 XMLString::release((char**)&decoded);
226 #endif
227             }
228         }
229     }
230     return m_ctx;
231 }
232 #endif
233
234 long RemotedResponse::sendResponse(std::istream& in, long status)
235 {
236     string msg;
237     char buf[1024];
238     while (in) {
239         in.read(buf,1024);
240         msg.append(buf,in.gcount());
241     }
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);
246     return status;
247 }
248
249 void RemotedResponse::setResponseHeader(const char* name, const char* value)
250 {
251     if (!m_output.isstruct())
252         m_output.structure();
253     DDF hdrs = m_output["headers"];
254     if (hdrs.isnull())
255         hdrs = m_output.addmember("headers").list();
256     DDF h = DDF(name).string(value);
257     hdrs.add(h);
258 }
259
260 long RemotedResponse::sendRedirect(const char* url)
261 {
262     if (!m_output.isstruct())
263         m_output.structure();
264     m_output.addmember("redirect").unsafe_string(url);
265     return HTTPResponse::XMLTOOLING_HTTP_STATUS_MOVED;
266 }
267
268 #endif
269
270 void RemotedHandler::setAddress(const char* address)
271 {
272     if (!m_address.empty())
273         throw ConfigurationException("Cannot register a remoting address twice for the same Handler.");
274     m_address = address;
275     SPConfig& conf = SPConfig::getConfig();
276     if (!conf.isEnabled(SPConfig::InProcess)) {
277         ListenerService* listener = conf.getServiceProvider()->getListenerService(false);
278         if (listener)
279             listener->regListener(m_address.c_str(),this);
280         else
281             Category::getInstance(SHIBSP_LOGCAT".Handler").info("no ListenerService available, handler remoting disabled");
282     }
283 }
284
285 RemotedHandler::RemotedHandler()
286 {
287 }
288
289 RemotedHandler::~RemotedHandler()
290 {
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);
295 }
296
297 DDF RemotedHandler::wrap(const SPRequest& request, const vector<string>* headers, bool certs) const
298 {
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());
313
314     if (headers) {
315         string hdr;
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());
319             if (!hdr.empty())
320                 hin.addmember(h->c_str()).unsafe_string(hdr.c_str());
321         }
322     }
323
324     if (certs) {
325 #ifndef SHIBSP_LITE
326         const vector<XSECCryptoX509*>& xvec = request.getClientCertificates();
327         if (!xvec.empty()) {
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());
331                 clist.add(x509);
332             }
333         }
334 #else
335         const vector<string>& xvec = request.getClientCertificates();
336         if (!xvec.empty()) {
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());
340                 clist.add(x509);
341             }
342         }
343 #endif
344     }
345
346 #ifdef HAVE_GSSAPI
347     const GSSRequest* gss = dynamic_cast<const GSSRequest*>(&request);
348     if (gss) {
349         gss_ctx_id_t ctx = gss->getGSSContext();
350         if (ctx != GSS_C_NO_CONTEXT) {
351             OM_uint32 minor;
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) {
357                 xsecsize_t len=0;
358                 XMLByte* out=Base64::encode(reinterpret_cast<const XMLByte*>(contextbuf.value), contextbuf.length, &len);
359                 if (out) {
360                     string ctx;
361                     ctx.append(reinterpret_cast<char*>(out), len);
362 #ifdef SHIBSP_XERCESC_HAS_XMLBYTE_RELEASE
363                     XMLString::release(&out);
364 #else
365                     XMLString::release((char**)&out);
366 #endif
367                     in.addmember("gss_context").string(ctx.c_str());
368                 }
369                 else {
370                     request.log(SPRequest::SPError, "error while base64-encoding GSS context");
371                 }
372             }
373             else {
374                 request.log(SPRequest::SPError, "error while exporting GSS context");
375             }
376         }
377     }
378 #endif
379
380     return in;
381 }
382
383 pair<bool,long> RemotedHandler::unwrap(SPRequest& request, DDF& out) const
384 {
385     DDF h = out["headers"];
386     DDF hdr = h.first();
387     while (hdr.isstring()) {
388 #ifdef HAVE_STRCASECMP
389         if (!strcasecmp(hdr.name(), "Content-Type"))
390 #else
391         if (!stricmp(hdr.name(), "Content-Type"))
392 #endif
393             request.setContentType(hdr.string());
394         else
395             request.setResponseHeader(hdr.name(), hdr.string());
396         hdr = h.next();
397     }
398     h = out["redirect"];
399     if (h.isstring())
400         return make_pair(true, request.sendRedirect(h.string()));
401     h = out["response"];
402     if (h.isstruct()) {
403         istringstream s(h["data"].string());
404         return make_pair(true, request.sendResponse(s, h["status"].integer()));
405     }
406     return make_pair(false,0L);
407 }
408
409 HTTPRequest* RemotedHandler::getRequest(DDF& in) const
410 {
411 #ifndef SHIBSP_LITE
412     return new RemotedRequest(in);
413 #else
414     throw ConfigurationException("Cannot process message using lite version of shibsp library.");
415 #endif
416 }
417
418 HTTPResponse* RemotedHandler::getResponse(DDF& out) const
419 {
420 #ifndef SHIBSP_LITE
421     return new RemotedResponse(out);
422 #else
423     throw ConfigurationException("Cannot process message using lite version of shibsp library.");
424 #endif
425 }