Better r.e. to prevent from substituing empty strings on some platforms
[mod_auth_kerb.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 static 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,
686                  const char *krb_service_name, krb5_ccache *ccache)
687 {
688    krb5_creds creds;
689    krb5_get_init_creds_opt options;
690    krb5_error_code ret;
691    krb5_ccache ret_ccache = NULL;
692    char *name = NULL;
693    krb5_keytab_entry entry;
694    krb5_kt_cursor cursor;
695
696    /* XXX error messages shouldn't be logged here (and in the while() loop in
697     * authenticate_user_krb5pwd() as weell), in order to avoid confusing log
698     * entries when using multiple realms */
699
700    memset(&creds, 0, sizeof(creds));
701
702    ret = krb5_unparse_name(context, principal, &name);
703    if (ret == 0) {
704       log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
705                  "Trying to get TGT for user %s", name);
706       free(name);
707    }
708
709    krb5_get_init_creds_opt_init(&options);
710    ret = krb5_get_init_creds_password(context, &creds, principal, 
711                                       (char *)password, NULL,
712                                       NULL, 0, NULL, &options);
713    if (ret) {
714       log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
715                  "krb5_get_init_creds_password() failed: %s",
716                  krb5_get_err_text(context, ret));
717       goto end;
718    }
719
720    /* XXX
721    {
722       char *realm;
723
724       krb5_get_default_realm(context, &realm);
725       log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
726                  "trying to verify password using key for %s/%s@%s",
727                  service, ap_get_server_name(r), realm);
728    }
729    */
730
731    /*if (krb_verify_kdc &&
732        (ret = verify_krb5_init_creds(r, context, &creds, server, keytab))) {
733        log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
734                   "failed to verify krb5 credentials: %s",
735                   krb5_get_err_text(context, ret));
736        goto end;
737    }*/
738
739    if (krb_verify_kdc) {
740      if (krb_service_name && strcmp(krb_service_name,"Any") == 0) {
741        ret = krb5_kt_start_seq_get(context, keytab, &cursor);
742        if(!ret) {
743          while((krb5_kt_next_entry(context, keytab, &entry, &cursor)) == 0){
744            if ((ret = verify_krb5_init_creds(r, context, &creds, entry.principal, keytab)) == 0) 
745              break;
746          }
747        }
748        if (ret) {
749          log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
750                     "failed to verify krb5 credentials: %s",
751                           krb5_get_err_text(context, ret));
752          krb5_kt_end_seq_get(context, keytab, &cursor);
753          krb5_kt_close(context, keytab);
754          goto end;
755        }
756        krb5_kt_end_seq_get(context, keytab, &cursor);
757        krb5_kt_close(context, keytab);
758      }
759      else {
760        if ((ret = verify_krb5_init_creds(r, context, &creds, server, keytab))) {
761        log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
762                   "failed to verify krb5 credentials: %s",
763                   krb5_get_err_text(context, ret));
764        goto end;
765        }
766      }
767    }
768
769 #ifdef HAVE_KRB5_CC_NEW_UNIQUE
770    ret = krb5_cc_new_unique(context, "MEMORY", NULL, &ret_ccache);
771 #else
772    ret = krb5_cc_resolve(context, "MEMORY:", &ret_ccache);
773 #endif
774
775    if (ret) {
776       log_rerror(APLOG_MARK, APLOG_ERR, 0, r, 
777                  "generating new memory ccache failed: %s",
778                  krb5_get_err_text(context, ret));
779       goto end;
780    }
781
782    ret = krb5_cc_initialize(context, ret_ccache, principal);
783    if (ret) {
784       log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
785                  "krb5_cc_initialize() failed: %s",
786                  krb5_get_err_text(context, ret));
787       goto end;
788    }
789
790    ret = krb5_cc_store_cred(context, ret_ccache, &creds);
791    if (ret) {
792       log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
793                  "krb5_cc_store_cred() failed: %s",
794                  krb5_get_err_text(context, ret));
795       goto end;
796    }
797    *ccache = ret_ccache;
798    ret_ccache = NULL;
799
800 end:
801    krb5_free_cred_contents(context, &creds);
802    if (ret_ccache)
803       krb5_cc_destroy(context, ret_ccache);
804
805    return ret;
806 }
807
808 static int
809 krb5_cache_cleanup(void *data)
810 {
811    krb5_context context;
812    krb5_ccache  cache;
813    krb5_error_code problem;
814    char *cache_name = (char *) data;
815
816    problem = krb5_init_context(&context);
817    if (problem) {
818       /* ap_log_error(APLOG_MARK, APLOG_ERR, 0, NULL, "krb5_init_context() failed"); */
819       return HTTP_INTERNAL_SERVER_ERROR;
820    }
821
822    problem = krb5_cc_resolve(context, cache_name, &cache);
823    if (problem) {
824       /* log_error(APLOG_MARK, APLOG_ERR, 0, NULL, 
825                 "krb5_cc_resolve() failed (%s: %s)",
826                 cache_name, krb5_get_err_text(context, problem)); */
827       return HTTP_INTERNAL_SERVER_ERROR;
828    }
829
830    krb5_cc_destroy(context, cache);
831    krb5_free_context(context);
832    return OK;
833 }
834
835 static int
836 create_krb5_ccache(krb5_context kcontext,
837                    request_rec *r,
838                    kerb_auth_config *conf,
839                    krb5_principal princ,
840                    krb5_ccache *ccache)
841 {
842    char *ccname;
843    int fd;
844    krb5_error_code problem;
845    int ret;
846    krb5_ccache tmp_ccache = NULL;
847
848    ccname = apr_psprintf(r->pool, "FILE:%s/krb5cc_apache_XXXXXX", P_tmpdir);
849    fd = mkstemp(ccname + strlen("FILE:"));
850    if (fd < 0) {
851       log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
852                  "mkstemp() failed: %s", strerror(errno));
853       ret = HTTP_INTERNAL_SERVER_ERROR;
854       goto end;
855    }
856    close(fd);
857
858    problem = krb5_cc_resolve(kcontext, ccname, &tmp_ccache);
859    if (problem) {
860       log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
861                  "krb5_cc_resolve() failed: %s",
862                  krb5_get_err_text(kcontext, problem));
863       ret = HTTP_INTERNAL_SERVER_ERROR;
864       unlink(ccname);
865       goto end;
866    }
867
868    problem = krb5_cc_initialize(kcontext, tmp_ccache, princ);
869    if (problem) {
870       log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
871                  "Cannot initialize krb5 ccache %s: krb5_cc_initialize() failed: %s",
872                  ccname, krb5_get_err_text(kcontext, problem));
873       ret = HTTP_INTERNAL_SERVER_ERROR;
874       goto end;
875    }
876
877    apr_table_setn(r->subprocess_env, "KRB5CCNAME", ccname);
878    apr_pool_cleanup_register(r->pool, ccname, krb5_cache_cleanup,
879                              apr_pool_cleanup_null);
880
881    *ccache = tmp_ccache;
882    tmp_ccache = NULL;
883
884    ret = OK;
885
886 end:
887    if (tmp_ccache)
888       krb5_cc_destroy(kcontext, tmp_ccache);
889
890    return ret;
891 }
892
893 static int
894 store_krb5_creds(krb5_context kcontext,
895                  request_rec *r,
896                  kerb_auth_config *conf,
897                  krb5_ccache delegated_cred)
898 {
899    char errstr[1024];
900    krb5_error_code problem;
901    krb5_principal princ;
902    krb5_ccache ccache;
903    int ret;
904
905    problem = krb5_cc_get_principal(kcontext, delegated_cred, &princ);
906    if (problem) {
907       snprintf(errstr, sizeof(errstr), "krb5_cc_get_principal() failed: %s",
908                krb5_get_err_text(kcontext, problem));
909       return HTTP_INTERNAL_SERVER_ERROR;
910    }
911
912    ret = create_krb5_ccache(kcontext, r, conf, princ, &ccache);
913    if (ret) {
914       krb5_free_principal(kcontext, princ);
915       return ret;
916    }
917
918 #ifdef HEIMDAL
919    problem = krb5_cc_copy_cache(kcontext, delegated_cred, ccache);
920 #else
921    problem = krb5_cc_copy_creds(kcontext, delegated_cred, ccache);
922 #endif
923    krb5_free_principal(kcontext, princ);
924    if (problem) {
925       snprintf(errstr, sizeof(errstr), "Failed to store credentials: %s",
926                krb5_get_err_text(kcontext, problem));
927       krb5_cc_destroy(kcontext, ccache);
928       return HTTP_INTERNAL_SERVER_ERROR;
929    }
930
931    krb5_cc_close(kcontext, ccache);
932    return OK;
933 }
934
935 static int
936 authenticate_user_krb5pwd(request_rec *r,
937                           kerb_auth_config *conf,
938                           const char *auth_line)
939 {
940    const char      *sent_pw = NULL; 
941    const char      *sent_name = NULL;
942    const char      *realms = NULL;
943    const char      *realm = NULL;
944    krb5_context    kcontext = NULL;
945    krb5_error_code code;
946    krb5_principal  client = NULL;
947    krb5_principal  server = NULL;
948    krb5_ccache     ccache = NULL;
949    krb5_keytab     keytab = NULL;
950    int             ret;
951    char            *name = NULL;
952    int             all_principals_unkown;
953    char            *p = NULL;
954
955    code = krb5_init_context(&kcontext);
956    if (code) {
957       log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
958                  "Cannot initialize Kerberos5 context (%d)", code);
959       return HTTP_INTERNAL_SERVER_ERROR;
960    }
961
962    sent_pw = ap_pbase64decode(r->pool, auth_line);
963    sent_name = ap_getword_nulls_nc (r->pool, (char **) &sent_pw, ':');
964
965    if (sent_pw == NULL || *sent_pw == '\0') {
966       log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
967                  "empty passwords are not accepted");
968       ret = HTTP_UNAUTHORIZED;
969       goto end;
970    }
971
972    if (conf->krb_5_keytab)
973       krb5_kt_resolve(kcontext, conf->krb_5_keytab, &keytab);
974
975    if (conf->krb_service_name && strchr(conf->krb_service_name, '/') != NULL)
976       ret = krb5_parse_name (kcontext, conf->krb_service_name, &server);
977    else
978       ret = krb5_sname_to_principal(kcontext, ap_get_server_name(r),
979                                     (conf->krb_service_name) ? conf->krb_service_name : SERVICE_NAME,
980                                     KRB5_NT_SRV_HST, &server);
981
982    if (ret) {
983       log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
984                  "Error parsing server name (%s): %s",
985                  (conf->krb_service_name) ? conf->krb_service_name : SERVICE_NAME,
986                  krb5_get_err_text(kcontext, ret));
987       ret = HTTP_UNAUTHORIZED;
988       goto end;
989    }
990
991    code = krb5_unparse_name(kcontext, server, &name);
992    if (code) {
993       log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
994                  "krb5_unparse_name() failed: %s",
995                  krb5_get_err_text(kcontext, code));
996       ret = HTTP_UNAUTHORIZED;
997       goto end;
998    }
999    log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, "Using %s as server principal for password verification", name);
1000    free(name);
1001    name = NULL;
1002
1003    p = strchr(sent_name, '@');
1004    if (p) {
1005       *p++ = '\0';
1006       if (conf->krb_auth_realms && !ap_find_token(r->pool, conf->krb_auth_realms, p)) {
1007          log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
1008                     "Specified realm `%s' not allowed by configuration", p);
1009          ret = HTTP_UNAUTHORIZED;
1010          goto end;
1011       }
1012    }
1013
1014    realms = (p) ? p : conf->krb_auth_realms;
1015    all_principals_unkown = 1;
1016    do {
1017       name = (char *) sent_name;
1018       if (realms && (realm = ap_getword_white(r->pool, &realms)))
1019          name = apr_psprintf(r->pool, "%s@%s", sent_name, realm);
1020
1021       if (client) {
1022          krb5_free_principal(kcontext, client);
1023          client = NULL;
1024       }
1025
1026       code = krb5_parse_name(kcontext, name, &client);
1027       if (code) {
1028          log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
1029                     "krb5_parse_name() failed: %s",
1030                     krb5_get_err_text(kcontext, code));
1031          continue;
1032       }
1033
1034       code = verify_krb5_user(r, kcontext, client, sent_pw,
1035                               server, keytab, conf->krb_verify_kdc, conf->krb_service_name, &ccache);
1036       if (!conf->krb_authoritative && code) {
1037          /* if we're not authoritative, we allow authentication to pass on
1038           * to another modules if (and only if) the user is not known to us */
1039          if (all_principals_unkown && code != KRB5KDC_ERR_C_PRINCIPAL_UNKNOWN)
1040             all_principals_unkown = 0;
1041       }
1042
1043       if (code == 0)
1044          break;
1045
1046       /* ap_getword_white() used above shifts the parameter, so it's not
1047          needed to touch the realms variable */
1048    } while (realms && *realms);
1049
1050    memset((char *)sent_pw, 0, strlen(sent_pw));
1051
1052    if (code) {
1053       if (!conf->krb_authoritative && all_principals_unkown == 1 && code == KRB5KDC_ERR_C_PRINCIPAL_UNKNOWN)
1054          ret = DECLINED;
1055       else
1056          ret = HTTP_UNAUTHORIZED;
1057
1058       goto end;
1059    }
1060
1061    code = krb5_unparse_name(kcontext, client, &name);
1062    if (code) {
1063       log_rerror(APLOG_MARK, APLOG_ERR, 0, r, "krb5_unparse_name() failed: %s",
1064                  krb5_get_err_text(kcontext, code));
1065       ret = HTTP_UNAUTHORIZED;
1066       goto end;
1067    }
1068    MK_USER = apr_pstrdup (r->pool, name);
1069    MK_AUTH_TYPE = "Kerberos";
1070    free(name);
1071
1072    if (conf->krb_save_credentials)
1073       store_krb5_creds(kcontext, r, conf, ccache);
1074
1075    ret = OK;
1076
1077 end:
1078    log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
1079               "kerb_authenticate_user_krb5pwd ret=%d user=%s authtype=%s",
1080               ret, (MK_USER)?MK_USER:"(NULL)", (MK_AUTH_TYPE)?MK_AUTH_TYPE:"(NULL)");
1081    if (client)
1082       krb5_free_principal(kcontext, client);
1083    if (server)
1084       krb5_free_principal(kcontext, server);
1085    if (ccache)
1086       krb5_cc_destroy(kcontext, ccache);
1087    if (keytab)
1088       krb5_kt_close(kcontext, keytab);
1089    krb5_free_context(kcontext);
1090
1091    return ret;
1092 }
1093
1094 /*********************************************************************
1095  * GSSAPI Authentication
1096  ********************************************************************/
1097
1098 static const char *
1099 get_gss_error(request_rec *r, OM_uint32 err_maj, OM_uint32 err_min, char *prefix)
1100 {
1101    OM_uint32 maj_stat, min_stat; 
1102    OM_uint32 msg_ctx = 0;
1103    gss_buffer_desc status_string;
1104    char *err_msg;
1105
1106    log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
1107               "GSS-API major_status:%8.8x, minor_status:%8.8x",
1108               err_maj, err_min);
1109
1110    err_msg = apr_pstrdup(r->pool, prefix);
1111    do {
1112       maj_stat = gss_display_status (&min_stat,
1113                                      err_maj,
1114                                      GSS_C_GSS_CODE,
1115                                      GSS_C_NO_OID,
1116                                      &msg_ctx,
1117                                      &status_string);
1118       if (!GSS_ERROR(maj_stat)) {
1119          err_msg = apr_pstrcat(r->pool, err_msg, ": ",
1120                                (char*) status_string.value, NULL);
1121          gss_release_buffer(&min_stat, &status_string);
1122       }
1123    } while (!GSS_ERROR(maj_stat) && msg_ctx != 0);
1124
1125    msg_ctx = 0;
1126    err_msg = apr_pstrcat(r->pool, err_msg, " (", NULL);
1127    do {
1128       maj_stat = gss_display_status (&min_stat,
1129                                      err_min,
1130                                      GSS_C_MECH_CODE,
1131                                      GSS_C_NULL_OID,
1132                                      &msg_ctx,
1133                                      &status_string);
1134       if (!GSS_ERROR(maj_stat)) {
1135          err_msg = apr_pstrcat(r->pool, err_msg, ", ",
1136                                (char *) status_string.value, NULL);
1137          gss_release_buffer(&min_stat, &status_string);
1138       }
1139    } while (!GSS_ERROR(maj_stat) && msg_ctx != 0);
1140    err_msg = apr_pstrcat(r->pool, err_msg, ")", NULL);
1141
1142    return err_msg;
1143 }
1144
1145 static int
1146 store_gss_creds(request_rec *r, kerb_auth_config *conf, char *princ_name,
1147                 gss_cred_id_t delegated_cred)
1148 {
1149    OM_uint32 maj_stat, min_stat;
1150    krb5_principal princ = NULL;
1151    krb5_ccache ccache = NULL;
1152    krb5_error_code problem;
1153    krb5_context context;
1154    int ret = HTTP_INTERNAL_SERVER_ERROR;
1155
1156    problem = krb5_init_context(&context);
1157    if (problem) {
1158       log_rerror(APLOG_MARK, APLOG_ERR, 0, r, "Cannot initialize krb5 context");
1159       return HTTP_INTERNAL_SERVER_ERROR;
1160    }
1161
1162    problem = krb5_parse_name(context, princ_name, &princ);
1163    if (problem) {
1164       log_rerror(APLOG_MARK, APLOG_ERR, 0, r, 
1165          "Cannot parse delegated username (%s)", krb5_get_err_text(context, problem));
1166       goto end;
1167    }
1168
1169    problem = create_krb5_ccache(context, r, conf, princ, &ccache);
1170    if (problem) {
1171       log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
1172          "Cannot create krb5 ccache (%s)", krb5_get_err_text(context, problem));
1173       goto end;
1174    }
1175
1176    maj_stat = gss_krb5_copy_ccache(&min_stat, delegated_cred, ccache);
1177    if (GSS_ERROR(maj_stat)) {
1178       log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
1179          "Cannot store delegated credential (%s)", 
1180          get_gss_error(r, maj_stat, min_stat, "gss_krb5_copy_ccache"));
1181       goto end;
1182    }
1183
1184    krb5_cc_close(context, ccache);
1185    ccache = NULL;
1186    ret = 0;
1187
1188 end:
1189    if (princ)
1190       krb5_free_principal(context, princ);
1191    if (ccache)
1192       krb5_cc_destroy(context, ccache);
1193    krb5_free_context(context);
1194    return ret;
1195 }
1196
1197 static int
1198 get_gss_creds(request_rec *r,
1199               kerb_auth_config *conf,
1200               gss_cred_id_t *server_creds)
1201 {
1202    gss_buffer_desc token = GSS_C_EMPTY_BUFFER;
1203    OM_uint32 major_status, minor_status, minor_status2;
1204    gss_name_t server_name = GSS_C_NO_NAME;
1205    char buf[1024];
1206    int have_server_princ;
1207
1208
1209    have_server_princ = conf->krb_service_name && strchr(conf->krb_service_name, '/') != NULL;
1210    if (have_server_princ)
1211       strncpy(buf, conf->krb_service_name, sizeof(buf));
1212    else if (conf->krb_service_name && strcmp(conf->krb_service_name,"Any") == 0) {      
1213       *server_creds = GSS_C_NO_CREDENTIAL;
1214       return 0;
1215    }
1216    else
1217       snprintf(buf, sizeof(buf), "%s@%s",
1218                (conf->krb_service_name) ? conf->krb_service_name : SERVICE_NAME,
1219                ap_get_server_name(r));
1220
1221    token.value = buf;
1222    token.length = strlen(buf) + 1;
1223
1224    major_status = gss_import_name(&minor_status, &token,
1225                                   (have_server_princ) ? (gss_OID) GSS_KRB5_NT_PRINCIPAL_NAME : (gss_OID) GSS_C_NT_HOSTBASED_SERVICE,
1226                                   &server_name);
1227    memset(&token, 0, sizeof(token));
1228    if (GSS_ERROR(major_status)) {
1229       log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
1230                  "%s", get_gss_error(r, major_status, minor_status,
1231                  "gss_import_name() failed"));
1232       return HTTP_INTERNAL_SERVER_ERROR;
1233    }
1234
1235    major_status = gss_display_name(&minor_status, server_name, &token, NULL);
1236    if (GSS_ERROR(major_status)) {
1237       /* Perhaps we could just ignore this error but it's safer to give up now,
1238          I think */
1239       log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
1240                  "%s", get_gss_error(r, major_status, minor_status,
1241                                      "gss_display_name() failed"));
1242       return HTTP_INTERNAL_SERVER_ERROR;
1243    }
1244
1245    log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, "Acquiring creds for %s",
1246               token.value);
1247    gss_release_buffer(&minor_status, &token);
1248    
1249    major_status = gss_acquire_cred(&minor_status, server_name, GSS_C_INDEFINITE,
1250                                    GSS_C_NO_OID_SET, GSS_C_ACCEPT,
1251                                    server_creds, NULL, NULL);
1252    gss_release_name(&minor_status2, &server_name);
1253    if (GSS_ERROR(major_status)) {
1254       log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
1255                  "%s", get_gss_error(r, major_status, minor_status,
1256                                      "gss_acquire_cred() failed"));
1257       return HTTP_INTERNAL_SERVER_ERROR;
1258    }
1259
1260 #ifndef HEIMDAL
1261    /*
1262     * With MIT Kerberos 5 1.3.x the gss_cred_id_t is the same as
1263     * krb5_gss_cred_id_t and krb5_gss_cred_id_rec contains a pointer to
1264     * the replay cache.
1265     * This allows us to override the replay cache function vector with
1266     * our own one.
1267     * Note that this is a dirty hack to get things working and there may
1268     * well be unknown side-effects.
1269     */
1270    {
1271       krb5_gss_cred_id_t gss_creds = (krb5_gss_cred_id_t) *server_creds;
1272
1273       /* First we try to verify we are linked with 1.3.x to prevent from
1274          crashing when linked with 1.4.x */
1275       if (gss_creds && (gss_creds->usage == GSS_C_ACCEPT)) {
1276          if (gss_creds->rcache && gss_creds->rcache->ops &&
1277              gss_creds->rcache->ops->type &&  
1278              memcmp(gss_creds->rcache->ops->type, "dfl", 3) == 0)
1279           /* Override the rcache operations */
1280          gss_creds->rcache->ops = &mod_auth_kerb_rc_ops;
1281       }
1282    }
1283 #endif
1284    
1285    return 0;
1286 }
1287
1288 #ifndef GSSAPI_SUPPORTS_SPNEGO
1289 static int
1290 cmp_gss_type(gss_buffer_t token, gss_OID oid)
1291 {
1292    unsigned char *p;
1293    size_t len;
1294
1295    if (token->length == 0)
1296       return GSS_S_DEFECTIVE_TOKEN;
1297
1298    p = token->value;
1299    if (*p++ != 0x60)
1300       return GSS_S_DEFECTIVE_TOKEN;
1301    len = *p++;
1302    if (len & 0x80) {
1303       if ((len & 0x7f) > 4)
1304          return GSS_S_DEFECTIVE_TOKEN;
1305       p += len & 0x7f;
1306    }
1307    if (*p++ != 0x06)
1308       return GSS_S_DEFECTIVE_TOKEN;
1309
1310    if (((OM_uint32) *p++) != oid->length)
1311       return GSS_S_DEFECTIVE_TOKEN;
1312
1313    return memcmp(p, oid->elements, oid->length);
1314 }
1315 #endif
1316
1317 static int
1318 authenticate_user_gss(request_rec *r, kerb_auth_config *conf,
1319                       const char *auth_line, char **negotiate_ret_value)
1320 {
1321   OM_uint32 major_status, minor_status, minor_status2;
1322   gss_buffer_desc input_token = GSS_C_EMPTY_BUFFER;
1323   gss_buffer_desc output_token = GSS_C_EMPTY_BUFFER;
1324   const char *auth_param = NULL;
1325   int ret;
1326   gss_name_t client_name = GSS_C_NO_NAME;
1327   gss_cred_id_t delegated_cred = GSS_C_NO_CREDENTIAL;
1328   OM_uint32 (KRB5_LIB_FUNCTION *accept_sec_token)
1329                          (OM_uint32 *, gss_ctx_id_t *, const gss_cred_id_t,
1330                          const gss_buffer_t, const gss_channel_bindings_t,
1331                          gss_name_t *, gss_OID *, gss_buffer_t, OM_uint32 *,
1332                          OM_uint32 *, gss_cred_id_t *);
1333   gss_OID_desc spnego_oid;
1334   gss_ctx_id_t context = GSS_C_NO_CONTEXT;
1335   gss_cred_id_t server_creds = GSS_C_NO_CREDENTIAL;
1336   OM_uint32 ret_flags = 0;
1337
1338   *negotiate_ret_value = "\0";
1339
1340   spnego_oid.length = 6;
1341   spnego_oid.elements = (void *)"\x2b\x06\x01\x05\x05\x02";
1342
1343   if (conf->krb_5_keytab) {
1344      char *ktname;
1345      /* we don't use the ap_* calls here, since the string passed to putenv()
1346       * will become part of the enviroment and shouldn't be free()ed by apache
1347       */
1348      ktname = malloc(strlen("KRB5_KTNAME=") + strlen(conf->krb_5_keytab) + 1);
1349      if (ktname == NULL) {
1350         log_rerror(APLOG_MARK, APLOG_ERR, 0, r, "malloc() failed: not enough memory");
1351         ret = HTTP_INTERNAL_SERVER_ERROR;
1352         goto end;
1353      }
1354      sprintf(ktname, "KRB5_KTNAME=%s", conf->krb_5_keytab);
1355      putenv(ktname);
1356 #ifdef HEIMDAL
1357      /* Seems to be also supported by latest MIT */
1358      gsskrb5_register_acceptor_identity(conf->krb_5_keytab);
1359 #endif
1360   }
1361
1362   ret = get_gss_creds(r, conf, &server_creds);
1363   if (ret)
1364      goto end;
1365
1366   /* ap_getword() shifts parameter */
1367   auth_param = ap_getword_white(r->pool, &auth_line);
1368   if (auth_param == NULL) {
1369      log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
1370                 "No Authorization parameter in request from client");
1371      ret = HTTP_UNAUTHORIZED;
1372      goto end;
1373   }
1374
1375   input_token.length = apr_base64_decode_len(auth_param) + 1;
1376   input_token.value = apr_pcalloc(r->connection->pool, input_token.length);
1377   if (input_token.value == NULL) {
1378      log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
1379                 "ap_pcalloc() failed (not enough memory)");
1380      ret = HTTP_INTERNAL_SERVER_ERROR;
1381      goto end;
1382   }
1383   input_token.length = apr_base64_decode(input_token.value, auth_param);
1384
1385 #ifdef GSSAPI_SUPPORTS_SPNEGO
1386   accept_sec_token = gss_accept_sec_context;
1387 #else
1388   accept_sec_token = (cmp_gss_type(&input_token, &spnego_oid) == 0) ?
1389                         gss_accept_sec_context_spnego : gss_accept_sec_context;
1390 #endif
1391
1392   log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, "Verifying client data using KRB5 GSS-API %s",
1393              (accept_sec_token == gss_accept_sec_context)
1394                ? ""
1395                : "with our SPNEGO lib");
1396
1397   major_status = accept_sec_token(&minor_status,
1398                                   &context,
1399                                   server_creds,
1400                                   &input_token,
1401                                   GSS_C_NO_CHANNEL_BINDINGS,
1402                                   &client_name,
1403                                   NULL,
1404                                   &output_token,
1405                                   &ret_flags,
1406                                   NULL,
1407                                   &delegated_cred);
1408   log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
1409              "Client %s us their credential",
1410              (ret_flags & GSS_C_DELEG_FLAG) ? "delegated" : "didn't delegate");
1411   if (output_token.length) {
1412      char *token = NULL;
1413      size_t len;
1414      
1415      len = apr_base64_encode_len(output_token.length) + 1;
1416      token = apr_pcalloc(r->connection->pool, len + 1);
1417      if (token == NULL) {
1418         log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
1419                    "ap_pcalloc() failed (not enough memory)");
1420         ret = HTTP_INTERNAL_SERVER_ERROR;
1421         gss_release_buffer(&minor_status2, &output_token);
1422         goto end;
1423      }
1424      apr_base64_encode(token, output_token.value, output_token.length);
1425      token[len] = '\0';
1426      *negotiate_ret_value = token;
1427      log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
1428                 "GSS-API token of length %d bytes will be sent back",
1429                 output_token.length);
1430      gss_release_buffer(&minor_status2, &output_token);
1431      set_kerb_auth_headers(r, conf, 0, 0, *negotiate_ret_value);
1432   }
1433
1434   if (GSS_ERROR(major_status)) {
1435      if (input_token.length > 7 && memcmp(input_token.value, "NTLMSSP", 7) == 0)
1436         log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
1437                   "Warning: received token seems to be NTLM, which isn't supported by the Kerberos module. Check your IE configuration.");
1438
1439      log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
1440                 "%s", get_gss_error(r, major_status, minor_status,
1441                                     "gss_accept_sec_context() failed"));
1442      /* Don't offer the Negotiate method again if call to GSS layer failed */
1443      *negotiate_ret_value = NULL;
1444      ret = HTTP_UNAUTHORIZED;
1445      goto end;
1446   }
1447
1448   /* Multiple authentication rounds aren't supported.  If we wanted a generic
1449    * GSS authentication we would have to do some magic with exporting context
1450    * etc. */
1451   if (major_status & GSS_S_CONTINUE_NEEDED) {
1452      log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
1453                 "Multi-iteration authentication isn't supported");
1454      ret = HTTP_UNAUTHORIZED;
1455      goto end;
1456   }
1457
1458   major_status = gss_display_name(&minor_status, client_name, &output_token, NULL);
1459   gss_release_name(&minor_status, &client_name); 
1460   if (GSS_ERROR(major_status)) {
1461     log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
1462                "%s", get_gss_error(r, major_status, minor_status,
1463                                    "gss_display_name() failed"));
1464     ret = HTTP_INTERNAL_SERVER_ERROR;
1465     goto end;
1466   }
1467
1468   MK_AUTH_TYPE = MECH_NEGOTIATE;
1469   MK_USER = apr_pstrdup(r->pool, output_token.value);
1470
1471   if (conf->krb_save_credentials && delegated_cred != GSS_C_NO_CREDENTIAL)
1472      store_gss_creds(r, conf, (char *)output_token.value, delegated_cred);
1473   
1474   gss_release_buffer(&minor_status, &output_token);
1475
1476   ret = OK;
1477
1478 end:
1479   if (delegated_cred)
1480      gss_release_cred(&minor_status, &delegated_cred);
1481
1482   if (output_token.length) 
1483      gss_release_buffer(&minor_status, &output_token);
1484
1485   if (client_name != GSS_C_NO_NAME)
1486      gss_release_name(&minor_status, &client_name);
1487
1488   if (server_creds != GSS_C_NO_CREDENTIAL)
1489      gss_release_cred(&minor_status, &server_creds);
1490
1491   if (context != GSS_C_NO_CONTEXT)
1492      gss_delete_sec_context(&minor_status, &context, GSS_C_NO_BUFFER);
1493
1494   return ret;
1495 }
1496
1497 static int
1498 do_krb5_an_to_ln(request_rec *r) {
1499   krb5_error_code code;
1500   int ret = HTTP_INTERNAL_SERVER_ERROR;
1501   char *MK_USER_LNAME = NULL;
1502   krb5_context    kcontext = NULL;
1503   krb5_principal client = NULL;
1504   
1505   code = krb5_init_context(&kcontext);
1506    if (code) {
1507       log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
1508                  "Cannot initialize Kerberos5 context (%d)", code);
1509       goto end;
1510    }
1511   
1512   code = krb5_parse_name(kcontext, MK_USER, &client);
1513       if (code) {
1514          log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
1515                     "krb5_parse_name() failed: %s",
1516                     krb5_get_err_text(kcontext, code));
1517            goto end;
1518   }
1519   MK_USER_LNAME = apr_pcalloc(r->pool, strlen(MK_USER)+1);
1520   if (MK_USER_LNAME == NULL) {
1521      log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
1522                 "ap_pcalloc() failed (not enough memory)");
1523      goto end;
1524   }
1525     code = krb5_aname_to_localname(kcontext, client, strlen(MK_USER), MK_USER_LNAME);
1526     if (code) {
1527                   if (code != KRB5_LNAME_NOTRANS) {
1528                         log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
1529                                    "krb5_aname_to_localname() failed: %s",
1530                                    krb5_get_err_text(kcontext, code));
1531
1532                   }
1533                   else {
1534                         log_rerror(APLOG_MARK, APLOG_NOTICE, 0, r,
1535                                    "krb5_aname_to_localname() found no "
1536                                    "mapping for principal %s",
1537                                    MK_USER);
1538                   }
1539           }
1540     else {
1541     log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
1542               "kerb_authenticate_a_name_to_local_name %s -> %s",
1543               (MK_USER)?MK_USER:"(NULL)", (MK_USER_LNAME)?MK_USER_LNAME:"(NULL)");
1544           MK_USER = apr_pstrdup(r->pool, MK_USER_LNAME);
1545           ret = OK;
1546           }
1547         end:
1548           if (client)
1549              krb5_free_principal(kcontext, client);
1550           if (kcontext)
1551              krb5_free_context(kcontext);
1552           return ret;
1553 }
1554
1555
1556 #endif /* KRB5 */
1557
1558 static krb5_conn_data *
1559 already_authorized(request_rec *r, char *auth_line)
1560 {
1561    krb5_conn_data *conn_data;
1562    char keyname[1024];
1563    
1564    snprintf(keyname, sizeof(keyname) - 1,
1565         "mod_auth_kerb::connection::%s::%ld", r->connection->remote_ip, 
1566         r->connection->id);
1567
1568    if (apr_pool_userdata_get((void**)&conn_data, keyname, r->connection->pool) != 0)
1569         return NULL;
1570
1571    if(conn_data) {
1572         if(strcmp(conn_data->authline, auth_line) == 0) {
1573                 log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, "matched previous auth request");
1574                 return conn_data;
1575         }
1576    }
1577    return NULL;
1578 }
1579
1580 static void
1581 save_authorized(request_rec *r, char *auth_line, const char *auth_type, int ret) {
1582     krb5_conn_data *prevauth;
1583     prevauth = (krb5_conn_data *)apr_palloc(r->connection->pool, sizeof(krb5_conn_data));
1584     
1585     char keyname[1024];
1586     
1587     prevauth->user = apr_pstrdup(r->connection->pool, MK_USER);
1588     prevauth->authline = apr_pstrdup(r->connection->pool, auth_line);
1589     prevauth->mech = apr_pstrdup(r->connection->pool, auth_type);
1590     prevauth->last_return = ret;
1591     
1592     snprintf(keyname, sizeof(keyname) - 1,
1593              "mod_auth_kerb::connection::%s::%ld",
1594              r->connection->remote_ip, r->connection->id);
1595     apr_pool_userdata_set(prevauth, keyname, NULL, r->connection->pool);
1596 }
1597
1598 static void
1599 set_kerb_auth_headers(request_rec *r, const kerb_auth_config *conf,
1600                       int use_krb4, int use_krb5pwd, char *negotiate_ret_value)
1601 {
1602    const char *auth_name = NULL;
1603    int set_basic = 0;
1604    char *negoauth_param;
1605    const char *header_name = 
1606       (r->proxyreq == PROXYREQ_PROXY) ? "Proxy-Authenticate" : "WWW-Authenticate";
1607
1608    /* get the user realm specified in .htaccess */
1609    auth_name = ap_auth_name(r);
1610
1611    /* XXX should the WWW-Authenticate header be cleared first?
1612     * apache in the proxy mode should retain client's authN headers? */
1613 #ifdef KRB5
1614    if (negotiate_ret_value != NULL && conf->krb_method_gssapi) {
1615       negoauth_param = (*negotiate_ret_value == '\0') ? MECH_NEGOTIATE :
1616                   apr_pstrcat(r->pool, MECH_NEGOTIATE " ", negotiate_ret_value, NULL);
1617       apr_table_add(r->err_headers_out, header_name, negoauth_param);
1618    }
1619    if ((use_krb5pwd && conf->krb_method_k5pass) || conf->krb_delegate_basic) {
1620       apr_table_add(r->err_headers_out, header_name,
1621                    apr_pstrcat(r->pool, "Basic realm=\"", auth_name, "\"", NULL));
1622       set_basic = 1;
1623    }
1624 #endif
1625
1626 #ifdef KRB4
1627    if (!set_basic && 
1628        ((use_krb4 && conf->krb_method_k4pass) || conf->krb_delegate_basic))
1629       apr_table_add(r->err_headers_out, header_name,
1630                   apr_pstrcat(r->pool, "Basic realm=\"", auth_name, "\"", NULL));
1631 #endif
1632 }
1633
1634 static int
1635 authenticate_user(request_rec *r, char *auth_line, const char *type, int use_krb4, int use_krb5)
1636 {
1637    int ret;
1638    krb5_conn_data *prevauth = NULL;
1639    kerb_auth_config *conf =
1640       (kerb_auth_config *) ap_get_module_config(r->per_dir_config,
1641                                                 &auth_kerb_module);
1642    char *negotiate_ret_value = NULL;
1643    const char *auth_type = NULL;
1644    
1645    if (!auth_line) {
1646       set_kerb_auth_headers(r, conf, use_krb4, use_krb5, 
1647                             (use_krb5) ? "\0" : NULL);
1648       return HTTP_UNAUTHORIZED;
1649    }
1650    auth_type = ap_getword_white(r->pool, (const char **)&auth_line);
1651
1652    /* If we are delegating Basic to other modules, DECLINE the request */
1653    if (conf->krb_delegate_basic &&
1654 #ifdef KRB5
1655        !conf->krb_method_k5pass &&
1656 #endif
1657 #ifdef KRB4
1658        !conf->krb_method_k4pass &&
1659 #endif
1660        (strcasecmp(auth_type, "Basic") == 0))
1661        return DECLINED;
1662    if ((prevauth = already_authorized(r, auth_line)) == NULL) {
1663       ret = HTTP_UNAUTHORIZED;
1664
1665 #ifdef KRB5
1666    if (use_krb5 && conf->krb_method_gssapi &&
1667        strcasecmp(auth_type, MECH_NEGOTIATE) == 0) {
1668       ret = authenticate_user_gss(r, conf, auth_line, &negotiate_ret_value);
1669    } else if (use_krb5 && (conf->krb_method_k5pass || strcasecmp(type, "Basic"))){
1670        ret = authenticate_user_krb5pwd(r, conf, auth_line);
1671    }
1672 #endif
1673
1674 #ifdef KRB4
1675    if (ret == HTTP_UNAUTHORIZED && use_krb4 && (conf->krb_method_k4pass || strcasecmp(type, "Basic")))
1676       ret = authenticate_user_krb4pwd(r, conf, auth_line);
1677 #endif
1678
1679       if (ret == HTTP_UNAUTHORIZED)
1680         set_kerb_auth_headers(r, conf, use_krb4, use_krb5, negotiate_ret_value);
1681
1682    } else {
1683       ret = prevauth->last_return;
1684       MK_USER = prevauth->user;
1685       MK_AUTH_TYPE = prevauth->mech;
1686    }
1687
1688    /*
1689     * save who was auth'd, if it's not already stashed.
1690     */
1691    if(!prevauth) {
1692       save_authorized(r, auth_line, auth_type, ret);
1693    }
1694
1695    if (ret == OK && conf->krb5_do_auth_to_local) {
1696       ret = do_krb5_an_to_ln(r);
1697    }
1698    return ret;
1699 }
1700
1701 static authn_status authn_krb_password(request_rec *r, const char *user,
1702                                        const char *password)
1703 {
1704    char *auth_line = NULL;
1705    int ret;
1706    const char *type = NULL;
1707    
1708    type = ap_auth_type(r);
1709    auth_line = ap_pbase64encode (r->pool, apr_psprintf(r->pool, "%s:%s", user, password));
1710    auth_line = apr_psprintf(r->pool, "Basic %s", auth_line);
1711
1712    ret = authenticate_user(r, auth_line, type, 1, 1);
1713    
1714    if (ret == OK) return AUTH_GRANTED;
1715    else return AUTH_USER_NOT_FOUND;
1716 }
1717
1718 static int
1719 kerb_authenticate_user(request_rec *r)
1720 {
1721    kerb_auth_config *conf = 
1722       (kerb_auth_config *) ap_get_module_config(r->per_dir_config,
1723                                                 &auth_kerb_module);
1724    char *auth_line = NULL;
1725    int ret, use_krb4 = 0, use_krb5 = 0;
1726    const char *type = NULL;
1727    
1728    /* get the type specified in .htaccess */
1729    type = ap_auth_type(r);
1730
1731    log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
1732               "kerb_authenticate_user entered with user %s and auth_type %s",
1733               (MK_USER)?MK_USER:"(NULL)",type?type:"(NULL)");
1734
1735    if (type && strcasecmp(type, "Kerberos") == 0)
1736       use_krb5 = use_krb4 = 1;
1737    else if(type && strcasecmp(type, "KerberosV5") == 0)
1738       use_krb5 = 1;
1739    else if(type && strcasecmp(type, "KerberosV4") == 0)
1740       use_krb4 = 1;
1741    else
1742       return DECLINED;
1743
1744 #if 0
1745    if (conf->krb_ssl_preauthentication) {
1746       const char *ssl_client_verify = ssl_var_lookup(r->pool, r->server,
1747                 r->connection, r, "SSL_CLIENT_VERIFY");
1748
1749       if (ssl_client_verify && strcmp(ssl_client_verify, "SUCCESS") == 0)
1750          return OK;
1751    }
1752 #endif
1753
1754    /* get what the user sent us in the HTTP header */
1755    auth_line = (char *)MK_TABLE_GET(r->headers_in, (r->proxyreq == PROXYREQ_PROXY)
1756                                             ? "Proxy-Authorization"
1757                                             : "Authorization");
1758    ret = authenticate_user(r, auth_line, type, use_krb4, use_krb5);
1759
1760    return ret;
1761 }
1762
1763 static int
1764 have_rcache_type(const char *type)
1765 {
1766    krb5_error_code ret;
1767    krb5_context context;
1768    krb5_rcache id = NULL;
1769    int found;
1770
1771    ret = krb5_init_context(&context);
1772    if (ret)
1773       return 0;
1774
1775    ret = krb5_rc_resolve_full(context, &id, "none:");
1776    found = (ret == 0);
1777
1778    if (ret == 0)
1779       krb5_rc_destroy(context, id);
1780    krb5_free_context(context);
1781
1782    return found;
1783 }
1784
1785 /*************************************************************************** 
1786  Module Setup/Configuration
1787  ***************************************************************************/
1788 #ifndef STANDARD20_MODULE_STUFF
1789 static void
1790 kerb_module_init(server_rec *dummy, pool *p)
1791 {
1792 #ifndef HEIMDAL
1793    /* Suppress the MIT replay cache.  Requires MIT Kerberos 1.4.0 or later.
1794       1.3.x are covered by the hack overiding the replay calls */
1795    if (getenv("KRB5RCACHETYPE") == NULL && have_rcache_type("none"))
1796       putenv(strdup("KRB5RCACHETYPE=none"));
1797 #endif
1798 }
1799
1800 module MODULE_VAR_EXPORT auth_kerb_module = {
1801         STANDARD_MODULE_STUFF,
1802         kerb_module_init,               /*      module initializer            */
1803         kerb_dir_create_config,         /*      per-directory config creator  */
1804         NULL,                           /*      per-directory config merger   */
1805         NULL,                           /*      per-server    config creator  */
1806         NULL,                           /*      per-server    config merger   */
1807         kerb_auth_cmds,                 /*      command table                 */
1808         NULL,                           /* [ 9] content handlers              */
1809         NULL,                           /* [ 2] URI-to-filename translation   */
1810         kerb_authenticate_user,         /* [ 5] check/validate user_id        */
1811         NULL,                           /* [ 6] check user_id is valid *here* */
1812         NULL,                           /* [ 4] check access by host address  */
1813         NULL,                           /* [ 7] MIME type checker/setter      */
1814         NULL,                           /* [ 8] fixups                        */
1815         NULL,                           /* [10] logger                        */
1816         NULL,                           /* [ 3] header parser                 */
1817         NULL,                           /*      process initialization        */
1818         NULL,                           /*      process exit/cleanup          */
1819         NULL                            /* [ 1] post read_request handling    */
1820 #ifdef EAPI
1821        ,NULL,                           /* EAPI: add_module                   */
1822         NULL,                           /* EAPI: remove_module                */
1823         NULL,                           /* EAPI: rewrite_command              */
1824         NULL                            /* EAPI: new_connection               */
1825 #endif
1826 };
1827 #else
1828 static int
1829 kerb_init_handler(apr_pool_t *p, apr_pool_t *plog,
1830                   apr_pool_t *ptemp, server_rec *s)
1831 {
1832    ap_add_version_component(p, "mod_auth_kerb/" MODAUTHKERB_VERSION);
1833 #ifndef HEIMDAL
1834    /* Suppress the MIT replay cache.  Requires MIT Kerberos 1.4.0 or later.
1835       1.3.x are covered by the hack overiding the replay calls */
1836    if (getenv("KRB5RCACHETYPE") == NULL && have_rcache_type("none"))
1837       putenv(strdup("KRB5RCACHETYPE=none"));
1838 #endif
1839    
1840    return OK;
1841 }
1842
1843 static void
1844 kerb_register_hooks(apr_pool_t *p)
1845 {
1846 #ifdef APACHE22
1847    static const authn_provider authn_krb_provider = {
1848       &authn_krb_password,
1849       NULL
1850    };
1851
1852    ap_register_provider(p, AUTHN_PROVIDER_GROUP, "kerberos", "0", &authn_krb_provider);
1853 #endif
1854    ap_hook_post_config(kerb_init_handler, NULL, NULL, APR_HOOK_MIDDLE);
1855    ap_hook_check_user_id(kerb_authenticate_user, NULL, NULL, APR_HOOK_MIDDLE);
1856 }
1857
1858 module AP_MODULE_DECLARE_DATA auth_kerb_module =
1859 {
1860    STANDARD20_MODULE_STUFF,
1861    kerb_dir_create_config,      /* create per-dir    conf structures  */
1862    NULL,                        /* merge  per-dir    conf structures  */
1863    NULL,                        /* create per-server conf structures  */
1864    NULL,                        /* merge  per-server conf structures  */
1865    kerb_auth_cmds,              /* table of configuration directives  */
1866    kerb_register_hooks          /* register hooks                     */
1867 };
1868 #endif