Added definition of KRB5_LIB_FUNCTION (taken from MIT), which seems not to be
[mod_auth_kerb.cvs/.git] / src / mod_auth_kerb.c
1 /*
2  * Daniel Kouril <kouril@users.sourceforge.net>
3  *
4  * Source and Documentation can be found at:
5  * http://modauthkerb.sourceforge.net/
6  *
7  * Based on work by
8  *   James E. Robinson, III <james@ncstate.net>
9  *   Daniel Henninger <daniel@ncsu.edu>
10  *   Ludek Sulak <xsulak@fi.muni.cz>
11  */
12
13 /*
14  * Copyright (c) 2004-2006 Masarykova universita
15  * (Masaryk University, Brno, Czech Republic)
16  * All rights reserved.
17  *
18  * Redistribution and use in source and binary forms, with or without
19  * modification, are permitted provided that the following conditions are met:
20  *
21  * 1. Redistributions of source code must retain the above copyright notice,
22  *    this list of conditions and the following disclaimer.
23  *
24  * 2. Redistributions in binary form must reproduce the above copyright
25  *    notice, this list of conditions and the following disclaimer in the
26  *    documentation and/or other materials provided with the distribution.
27  *
28  * 3. Neither the name of the University nor the names of its contributors may
29  *    be used to endorse or promote products derived from this software
30  *    without specific prior written permission.
31  *
32  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
33  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
34  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
35  * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
36  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
37  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
38  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
39  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
40  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
41  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
42  * POSSIBILITY OF SUCH DAMAGE.
43  */
44
45 #ident "$Id$"
46
47 #include "config.h"
48
49 #include <stdlib.h>
50 #include <stdio.h>
51 #include <stdarg.h>
52
53 #define MODAUTHKERB_VERSION "5.1"
54
55 #define MECH_NEGOTIATE "Negotiate"
56 #define SERVICE_NAME "HTTP"
57
58 #include <httpd.h>
59 #include <http_config.h>
60 #include <http_core.h>
61 #include <http_log.h>
62 #include <http_protocol.h>
63 #include <http_request.h>
64
65 #ifdef STANDARD20_MODULE_STUFF
66 #include <apr_strings.h>
67 #include <apr_base64.h>
68 #else
69 #define apr_pstrdup             ap_pstrdup
70 #define apr_psprintf            ap_psprintf
71 #define apr_pstrcat             ap_pstrcat
72 #define apr_pcalloc             ap_pcalloc
73 #define apr_table_setn          ap_table_setn
74 #define apr_table_add           ap_table_add
75 #define apr_base64_decode_len   ap_base64decode_len
76 #define apr_base64_decode       ap_base64decode
77 #define apr_base64_encode_len   ap_base64encode_len
78 #define apr_base64_encode       ap_base64encode
79 #define apr_pool_cleanup_null   ap_null_cleanup
80 #define apr_pool_cleanup_register       ap_register_cleanup
81 #endif /* STANDARD20_MODULE_STUFF */
82
83 #ifdef _WIN32
84 #define vsnprintf _vsnprintf
85 #define snprintf _snprintf
86 #endif
87
88 #ifdef KRB5
89 #include <krb5.h>
90 #ifdef HEIMDAL
91 #  include <gssapi.h>
92 #else
93 #  include <gssapi/gssapi.h>
94 #  include <gssapi/gssapi_generic.h>
95 #  include <gssapi/gssapi_krb5.h>
96 #  define GSS_C_NT_USER_NAME gss_nt_user_name
97 #  define GSS_C_NT_HOSTBASED_SERVICE gss_nt_service_name
98 #  define GSS_KRB5_NT_PRINCIPAL_NAME gss_nt_krb5_name
99 #  define krb5_get_err_text(context,code) error_message(code)
100 #endif
101 #ifndef GSSAPI_SUPPORTS_SPNEGO
102 #  include "spnegokrb5.h"
103 #endif
104 #endif /* KRB5 */
105
106 #ifdef KRB4
107 /* Prevent warning about closesocket redefinition (Apache's ap_config.h and 
108  * MIT Kerberos' port-sockets.h both define it as close) */
109 #ifdef closesocket
110 #  undef closesocket
111 #endif
112 #include <krb.h>
113 #include <netdb.h> /* gethostbyname() */
114 #endif /* KRB4 */
115
116 #ifndef _WIN32
117 /* should be HAVE_UNISTD_H instead */
118 #include <unistd.h>
119 #endif
120
121 #ifndef KRB5_LIB_FUNCTION
122 #  if defined(_WIN32)
123 #    define KRB5_LIB_FUNCTION _stdcall
124 #  else
125 #    define KRB5_LIB_FUNCTION
126 #  endif
127 #endif
128
129 #ifdef STANDARD20_MODULE_STUFF
130 module AP_MODULE_DECLARE_DATA auth_kerb_module;
131 #else
132 module auth_kerb_module;
133 #endif
134
135 /*************************************************************************** 
136  Macros To Ease Compatibility
137  ***************************************************************************/
138 #ifdef STANDARD20_MODULE_STUFF
139 #define MK_POOL apr_pool_t
140 #define MK_TABLE_GET apr_table_get
141 #define MK_USER r->user
142 #define MK_AUTH_TYPE r->ap_auth_type
143 #else
144 #define MK_POOL pool
145 #define MK_TABLE_GET ap_table_get
146 #define MK_USER r->connection->user
147 #define MK_AUTH_TYPE r->connection->ap_auth_type
148 #define PROXYREQ_PROXY STD_PROXY
149 #endif
150
151 /*************************************************************************** 
152  Auth Configuration Structure
153  ***************************************************************************/
154 typedef struct {
155         char *krb_auth_realms;
156         int krb_save_credentials;
157         int krb_verify_kdc;
158         const char *krb_service_name;
159         int krb_authoritative;
160         int krb_delegate_basic;
161 #if 0
162         int krb_ssl_preauthentication;
163 #endif
164 #ifdef KRB5
165         char *krb_5_keytab;
166         int krb_method_gssapi;
167         int krb_method_k5pass;
168 #endif
169 #ifdef KRB4
170         char *krb_4_srvtab;
171         int krb_method_k4pass;
172 #endif
173 } kerb_auth_config;
174
175 static void
176 set_kerb_auth_headers(request_rec *r, const kerb_auth_config *conf,
177                       int use_krb4, int use_krb5pwd, char *negotiate_ret_value);
178
179 static const char*
180 krb5_save_realms(cmd_parms *cmd, void *sec, const char *arg);
181
182 #ifdef STANDARD20_MODULE_STUFF
183 #define command(name, func, var, type, usage)           \
184   AP_INIT_ ## type (name, (void*) func,                 \
185         (void*)APR_OFFSETOF(kerb_auth_config, var),     \
186         OR_AUTHCFG | RSRC_CONF, usage)
187 #else
188 #define command(name, func, var, type, usage)           \
189   { name, func,                                         \
190     (void*)XtOffsetOf(kerb_auth_config, var),           \
191     OR_AUTHCFG | RSRC_CONF, type, usage }
192 #endif
193
194 static const command_rec kerb_auth_cmds[] = {
195    command("KrbAuthRealms", krb5_save_realms, krb_auth_realms,
196      RAW_ARGS, "Realms to attempt authentication against (can be multiple)."),
197
198    command("KrbAuthRealm", krb5_save_realms, krb_auth_realms,
199      RAW_ARGS, "Alias for KrbAuthRealms."),
200
201    command("KrbSaveCredentials", ap_set_flag_slot, krb_save_credentials,
202      FLAG, "Save and store credentials/tickets retrieved during auth."),
203
204    command("KrbVerifyKDC", ap_set_flag_slot, krb_verify_kdc,
205      FLAG, "Verify tickets against keytab to prevent KDC spoofing attacks."),
206
207    command("KrbServiceName", ap_set_string_slot, krb_service_name,
208      TAKE1, "Full or partial service name to be used by Apache for authentication."),
209
210    command("KrbAuthoritative", ap_set_flag_slot, krb_authoritative,
211      FLAG, "Set to 'off' to allow access control to be passed along to lower modules iff the UserID is not known to this module."),
212
213    command("KrbDelegateBasic", ap_set_flag_slot, krb_delegate_basic,
214      FLAG, "Always offer Basic authentication regardless of KrbMethodK5Pass and pass on authentication to lower modules if Basic headers arrive."),
215
216 #if 0
217    command("KrbEnableSSLPreauthentication", ap_set_flag_slot, krb_ssl_preauthentication,
218      FLAG, "Don't do Kerberos authentication if the user is already authenticated using SSL and her client certificate."),
219 #endif
220
221 #ifdef KRB5
222    command("Krb5Keytab", ap_set_file_slot, krb_5_keytab,
223      TAKE1, "Location of Kerberos V5 keytab file."),
224
225    command("KrbMethodNegotiate", ap_set_flag_slot, krb_method_gssapi,
226      FLAG, "Enable Negotiate authentication method."),
227
228    command("KrbMethodK5Passwd", ap_set_flag_slot, krb_method_k5pass,
229      FLAG, "Enable Kerberos V5 password authentication."),
230 #endif 
231
232 #ifdef KRB4
233    command("Krb4Srvtab", ap_set_file_slot, krb_4_srvtab,
234      TAKE1, "Location of Kerberos V4 srvtab file."),
235
236    command("KrbMethodK4Passwd", ap_set_flag_slot, krb_method_k4pass,
237      FLAG, "Enable Kerberos V4 password authentication."),
238 #endif
239
240    { NULL }
241 };
242
243 #ifdef _WIN32
244 int
245 mkstemp(char *template)
246 {
247     int start, i;
248     pid_t val;
249     val = getpid();
250     start = strlen(template) - 1;
251     while(template[start] == 'X') {
252         template[start] = '0' + val % 10;
253         val /= 10;
254         start--;
255     }
256     
257     do{
258         int fd;
259         fd = open(template, O_RDWR | O_CREAT | O_EXCL, 0600);
260         if(fd >= 0 || errno != EEXIST)
261             return fd;
262         i = start + 1;
263         do{
264             if(template[i] == 0)
265                 return -1;
266             template[i]++;
267             if(template[i] == '9' + 1)
268                 template[i] = 'a';
269             if(template[i] <= 'z')
270                 break;
271             template[i] = 'a';
272             i++;
273         }while(1);
274     }while(1);
275 }
276 #endif
277
278 #if defined(KRB5) && !defined(HEIMDAL)
279 /* Needed to work around problems with replay caches */
280 #include "mit-internals.h"
281
282 /* This is our replacement krb5_rc_store function */
283 static krb5_error_code KRB5_LIB_FUNCTION
284 mod_auth_kerb_rc_store(krb5_context context, krb5_rcache rcache,
285                        krb5_donot_replay_internal *donot_replay)
286 {
287    return 0;
288 }
289
290 /* And this is the operations vector for our replay cache */
291 const krb5_rc_ops_internal mod_auth_kerb_rc_ops = {
292   0,
293   "dfl",
294   krb5_rc_dfl_init,
295   krb5_rc_dfl_recover,
296   krb5_rc_dfl_destroy,
297   krb5_rc_dfl_close,
298   mod_auth_kerb_rc_store,
299   krb5_rc_dfl_expunge,
300   krb5_rc_dfl_get_span,
301   krb5_rc_dfl_get_name,
302   krb5_rc_dfl_resolve
303 };
304 #endif
305
306
307 /*************************************************************************** 
308  Auth Configuration Initialization
309  ***************************************************************************/
310 static void *kerb_dir_create_config(MK_POOL *p, char *d)
311 {
312         kerb_auth_config *rec;
313
314         rec = (kerb_auth_config *) apr_pcalloc(p, sizeof(kerb_auth_config));
315         ((kerb_auth_config *)rec)->krb_verify_kdc = 1;
316         ((kerb_auth_config *)rec)->krb_service_name = NULL;
317         ((kerb_auth_config *)rec)->krb_authoritative = 1;
318         ((kerb_auth_config *)rec)->krb_delegate_basic = 0;
319 #if 0
320         ((kerb_auth_config *)rec)->krb_ssl_preauthentication = 0;
321 #endif
322 #ifdef KRB5
323         ((kerb_auth_config *)rec)->krb_method_k5pass = 1;
324         ((kerb_auth_config *)rec)->krb_method_gssapi = 1;
325 #endif
326 #ifdef KRB4
327         ((kerb_auth_config *)rec)->krb_method_k4pass = 1;
328 #endif
329         return rec;
330 }
331
332 static const char*
333 krb5_save_realms(cmd_parms *cmd, void *vsec, const char *arg)
334 {
335    kerb_auth_config *sec = (kerb_auth_config *) vsec;
336    sec->krb_auth_realms= apr_pstrdup(cmd->pool, arg);
337    return NULL;
338 }
339
340 static void
341 log_rerror(const char *file, int line, int level, int status,
342            const request_rec *r, const char *fmt, ...)
343 {
344    char errstr[1024];
345    va_list ap;
346
347    va_start(ap, fmt);
348    vsnprintf(errstr, sizeof(errstr), fmt, ap);
349    va_end(ap);
350
351    
352 #ifdef STANDARD20_MODULE_STUFF
353    ap_log_rerror(file, line, level | APLOG_NOERRNO, status, r, "%s", errstr);
354 #else
355    ap_log_rerror(file, line, level | APLOG_NOERRNO, r, "%s", errstr);
356 #endif
357 }
358
359 #ifdef KRB4
360 /*************************************************************************** 
361  Username/Password Validation for Krb4
362  ***************************************************************************/
363 static int
364 verify_krb4_user(request_rec *r, const char *name, const char *instance,
365                  const char *realm, const char *password, const char *linstance, const char *srvtab, int krb_verify_kdc)
366 {
367    int ret;
368    char *phost;
369    unsigned long addr;
370    struct hostent *hp;
371    const char *hostname;
372    KTEXT_ST ticket;
373    AUTH_DAT authdata;
374    char lrealm[REALM_SZ];
375
376    ret = krb_get_pw_in_tkt(name, instance, realm, "krbtgt", realm, 
377                            DEFAULT_TKT_LIFE, password);
378    if (ret) {
379       log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
380                  "Cannot get krb4 ticket: krb_get_pw_in_tkt() failed: %s",
381                  krb_get_err_text(ret));
382       return ret;
383    }
384
385    if (!krb_verify_kdc)
386       return ret;
387
388    hostname = ap_get_server_name(r);
389
390    hp = gethostbyname(hostname);
391    if (hp == NULL) {
392       dest_tkt();
393       log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
394                  "Cannot verify krb4 ticket: gethostbyname() failed: %s",
395                  hstrerror(h_errno));
396       return h_errno;
397    }
398    memcpy(&addr, hp->h_addr, sizeof(addr));
399
400    phost = krb_get_phost((char *)hostname);
401
402    krb_get_lrealm(lrealm, 1);
403
404    ret = krb_mk_req(&ticket, linstance, phost, lrealm, 0);
405    if (ret) {
406       log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
407                  "Cannot verify krb4 ticket: krb_mk_req() failed: %s",
408                  krb_get_err_text(ret));
409       dest_tkt();
410       return ret;
411    }
412
413    ret = krb_rd_req(&ticket, (char *)linstance, phost, addr, &authdata, (char *)srvtab);
414    if (ret) {
415       log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
416                  "Cannot verify krb4 ticket: krb_rd_req() failed: %s",
417                  krb_get_err_text(ret));
418       dest_tkt();
419    }
420
421    return ret;
422 }
423
424 static int
425 krb4_cache_cleanup(void *data)
426 {
427    char *tkt_file = (char *) data;
428    
429    krb_set_tkt_string(tkt_file);
430    dest_tkt();
431    return OK;
432 }
433
434 static int 
435 authenticate_user_krb4pwd(request_rec *r,
436                           kerb_auth_config *conf,
437                           const char *auth_line)
438 {
439    int ret;
440    const char *sent_pw;
441    const char *sent_name;
442    char *sent_instance;
443    char tkt_file[32];
444    char *tkt_file_p = NULL;
445    int fd;
446    const char *realms;
447    const char *realm;
448    char *user;
449    char lrealm[REALM_SZ];
450    int all_principals_unkown;
451
452    sent_pw = ap_pbase64decode(r->pool, auth_line);
453    sent_name = ap_getword (r->pool, &sent_pw, ':');
454
455    sent_instance = strchr(sent_name, '.');
456    if (sent_instance)
457       *sent_instance++ = '\0'; 
458
459    snprintf(tkt_file, sizeof(tkt_file), "/tmp/apache_tkt_XXXXXX");
460    fd = mkstemp(tkt_file);
461    if (fd < 0) {
462       log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
463                  "Cannot create krb4 ccache: mkstemp() failed: %s",
464                  strerror(errno));
465       return HTTP_INTERNAL_SERVER_ERROR;
466    }
467
468    tkt_file_p = apr_pstrdup(r->pool, tkt_file);
469    apr_pool_cleanup_register(r->pool, tkt_file_p, krb4_cache_cleanup,
470                              apr_pool_cleanup_null);
471    
472    krb_set_tkt_string(tkt_file);
473
474    all_principals_unkown = 1;
475    realms = conf->krb_auth_realms;
476    do {
477       memset(lrealm, 0, sizeof(lrealm));
478       realm = NULL;
479       if (realms)
480          realm = ap_getword_white(r->pool, &realms);
481
482       if (realm == NULL) {
483          ret = krb_get_lrealm(lrealm, 1);
484          if (ret)
485             break;
486          realm = lrealm;
487       }
488
489       /* XXX conf->krb_service_name */
490       ret = verify_krb4_user(r, (char *)sent_name, 
491                              (sent_instance) ? sent_instance : "",
492                              (char *)realm, (char *)sent_pw,
493                              conf->krb_service_name,
494                              conf->krb_4_srvtab, conf->krb_verify_kdc);
495       if (!conf->krb_authoritative && ret) {
496          /* if we're not authoritative, we allow authentication to pass on
497           * to another modules if (and only if) the user is not known to us */
498          if (all_principals_unkown && ret != KDC_PR_UNKNOWN)
499             all_principals_unkown = 0;
500       }
501
502       if (ret == 0)
503          break;
504    } while (realms && *realms);
505
506    if (ret) {
507       /* XXX log only in the verify_krb4_user() call */
508       log_rerror(APLOG_MARK, APLOG_ERR, 0, r, "Verifying krb4 password failed");
509       ret = (!conf->krb_authoritative && all_principals_unkown == 1 && ret == KDC_PR_UNKNOWN) ?
510                  DECLINED : HTTP_UNAUTHORIZED;
511       goto end;
512    }
513
514    user = apr_pstrdup(r->pool, sent_name);
515    if (sent_instance)
516       user = apr_pstrcat(r->pool, user, ".", sent_instance, NULL);
517    user = apr_pstrcat(r->pool, user, "@", realm, NULL);
518
519    MK_USER = user;
520    MK_AUTH_TYPE = "Basic";
521    apr_table_setn(r->subprocess_env, "KRBTKFILE", tkt_file_p);
522
523    if (!conf->krb_save_credentials)
524       krb4_cache_cleanup(tkt_file);
525
526 end:
527    if (ret)
528       krb4_cache_cleanup(tkt_file);
529    close(fd);
530    tf_close();
531
532    return ret;
533 }
534 #endif /* KRB4 */
535
536 #ifdef KRB5
537 /*************************************************************************** 
538  Username/Password Validation for Krb5
539  ***************************************************************************/
540
541 /* MIT kerberos uses replay cache checks even during credential verification
542  * (i.e. in krb5_verify_init_creds()), which is obviosuly useless. In order to
543  * avoid problems with multiple apache processes accessing the same rcache file
544  * we had to use this call instead, which is only a bit modified version of
545  * krb5_verify_init_creds() */
546 static krb5_error_code
547 verify_krb5_init_creds(request_rec *r, krb5_context context, krb5_creds *creds,
548                        krb5_principal ap_req_server, krb5_keytab ap_req_keytab)
549 {
550    krb5_error_code ret;
551    krb5_data req;
552    krb5_ccache local_ccache = NULL;
553    krb5_creds *new_creds = NULL;
554    krb5_auth_context auth_context = NULL;
555    krb5_keytab keytab = NULL;
556    char *server_name;
557
558    memset(&req, 0, sizeof(req));
559
560    if (ap_req_keytab == NULL) {
561       ret = krb5_kt_default (context, &keytab);
562       if (ret)
563          return ret;
564    } else
565       keytab = ap_req_keytab;
566
567    ret = krb5_cc_resolve(context, "MEMORY:", &local_ccache);
568    if (ret) {
569       log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
570                  "krb5_cc_resolve() failed when verifying KDC");
571       return ret;
572    }
573
574    ret = krb5_cc_initialize(context, local_ccache, creds->client);
575    if (ret) {
576       log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
577                  "krb5_cc_initialize() failed when verifying KDC");
578       goto end;
579    }
580
581    ret = krb5_cc_store_cred (context, local_ccache, creds);
582    if (ret) {
583       log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
584                  "krb5_cc_initialize() failed when verifying KDC");
585       goto end;
586    }
587    
588    ret = krb5_unparse_name(context, ap_req_server, &server_name);
589    if (ret) {
590       log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
591                  "krb5_unparse_name() failed when verifying KDC");
592       goto end;
593    }
594    log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
595               "Trying to verify authenticity of KDC using principal %s", server_name);
596    free(server_name);
597
598    if (!krb5_principal_compare (context, ap_req_server, creds->server)) {
599       krb5_creds match_cred;
600
601       memset (&match_cred, 0, sizeof(match_cred));
602
603       match_cred.client = creds->client;
604       match_cred.server = ap_req_server;
605
606       ret = krb5_get_credentials (context, 0, local_ccache, 
607                                   &match_cred, &new_creds);
608       if (ret) {
609          log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
610                     "krb5_get_credentials() failed when verifying KDC");
611          goto end;
612       }
613       creds = new_creds;
614    }
615
616    ret = krb5_mk_req_extended (context, &auth_context, 0, NULL, creds, &req);
617    if (ret) {
618       log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
619                  "krb5_mk_req_extended() failed when verifying KDC");
620       goto end;
621    }
622
623    krb5_auth_con_free (context, auth_context);
624    auth_context = NULL;
625    ret = krb5_auth_con_init(context, &auth_context);
626    if (ret) {
627       log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
628                  "krb5_auth_con_init() failed when verifying KDC");
629       goto end;
630    }
631    /* use KRB5_AUTH_CONTEXT_DO_SEQUENCE to skip replay cache checks */
632    krb5_auth_con_setflags(context, auth_context, KRB5_AUTH_CONTEXT_DO_SEQUENCE);
633
634    ret = krb5_rd_req (context, &auth_context, &req, ap_req_server,
635                       keytab, 0, NULL);
636    if (ret) {
637       log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
638                  "krb5_rd_req() failed when verifying KDC");
639       goto end;
640    }
641
642 end:
643 #ifdef HEIMDAL
644    /* XXX Do I ever want to support Heimdal 0.4 ??? */
645    krb5_data_free(&req);
646 #else
647    krb5_free_data_contents(context, &req);
648 #endif
649    if (auth_context)
650       krb5_auth_con_free (context, auth_context);
651    if (new_creds)
652       krb5_free_creds (context, new_creds);
653    if (ap_req_keytab == NULL && keytab)
654       krb5_kt_close (context, keytab);
655    if (local_ccache)
656       krb5_cc_destroy (context, local_ccache);
657
658    return ret;
659 }
660
661 /* Inspired by krb5_verify_user from Heimdal */
662 static krb5_error_code
663 verify_krb5_user(request_rec *r, krb5_context context, krb5_principal principal,
664                  const char *password, krb5_principal server,
665                  krb5_keytab keytab, int krb_verify_kdc, krb5_ccache *ccache)
666 {
667    krb5_creds creds;
668    krb5_error_code ret;
669    krb5_ccache ret_ccache = NULL;
670    char *name = NULL;
671
672    /* XXX error messages shouldn't be logged here (and in the while() loop in
673     * authenticate_user_krb5pwd() as weell), in order to avoid confusing log
674     * entries when using multiple realms */
675
676    memset(&creds, 0, sizeof(creds));
677
678    ret = krb5_unparse_name(context, principal, &name);
679    if (ret == 0) {
680       log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
681                  "Trying to get TGT for user %s", name);
682       free(name);
683    }
684
685    ret = krb5_get_init_creds_password(context, &creds, principal, 
686                                       (char *)password, NULL,
687                                       NULL, 0, NULL, NULL);
688    if (ret) {
689       log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
690                  "krb5_get_init_creds_password() failed: %s",
691                  krb5_get_err_text(context, ret));
692       goto end;
693    }
694
695    /* XXX
696    {
697       char *realm;
698
699       krb5_get_default_realm(context, &realm);
700       log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
701                  "trying to verify password using key for %s/%s@%s",
702                  service, ap_get_server_name(r), realm);
703    }
704    */
705
706    if (krb_verify_kdc &&
707        (ret = verify_krb5_init_creds(r, context, &creds, server, keytab))) {
708        log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
709                   "failed to verify krb5 credentials: %s",
710                   krb5_get_err_text(context, ret));
711        goto end;
712    }
713
714    ret = krb5_cc_resolve(context, "MEMORY:", &ret_ccache);
715    if (ret) {
716       log_rerror(APLOG_MARK, APLOG_ERR, 0, r, 
717                  "generating new memory ccache failed: %s",
718                  krb5_get_err_text(context, ret));
719       goto end;
720    }
721
722    ret = krb5_cc_initialize(context, ret_ccache, principal);
723    if (ret) {
724       log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
725                  "krb5_cc_initialize() failed: %s",
726                  krb5_get_err_text(context, ret));
727       goto end;
728    }
729
730    ret = krb5_cc_store_cred(context, ret_ccache, &creds);
731    if (ret) {
732       log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
733                  "krb5_cc_store_cred() failed: %s",
734                  krb5_get_err_text(context, ret));
735       goto end;
736    }
737    *ccache = ret_ccache;
738    ret_ccache = NULL;
739
740 end:
741    krb5_free_cred_contents(context, &creds);
742    if (ret_ccache)
743       krb5_cc_destroy(context, ret_ccache);
744
745    return ret;
746 }
747
748 static int
749 krb5_cache_cleanup(void *data)
750 {
751    krb5_context context;
752    krb5_ccache  cache;
753    krb5_error_code problem;
754    char *cache_name = (char *) data;
755
756    problem = krb5_init_context(&context);
757    if (problem) {
758       /* ap_log_error(APLOG_MARK, APLOG_ERR, 0, NULL, "krb5_init_context() failed"); */
759       return HTTP_INTERNAL_SERVER_ERROR;
760    }
761
762    problem = krb5_cc_resolve(context, cache_name, &cache);
763    if (problem) {
764       /* log_error(APLOG_MARK, APLOG_ERR, 0, NULL, 
765                 "krb5_cc_resolve() failed (%s: %s)",
766                 cache_name, krb5_get_err_text(context, problem)); */
767       return HTTP_INTERNAL_SERVER_ERROR;
768    }
769
770    krb5_cc_destroy(context, cache);
771    krb5_free_context(context);
772    return OK;
773 }
774
775 static int
776 create_krb5_ccache(krb5_context kcontext,
777                    request_rec *r,
778                    kerb_auth_config *conf,
779                    krb5_principal princ,
780                    krb5_ccache *ccache)
781 {
782    char *ccname;
783    int fd;
784    krb5_error_code problem;
785    int ret;
786    krb5_ccache tmp_ccache = NULL;
787
788    ccname = apr_psprintf(r->pool, "FILE:%s/krb5cc_apache_XXXXXX", P_tmpdir);
789    fd = mkstemp(ccname + strlen("FILE:"));
790    if (fd < 0) {
791       log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
792                  "mkstemp() failed: %s", strerror(errno));
793       ret = HTTP_INTERNAL_SERVER_ERROR;
794       goto end;
795    }
796    close(fd);
797
798    problem = krb5_cc_resolve(kcontext, ccname, &tmp_ccache);
799    if (problem) {
800       log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
801                  "krb5_cc_resolve() failed: %s",
802                  krb5_get_err_text(kcontext, problem));
803       ret = HTTP_INTERNAL_SERVER_ERROR;
804       unlink(ccname);
805       goto end;
806    }
807
808    problem = krb5_cc_initialize(kcontext, tmp_ccache, princ);
809    if (problem) {
810       log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
811                  "Cannot initialize krb5 ccache %s: krb5_cc_initialize() failed: %s",
812                  ccname, krb5_get_err_text(kcontext, problem));
813       ret = HTTP_INTERNAL_SERVER_ERROR;
814       goto end;
815    }
816
817    apr_table_setn(r->subprocess_env, "KRB5CCNAME", ccname);
818    apr_pool_cleanup_register(r->pool, ccname, krb5_cache_cleanup,
819                              apr_pool_cleanup_null);
820
821    *ccache = tmp_ccache;
822    tmp_ccache = NULL;
823
824    ret = OK;
825
826 end:
827    if (tmp_ccache)
828       krb5_cc_destroy(kcontext, tmp_ccache);
829
830    return ret;
831 }
832
833 static int
834 store_krb5_creds(krb5_context kcontext,
835                  request_rec *r,
836                  kerb_auth_config *conf,
837                  krb5_ccache delegated_cred)
838 {
839    char errstr[1024];
840    krb5_error_code problem;
841    krb5_principal princ;
842    krb5_ccache ccache;
843    int ret;
844
845    problem = krb5_cc_get_principal(kcontext, delegated_cred, &princ);
846    if (problem) {
847       snprintf(errstr, sizeof(errstr), "krb5_cc_get_principal() failed: %s",
848                krb5_get_err_text(kcontext, problem));
849       return HTTP_INTERNAL_SERVER_ERROR;
850    }
851
852    ret = create_krb5_ccache(kcontext, r, conf, princ, &ccache);
853    if (ret) {
854       krb5_free_principal(kcontext, princ);
855       return ret;
856    }
857
858 #ifdef HEIMDAL
859    problem = krb5_cc_copy_cache(kcontext, delegated_cred, ccache);
860 #else
861    problem = krb5_cc_copy_creds(kcontext, delegated_cred, ccache);
862 #endif
863    krb5_free_principal(kcontext, princ);
864    if (problem) {
865       snprintf(errstr, sizeof(errstr), "Failed to store credentials: %s",
866                krb5_get_err_text(kcontext, problem));
867       krb5_cc_destroy(kcontext, ccache);
868       return HTTP_INTERNAL_SERVER_ERROR;
869    }
870
871    krb5_cc_close(kcontext, ccache);
872    return OK;
873 }
874
875
876 static int
877 authenticate_user_krb5pwd(request_rec *r,
878                           kerb_auth_config *conf,
879                           const char *auth_line)
880 {
881    const char      *sent_pw = NULL; 
882    const char      *sent_name = NULL;
883    const char      *realms = NULL;
884    const char      *realm = NULL;
885    krb5_context    kcontext = NULL;
886    krb5_error_code code;
887    krb5_principal  client = NULL;
888    krb5_principal  server = NULL;
889    krb5_ccache     ccache = NULL;
890    krb5_keytab     keytab = NULL;
891    int             ret;
892    char            *name = NULL;
893    int             all_principals_unkown;
894    char            *p = NULL;
895
896    code = krb5_init_context(&kcontext);
897    if (code) {
898       log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
899                  "Cannot initialize Kerberos5 context (%d)", code);
900       return HTTP_INTERNAL_SERVER_ERROR;
901    }
902
903    sent_pw = ap_pbase64decode(r->pool, auth_line);
904    sent_name = ap_getword (r->pool, &sent_pw, ':');
905
906    if (sent_pw == NULL || *sent_pw == '\0') {
907       log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
908                  "empty passwords are not accepted");
909       ret = HTTP_UNAUTHORIZED;
910       goto end;
911    }
912
913    if (conf->krb_5_keytab)
914       krb5_kt_resolve(kcontext, conf->krb_5_keytab, &keytab);
915
916    if (conf->krb_service_name && strchr(conf->krb_service_name, '/') != NULL)
917       ret = krb5_parse_name (kcontext, conf->krb_service_name, &server);
918    else
919       ret = krb5_sname_to_principal(kcontext, ap_get_server_name(r),
920                                     (conf->krb_service_name) ? conf->krb_service_name : SERVICE_NAME,
921                                     KRB5_NT_SRV_HST, &server);
922
923    if (ret) {
924       log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
925                  "Error parsing server name (%s): %s",
926                  (conf->krb_service_name) ? conf->krb_service_name : SERVICE_NAME,
927                  krb5_get_err_text(kcontext, ret));
928       ret = HTTP_UNAUTHORIZED;
929       goto end;
930    }
931
932    code = krb5_unparse_name(kcontext, server, &name);
933    if (code) {
934       log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
935                  "krb5_unparse_name() failed: %s",
936                  krb5_get_err_text(kcontext, code));
937       ret = HTTP_UNAUTHORIZED;
938       goto end;
939    }
940    log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, "Using %s as server principal for password verification", name);
941    free(name);
942    name = NULL;
943
944    p = strchr(sent_name, '@');
945    if (p) {
946       *p++ = '\0';
947       if (conf->krb_auth_realms && !ap_find_token(r->pool, conf->krb_auth_realms, p)) {
948          log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
949                     "Specified realm `%s' not allowed by configuration", p);
950          ret = HTTP_UNAUTHORIZED;
951          goto end;
952       }
953    }
954
955    realms = (p) ? p : conf->krb_auth_realms;
956    all_principals_unkown = 1;
957    do {
958       name = (char *) sent_name;
959       if (realms && (realm = ap_getword_white(r->pool, &realms)))
960          name = apr_psprintf(r->pool, "%s@%s", sent_name, realm);
961
962       if (client) {
963          krb5_free_principal(kcontext, client);
964          client = NULL;
965       }
966
967       code = krb5_parse_name(kcontext, name, &client);
968       if (code) {
969          log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
970                     "krb5_parse_name() failed: %s",
971                     krb5_get_err_text(kcontext, code));
972          continue;
973       }
974
975       code = verify_krb5_user(r, kcontext, client, sent_pw,
976                               server, keytab, conf->krb_verify_kdc, &ccache);
977       if (!conf->krb_authoritative && code) {
978          /* if we're not authoritative, we allow authentication to pass on
979           * to another modules if (and only if) the user is not known to us */
980          if (all_principals_unkown && code != KRB5KDC_ERR_C_PRINCIPAL_UNKNOWN)
981             all_principals_unkown = 0;
982       }
983
984       if (code == 0)
985          break;
986
987       /* ap_getword_white() used above shifts the parameter, so it's not
988          needed to touch the realms variable */
989    } while (realms && *realms);
990
991    memset((char *)sent_pw, 0, strlen(sent_pw));
992
993    if (code) {
994       if (!conf->krb_authoritative && all_principals_unkown == 1 && code == KRB5KDC_ERR_C_PRINCIPAL_UNKNOWN)
995          ret = DECLINED;
996       else
997          ret = HTTP_UNAUTHORIZED;
998
999       goto end;
1000    }
1001
1002    code = krb5_unparse_name(kcontext, client, &name);
1003    if (code) {
1004       log_rerror(APLOG_MARK, APLOG_ERR, 0, r, "krb5_unparse_name() failed: %s",
1005                  krb5_get_err_text(kcontext, code));
1006       ret = HTTP_UNAUTHORIZED;
1007       goto end;
1008    }
1009    MK_USER = apr_pstrdup (r->pool, name);
1010    MK_AUTH_TYPE = "Basic";
1011    free(name);
1012
1013    if (conf->krb_save_credentials)
1014       store_krb5_creds(kcontext, r, conf, ccache);
1015
1016    ret = OK;
1017
1018 end:
1019    log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
1020               "kerb_authenticate_user_krb5pwd ret=%d user=%s authtype=%s",
1021               ret, (MK_USER)?MK_USER:"(NULL)", (MK_AUTH_TYPE)?MK_AUTH_TYPE:"(NULL)");
1022    if (client)
1023       krb5_free_principal(kcontext, client);
1024    if (server)
1025       krb5_free_principal(kcontext, server);
1026    if (ccache)
1027       krb5_cc_destroy(kcontext, ccache);
1028    if (keytab)
1029       krb5_kt_close(kcontext, keytab);
1030    krb5_free_context(kcontext);
1031
1032    return ret;
1033 }
1034
1035 /*********************************************************************
1036  * GSSAPI Authentication
1037  ********************************************************************/
1038
1039 static const char *
1040 get_gss_error(MK_POOL *p, OM_uint32 err_maj, OM_uint32 err_min, char *prefix)
1041 {
1042    OM_uint32 maj_stat, min_stat; 
1043    OM_uint32 msg_ctx = 0;
1044    gss_buffer_desc status_string;
1045    char *err_msg;
1046
1047    err_msg = apr_pstrdup(p, prefix);
1048    do {
1049       maj_stat = gss_display_status (&min_stat,
1050                                      err_maj,
1051                                      GSS_C_GSS_CODE,
1052                                      GSS_C_NO_OID,
1053                                      &msg_ctx,
1054                                      &status_string);
1055       if (GSS_ERROR(maj_stat))
1056          break;
1057       err_msg = apr_pstrcat(p, err_msg, ": ", (char*) status_string.value, NULL);
1058       gss_release_buffer(&min_stat, &status_string);
1059       
1060       maj_stat = gss_display_status (&min_stat,
1061                                      err_min,
1062                                      GSS_C_MECH_CODE,
1063                                      GSS_C_NULL_OID,
1064                                      &msg_ctx,
1065                                      &status_string);
1066       if (!GSS_ERROR(maj_stat)) {
1067          err_msg = apr_pstrcat(p, err_msg,
1068                               " (", (char*) status_string.value, ")", NULL);
1069          gss_release_buffer(&min_stat, &status_string);
1070       }
1071    } while (!GSS_ERROR(maj_stat) && msg_ctx != 0);
1072
1073    return err_msg;
1074 }
1075
1076 static int
1077 store_gss_creds(request_rec *r, kerb_auth_config *conf, char *princ_name,
1078                 gss_cred_id_t delegated_cred)
1079 {
1080    OM_uint32 maj_stat, min_stat;
1081    krb5_principal princ = NULL;
1082    krb5_ccache ccache = NULL;
1083    krb5_error_code problem;
1084    krb5_context context;
1085    int ret = HTTP_INTERNAL_SERVER_ERROR;
1086
1087    problem = krb5_init_context(&context);
1088    if (problem) {
1089       log_rerror(APLOG_MARK, APLOG_ERR, 0, r, "Cannot initialize krb5 context");
1090       return HTTP_INTERNAL_SERVER_ERROR;
1091    }
1092
1093    problem = krb5_parse_name(context, princ_name, &princ);
1094    if (problem) {
1095       log_rerror(APLOG_MARK, APLOG_ERR, 0, r, 
1096          "Cannot parse delegated username (%s)", krb5_get_err_text(context, problem));
1097       goto end;
1098    }
1099
1100    problem = create_krb5_ccache(context, r, conf, princ, &ccache);
1101    if (problem) {
1102       log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
1103          "Cannot create krb5 ccache (%s)", krb5_get_err_text(context, problem));
1104       goto end;
1105    }
1106
1107    maj_stat = gss_krb5_copy_ccache(&min_stat, delegated_cred, ccache);
1108    if (GSS_ERROR(maj_stat)) {
1109       log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
1110          "Cannot store delegated credential (%s)", 
1111          get_gss_error(r->pool, maj_stat, min_stat, "gss_krb5_copy_ccache"));
1112       goto end;
1113    }
1114
1115    krb5_cc_close(context, ccache);
1116    ccache = NULL;
1117    ret = 0;
1118
1119 end:
1120    if (princ)
1121       krb5_free_principal(context, princ);
1122    if (ccache)
1123       krb5_cc_destroy(context, ccache);
1124    krb5_free_context(context);
1125    return ret;
1126 }
1127
1128 static int
1129 get_gss_creds(request_rec *r,
1130               kerb_auth_config *conf,
1131               gss_cred_id_t *server_creds)
1132 {
1133    gss_buffer_desc token = GSS_C_EMPTY_BUFFER;
1134    OM_uint32 major_status, minor_status, minor_status2;
1135    gss_name_t server_name = GSS_C_NO_NAME;
1136    char buf[1024];
1137    int have_server_princ;
1138
1139
1140    have_server_princ = conf->krb_service_name && strchr(conf->krb_service_name, '/') != NULL;
1141    if (have_server_princ)
1142       strncpy(buf, conf->krb_service_name, sizeof(buf));
1143    else
1144       snprintf(buf, sizeof(buf), "%s@%s",
1145                (conf->krb_service_name) ? conf->krb_service_name : SERVICE_NAME,
1146                ap_get_server_name(r));
1147
1148    token.value = buf;
1149    token.length = strlen(buf) + 1;
1150
1151    major_status = gss_import_name(&minor_status, &token,
1152                                   (have_server_princ) ? GSS_KRB5_NT_PRINCIPAL_NAME : GSS_C_NT_HOSTBASED_SERVICE,
1153                                   &server_name);
1154    memset(&token, 0, sizeof(token));
1155    if (GSS_ERROR(major_status)) {
1156       log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
1157                  "%s", get_gss_error(r->pool, major_status, minor_status,
1158                  "gss_import_name() failed"));
1159       return HTTP_INTERNAL_SERVER_ERROR;
1160    }
1161
1162    major_status = gss_display_name(&minor_status, server_name, &token, NULL);
1163    if (GSS_ERROR(major_status)) {
1164       /* Perhaps we could just ignore this error but it's safer to give up now,
1165          I think */
1166       log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
1167                  "%s", get_gss_error(r->pool, major_status, minor_status,
1168                                      "gss_display_name() failed"));
1169       return HTTP_INTERNAL_SERVER_ERROR;
1170    }
1171
1172    log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, "Acquiring creds for %s",
1173               token.value);
1174    gss_release_buffer(&minor_status, &token);
1175    
1176    major_status = gss_acquire_cred(&minor_status, server_name, GSS_C_INDEFINITE,
1177                                    GSS_C_NO_OID_SET, GSS_C_ACCEPT,
1178                                    server_creds, NULL, NULL);
1179    gss_release_name(&minor_status2, &server_name);
1180    if (GSS_ERROR(major_status)) {
1181       log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
1182                  "%s", get_gss_error(r->pool, major_status, minor_status,
1183                                      "gss_acquire_cred() failed"));
1184       return HTTP_INTERNAL_SERVER_ERROR;
1185    }
1186
1187 #ifndef HEIMDAL
1188    /*
1189     * With MIT Kerberos 5 1.3.x the gss_cred_id_t is the same as
1190     * krb5_gss_cred_id_t and krb5_gss_cred_id_rec contains a pointer to
1191     * the replay cache.
1192     * This allows us to override the replay cache function vector with
1193     * our own one.
1194     * Note that this is a dirty hack to get things working and there may
1195     * well be unknown side-effects.
1196     */
1197    {
1198       krb5_gss_cred_id_t gss_creds = (krb5_gss_cred_id_t) *server_creds;
1199
1200       /* First we try to verify we are linked with 1.3.x to prevent from
1201          crashing when linked with 1.4.x */
1202       if (gss_creds && (gss_creds->usage == GSS_C_ACCEPT)) {
1203          if (gss_creds->rcache && gss_creds->rcache->ops &&
1204              gss_creds->rcache->ops->type &&  
1205              memcmp(gss_creds->rcache->ops->type, "dfl", 3) == 0)
1206           /* Override the rcache operations */
1207          gss_creds->rcache->ops = &mod_auth_kerb_rc_ops;
1208       }
1209    }
1210 #endif
1211    
1212    return 0;
1213 }
1214
1215 static int
1216 cmp_gss_type(gss_buffer_t token, gss_OID oid)
1217 {
1218    unsigned char *p;
1219    size_t len;
1220
1221    if (token->length == 0)
1222       return GSS_S_DEFECTIVE_TOKEN;
1223
1224    p = token->value;
1225    if (*p++ != 0x60)
1226       return GSS_S_DEFECTIVE_TOKEN;
1227    len = *p++;
1228    if (len & 0x80) {
1229       if ((len & 0x7f) > 4)
1230          return GSS_S_DEFECTIVE_TOKEN;
1231       p += len & 0x7f;
1232    }
1233    if (*p++ != 0x06)
1234       return GSS_S_DEFECTIVE_TOKEN;
1235
1236    if (((OM_uint32) *p++) != oid->length)
1237       return GSS_S_DEFECTIVE_TOKEN;
1238
1239    return memcmp(p, oid->elements, oid->length);
1240 }
1241
1242 static int
1243 authenticate_user_gss(request_rec *r, kerb_auth_config *conf,
1244                       const char *auth_line, char **negotiate_ret_value)
1245 {
1246   OM_uint32 major_status, minor_status, minor_status2;
1247   gss_buffer_desc input_token = GSS_C_EMPTY_BUFFER;
1248   gss_buffer_desc output_token = GSS_C_EMPTY_BUFFER;
1249   const char *auth_param = NULL;
1250   int ret;
1251   gss_name_t client_name = GSS_C_NO_NAME;
1252   gss_cred_id_t delegated_cred = GSS_C_NO_CREDENTIAL;
1253   OM_uint32 (KRB5_LIB_FUNCTION *accept_sec_token)
1254                          (OM_uint32 *, gss_ctx_id_t *, const gss_cred_id_t,
1255                          const gss_buffer_t, const gss_channel_bindings_t,
1256                          gss_name_t *, gss_OID *, gss_buffer_t, OM_uint32 *,
1257                          OM_uint32 *, gss_cred_id_t *);
1258   gss_OID_desc spnego_oid;
1259   gss_ctx_id_t context = GSS_C_NO_CONTEXT;
1260   gss_cred_id_t server_creds = GSS_C_NO_CREDENTIAL;
1261
1262   *negotiate_ret_value = "\0";
1263
1264   spnego_oid.length = 6;
1265   spnego_oid.elements = (void *)"\x2b\x06\x01\x05\x05\x02";
1266
1267   if (conf->krb_5_keytab) {
1268      char *ktname;
1269      /* we don't use the ap_* calls here, since the string passed to putenv()
1270       * will become part of the enviroment and shouldn't be free()ed by apache
1271       */
1272      ktname = malloc(strlen("KRB5_KTNAME=") + strlen(conf->krb_5_keytab) + 1);
1273      if (ktname == NULL) {
1274         log_rerror(APLOG_MARK, APLOG_ERR, 0, r, "malloc() failed: not enough memory");
1275         ret = HTTP_INTERNAL_SERVER_ERROR;
1276         goto end;
1277      }
1278      sprintf(ktname, "KRB5_KTNAME=%s", conf->krb_5_keytab);
1279      putenv(ktname);
1280 #ifdef HEIMDAL
1281      /* Seems to be also supported by latest MIT */
1282      gsskrb5_register_acceptor_identity(conf->krb_5_keytab);
1283 #endif
1284   }
1285
1286   ret = get_gss_creds(r, conf, &server_creds);
1287   if (ret)
1288      goto end;
1289
1290   /* ap_getword() shifts parameter */
1291   auth_param = ap_getword_white(r->pool, &auth_line);
1292   if (auth_param == NULL) {
1293      log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
1294                 "No Authorization parameter in request from client");
1295      ret = HTTP_UNAUTHORIZED;
1296      goto end;
1297   }
1298
1299   input_token.length = apr_base64_decode_len(auth_param) + 1;
1300   input_token.value = apr_pcalloc(r->connection->pool, input_token.length);
1301   if (input_token.value == NULL) {
1302      log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
1303                 "ap_pcalloc() failed (not enough memory)");
1304      ret = HTTP_INTERNAL_SERVER_ERROR;
1305      goto end;
1306   }
1307   input_token.length = apr_base64_decode(input_token.value, auth_param);
1308
1309 #ifdef GSSAPI_SUPPORTS_SPNEGO
1310   accept_sec_token = gss_accept_sec_context;
1311 #else
1312   accept_sec_token = (cmp_gss_type(&input_token, &spnego_oid) == 0) ?
1313                         gss_accept_sec_context_spnego : gss_accept_sec_context;
1314 #endif
1315
1316   log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, "Verifying client data using %s",
1317              (accept_sec_token == gss_accept_sec_context)
1318                ? "KRB5 GSS-API"
1319                : "SPNEGO GSS-API");
1320
1321   major_status = accept_sec_token(&minor_status,
1322                                   &context,
1323                                   server_creds,
1324                                   &input_token,
1325                                   GSS_C_NO_CHANNEL_BINDINGS,
1326                                   &client_name,
1327                                   NULL,
1328                                   &output_token,
1329                                   NULL,
1330                                   NULL,
1331                                   &delegated_cred);
1332   log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
1333              "Verification returned code %d", major_status);
1334   if (output_token.length) {
1335      char *token = NULL;
1336      size_t len;
1337      
1338      len = apr_base64_encode_len(output_token.length) + 1;
1339      token = apr_pcalloc(r->connection->pool, len + 1);
1340      if (token == NULL) {
1341         log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
1342                    "ap_pcalloc() failed (not enough memory)");
1343         ret = HTTP_INTERNAL_SERVER_ERROR;
1344         gss_release_buffer(&minor_status2, &output_token);
1345         goto end;
1346      }
1347      apr_base64_encode(token, output_token.value, output_token.length);
1348      token[len] = '\0';
1349      *negotiate_ret_value = token;
1350      log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
1351                 "GSS-API token of length %d bytes will be sent back",
1352                 output_token.length);
1353      gss_release_buffer(&minor_status2, &output_token);
1354      set_kerb_auth_headers(r, conf, 0, 0, *negotiate_ret_value);
1355   }
1356
1357   if (GSS_ERROR(major_status)) {
1358      if (input_token.length > 7 && memcmp(input_token.value, "NTLMSSP", 7) == 0)
1359         log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
1360                   "Warning: received token seems to be NTLM, which isn't supported by the Kerberos module. Check your IE configuration.");
1361
1362      log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
1363                 "%s", get_gss_error(r->pool, major_status, minor_status,
1364                                     "gss_accept_sec_context() failed"));
1365      /* Don't offer the Negotiate method again if call to GSS layer failed */
1366      *negotiate_ret_value = NULL;
1367      ret = HTTP_UNAUTHORIZED;
1368      goto end;
1369   }
1370
1371 #if 0
1372   /* This is a _Kerberos_ module so multiple authentication rounds aren't
1373    * supported. If we wanted a generic GSS authentication we would have to do
1374    * some magic with exporting context etc. */
1375   if (major_status & GSS_S_CONTINUE_NEEDED) {
1376      ret = HTTP_UNAUTHORIZED;
1377      goto end;
1378   }
1379 #endif
1380
1381   major_status = gss_display_name(&minor_status, client_name, &output_token, NULL);
1382   gss_release_name(&minor_status, &client_name); 
1383   if (GSS_ERROR(major_status)) {
1384     log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
1385                "%s", get_gss_error(r->pool, major_status, minor_status,
1386                                    "gss_display_name() failed"));
1387     ret = HTTP_INTERNAL_SERVER_ERROR;
1388     goto end;
1389   }
1390
1391   MK_AUTH_TYPE = MECH_NEGOTIATE;
1392   MK_USER = apr_pstrdup(r->pool, output_token.value);
1393
1394   if (conf->krb_save_credentials && delegated_cred != GSS_C_NO_CREDENTIAL)
1395      store_gss_creds(r, conf, (char *)output_token.value, delegated_cred);
1396
1397   gss_release_buffer(&minor_status, &output_token);
1398
1399   ret = OK;
1400
1401 end:
1402   if (delegated_cred)
1403      gss_release_cred(&minor_status, &delegated_cred);
1404
1405   if (output_token.length) 
1406      gss_release_buffer(&minor_status, &output_token);
1407
1408   if (client_name != GSS_C_NO_NAME)
1409      gss_release_name(&minor_status, &client_name);
1410
1411   if (server_creds != GSS_C_NO_CREDENTIAL)
1412      gss_release_cred(&minor_status, &server_creds);
1413
1414   if (context != GSS_C_NO_CONTEXT)
1415      gss_delete_sec_context(&minor_status, &context, GSS_C_NO_BUFFER);
1416
1417   return ret;
1418 }
1419 #endif /* KRB5 */
1420
1421 static int
1422 already_succeeded(request_rec *r)
1423 {
1424    if (ap_is_initial_req(r) || MK_AUTH_TYPE == NULL)
1425       return 0;
1426    if (strcmp(MK_AUTH_TYPE, MECH_NEGOTIATE) ||
1427        (strcmp(MK_AUTH_TYPE, "Basic") && strchr(MK_USER, '@')))
1428       return 1;
1429    return 0;
1430 }
1431
1432 static void
1433 set_kerb_auth_headers(request_rec *r, const kerb_auth_config *conf,
1434                       int use_krb4, int use_krb5pwd, char *negotiate_ret_value)
1435 {
1436    const char *auth_name = NULL;
1437    int set_basic = 0;
1438    char *negoauth_param;
1439    const char *header_name = 
1440       (r->proxyreq == PROXYREQ_PROXY) ? "Proxy-Authenticate" : "WWW-Authenticate";
1441
1442    /* get the user realm specified in .htaccess */
1443    auth_name = ap_auth_name(r);
1444
1445    /* XXX should the WWW-Authenticate header be cleared first?
1446     * apache in the proxy mode should retain client's authN headers? */
1447 #ifdef KRB5
1448    if (negotiate_ret_value != NULL && conf->krb_method_gssapi) {
1449       negoauth_param = (*negotiate_ret_value == '\0') ? MECH_NEGOTIATE :
1450                   apr_pstrcat(r->pool, MECH_NEGOTIATE " ", negotiate_ret_value, NULL);
1451       apr_table_add(r->err_headers_out, header_name, negoauth_param);
1452    }
1453    if ((use_krb5pwd && conf->krb_method_k5pass) || conf->krb_delegate_basic) {
1454       apr_table_add(r->err_headers_out, header_name,
1455                    apr_pstrcat(r->pool, "Basic realm=\"", auth_name, "\"", NULL));
1456       set_basic = 1;
1457    }
1458 #endif
1459
1460 #ifdef KRB4
1461    if (!set_basic && 
1462        ((use_krb4 && conf->krb_method_k4pass) || conf->krb_delegate_basic))
1463       apr_table_add(r->err_headers_out, header_name,
1464                   apr_pstrcat(r->pool, "Basic realm=\"", auth_name, "\"", NULL));
1465 #endif
1466 }
1467
1468 static int
1469 kerb_authenticate_user(request_rec *r)
1470 {
1471    kerb_auth_config *conf = 
1472       (kerb_auth_config *) ap_get_module_config(r->per_dir_config,
1473                                                 &auth_kerb_module);
1474    const char *auth_type = NULL;
1475    const char *auth_line = NULL;
1476    const char *type = NULL;
1477    int use_krb5 = 0, use_krb4 = 0;
1478    int ret;
1479    static int last_return = HTTP_UNAUTHORIZED;
1480    char *negotiate_ret_value = NULL;
1481
1482    /* get the type specified in .htaccess */
1483    type = ap_auth_type(r);
1484
1485    log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
1486               "kerb_authenticate_user entered with user %s and auth_type %s",
1487               (MK_USER)?MK_USER:"(NULL)",type?type:"(NULL)");
1488
1489    if (type && strcasecmp(type, "Kerberos") == 0)
1490       use_krb5 = use_krb4 = 1;
1491    else if(type && strcasecmp(type, "KerberosV5") == 0)
1492       use_krb5 = 1;
1493    else if(type && strcasecmp(type, "KerberosV4") == 0)
1494       use_krb4 = 1;
1495    else
1496       return DECLINED;
1497
1498 #if 0
1499    if (conf->krb_ssl_preauthentication) {
1500       const char *ssl_client_verify = ssl_var_lookup(r->pool, r->server,
1501                 r->connection, r, "SSL_CLIENT_VERIFY");
1502
1503       if (ssl_client_verify && strcmp(ssl_client_verify, "SUCCESS") == 0)
1504          return OK;
1505    }
1506 #endif
1507
1508    /* get what the user sent us in the HTTP header */
1509    auth_line = MK_TABLE_GET(r->headers_in, (r->proxyreq == PROXYREQ_PROXY)
1510                                             ? "Proxy-Authorization"
1511                                             : "Authorization");
1512    if (!auth_line) {
1513       set_kerb_auth_headers(r, conf, use_krb4, use_krb5, 
1514                             (use_krb5) ? "\0" : NULL);
1515       return HTTP_UNAUTHORIZED;
1516    }
1517    auth_type = ap_getword_white(r->pool, &auth_line);
1518
1519    /* If we are delegating Basic to other modules, DECLINE the request */
1520    if (conf->krb_delegate_basic &&
1521 #ifdef KRB5
1522        !conf->krb_method_k5pass &&
1523 #endif
1524 #ifdef KRB4
1525        !conf->krb_method_k4pass &&
1526 #endif
1527        (strcasecmp(auth_type, "Basic") == 0))
1528        return DECLINED;
1529
1530    if (already_succeeded(r))
1531       return last_return;
1532
1533    ret = HTTP_UNAUTHORIZED;
1534
1535 #ifdef KRB5
1536    if (use_krb5 && conf->krb_method_gssapi &&
1537        strcasecmp(auth_type, MECH_NEGOTIATE) == 0) {
1538       ret = authenticate_user_gss(r, conf, auth_line, &negotiate_ret_value);
1539    } else if (use_krb5 && conf->krb_method_k5pass &&
1540               strcasecmp(auth_type, "Basic") == 0) {
1541        ret = authenticate_user_krb5pwd(r, conf, auth_line);
1542    }
1543 #endif
1544
1545 #ifdef KRB4
1546    if (ret == HTTP_UNAUTHORIZED && use_krb4 && conf->krb_method_k4pass &&
1547        strcasecmp(auth_type, "Basic") == 0)
1548       ret = authenticate_user_krb4pwd(r, conf, auth_line);
1549 #endif
1550
1551    if (ret == HTTP_UNAUTHORIZED)
1552       set_kerb_auth_headers(r, conf, use_krb4, use_krb5, negotiate_ret_value);
1553
1554    /* XXX log_debug: if ret==OK, log(user XY authenticated) */
1555
1556    last_return = ret;
1557    return ret;
1558 }
1559
1560 int
1561 have_rcache_type(const char *type)
1562 {
1563    krb5_error_code ret;
1564    krb5_context context;
1565    krb5_rcache id = NULL;
1566    int found;
1567
1568    ret = krb5_init_context(&context);
1569    if (ret)
1570       return 0;
1571
1572    ret = krb5_rc_resolve_full(context, &id, "none:");
1573    found = (ret == 0);
1574
1575    if (ret == 0)
1576       krb5_rc_destroy(context, id);
1577    krb5_free_context(context);
1578
1579    return found;
1580 }
1581
1582 /*************************************************************************** 
1583  Module Setup/Configuration
1584  ***************************************************************************/
1585 #ifndef STANDARD20_MODULE_STUFF
1586 static void
1587 kerb_module_init(server_rec *dummy, pool *p)
1588 {
1589 #ifndef HEIMDAL
1590    /* Suppress the MIT replay cache.  Requires MIT Kerberos 1.4.0 or later.
1591       1.3.x are covered by the hack overiding the replay calls */
1592    if (getenv("KRB5RCACHETYPE") == NULL && have_rcache_type("none"))
1593       putenv(strdup("KRB5RCACHETYPE=none"));
1594 #endif
1595 }
1596
1597 module MODULE_VAR_EXPORT auth_kerb_module = {
1598         STANDARD_MODULE_STUFF,
1599         kerb_module_init,               /*      module initializer            */
1600         kerb_dir_create_config,         /*      per-directory config creator  */
1601         NULL,                           /*      per-directory config merger   */
1602         NULL,                           /*      per-server    config creator  */
1603         NULL,                           /*      per-server    config merger   */
1604         kerb_auth_cmds,                 /*      command table                 */
1605         NULL,                           /* [ 9] content handlers              */
1606         NULL,                           /* [ 2] URI-to-filename translation   */
1607         kerb_authenticate_user,         /* [ 5] check/validate user_id        */
1608         NULL,                           /* [ 6] check user_id is valid *here* */
1609         NULL,                           /* [ 4] check access by host address  */
1610         NULL,                           /* [ 7] MIME type checker/setter      */
1611         NULL,                           /* [ 8] fixups                        */
1612         NULL,                           /* [10] logger                        */
1613         NULL,                           /* [ 3] header parser                 */
1614         NULL,                           /*      process initialization        */
1615         NULL,                           /*      process exit/cleanup          */
1616         NULL                            /* [ 1] post read_request handling    */
1617 #ifdef EAPI
1618        ,NULL,                           /* EAPI: add_module                   */
1619         NULL,                           /* EAPI: remove_module                */
1620         NULL,                           /* EAPI: rewrite_command              */
1621         NULL                            /* EAPI: new_connection               */
1622 #endif
1623 };
1624 #else
1625 static int
1626 kerb_init_handler(apr_pool_t *p, apr_pool_t *plog,
1627                   apr_pool_t *ptemp, server_rec *s)
1628 {
1629    ap_add_version_component(p, "mod_auth_kerb/" MODAUTHKERB_VERSION);
1630 #ifndef HEIMDAL
1631    /* Suppress the MIT replay cache.  Requires MIT Kerberos 1.4.0 or later.
1632       1.3.x are covered by the hack overiding the replay calls */
1633    if (getenv("KRB5RCACHETYPE") == NULL && have_rcache_type("none"))
1634       putenv(strdup("KRB5RCACHETYPE=none"));
1635 #endif
1636    
1637    return OK;
1638 }
1639
1640 static void
1641 kerb_register_hooks(apr_pool_t *p)
1642 {
1643    ap_hook_post_config(kerb_init_handler, NULL, NULL, APR_HOOK_MIDDLE);
1644    ap_hook_check_user_id(kerb_authenticate_user, NULL, NULL, APR_HOOK_MIDDLE);
1645 }
1646
1647 module AP_MODULE_DECLARE_DATA auth_kerb_module =
1648 {
1649    STANDARD20_MODULE_STUFF,
1650    kerb_dir_create_config,      /* create per-dir    conf structures  */
1651    NULL,                        /* merge  per-dir    conf structures  */
1652    NULL,                        /* create per-server conf structures  */
1653    NULL,                        /* merge  per-server conf structures  */
1654    kerb_auth_cmds,              /* table of configuration directives  */
1655    kerb_register_hooks          /* register hooks                     */
1656 };
1657 #endif