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