2 * Copyright (c) 2012, 2013, 2014 JANET(UK)
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
9 * 1. Redistributions of source code must retain the above copyright
10 * notice, this list of conditions and the following disclaimer.
12 * 2. Redistributions in binary form must reproduce the above copyright
13 * notice, this list of conditions and the following disclaimer in the
14 * documentation and/or other materials provided with the distribution.
16 * 3. Neither the name of JANET(UK) nor the names of its contributors
17 * may be used to endorse or promote products derived from this software
18 * without specific prior written permission.
20 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
21 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
22 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
23 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
24 * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
25 * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
26 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
27 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
29 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
30 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
31 * OF THE POSSIBILITY OF SUCH DAMAGE.
33 * NOTE: Some code in this module was derived from code in
34 * mod_auth_gssapi.c which is copyrighted by CESNET. See that file
35 * for full copyright details.
37 * NOTE: Portions of the code in this file were derived from example
38 * code distributed under the Apache 2.0 license:
39 * http://www.apache.org/licenses/LICENSE-2.0
41 * This module implements the Apache server side of the GSSWeb
42 * authentiction type which allows Moonshot to be used for
43 * authentication in web applications. The module consists of two
44 * components: the hook function (gssweb_authenticate_user) that does
45 * most of the work, and an output filter (gssweb_authenticate_filter)
46 * that is registered by the hook function to send the output token
47 * back to the client in a json message that wraps the original
50 * This module uses a simple protocol between the client and server
51 * to exchange GSS tokens and nonce information. The protocol is
52 * described in the protocol.txt file included with module source.
56 #include "mod_auth_gssweb.h"
58 module AP_MODULE_DECLARE_DATA auth_gssweb_module;
60 #define command(name, func, var, type, usage) \
61 AP_INIT_ ## type (name, (void*) func, \
62 (void*)APR_OFFSETOF(gss_auth_config, var), \
63 OR_AUTHCFG | RSRC_CONF, usage)
65 static const command_rec gssweb_config_cmds[] = {
66 command("GSSServiceName", ap_set_string_slot, service_name,
67 TAKE1, "Service name used for Apache authentication."),
72 #define DEFAULT_ENCTYPE "application/x-www-form-urlencoded"
73 #define GSS_MAX_TOKEN_SIZE 4096 //TBD -- check this value
75 /* gssweb_read_req() -- reads the request data into a buffer
77 static int gssweb_read_req(request_rec *r, const char **rbuf, apr_off_t *size)
81 if((rc = ap_setup_client_block(r, REQUEST_CHUNKED_ERROR))) {
82 gss_log(APLOG_MARK, APLOG_ERR, 0, r, "gssweb_get_post_data: Failed to set up client block");
86 if(ap_should_client_block(r)) {
87 char argsbuffer[HUGE_STRING_LEN];
88 apr_off_t rsize, len_read, rpos = 0;
89 apr_off_t length = r->remaining;
91 *rbuf = (const char *) apr_pcalloc(r->pool, (apr_size_t) (length + 1));
93 while((len_read = ap_get_client_block(r, argsbuffer, sizeof(argsbuffer))) > 0) {
94 if((rpos + len_read) > length) {
95 rsize = length - rpos;
101 memcpy((char *) *rbuf + rpos, argsbuffer, (size_t) rsize);
108 /* gssweb_get_post_data() -- Gets the token and nonce from the request
111 static int gssweb_get_post_data(request_rec *r, unsigned int *nonce, gss_buffer_desc *input_token)
115 const char *key, *val, *type;
120 input_token->length = 0;
121 input_token->value = NULL;
123 gss_log(APLOG_MARK, APLOG_DEBUG, 0, r, "gssweb_get_post_data: Entering function");
125 if(r->method_number != M_POST) {
126 gss_log(APLOG_MARK, APLOG_ERR, 0, r, "gssweb_get_post_data: Request data is not a POST, declining.");
130 type = apr_table_get(r->headers_in, "Content-Type");
131 if(strncasecmp(type, DEFAULT_ENCTYPE, strlen(DEFAULT_ENCTYPE)) != 0) {
132 gss_log(APLOG_MARK, APLOG_ERR, 0, r, "gssweb_get_post_data: Unexpected content type, declining.");
136 if((rc = gssweb_read_req(r, &data, &datalen)) != OK) {
137 gss_log(APLOG_MARK, APLOG_ERR, 0, r, "gssweb_get_post_data: Data read error, rc = %d", rc);
141 while(*data && (val = ap_getword(r->pool, &data, '&'))) {
142 key = ap_getword(r->pool, &val, '=');
143 ap_unescape_url((char*)key);
144 ap_unescape_url((char*)val);
145 if (0 == strcasecmp(key, "token")) {
146 gss_log(APLOG_MARK, APLOG_DEBUG, 0, r, "gssweb_get_post_data: Found encoded token: %s", val);
147 len = apr_base64_decode_len(val);
148 if (NULL == (input_token->value = apr_pcalloc(r->pool, len+1))) {
150 input_token->length = apr_base64_decode(input_token->value, val);
152 else if (0 == strcasecmp(key, "nonce")) {
153 gss_log(APLOG_MARK, APLOG_DEBUG, 0, r, "gssweb_get_post_data: Found nonce: %s", val);
157 gss_log(APLOG_MARK, APLOG_ERR, 0, r, "gssweb_get_post_data: unknown key (%s), ignored", key);
160 if ((0 == *nonce) || (0 == input_token->length)) {
161 gss_log(APLOG_MARK, APLOG_ERR, 0, r, "gssweb_get_post_data: nonce (%d) or token len (%d) is 0, declining", *nonce, input_token->length);
165 gss_log(APLOG_MARK, APLOG_DEBUG, 0, r, "gssweb_get_post_data: returning nonce (%d) and token (%d bytes)", *nonce, input_token->length);
170 /* gssweb_authenticate_filter() -- Output filter for gssweb authentication.
171 * Wraps original response in JSON -- adding JSON to the beginning of the
172 * response, escapes double quotes in the original response, and adds JSON
173 * to the end of the response. Handles responses that involve more than
174 * one filter call by maintaining state until an EOS bucket is received.
176 static apr_status_t gssweb_authenticate_filter (ap_filter_t *f,
177 apr_bucket_brigade *brig_in)
179 request_rec *r = f->r;
180 conn_rec *c = r->connection;
181 apr_bucket_brigade *brig_out;
182 apr_bucket *bkt_in = NULL;
183 apr_bucket *bkt_out = NULL;
184 apr_bucket *bkt_eos = NULL;
185 const char *data = NULL;
187 apr_size_t enc_len = 0;
191 gss_conn_ctx conn_ctx = NULL;
192 const char *c_type = NULL;
193 const char *c_len = NULL;
194 apr_status_t ret = 0;
196 gss_log(APLOG_MARK, APLOG_DEBUG, 0, f->r, "Entering GSSWeb filter");
198 /* Get the context from the request. If the context is NULL or
199 * there is no outstanding request (no nonce set), just forward
200 * all of the buckets as-is, because the client isn't gssweb
202 if ((NULL == (conn_ctx = gss_retrieve_conn_ctx(r))) ||
203 (0 == conn_ctx->nonce)) {
204 for (bkt_in = APR_BRIGADE_FIRST(brig_in);
205 bkt_in != APR_BRIGADE_SENTINEL(brig_in);
206 bkt_in = APR_BUCKET_NEXT(bkt_in))
208 if (NULL == (brig_out = apr_brigade_create(r->pool, c->bucket_alloc))) {
209 apr_brigade_cleanup(brig_in);
210 return HTTP_INTERNAL_SERVER_ERROR;
212 apr_bucket_copy(bkt_in, &bkt_out);
213 APR_BRIGADE_INSERT_TAIL(brig_out, bkt_out);
214 ap_pass_brigade(f->next, brig_out);
216 gss_log(APLOG_MARK, APLOG_ERR, 0, r, "gssweb_authenticate_filter: Failed to find valid context");
217 apr_brigade_cleanup(brig_in);
221 c_type = apr_table_get(r->headers_in, "Content-Type");
222 c_len = apr_table_get(r->headers_in, "Content-Length");
223 /* clear content-length and MD5 checksum */
224 apr_table_unset(r->headers_out, "Content-Length");
225 apr_table_unset(r->headers_out, "Content-MD5");
226 gss_log(APLOG_MARK, APLOG_DEBUG, 0, r, "gssweb_authenticate_filter: Received Content-Type: %s, Content-Length: %d", c_type, c_len);
228 /* If this is the first call for a response, send opening JSON block */
229 if (GSS_FILT_NEW == conn_ctx->filter_stat) {
230 gss_log(APLOG_MARK, APLOG_DEBUG, 0, r, "gssweb_authenticate_filter: First filter call for response");
231 if (NULL == (brig_out = apr_brigade_create(r->pool, c->bucket_alloc))) {
232 conn_ctx->filter_stat = GSS_FILT_ERROR;
233 gss_log(APLOG_MARK, APLOG_ERR, 0, r, "gssweb_authenticate_filter: Unable to allocate output brigade (opening)");
234 apr_brigade_cleanup(brig_in);
235 return HTTP_INTERNAL_SERVER_ERROR;
238 /* Encode the output token */
239 len = apr_base64_encode_len(conn_ctx->output_token.length);
240 if (NULL == (stoken = apr_bucket_alloc(len+1, c->bucket_alloc))) {
241 gss_log(APLOG_MARK, APLOG_ERR, 0, r, "gssweb_authenticate_filter: Unable to allocate space for encoded output token");
242 apr_brigade_cleanup(brig_in);
243 apr_brigade_cleanup(brig_out);
244 return HTTP_INTERNAL_SERVER_ERROR;
246 apr_base64_encode_binary(stoken, conn_ctx->output_token.value, conn_ctx->output_token.length);
248 if (NULL == (data = apr_bucket_alloc(len+1024, c->bucket_alloc))) {
249 gss_log(APLOG_MARK, APLOG_ERR, 0, r, "gssweb_authenticate_filter: Unable to allocate space for opening JSON block");
250 apr_brigade_cleanup(brig_in);
251 apr_brigade_cleanup(brig_out);
252 return HTTP_INTERNAL_SERVER_ERROR;
255 /* Send opening JSON block */
256 snprintf((char *)data, len+1024,
257 "{\"gssweb\": {\n\"token\": \"%s\",\n\"nonce\": \"%d\"},\n\"application\": {\n\"data\": \"",
258 stoken, conn_ctx->nonce);
259 gss_log(APLOG_MARK, APLOG_DEBUG, 0, r, "gssweb_authenticate_filter: Sending (%d bytes): %s", strlen(data), data);
261 bkt_out = apr_bucket_heap_create(data, strlen(data), apr_bucket_free,
263 APR_BRIGADE_INSERT_TAIL(brig_out, bkt_out);
264 if (0 != (ret = ap_pass_brigade(f->next, brig_out))) {
265 apr_brigade_cleanup(brig_in);
266 apr_brigade_cleanup(brig_out);
270 conn_ctx->filter_stat = GSS_FILT_INPROGRESS;
273 /* Loop through the app data buckets, escaping and sending each one */
274 for (bkt_in = APR_BRIGADE_FIRST(brig_in);
275 bkt_in != APR_BRIGADE_SENTINEL(brig_in);
276 bkt_in = APR_BUCKET_NEXT(bkt_in))
278 if (NULL == (brig_out = apr_brigade_create(r->pool, c->bucket_alloc))) {
279 gss_log(APLOG_MARK, APLOG_ERR, 0, r, "gssweb_authenticate_filter: Unable to allocate brigade (loop)");
280 conn_ctx->filter_stat = GSS_FILT_ERROR;
281 apr_brigade_cleanup(brig_in);
282 return HTTP_INTERNAL_SERVER_ERROR;
285 /* if this is an EOS, send the JSON closing block */
286 if(APR_BUCKET_IS_EOS(bkt_in))
288 /* create and add the JSON closing block */
290 if (NULL == (data = apr_bucket_alloc(1024, c->bucket_alloc))) {
291 gss_log(APLOG_MARK, APLOG_ERR, 0, r, "gssweb_authenticate_filter: Unable to allocate space for closing JSON block");
292 apr_brigade_cleanup(brig_in);
293 apr_brigade_cleanup(brig_out);
294 return HTTP_INTERNAL_SERVER_ERROR;
297 snprintf((char *)data, 1024, "\",\n\"content-type\": \"%s\",\n\"content-length\": \"%s\"\n}\n}", c_type, c_len);
298 gss_log(APLOG_MARK, APLOG_DEBUG, 0, r, "gssweb_authenticate_filter: Sending (%d bytes) %s", strlen(data), data);
300 bkt_out = apr_bucket_heap_create(data, strlen(data), apr_bucket_free,
302 APR_BRIGADE_INSERT_TAIL(brig_out, bkt_out);
304 /* Indicate that the next filter call is a new response */
305 conn_ctx->filter_stat = GSS_FILT_NEW;
307 /* set EOS in the outbound brigade */
308 bkt_eos = apr_bucket_eos_create(c->bucket_alloc);
309 APR_BRIGADE_INSERT_TAIL (brig_out, bkt_eos);
311 /* set application type to 'application/json' */
312 apr_table_set(r->headers_out, "Content-Type", "application/json");
314 /* clear content-length and MD5 checksum */
315 apr_table_unset(r->headers_out, "Content-Length");
316 apr_table_unset(r->headers_out, "Content-MD5");
318 /* pass the brigade */
319 gss_log(APLOG_MARK, APLOG_DEBUG, 0, r, "gssweb_authenticate_filter: Sending: EOS");
320 if (0 != (ret = ap_pass_brigade(f->next, brig_out))) {
321 conn_ctx->filter_stat = GSS_FILT_ERROR;
322 apr_brigade_cleanup(brig_in);
323 apr_brigade_cleanup(brig_out);
329 /* Read application data from each input bucket */
330 apr_bucket_read(bkt_in, &data, &len, APR_BLOCK_READ);
332 /* Base64 encode the data (if any) */
334 enc_len = apr_base64_encode_len(len);
335 if (NULL == (buf = apr_bucket_alloc(enc_len, c->bucket_alloc))) {
336 gss_log(APLOG_MARK, APLOG_ERR, 0, r, "gssweb_authenticate_filter: Unable to allocate space for encoded application data");
337 apr_brigade_cleanup(brig_in);
338 apr_brigade_cleanup(brig_out);
339 return HTTP_INTERNAL_SERVER_ERROR;
341 enc_len = apr_base64_encode_binary(buf, data, len);
343 /* Put the data in a bucket and add it to the the output brigade */
344 bkt_out = apr_bucket_heap_create(buf, enc_len-1, apr_bucket_free, c->bucket_alloc);
346 gss_log(APLOG_MARK, APLOG_DEBUG, 0, r, "gssweb_authenticate_filter: Sending (%d bytes)", enc_len);
347 APR_BRIGADE_INSERT_TAIL(brig_out, bkt_out);
349 /* Send the output brigade */
350 if (OK != (ret = ap_pass_brigade(f->next, brig_out))) {
351 apr_brigade_cleanup(brig_in);
352 apr_brigade_cleanup(brig_out);
358 /* Make sure we don't see the same data again */
359 apr_brigade_cleanup(brig_in);
363 /* gssweb_add_filter() -- Hook to add our output filter to the request
364 * (r). Called for all error responses through the
365 * gssweb_insert_error_filter hook.
368 gssweb_add_filter(request_rec *r)
370 gss_conn_ctx conn_ctx = NULL;
372 /* Get the context for this request, if any */
373 conn_ctx = gss_retrieve_conn_ctx(r);
375 /* Add the output filter */
376 ap_add_output_filter("gssweb_auth_filter", (void *)conn_ctx, r, r->connection);
380 /* gssweb_authenticate_user() -- Hook to perform actual user
381 * authentication. Will be called once for each round trip in the GSS
382 * authentication loop. Reads the tokend from the request, calls
383 * gss_accept_sec_context(), and stores the output token and context
384 * in the user data areas. Adds output filter to send the GSS
385 * output token back to the client.
388 gssweb_authenticate_user(request_rec *r)
390 const char *auth_line = NULL;
391 char *auth_type = NULL;
392 char *negotiate_ret_value = NULL;
393 gss_conn_ctx conn_ctx = NULL;
395 OM_uint32 major_status, minor_status, minor_status2;
396 gss_buffer_desc input_token = GSS_C_EMPTY_BUFFER;
397 gss_buffer_desc output_token = GSS_C_EMPTY_BUFFER;
398 gss_name_t client_name = GSS_C_NO_NAME;
399 gss_cred_id_t delegated_cred = GSS_C_NO_CREDENTIAL;
400 OM_uint32 ret_flags = 0;
402 int release_output_token = 1;
403 gss_auth_config *conf = NULL;
405 gss_log(APLOG_MARK, APLOG_DEBUG, 0, r, "Entering GSSWeb authentication");
407 /* Get the module configuration */
408 conf = (gss_auth_config *) ap_get_module_config(r->per_dir_config,
409 &auth_gssweb_module);
411 /* Check if this is for our auth type */
412 auth_type = (char *)ap_auth_type(r);
413 if (auth_type == NULL || strcasecmp(auth_type, "GSSWeb") != 0) {
414 gss_log(APLOG_MARK, APLOG_DEBUG, 0, r,
415 "gssweb_authenticate_user: AuthType '%s' is not GSSWeb, bailing out",
416 (auth_type) ? auth_type : "(NULL)");
421 /* Retrieve the existing context (if any), or create one */
422 if ((NULL == (conn_ctx = gss_retrieve_conn_ctx(r))) &&
423 (NULL == (conn_ctx = gss_create_conn_ctx(r, conf)))) {
424 gss_log(APLOG_MARK, APLOG_ERR, 0, r, "gssweb_authenticate_user: Unable to find or create context");
427 /* Read the token and nonce from the POST */
428 if (0 != gssweb_get_post_data(r, &nonce, &input_token)) {
429 /* If we get spurious msg on an established session, say OK again */
430 if (GSS_CTX_ESTABLISHED == conn_ctx->state)
432 /* ...otherwise, if we are in progress, return HTTP_UNAUTHORIZED */
433 if (GSS_CTX_IN_PROGRESS == conn_ctx->state)
434 ret = HTTP_UNAUTHORIZED;
435 /* If this would start a new session, free the context and return DECLINED */
437 gss_cleanup_conn_ctx(conn_ctx);
442 gss_log(APLOG_MARK, APLOG_DEBUG, 0, r, "gssweb_authenticate_user: GSSWeb nonce value = %u.", nonce);
444 /* If the nonce does not match, release old context and create new */
445 if ((0 != conn_ctx->nonce) && (conn_ctx->nonce != nonce)) {
446 gss_log(APLOG_MARK, APLOG_DEBUG, 0, r,
447 "gssweb_authenticate_user: Nonce in context (%d) does not match nonce in input (%d), new request", conn_ctx->nonce, nonce);
448 gss_cleanup_conn_ctx(conn_ctx);
449 if (NULL == (conn_ctx = gss_create_conn_ctx (r, conf))) {
450 gss_log(APLOG_MARK, APLOG_ERR, 0, r, "gssweb_authenticate_user: Failed to create GSS context");
451 ret = HTTP_INTERNAL_SERVER_ERROR;
456 /* If the output filter reported an internal server error, return it */
457 if (GSS_FILT_ERROR == conn_ctx->filter_stat) {
458 gss_log(APLOG_MARK, APLOG_ERR, 0, r,
459 "gssweb_authenticate_user: Output filter returned error, reporting.");
460 ret = HTTP_INTERNAL_SERVER_ERROR;
464 /* Add the output filter to this request (for non-error returns) */
465 ap_add_output_filter("gssweb_auth_filter", (void *)conn_ctx, r, r->connection);
467 /* Call gss_accept_sec_context */
468 major_status = gss_accept_sec_context(&minor_status,
470 conn_ctx->server_creds,
472 GSS_C_NO_CHANNEL_BINDINGS,
479 gss_log(APLOG_MARK, APLOG_DEBUG, 0, r,
480 "gssweb_authenticate_user: Client %s us their credential",
481 (ret_flags & GSS_C_DELEG_FLAG) ? "delegated" : "didn't delegate");
483 if (GSS_ERROR(major_status)) {
484 gss_log(APLOG_MARK, APLOG_ERR, 0, r,
485 "%s", get_gss_error(r, major_status, minor_status,
486 "gssweb_authenticate_user: Failed to establish authentication"));
487 conn_ctx->state = GSS_CTX_FAILED;
491 /* If there was no token returned, clear token from context and exit */
492 if (0 == output_token.length) {
493 gss_log(APLOG_MARK, APLOG_ERR, 0, r, "gssweb_authenticate_user: No output token");
494 gss_delete_sec_context(&minor_status, &conn_ctx->context, GSS_C_NO_BUFFER);
495 conn_ctx->context = GSS_C_NO_CONTEXT;
496 conn_ctx->state = GSS_CTX_FAILED;
497 if (0 != conn_ctx->output_token.length)
498 gss_release_buffer(&minor_status, &(conn_ctx->output_token));
499 conn_ctx->output_token.length = 0;
500 ret = HTTP_UNAUTHORIZED;
504 /* Store the nonce & ouput token in the stored context */
505 conn_ctx->nonce = nonce;
506 conn_ctx->output_token = output_token;
507 release_output_token = 0;
509 /* If we aren't done yet, go around again */
510 if (major_status & GSS_S_CONTINUE_NEEDED) {
511 gss_log(APLOG_MARK, APLOG_DEBUG, 0, r, "gssweb_authenticate_user: Accept sec context complete, continue needed");
512 conn_ctx->state = GSS_CTX_IN_PROGRESS;
513 ret = HTTP_UNAUTHORIZED;
517 gss_log(APLOG_MARK, APLOG_DEBUG, 0, r, "gssweb_authenticate_user: Authentication succeeded!!");
518 conn_ctx->state = GSS_CTX_ESTABLISHED;
519 r->user = apr_pstrdup(r->pool, conn_ctx->user);
520 r->ap_auth_type = "GSSWeb";
525 gss_release_cred(&minor_status, &delegated_cred);
527 if ((release_output_token) && (output_token.length))
528 gss_release_buffer(&minor_status, &output_token);
530 if (client_name != GSS_C_NO_NAME)
531 gss_release_name(&minor_status, &client_name);
537 gssweb_register_hooks(apr_pool_t *p)
539 /* register the gssweb output filter */
540 ap_register_output_filter("gssweb_auth_filter", gssweb_authenticate_filter, NULL, AP_FTYPE_RESOURCE);
543 ap_hook_check_user_id(gssweb_authenticate_user, NULL, NULL, APR_HOOK_MIDDLE);
544 ap_hook_insert_error_filter(gssweb_add_filter, NULL, NULL, APR_HOOK_MIDDLE);
547 module AP_MODULE_DECLARE_DATA auth_gssweb_module = {
548 STANDARD20_MODULE_STUFF,
549 gss_config_dir_create,
554 gssweb_register_hooks