Filter is successfully called, still needs to do job properly.
[mod_auth_kerb.cvs/.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     { NULL }
49 };
50
51 static void
52 set_http_headers(request_rec *r, const gss_auth_config *conf,
53                  char *negotiate_ret_value)
54 {
55     char *negoauth_param;
56     const char *header_name = (r->proxyreq == PROXYREQ_PROXY) ?
57         "Proxy-Authenticate" : "WWW-Authenticate";
58
59     if (negotiate_ret_value == NULL)
60         return;
61
62     negoauth_param = (*negotiate_ret_value == '\0') ? "Negotiate" :
63         apr_pstrcat(r->pool, "Negotiate ", negotiate_ret_value, NULL);
64     apr_table_add(r->err_headers_out, header_name, negoauth_param);
65 }
66
67 static int
68 gss_authenticate(request_rec *r, gss_auth_config *conf, gss_conn_ctx ctx,
69                  const char *auth_line, char **negotiate_ret_value)
70 {
71   OM_uint32 major_status, minor_status, minor_status2;
72   gss_buffer_desc input_token = GSS_C_EMPTY_BUFFER;
73   gss_buffer_desc output_token = GSS_C_EMPTY_BUFFER;
74   const char *auth_param = NULL;
75   int ret;
76   gss_name_t client_name = GSS_C_NO_NAME;
77   gss_cred_id_t delegated_cred = GSS_C_NO_CREDENTIAL;
78   gss_cred_id_t server_creds = GSS_C_NO_CREDENTIAL;
79   OM_uint32 ret_flags = 0;
80   gss_OID_desc spnego_oid;
81   OM_uint32 (*accept_sec_context)
82                 (OM_uint32 *, gss_ctx_id_t *, const gss_cred_id_t,
83                  const gss_buffer_t, const gss_channel_bindings_t,
84                  gss_name_t *, gss_OID *, gss_buffer_t, OM_uint32 *,
85                  OM_uint32 *, gss_cred_id_t *);
86
87   *negotiate_ret_value = "\0";
88
89   spnego_oid.length = 6;
90   spnego_oid.elements = (void *)"\x2b\x06\x01\x05\x05\x02";
91
92   if (conf->krb5_keytab) {
93      char *ktname;
94      /* we don't use the ap_* calls here, since the string passed to putenv()
95       * will become part of the enviroment and shouldn't be free()ed by apache
96       */
97      ktname = malloc(strlen("KRB5_KTNAME=") + strlen(conf->krb5_keytab) + 1);
98      if (ktname == NULL) {
99         gss_log(APLOG_MARK, APLOG_ERR, 0, r, "malloc() failed: not enough memory");
100         ret = HTTP_INTERNAL_SERVER_ERROR;
101         goto end;
102      }
103      sprintf(ktname, "KRB5_KTNAME=%s", conf->krb5_keytab);
104      putenv(ktname);
105 #ifdef HEIMDAL
106      /* Seems to be also supported by latest MIT */
107      gsskrb5_register_acceptor_identity(conf->krb_5_keytab);
108 #endif
109   }
110
111   ret = get_gss_creds(r, conf, &server_creds);
112   if (ret)
113      goto end;
114
115   /* ap_getword() shifts parameter */
116   auth_param = ap_getword_white(r->pool, &auth_line);
117   if (auth_param == NULL) {
118      gss_log(APLOG_MARK, APLOG_ERR, 0, r,
119              "No Authorization parameter in request from client");
120      ret = HTTP_UNAUTHORIZED;
121      goto end;
122   }
123
124   if (ctx->state == GSS_CTX_ESTABLISHED) {
125       gss_delete_sec_context(&minor_status, &ctx->context, GSS_C_NO_BUFFER);
126       ctx->context = GSS_C_NO_CONTEXT;
127       ctx->state = GSS_CTX_EMPTY;
128   }
129
130   input_token.length = apr_base64_decode_len(auth_param) + 1;
131   input_token.value = apr_pcalloc(r->connection->pool, input_token.length);
132   if (input_token.value == NULL) {
133      gss_log(APLOG_MARK, APLOG_ERR, 0, r,
134              "ap_pcalloc() failed (not enough memory)");
135      ret = HTTP_INTERNAL_SERVER_ERROR;
136      goto end;
137   }
138   input_token.length = apr_base64_decode(input_token.value, auth_param);
139
140   /* LOG length, type */
141
142 #ifdef GSSAPI_SUPPORTS_SPNEGO
143   accept_sec_context = gss_accept_sec_context;
144 #else
145   accept_sec_context = (cmp_gss_type(&input_token, &spnego_oid) == 0) ?
146                       gss_accept_sec_context_spnego : gss_accept_sec_context;
147 #endif  
148
149   major_status = accept_sec_context(&minor_status,
150                                   &ctx->context,
151                                   server_creds,
152                                   &input_token,
153                                   GSS_C_NO_CHANNEL_BINDINGS,
154                                   NULL,
155                                   NULL,
156                                   &output_token,
157                                   &ret_flags,
158                                   NULL,
159                                   &delegated_cred);
160   gss_log(APLOG_MARK, APLOG_DEBUG, 0, r,
161           "Client %s us their credential",
162           (ret_flags & GSS_C_DELEG_FLAG) ? "delegated" : "didn't delegate");
163   if (output_token.length) {
164      char *token = NULL;
165      size_t len;
166      
167      len = apr_base64_encode_len(output_token.length) + 1;
168      token = apr_pcalloc(r->connection->pool, len + 1);
169      if (token == NULL) {
170         gss_log(APLOG_MARK, APLOG_ERR, 0, r,
171                 "ap_pcalloc() failed (not enough memory)");
172         ret = HTTP_INTERNAL_SERVER_ERROR;
173         gss_release_buffer(&minor_status2, &output_token);
174         goto end;
175      }
176      apr_base64_encode(token, output_token.value, output_token.length);
177      token[len] = '\0';
178      *negotiate_ret_value = token;
179      gss_log(APLOG_MARK, APLOG_DEBUG, 0, r,
180              "GSS-API token of length %d bytes will be sent back",
181              output_token.length);
182      gss_release_buffer(&minor_status2, &output_token);
183   }
184
185   if (GSS_ERROR(major_status)) {
186      gss_log(APLOG_MARK, APLOG_ERR, 0, r,
187              "%s", get_gss_error(r, major_status, minor_status,
188                                  "Failed to establish authentication"));
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   gss_release_name(&minor_status, &client_name); 
218   if (GSS_ERROR(major_status)) {
219     gss_log(APLOG_MARK, APLOG_ERR, 0, r,
220             "%s", get_gss_error(r, major_status, minor_status,
221                                 "gss_display_name() failed"));
222     ret = HTTP_INTERNAL_SERVER_ERROR;
223     goto end;
224   }
225
226   ctx->state = GSS_CTX_ESTABLISHED;
227   ctx->user = apr_pstrdup(r->pool, output_token.value);
228   gss_release_buffer(&minor_status, &output_token);
229
230   ret = OK;
231
232 end:
233   if (delegated_cred)
234      gss_release_cred(&minor_status, &delegated_cred);
235
236   if (output_token.length) 
237      gss_release_buffer(&minor_status, &output_token);
238
239   if (client_name != GSS_C_NO_NAME)
240      gss_release_name(&minor_status, &client_name);
241
242   if (server_creds != GSS_C_NO_CREDENTIAL)
243      gss_release_cred(&minor_status, &server_creds);
244
245   return ret;
246 }
247
248 static int
249 gss_authenticate_user(request_rec *r)
250 {
251     gss_auth_config *conf = 
252         (gss_auth_config *) ap_get_module_config(r->per_dir_config,
253                                                 &auth_gssapi_module);
254     const char *auth_line = NULL;
255     const char *type = NULL;
256     char *auth_type = NULL;
257     char *negotiate_ret_value = NULL;
258     gss_conn_ctx conn_ctx = NULL;
259     int ret;
260
261     gss_log(APLOG_MARK, APLOG_DEBUG, 0, r, "Entering GSSAPI authentication");
262    
263     /* get the type specified in Apache configuration */
264     type = ap_auth_type(r);
265     if (type == NULL || strcmp(type, "Negotiate") != 0) {
266         gss_log(APLOG_MARK, APLOG_DEBUG, 0, r,
267                 "AuthType '%s' is not for us, bailing out",
268                 (type) ? type : "(NULL)");
269
270         return DECLINED;
271     }
272
273     /* get what the user sent us in the HTTP header */
274     auth_line = apr_table_get(r->headers_in, (r->proxyreq == PROXYREQ_PROXY)
275                                             ? "Proxy-Authorization"
276                                             : "Authorization");
277     if (auth_line == NULL) {
278         gss_log(APLOG_MARK, APLOG_DEBUG, 0, r,
279                 "Client hasn't sent any authentication data, giving up");
280         set_http_headers(r, conf, "\0");
281         return HTTP_UNAUTHORIZED;
282     }
283
284     auth_type = ap_getword_white(r->pool, &auth_line);
285     if (strcasecmp(auth_type, "Negotiate") != 0) {
286         gss_log(APLOG_MARK, APLOG_DEBUG, 0, r,
287                 "Unsupported authentication type (%s) requested by client",
288                 (auth_type) ? auth_type : "(NULL)");
289         set_http_headers(r, conf, "\0");
290         return HTTP_UNAUTHORIZED;
291     }
292
293     conn_ctx = gss_get_conn_ctx(r);
294     if (conn_ctx == NULL) {
295         gss_log(APLOG_MARK, APLOG_ERR, 0, r,
296                 "Failed to create internal context: probably not enough memory");
297         return HTTP_INTERNAL_SERVER_ERROR;
298     }
299
300     /* optimizing hack */
301     if (conn_ctx->state == GSS_CTX_ESTABLISHED && auth_line == NULL) {
302         r->user = apr_pstrdup(r->pool, conn_ctx->user);
303         r->ap_auth_type = "Negotiate";
304         return OK;
305     }
306
307     /* XXXX subrequests ignored, only successful accesses taken into account! */
308     if (!ap_is_initial_req(r) && conn_ctx->state == GSS_CTX_ESTABLISHED) {
309         r->user = apr_pstrdup(r->pool, conn_ctx->user);
310         r->ap_auth_type = "Negotiate";
311         return OK;
312     }
313
314     ret = gss_authenticate(r, conf, conn_ctx,
315                            auth_line, &negotiate_ret_value);
316     if (ret == HTTP_UNAUTHORIZED || ret == OK) {
317         /* LOG?? */
318         set_http_headers(r, conf, negotiate_ret_value);
319     }
320
321     if (ret == OK) {
322         r->user = apr_pstrdup(r->pool, conn_ctx->user);
323         r->ap_auth_type = "Negotiate";
324     }
325
326     /* debug LOG ??? */
327
328     return ret;
329 }
330
331 static void
332 gss_register_hooks(apr_pool_t *p)
333 {
334     ap_hook_check_user_id(gss_authenticate_user, NULL, NULL, APR_HOOK_MIDDLE);
335 }
336
337 module AP_MODULE_DECLARE_DATA auth_gssapi_module = {
338     STANDARD20_MODULE_STUFF,
339     gss_config_dir_create,
340     NULL,
341     NULL,
342     NULL,
343     gss_config_cmds,
344     gss_register_hooks
345 };