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