Export error environment variables.
[mod_auth_kerb.git] / mod_auth_gssapi.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 #include "mod_auth_gssapi.h"
33
34 module AP_MODULE_DECLARE_DATA auth_gssapi_module;
35
36 #define command(name, func, var, type, usage)           \
37   AP_INIT_ ## type (name, (void*) func,                 \
38         (void*)APR_OFFSETOF(gss_auth_config, var),      \
39         OR_AUTHCFG | RSRC_CONF, usage)
40
41 static const command_rec gss_config_cmds[] = {
42     command("GSSServiceName", ap_set_string_slot, service_name,
43             TAKE1, "Service name used for Apache authentication."),
44
45     command("GSSKrb5Keytab", ap_set_string_slot, krb5_keytab,
46             TAKE1, "Location of Kerberos V5 keytab file."),
47
48     AP_INIT_RAW_ARGS("GssapiNameAttributes", mag_name_attrs, NULL, OR_AUTHCFG | RSRC_CONF,
49                      "Name Attributes to be exported as environ variables"),
50     { NULL }
51 };
52
53 static void
54 set_http_headers(request_rec *r, const gss_auth_config *conf,
55                  char *negotiate_ret_value)
56 {
57     char *negoauth_param;
58     const char *header_name = (r->proxyreq == PROXYREQ_PROXY) ?
59         "Proxy-Authenticate" : "WWW-Authenticate";
60
61     if (negotiate_ret_value == NULL)
62         return;
63
64     negoauth_param = (*negotiate_ret_value == '\0') ? "Negotiate" :
65         apr_pstrcat(r->pool, "Negotiate ", negotiate_ret_value, NULL);
66     apr_table_add(r->err_headers_out, header_name, negoauth_param);
67 }
68
69 static int
70 gss_authenticate(request_rec *r, gss_auth_config *conf, gss_conn_ctx ctx,
71                  const char *auth_line, char **negotiate_ret_value)
72 {
73   OM_uint32 major_status, minor_status, minor_status2;
74   gss_buffer_desc input_token = GSS_C_EMPTY_BUFFER;
75   gss_buffer_desc output_token = GSS_C_EMPTY_BUFFER;
76   const char *auth_param = NULL;
77   int ret;
78   gss_name_t client_name = GSS_C_NO_NAME;
79   gss_cred_id_t delegated_cred = GSS_C_NO_CREDENTIAL;
80   gss_cred_id_t server_creds = GSS_C_NO_CREDENTIAL;
81   OM_uint32 ret_flags = 0;
82   gss_OID_desc spnego_oid;
83   OM_uint32 (*accept_sec_context)
84                 (OM_uint32 *, gss_ctx_id_t *, const gss_cred_id_t,
85                  const gss_buffer_t, const gss_channel_bindings_t,
86                  gss_name_t *, gss_OID *, gss_buffer_t, OM_uint32 *,
87                  OM_uint32 *, gss_cred_id_t *);
88
89   *negotiate_ret_value = "\0";
90
91   spnego_oid.length = 6;
92   spnego_oid.elements = (void *)"\x2b\x06\x01\x05\x05\x02";
93
94   if (conf->krb5_keytab) {
95      char *ktname;
96      /* we don't use the ap_* calls here, since the string passed to putenv()
97       * will become part of the enviroment and shouldn't be free()ed by apache
98       */
99      ktname = malloc(strlen("KRB5_KTNAME=") + strlen(conf->krb5_keytab) + 1);
100      if (ktname == NULL) {
101         gss_log(APLOG_MARK, APLOG_ERR, 0, r, "malloc() failed: not enough memory");
102         ret = HTTP_INTERNAL_SERVER_ERROR;
103         goto end;
104      }
105      sprintf(ktname, "KRB5_KTNAME=%s", conf->krb5_keytab);
106      putenv(ktname);
107 #ifdef HEIMDAL
108      /* Seems to be also supported by latest MIT */
109      gsskrb5_register_acceptor_identity(conf->krb_5_keytab);
110 #endif
111   }
112
113   /* ap_getword() shifts parameter */
114   auth_param = ap_getword_white(r->pool, &auth_line);
115   if (auth_param == NULL) {
116      gss_log(APLOG_MARK, APLOG_ERR, 0, r,
117              "No Authorization parameter in request from client");
118      ret = HTTP_UNAUTHORIZED;
119      goto end;
120   }
121
122   if (ctx->state == GSS_CTX_ESTABLISHED) {
123       gss_delete_sec_context(&minor_status, &ctx->context, GSS_C_NO_BUFFER);
124       ctx->context = GSS_C_NO_CONTEXT;
125       ctx->state = GSS_CTX_EMPTY;
126   }
127
128   input_token.length = apr_base64_decode_len(auth_param) + 1;
129   input_token.value = apr_pcalloc(r->connection->pool, input_token.length);
130   if (input_token.value == NULL) {
131      gss_log(APLOG_MARK, APLOG_ERR, 0, r,
132              "ap_pcalloc() failed (not enough memory)");
133      ret = HTTP_INTERNAL_SERVER_ERROR;
134      goto end;
135   }
136   input_token.length = apr_base64_decode(input_token.value, auth_param);
137
138   /* LOG length, type */
139
140 #ifdef GSSAPI_SUPPORTS_SPNEGO
141   accept_sec_context = gss_accept_sec_context;
142 #else
143   accept_sec_context = (cmp_gss_type(&input_token, &spnego_oid) == 0) ?
144                       gss_accept_sec_context_spnego : gss_accept_sec_context;
145 #endif
146
147   major_status = accept_sec_context(&minor_status,
148                                   &ctx->context,
149                                   server_creds,
150                                   &input_token,
151                                   GSS_C_NO_CHANNEL_BINDINGS,
152                                   NULL,
153                                   NULL,
154                                   &output_token,
155                                   &ret_flags,
156                                   NULL,
157                                   &delegated_cred);
158   gss_log(APLOG_MARK, APLOG_DEBUG, 0, r,
159           "Client %s us their credential",
160           (ret_flags & GSS_C_DELEG_FLAG) ? "delegated" : "didn't delegate");
161   if (output_token.length) {
162      char *token = NULL;
163      size_t len;
164
165      len = apr_base64_encode_len(output_token.length) + 1;
166      token = apr_pcalloc(r->connection->pool, len + 1);
167      if (token == NULL) {
168         gss_log(APLOG_MARK, APLOG_ERR, 0, r,
169                 "ap_pcalloc() failed (not enough memory)");
170         ret = HTTP_INTERNAL_SERVER_ERROR;
171         gss_release_buffer(&minor_status2, &output_token);
172         goto end;
173      }
174      apr_base64_encode(token, output_token.value, output_token.length);
175      token[len] = '\0';
176      *negotiate_ret_value = token;
177      gss_log(APLOG_MARK, APLOG_DEBUG, 0, r,
178              "GSS-API token of length %d bytes will be sent back",
179              output_token.length);
180      gss_release_buffer(&minor_status2, &output_token);
181   }
182
183   if (GSS_ERROR(major_status)) {
184      // at least this error should be populated, to provider further information
185      // to the user (maybe)
186      char *error = get_gss_error(r, major_status, minor_status, "Failed to establish authentication");
187      apr_table_set(r->subprocess_env, "GSS_ERROR_STR", error);
188      gss_log(APLOG_MARK, APLOG_ERR, 0, r, error);
189 #if 0
190      /* Don't offer the Negotiate method again if call to GSS layer failed */
191      /* XXX ... which means we don't return the "error" output */
192      *negotiate_ret_value = NULL;
193 #endif
194      gss_delete_sec_context(&minor_status, &ctx->context, GSS_C_NO_BUFFER);
195      ctx->context = GSS_C_NO_CONTEXT;
196      ctx->state = GSS_CTX_EMPTY;
197      ret = HTTP_UNAUTHORIZED;
198      goto end;
199   }
200
201   if (major_status & GSS_S_CONTINUE_NEEDED) {
202      ctx->state = GSS_CTX_IN_PROGRESS;
203      ret = HTTP_UNAUTHORIZED;
204      goto end;
205   }
206
207   major_status = gss_inquire_context(&minor_status, ctx->context, &client_name,
208                                      NULL, NULL, NULL, NULL, NULL, NULL);
209   if (GSS_ERROR(major_status)) {
210       gss_log(APLOG_MARK, APLOG_ERR, 0, r,
211               "%s", get_gss_error(r, major_status, minor_status, "gss_inquire_context() failed"));
212       ret = HTTP_INTERNAL_SERVER_ERROR;
213       goto end;
214   }
215
216   major_status = gss_display_name(&minor_status, client_name, &output_token, NULL);
217   ctx->user = apr_pstrndup(r->pool, output_token.value, output_token.length);
218
219   if (conf->name_attributes) {
220     mag_get_name_attributes(r, conf, client_name, ctx);
221     mag_set_req_data(r, conf, ctx);
222   }
223
224
225   gss_release_name(&minor_status, &client_name);
226   if (GSS_ERROR(major_status)) {
227     gss_log(APLOG_MARK, APLOG_ERR, 0, r,
228             "%s", get_gss_error(r, major_status, minor_status,
229                                 "gss_display_name() failed"));
230     ret = HTTP_INTERNAL_SERVER_ERROR;
231     goto end;
232   }
233
234   ctx->state = GSS_CTX_ESTABLISHED;
235   gss_release_buffer(&minor_status, &output_token);
236
237   ret = OK;
238
239 end:
240   if (delegated_cred)
241      gss_release_cred(&minor_status, &delegated_cred);
242
243   if (output_token.length)
244      gss_release_buffer(&minor_status, &output_token);
245
246   if (client_name != GSS_C_NO_NAME)
247      gss_release_name(&minor_status, &client_name);
248
249   if (server_creds != GSS_C_NO_CREDENTIAL)
250      gss_release_cred(&minor_status, &server_creds);
251
252   return ret;
253 }
254
255 static int mag_post_config(apr_pool_t *cfgpool, apr_pool_t *log,
256                            apr_pool_t *temp, server_rec *s)
257 {
258     ap_add_version_component(cfgpool, "Moonshot mod_auth_gssapi");
259     return OK;
260 }
261
262 #define MAG_ERROR_NO_AUTH_DATA    "NO_AUTH_DATA"
263 #define MAG_ERROR_UNSUP_AUTH_TYPE "UNSUP_AUTH_TYPE"
264 #define MAG_ERROR_GSS_MECH        "GSS_MECH_ERROR"
265
266 static int
267 gss_authenticate_user(request_rec *r)
268 {
269     gss_auth_config *conf =
270         (gss_auth_config *) ap_get_module_config(r->per_dir_config,
271                                                 &auth_gssapi_module);
272     const char *auth_line = NULL;
273     const char *type = NULL;
274     char *auth_type = NULL;
275     char *negotiate_ret_value = NULL;
276     gss_conn_ctx conn_ctx = NULL;
277     int ret;
278
279     gss_log(APLOG_MARK, APLOG_DEBUG, 0, r, "Entering GSSAPI authentication");
280
281     /* get the type specified in Apache configuration */
282     type = ap_auth_type(r);
283     if (type == NULL || strcmp(type, "Negotiate") != 0) {
284         gss_log(APLOG_MARK, APLOG_DEBUG, 0, r,
285                 "AuthType '%s' is not for us, bailing out",
286                 (type) ? type : "(NULL)");
287
288         return DECLINED;
289     }
290
291     /* get what the user sent us in the HTTP header */
292     auth_line = apr_table_get(r->headers_in, (r->proxyreq == PROXYREQ_PROXY)
293                                             ? "Proxy-Authorization"
294                                             : "Authorization");
295     if (auth_line == NULL) {
296         gss_log(APLOG_MARK, APLOG_DEBUG, 0, r,
297                 "Client hasn't sent any authentication data, giving up");
298         set_http_headers(r, conf, "\0");
299         apr_table_set(r->subprocess_env, "MAG_ERROR", MAG_ERROR_NO_AUTH_DATA);
300         return HTTP_UNAUTHORIZED;
301     }
302
303     auth_type = ap_getword_white(r->pool, &auth_line);
304     if (strcasecmp(auth_type, "Negotiate") != 0) {
305         gss_log(APLOG_MARK, APLOG_DEBUG, 0, r,
306                 "Unsupported authentication type (%s) requested by client",
307                 (auth_type) ? auth_type : "(NULL)");
308         set_http_headers(r, conf, "\0");
309         apr_table_set(r->subprocess_env, "MAG_ERROR", MAG_ERROR_UNSUP_AUTH_TYPE);
310         return HTTP_UNAUTHORIZED;
311     }
312
313     if ((NULL == (conn_ctx = gss_retrieve_conn_ctx(r))) &&
314         (NULL == (conn_ctx = gss_create_conn_ctx(r, conf)))) {
315         gss_log(APLOG_MARK, APLOG_ERR, 0, r,
316                 "Failed to create internal context: probably not enough memory");
317         return HTTP_INTERNAL_SERVER_ERROR;
318     }
319
320     /* optimizing hack */
321     if (conn_ctx->state == GSS_CTX_ESTABLISHED && auth_line == NULL) {
322         r->user = apr_pstrdup(r->pool, conn_ctx->user);
323         r->ap_auth_type = "Negotiate";
324         return OK;
325     }
326
327     /* XXXX subrequests ignored, only successful accesses taken into account! */
328     if (!ap_is_initial_req(r) && conn_ctx->state == GSS_CTX_ESTABLISHED) {
329         r->user = apr_pstrdup(r->pool, conn_ctx->user);
330         r->ap_auth_type = "Negotiate";
331         return OK;
332     }
333
334     ret = gss_authenticate(r, conf, conn_ctx,
335                            auth_line, &negotiate_ret_value);
336     if (ret == HTTP_UNAUTHORIZED || ret == OK) {
337         /* LOG?? */
338         set_http_headers(r, conf, negotiate_ret_value);
339     }
340
341     if (ret == OK) {
342         r->user = apr_pstrdup(r->pool, conn_ctx->user);
343         r->ap_auth_type = "Negotiate";
344     } else {
345       apr_table_set(r->subprocess_env, "MAG_ERROR", MAG_ERROR_GSS_MECH);
346     }
347     /* debug LOG ??? */
348
349     return ret;
350 }
351
352 static void
353 gss_register_hooks(apr_pool_t *p)
354 {
355     ap_hook_check_user_id(gss_authenticate_user, NULL, NULL, APR_HOOK_MIDDLE);
356     ap_hook_post_config(mag_post_config, NULL, NULL, APR_HOOK_MIDDLE);
357 }
358
359 module AP_MODULE_DECLARE_DATA auth_gssapi_module = {
360     STANDARD20_MODULE_STUFF,
361     gss_config_dir_create,
362     NULL,
363     NULL,
364     NULL,
365     gss_config_cmds,
366     gss_register_hooks
367 };