f59fe728391e6e6fce17c61782b89d2e28cd893e
[mod_auth_kerb.cvs/.git] / mod_auth_gssweb.c
1 /*
2  * Copyright (c) 2010 CESNET
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions are met:
7  *
8  * 1. Redistributions of source code must retain the above copyright notice,
9  *    this list of conditions and the following disclaimer.
10  *
11  * 2. Redistributions in binary form must reproduce the above copyright
12  *    notice, this list of conditions and the following disclaimer in the
13  *    documentation and/or other materials provided with the distribution.
14  *
15  * 3. Neither the name of CESNET nor the names of its contributors may
16  *    be used to endorse or promote products derived from this software
17  *    without specific prior written permission.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
20  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22  * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
23  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
24  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
25  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
26  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
27  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
28  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
29  * POSSIBILITY OF SUCH DAMAGE.
30  */
31
32 /* 
33  * NOTE: Portions of the code in this file were derived from example
34  * code distributed under the Apache 2.0 license:
35  *     http://www.apache.org/licenses/LICENSE-2.0
36  * The example code was modified for inclusion in this module.
37  * 
38  * This module implements the Apache server side of the GSSWeb
39  * authentiction type which allows Moonshot to be used for
40  * authentication in web applications.  The module consists of two
41  * components: the hook function (gssweb_authenticate_user) that does
42  * most of the work, and an output filter (gssweb_authenticate_filter)
43  * that is registered by the hook function to send the output token
44  * back to the client in a json message that wraps the original
45  * response content.
46  *
47  * This module uses a simple protocol between the client and server
48  * to exchange GSS tokens and nonce information.  The protocol is 
49  * described in the protocol.txt file included with module source.
50  */
51
52 #include "mod_auth_gssweb.h"
53
54 module AP_MODULE_DECLARE_DATA auth_gssweb_module;
55
56 #define command(name, func, var, type, usage)           \
57   AP_INIT_ ## type (name, (void*) func,                 \
58         (void*)APR_OFFSETOF(gss_auth_config, var),      \
59         OR_AUTHCFG | RSRC_CONF, usage)
60
61 static const command_rec gssweb_config_cmds[] = {
62     command("GSSServiceName", ap_set_string_slot, service_name,
63             TAKE1, "Service name used for Apache authentication."),
64
65     { NULL }
66 };
67   
68 #define DEFAULT_ENCTYPE         "application/x-www-form-urlencoded"
69 #define GSS_MAX_TOKEN_SIZE      4096    //TBD -- check this value
70
71 /* gssweb_read_post() -- Reads the post data associated with a
72  * request.
73  */
74 static int gssweb_read_post(request_rec *r, const char **rbuf)
75 {
76   int rc;
77   if ((rc = ap_setup_client_block(r, REQUEST_CHUNKED_ERROR)) != OK) {
78     return rc;
79   }
80   if (ap_should_client_block(r)) {
81     char argsbuffer[GSS_MAX_TOKEN_SIZE+256];
82     int rsize, len_read, rpos = 0;
83     long length = r->remaining;
84     *rbuf = ap_pcalloc(r->pool, length + 1);
85     ap_hard_timeout("util_read", r);
86     while ((len_read =
87             ap_get_client_block(r, argsbuffer, sizeof(argsbuffer))) > 0) { 
88       ap_reset_timeout(r);
89       if ((rpos + len_read) > length) {
90         rsize = length - rpos;
91       }
92       else {
93         rsize = len_read;
94       }
95       memcpy((char*)*rbuf + rpos, argsbuffer, rsize);
96       rpos += rsize;
97     }
98     ap_kill_timeout(r);
99   }
100   return rc;
101 }
102
103 /* gssweb_get_post_data() -- Gets the token and nonce from the request
104  * data.
105  */
106 static int gssweb_get_post_data(request_rec *r, int *nonce, gss_buffer_desc *input_token)
107 {
108   const char *data;
109   const char *key, *val, *type;
110   int rc = 0;
111
112   if(r->method_number != M_POST) {
113     return DECLINED;
114   }
115
116   type = ap_table_get(r->headers_in, "Content-Type");
117   if(strcasecmp(type, DEFAULT_ENCTYPE) != 0) {
118     return DECLINED;
119   }
120
121   if((rc = util_read(r, &data)) != OK) {
122     return rc;
123   }
124   if(*tab) {
125     ap_clear_table(*tab);
126   }
127   else {
128     *tab = ap_make_table(r->pool, 8);
129   }
130   while(*data && (val = ap_getword(r->pool, &data, '&'))) { 
131     key = ap_getword(r->pool, &val, '=');
132     ap_unescape_url((char*)key);
133     ap_unescape_url((char*)val);
134     ap_table_merge(*tab, key, val);
135   }
136   return OK;
137 }
138
139 /* gssweb_authenticate_filter() -- Output filter for gssweb authentication.
140  * Wraps original response in JSON -- adding JSON to the beginning of the 
141  * response, escapes double quotes in the original response, and adds JSON
142  * to the end of the response.  Handles responses that involve more than
143  * one filter call by maintaining state until an EOS bucket is received.
144  */
145 static apr_status_t gssweb_authenticate_filter (ap_filter_t *f,
146                                         apr_bucket_brigade *pbbIn)
147 {
148   request_rec *r = f->r;
149   conn_rec *c = r->connection;
150   apr_bucket *pbktIn;
151   apr_bucket_brigade *pbbOut;
152
153   pbbOut=apr_brigade_create(r->pool, c->bucket_alloc);
154   for (pbktIn = APR_BRIGADE_FIRST(pbbIn);
155        pbktIn != APR_BRIGADE_SENTINEL(pbbIn);
156        pbktIn = APR_BUCKET_NEXT(pbktIn))
157     {
158       const char *data;
159       apr_size_t len;
160       char *buf;
161       apr_size_t n;
162       apr_bucket *pbktOut;
163
164       if(APR_BUCKET_IS_EOS(pbktIn))
165         {
166           apr_bucket *pbktEOS=apr_bucket_eos_create(c->bucket_alloc);
167           APR_BRIGADE_INSERT_TAIL(pbbOut,pbktEOS);
168           continue;
169         }
170
171       /* read */
172       apr_bucket_read(pbktIn,&data,&len,APR_BLOCK_READ);
173
174       /* write */
175       buf = apr_bucket_alloc(len, c->bucket_alloc);
176       for(n=0 ; n < len ; ++n)
177         buf[n] = apr_toupper(data[n]);
178
179       pbktOut = apr_bucket_heap_create(buf, len, apr_bucket_free,
180                                        c->bucket_alloc);
181       APR_BRIGADE_INSERT_TAIL(pbbOut,pbktOut);
182     }
183
184   /* Q: is there any advantage to passing a brigade for each bucket? 
185    * A: obviously, it can cut down server resource consumption, if this
186    * experimental module was fed a file of 4MB, it would be using 8MB for
187    * the 'read' buckets and the 'write' buckets.
188    *
189    * Note it is more efficient to consume (destroy) each bucket as it's
190    * processed above than to do a single cleanup down here.  In any case,
191    * don't let our caller pass the same buckets to us, twice;
192    */
193   apr_brigade_cleanup(pbbIn);
194   return ap_pass_brigade(f->next,pbbOut);
195 }
196
197 /* gssweb_authenticate_user() -- Hook to perform actual user
198  * authentication.  Will be called once for each round trip in the GSS
199  * authentication loop.  Reads the tokend from the request, calls
200  * gss_accept_sec_context(), and stores the output token and context
201  * in the user data area. Registers output filter to send the GSS
202  * output token back to the client.
203  */
204 static int
205 gssweb_authenticate_user(request_rec *r) 
206 {
207   gss_auth_config *conf = 
208     (gss_auth_config *) ap_get_module_config(r->per_dir_config,
209                                                 &auth_gssweb_module);
210   const char *auth_line = NULL;
211   const char *type = NULL;
212   char *auth_type = NULL;
213   char *negotiate_ret_value = NULL;
214   gss_conn_ctx conn_ctx = NULL;
215   int ret;
216   OM_uint32 major_status, minor_status, minor_status2;
217   gss_buffer_desc input_token = GSS_C_EMPTY_BUFFER;
218   gss_buffer_desc output_token = GSS_C_EMPTY_BUFFER;
219   const char *posted_token = NULL;
220   gss_name_t client_name = GSS_C_NO_NAME;
221   gss_cred_id_t delegated_cred = GSS_C_NO_CREDENTIAL;
222   gss_cred_id_t server_creds = GSS_C_NO_CREDENTIAL;
223   OM_uint32 ret_flags = 0;
224   unsigned int nonce;
225
226   gss_log(APLOG_MARK, APLOG_DEBUG, 0, r, "Entering GSSWeb authentication");
227    
228   /* Check if this is for our auth type */
229   type = ap_auth_type(r);
230   if (type == NULL || strcasecmp(type, "GSSWeb") != 0) {
231         gss_log(APLOG_MARK, APLOG_DEBUG, 0, r,
232                 "AuthType '%s' is not GSSWeb, bailing out",
233                 (type) ? type : "(NULL)");
234
235         return DECLINED;
236   }
237
238   /* Set up a GSS context for this request, if there isn't one already */
239   conn_ctx = gss_get_conn_ctx(r);
240   if (conn_ctx == NULL) {
241     gss_log(APLOG_MARK, APLOG_ERR, 0, r, "Failed to create internal context: probably not enough memory");
242     return HTTP_INTERNAL_SERVER_ERROR;
243   }
244
245   /* Read the token and nonce from the POST */
246   if (0 != gssweb_get_post_data(r, &nonce, &input_token)) {
247     ret = HTTP_UNAUTHORIZED;
248     gss_log(APLOG_MARK, APLOG_ERR, 0, r, "Unable to read nonce or input token.");
249     goto end;
250   }
251   gss_log(APLOG_MARK, APLOG_DEBUG, 0, r, "GSSWeb nonce value = %u.", nonce);
252    
253   /* If the nonce is set and doesn't match, start over */
254   if ((0 != conn_ctx->nonce) && (conn_ctx->nonce != nonce)) {
255     if (GSS_C_NO_CONTEXT != conn_ctx->context) {
256       gss_delete_sec_context(&minor_status, &conn_ctx->context, GSS_C_NO_BUFFER);
257     }
258     conn_ctx->context = GSS_C_NO_CONTEXT;
259     conn_ctx->state = GSS_CTX_EMPTY;
260     conn_ctx->user = NULL;
261     if (0 != conn_ctx->output_token.length) {
262       gss_release_buffer(&minor_status, &conn_ctx->output_token);
263     }
264       conn_ctx->output_token = GSS_C_EMPTY_BUFFER;
265   }
266  
267   /* If the output filter reported an internal server error, return it */
268   if (GSS_CTX_ERROR == conn_ctx->state) {
269     ret = HTTP_INTERNAL_SERVER_ERROR;
270     gss_log(APLOG_MARK, APLOG_ERR, 0, r,
271             "Output filter returned internal server error, reporting.");
272     goto end;
273   }
274
275   /* If this is a new authentiction cycle, set-up the output filter. */
276   if (GSS_CTX_EMPTY == conn_ctx->state)
277  {
278    ap_add_output_filter("gssweb_auth_filter",conn_ctx->ctx,r,r->connection);
279    ap_register_output_filter("gssweb_auth_filter",gssweb_authenticate_filter,AP_FTYPE_RESOURCE);
280
281   }
282
283   /* Acquire server credentials */
284   ret = get_gss_creds(r, conf, &server_creds);
285   if (ret)
286     goto end;
287     
288   /* Decode input token */
289   input_token.length = apr_base64_decode(input_token.value, posted_token);
290   
291   /* Call gss_accept_sec_context */
292   major_status = gss_accept_sec_context(&minor_status,
293                                         &ctx->context,
294                                         server_creds,
295                                         &input_token,
296                                         GSS_C_NO_CHANNEL_BINDINGS,
297                                         NULL,
298                                         NULL,
299                                         &output_token,
300                                         &ret_flags,
301                                         NULL,
302                                         &delegated_cred);
303   gss_log(APLOG_MARK, APLOG_DEBUG, 0, r,
304           "Client %s us their credential",
305           (ret_flags & GSS_C_DELEG_FLAG) ? "delegated" : "didn't delegate");
306
307   if (GSS_ERROR(major_status)) {
308     gss_log(APLOG_MARK, APLOG_ERR, 0, r,
309             "%s", get_gss_error(r, major_status, minor_status,
310                                 "Failed to establish authentication"));
311     gss_delete_sec_context(&minor_status, &ctx->context, GSS_C_NO_BUFFER);
312     ctx->context = GSS_C_NO_CONTEXT;
313     ctx->state = GSS_CTX_EMPTY;
314     ret = HTTP_UNAUTHORIZED;
315     goto end;
316   }
317
318   /* Store the nonce & ouput token in the stored context */
319   conn_ctx->nonce = nonce;
320   conn_ctx->output_token = output_token;
321     
322   /* If we aren't done yet, go around again */
323   if (major_status & GSS_S_CONTINUE_NEEDED) {
324     ctx->state = GSS_CTX_IN_PROGRESS;
325     ret = HTTP_UNAUTHORIZED;
326     goto end;
327   }
328
329   ctx->state = GSS_CTX_ESTABLISHED;
330   // TBD -- set the user and authtype in the request structure
331   ret = OK;
332
333  end:
334   if (delegated_cred)
335     gss_release_cred(&minor_status, &delegated_cred);
336   
337   if (output_token.length) 
338     gss_release_buffer(&minor_status, &output_token);
339     
340   if (client_name != GSS_C_NO_NAME)
341     gss_release_name(&minor_status, &client_name);
342
343   if (server_creds != GSS_C_NO_CREDENTIAL)
344     gss_release_cred(&minor_status, &server_creds);
345
346   return ret;
347 }
348
349 static void
350 gssweb_register_hooks(apr_pool_t *p)
351 {
352     ap_hook_check_user_id(gssweb_authenticate_user, NULL, NULL, APR_HOOK_MIDDLE);
353 }
354
355 module AP_MODULE_DECLARE_DATA auth_gssweb_module = {
356     STANDARD20_MODULE_STUFF,
357     gss_config_dir_create,
358     NULL,
359     NULL,
360     NULL,
361     gssweb_config_cmds,
362     gssweb_register_hooks
363 };