Add gssweb sources
[mod_auth_kerb.cvs/.git] / gss.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 void
35 gss_log(const char *file, int line, int level, int status,
36         const request_rec *r, const char *fmt, ...)
37 {
38     char errstr[1024];
39     va_list ap;
40
41     va_start(ap, fmt);
42     vsnprintf(errstr, sizeof(errstr), fmt, ap);
43     va_end(ap);
44    
45     ap_log_rerror(file, line, level | APLOG_NOERRNO, status, r, "%s", errstr);
46 }
47
48 apr_status_t
49 cleanup_conn_ctx(void *data)
50 {
51     gss_conn_ctx ctx = (gss_conn_ctx) data;
52     OM_uint32 minor_status;
53
54     if (ctx && ctx->context != GSS_C_NO_CONTEXT)
55         gss_delete_sec_context(&minor_status, &ctx->context, GSS_C_NO_BUFFER);
56
57     return APR_SUCCESS;
58 }
59
60 gss_conn_ctx
61 gss_get_conn_ctx(request_rec *r)
62 {
63     char key[1024];
64     gss_conn_ctx ctx = NULL;
65
66     snprintf(key, sizeof(key), "mod_auth_gssapi:conn_ctx");
67     apr_pool_userdata_get((void **)&ctx, key, r->connection->pool);
68     /* XXX LOG */
69     if (ctx == NULL) {
70         ctx = (gss_conn_ctx) apr_palloc(r->connection->pool, sizeof(*ctx));
71         if (ctx == NULL)
72             return NULL;
73         ctx->context = GSS_C_NO_CONTEXT;
74         ctx->state = GSS_CTX_EMPTY;
75         ctx->user = NULL;
76         apr_pool_userdata_set(ctx, key, cleanup_conn_ctx, r->connection->pool);
77     }
78     return ctx;
79 }
80
81 void *
82 gss_config_dir_create(apr_pool_t *p, char *d)
83 {
84     gss_auth_config *conf;
85
86     conf = (gss_auth_config *) apr_pcalloc(p, sizeof(*conf));
87     return conf;
88 }
89
90
91 static const char *
92 get_gss_error(request_rec *r, OM_uint32 err_maj, OM_uint32 err_min, char *prefix)
93 {
94    OM_uint32 maj_stat, min_stat; 
95    OM_uint32 msg_ctx = 0;
96    gss_buffer_desc status_string;
97    char *err_msg;
98    int first_pass;
99
100    gss_log(APLOG_MARK, APLOG_DEBUG, 0, r,
101            "GSS-API major_status:%8.8x, minor_status:%8.8x",
102            err_maj, err_min);
103
104    err_msg = apr_pstrdup(r->pool, prefix);
105    do {
106       maj_stat = gss_display_status (&min_stat,
107                                      err_maj,
108                                      GSS_C_GSS_CODE,
109                                      GSS_C_NO_OID,
110                                      &msg_ctx,
111                                      &status_string);
112       if (!GSS_ERROR(maj_stat)) {
113          err_msg = apr_pstrcat(r->pool, err_msg,
114                                ": ", (char*) status_string.value, NULL);
115          gss_release_buffer(&min_stat, &status_string);
116          first_pass = 0;
117       }
118    } while (!GSS_ERROR(maj_stat) && msg_ctx != 0);
119
120    msg_ctx = 0;
121    err_msg = apr_pstrcat(r->pool, err_msg, " (", NULL);
122    first_pass = 1;
123    do {
124       maj_stat = gss_display_status (&min_stat,
125                                      err_min,
126                                      GSS_C_MECH_CODE,
127                                      GSS_C_NULL_OID,
128                                      &msg_ctx,
129                                      &status_string);
130       if (!GSS_ERROR(maj_stat)) {
131          err_msg = apr_pstrcat(r->pool, err_msg,
132                                (first_pass) ? "" : ", ",
133                                (char *) status_string.value,
134                                NULL);
135          gss_release_buffer(&min_stat, &status_string);
136          first_pass = 0;
137       }
138    } while (!GSS_ERROR(maj_stat) && msg_ctx != 0);
139    err_msg = apr_pstrcat(r->pool, err_msg, ")", NULL);
140
141    return err_msg;
142 }
143
144 static int
145 get_gss_creds(request_rec *r,
146               gss_auth_config *conf,
147               gss_cred_id_t *server_creds)
148 {
149    gss_buffer_desc token = GSS_C_EMPTY_BUFFER;
150    OM_uint32 major_status, minor_status, minor_status2;
151    gss_name_t server_name = GSS_C_NO_NAME;
152    char buf[1024];
153    int have_server_princ;
154
155    if (conf->service_name && strcmp(conf->service_name, "Any") == 0) {
156        *server_creds = GSS_C_NO_CREDENTIAL;
157        return 0;
158    }
159
160    have_server_princ = conf->service_name && strchr(conf->service_name, '/') != NULL;
161    if (have_server_princ)
162        strncpy(buf, conf->service_name, sizeof(buf));
163    else
164        snprintf(buf, sizeof(buf), "%s@%s",
165                (conf->service_name) ? conf->service_name : SERVICE_NAME,
166                ap_get_server_name(r));
167
168    token.value = buf;
169    token.length = strlen(buf) + 1;
170
171    major_status = gss_import_name(&minor_status, &token,
172                                   (have_server_princ) ? (gss_OID) GSS_KRB5_NT_PRINCIPAL_NAME : (gss_OID) GSS_C_NT_HOSTBASED_SERVICE,
173                                   &server_name);
174    memset(&token, 0, sizeof(token));
175    if (GSS_ERROR(major_status)) {
176       gss_log(APLOG_MARK, APLOG_ERR, 0, r,
177               "%s", get_gss_error(r, major_status, minor_status,
178               "gss_import_name() failed"));
179       return HTTP_INTERNAL_SERVER_ERROR;
180    }
181
182    major_status = gss_display_name(&minor_status, server_name, &token, NULL);
183    if (GSS_ERROR(major_status)) {
184       /* Perhaps we could just ignore this error but it's safer to give up now,
185          I think */
186       gss_log(APLOG_MARK, APLOG_ERR, 0, r,
187               "%s", get_gss_error(r, major_status, minor_status,
188                                   "gss_display_name() failed"));
189       return HTTP_INTERNAL_SERVER_ERROR;
190    }
191
192    gss_log(APLOG_MARK, APLOG_DEBUG, 0, r, "Acquiring creds for %s", token.value);
193    gss_release_buffer(&minor_status, &token);
194    
195    major_status = gss_acquire_cred(&minor_status, server_name, GSS_C_INDEFINITE,
196                                    GSS_C_NO_OID_SET, GSS_C_ACCEPT,
197                                    server_creds, NULL, NULL);
198    gss_release_name(&minor_status2, &server_name);
199    if (GSS_ERROR(major_status)) {
200       gss_log(APLOG_MARK, APLOG_ERR, 0, r,
201               "%s", get_gss_error(r, major_status, minor_status,
202                                   "Failed to load GSS-API credentials"));
203       return HTTP_INTERNAL_SERVER_ERROR;
204    }
205
206    return 0;
207 }
208
209 static int
210 cmp_gss_type(gss_buffer_t token, gss_OID oid)
211 {
212    unsigned char *p;
213    size_t len;
214
215    if (token->length == 0)
216       return GSS_S_DEFECTIVE_TOKEN;
217
218    p = token->value;
219    if (*p++ != 0x60)
220       return GSS_S_DEFECTIVE_TOKEN;
221    len = *p++;
222    if (len & 0x80) {
223       if ((len & 0x7f) > 4)
224          return GSS_S_DEFECTIVE_TOKEN;
225       p += len & 0x7f;
226    }
227    if (*p++ != 0x06)
228       return GSS_S_DEFECTIVE_TOKEN;
229
230    if (((OM_uint32) *p++) != oid->length)
231       return GSS_S_DEFECTIVE_TOKEN;
232
233    return memcmp(p, oid->elements, oid->length);
234 }
235
236 int
237 gss_authenticate(request_rec *r, gss_auth_config *conf, gss_conn_ctx ctx,
238                  const char *auth_line, char **negotiate_ret_value)
239 {
240   OM_uint32 major_status, minor_status, minor_status2;
241   gss_buffer_desc input_token = GSS_C_EMPTY_BUFFER;
242   gss_buffer_desc output_token = GSS_C_EMPTY_BUFFER;
243   const char *auth_param = NULL;
244   int ret;
245   gss_name_t client_name = GSS_C_NO_NAME;
246   gss_cred_id_t delegated_cred = GSS_C_NO_CREDENTIAL;
247   gss_cred_id_t server_creds = GSS_C_NO_CREDENTIAL;
248   OM_uint32 ret_flags = 0;
249   gss_OID_desc spnego_oid;
250   OM_uint32 (*accept_sec_context)
251                 (OM_uint32 *, gss_ctx_id_t *, const gss_cred_id_t,
252                  const gss_buffer_t, const gss_channel_bindings_t,
253                  gss_name_t *, gss_OID *, gss_buffer_t, OM_uint32 *,
254                  OM_uint32 *, gss_cred_id_t *);
255
256   *negotiate_ret_value = "\0";
257
258   spnego_oid.length = 6;
259   spnego_oid.elements = (void *)"\x2b\x06\x01\x05\x05\x02";
260
261   if (conf->krb5_keytab) {
262      char *ktname;
263      /* we don't use the ap_* calls here, since the string passed to putenv()
264       * will become part of the enviroment and shouldn't be free()ed by apache
265       */
266      ktname = malloc(strlen("KRB5_KTNAME=") + strlen(conf->krb5_keytab) + 1);
267      if (ktname == NULL) {
268         gss_log(APLOG_MARK, APLOG_ERR, 0, r, "malloc() failed: not enough memory");
269         ret = HTTP_INTERNAL_SERVER_ERROR;
270         goto end;
271      }
272      sprintf(ktname, "KRB5_KTNAME=%s", conf->krb5_keytab);
273      putenv(ktname);
274 #ifdef HEIMDAL
275      /* Seems to be also supported by latest MIT */
276      gsskrb5_register_acceptor_identity(conf->krb_5_keytab);
277 #endif
278   }
279
280   ret = get_gss_creds(r, conf, &server_creds);
281   if (ret)
282      goto end;
283
284   /* ap_getword() shifts parameter */
285   auth_param = ap_getword_white(r->pool, &auth_line);
286   if (auth_param == NULL) {
287      gss_log(APLOG_MARK, APLOG_ERR, 0, r,
288              "No Authorization parameter in request from client");
289      ret = HTTP_UNAUTHORIZED;
290      goto end;
291   }
292
293   if (ctx->state == GSS_CTX_ESTABLISHED) {
294       gss_delete_sec_context(&minor_status, &ctx->context, GSS_C_NO_BUFFER);
295       ctx->context = GSS_C_NO_CONTEXT;
296       ctx->state = GSS_CTX_EMPTY;
297   }
298
299   input_token.length = apr_base64_decode_len(auth_param) + 1;
300   input_token.value = apr_pcalloc(r->connection->pool, input_token.length);
301   if (input_token.value == NULL) {
302      gss_log(APLOG_MARK, APLOG_ERR, 0, r,
303              "ap_pcalloc() failed (not enough memory)");
304      ret = HTTP_INTERNAL_SERVER_ERROR;
305      goto end;
306   }
307   input_token.length = apr_base64_decode(input_token.value, auth_param);
308
309   /* LOG length, type */
310
311 #ifdef GSSAPI_SUPPORTS_SPNEGO
312   accept_sec_context = gss_accept_sec_context;
313 #else
314   accept_sec_context = (cmp_gss_type(&input_token, &spnego_oid) == 0) ?
315                       gss_accept_sec_context_spnego : gss_accept_sec_context;
316 #endif  
317
318   major_status = accept_sec_context(&minor_status,
319                                   &ctx->context,
320                                   server_creds,
321                                   &input_token,
322                                   GSS_C_NO_CHANNEL_BINDINGS,
323                                   NULL,
324                                   NULL,
325                                   &output_token,
326                                   &ret_flags,
327                                   NULL,
328                                   &delegated_cred);
329   gss_log(APLOG_MARK, APLOG_DEBUG, 0, r,
330           "Client %s us their credential",
331           (ret_flags & GSS_C_DELEG_FLAG) ? "delegated" : "didn't delegate");
332   if (output_token.length) {
333      char *token = NULL;
334      size_t len;
335      
336      len = apr_base64_encode_len(output_token.length) + 1;
337      token = apr_pcalloc(r->connection->pool, len + 1);
338      if (token == NULL) {
339         gss_log(APLOG_MARK, APLOG_ERR, 0, r,
340                 "ap_pcalloc() failed (not enough memory)");
341         ret = HTTP_INTERNAL_SERVER_ERROR;
342         gss_release_buffer(&minor_status2, &output_token);
343         goto end;
344      }
345      apr_base64_encode(token, output_token.value, output_token.length);
346      token[len] = '\0';
347      *negotiate_ret_value = token;
348      gss_log(APLOG_MARK, APLOG_DEBUG, 0, r,
349              "GSS-API token of length %d bytes will be sent back",
350              output_token.length);
351      gss_release_buffer(&minor_status2, &output_token);
352   }
353
354   if (GSS_ERROR(major_status)) {
355      gss_log(APLOG_MARK, APLOG_ERR, 0, r,
356              "%s", get_gss_error(r, major_status, minor_status,
357                                  "Failed to establish authentication"));
358 #if 0
359      /* Don't offer the Negotiate method again if call to GSS layer failed */
360      /* XXX ... which means we don't return the "error" output */
361      *negotiate_ret_value = NULL;
362 #endif
363      gss_delete_sec_context(&minor_status, &ctx->context, GSS_C_NO_BUFFER);
364      ctx->context = GSS_C_NO_CONTEXT;
365      ctx->state = GSS_CTX_EMPTY;
366      ret = HTTP_UNAUTHORIZED;
367      goto end;
368   }
369
370   if (major_status & GSS_S_CONTINUE_NEEDED) {
371      ctx->state = GSS_CTX_IN_PROGRESS;
372      ret = HTTP_UNAUTHORIZED;
373      goto end;
374   }
375
376   major_status = gss_inquire_context(&minor_status, ctx->context, &client_name,
377                                      NULL, NULL, NULL, NULL, NULL, NULL);
378   if (GSS_ERROR(major_status)) {
379       gss_log(APLOG_MARK, APLOG_ERR, 0, r,
380               "%s", get_gss_error(r, major_status, minor_status, "gss_inquire_context() failed"));
381       ret = HTTP_INTERNAL_SERVER_ERROR;
382       goto end;
383   }
384
385   major_status = gss_display_name(&minor_status, client_name, &output_token, NULL);
386   gss_release_name(&minor_status, &client_name); 
387   if (GSS_ERROR(major_status)) {
388     gss_log(APLOG_MARK, APLOG_ERR, 0, r,
389             "%s", get_gss_error(r, major_status, minor_status,
390                                 "gss_display_name() failed"));
391     ret = HTTP_INTERNAL_SERVER_ERROR;
392     goto end;
393   }
394
395   ctx->state = GSS_CTX_ESTABLISHED;
396   ctx->user = apr_pstrdup(r->pool, output_token.value);
397   gss_release_buffer(&minor_status, &output_token);
398
399   ret = OK;
400
401 end:
402   if (delegated_cred)
403      gss_release_cred(&minor_status, &delegated_cred);
404
405   if (output_token.length) 
406      gss_release_buffer(&minor_status, &output_token);
407
408   if (client_name != GSS_C_NO_NAME)
409      gss_release_name(&minor_status, &client_name);
410
411   if (server_creds != GSS_C_NO_CREDENTIAL)
412      gss_release_cred(&minor_status, &server_creds);
413
414   return ret;
415 }