e6c8bdb0a2c411f03fca987ff5ade583c1caed52
[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 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 #define MODAUTHKERB_VERSION "5.0-rc4"
50
51 #include <httpd.h>
52 #include <http_config.h>
53 #include <http_core.h>
54 #include <http_log.h>
55 #include <http_protocol.h>
56 #include <http_request.h>
57
58 #ifdef STANDARD20_MODULE_STUFF
59 #include <ap_compat.h>
60 #include <apr_strings.h>
61 #endif
62
63
64 #ifdef KRB5
65 #include <krb5.h>
66 #ifdef HEIMDAL
67 #  include <gssapi.h>
68 #else
69 #  include <gssapi/gssapi.h>
70 #  include <gssapi/gssapi_generic.h>
71 #  define GSS_C_NT_USER_NAME gss_nt_user_name
72 #  define GSS_C_NT_HOSTBASED_SERVICE gss_nt_service_name
73 #  define krb5_get_err_text(context,code) error_message(code)
74 #endif
75 #include "spnegokrb5.h"
76 #endif /* KRB5 */
77
78 #ifdef KRB4
79 /* Prevent warning about closesocket redefinition (Apache's ap_config.h and 
80  * MIT Kerberos' port-sockets.h both define it as close) */
81 #ifdef closesocket
82 #  undef closesocket
83 #endif
84 #include <krb.h>
85 #include <netdb.h> /* gethostbyname() */
86 #endif /* KRB4 */
87
88 #ifdef STANDARD20_MODULE_STUFF
89 module AP_MODULE_DECLARE_DATA auth_kerb_module;
90 #else
91 module auth_kerb_module;
92 #endif
93
94 /*************************************************************************** 
95  Macros To Ease Compatibility
96  ***************************************************************************/
97 #ifdef STANDARD20_MODULE_STUFF
98 #define MK_POOL apr_pool_t
99 #define MK_TABLE_GET apr_table_get
100 #define MK_USER r->user
101 #define MK_AUTH_TYPE r->ap_auth_type
102 #else
103 #define MK_POOL pool
104 #define MK_TABLE_GET ap_table_get
105 #define MK_USER r->connection->user
106 #define MK_AUTH_TYPE r->connection->ap_auth_type
107 #define PROXYREQ_PROXY STD_PROXY
108 #endif
109
110 /*************************************************************************** 
111  Auth Configuration Structure
112  ***************************************************************************/
113 typedef struct {
114         char *krb_auth_realms;
115         int krb_save_credentials;
116         int krb_verify_kdc;
117         char *krb_service_name;
118         int krb_authoritative;
119 #ifdef KRB5
120         char *krb_5_keytab;
121         int krb_method_gssapi;
122         int krb_method_k5pass;
123 #endif
124 #ifdef KRB4
125         char *krb_4_srvtab;
126         int krb_method_k4pass;
127 #endif
128 } kerb_auth_config;
129
130 static void
131 set_kerb_auth_headers(request_rec *r, const kerb_auth_config *conf,
132                       int use_krb4, int use_krb5pwd, char *negotiate_ret_value);
133
134 static const char*
135 krb5_save_realms(cmd_parms *cmd, kerb_auth_config *sec, char *arg);
136
137 #ifdef STANDARD20_MODULE_STUFF
138 #define command(name, func, var, type, usage)           \
139   AP_INIT_ ## type (name, func,                         \
140         (void*)APR_XtOffsetOf(kerb_auth_config, var),   \
141         OR_AUTHCFG, usage)
142 #else
143 #define command(name, func, var, type, usage)           \
144   { name, func,                                         \
145     (void*)XtOffsetOf(kerb_auth_config, var),           \
146     OR_AUTHCFG, type, usage }
147 #endif
148
149 static const command_rec kerb_auth_cmds[] = {
150    command("KrbAuthRealms", krb5_save_realms, krb_auth_realms,
151      RAW_ARGS, "Realms to attempt authentication against (can be multiple)."),
152
153    command("KrbAuthRealm", krb5_save_realms, krb_auth_realms,
154      RAW_ARGS, "Alias for KrbAuthRealms."),
155
156    command("KrbSaveCredentials", ap_set_flag_slot, krb_save_credentials,
157      FLAG, "Save and store credentials/tickets retrieved during auth."),
158
159    command("KrbVerifyKDC", ap_set_flag_slot, krb_verify_kdc,
160      FLAG, "Verify tickets against keytab to prevent KDC spoofing attacks."),
161
162    command("KrbServiceName", ap_set_string_slot, krb_service_name,
163      TAKE1, "Service name to be used by Apache for authentication."),
164
165    command("KrbAuthoritative", ap_set_flag_slot, krb_authoritative,
166      FLAG, "Set to 'off' to allow access control to be passed along to lower modules if the UserID is not known to this module."),
167
168 #ifdef KRB5
169    command("Krb5Keytab", ap_set_file_slot, krb_5_keytab,
170      TAKE1, "Location of Kerberos V5 keytab file."),
171
172    command("KrbMethodNegotiate", ap_set_flag_slot, krb_method_gssapi,
173      FLAG, "Enable Negotiate authentication method."),
174
175    command("KrbMethodK5Passwd", ap_set_flag_slot, krb_method_k5pass,
176      FLAG, "Enable Kerberos V5 password authentication."),
177 #endif 
178
179 #ifdef KRB4
180    command("Krb4Srvtab", ap_set_file_slot, krb_4_srvtab,
181      TAKE1, "Location of Kerberos V4 srvtab file."),
182
183    command("KrbMethodK4Passwd", ap_set_flag_slot, krb_method_k4pass,
184      FLAG, "Enable Kerberos V4 password authentication."),
185 #endif
186
187    { NULL }
188 };
189
190 #if defined(KRB5) && !defined(HEIMDAL)
191 /* Needed to work around problems with replay caches */
192 #include "mit-internals.h"
193
194 /* This is our replacement krb5_rc_store function */
195 static krb5_error_code
196 mod_auth_kerb_rc_store(krb5_context context, krb5_rcache rcache,
197                         krb5_donot_replay *donot_replay)
198 {
199    return 0;
200 }
201
202 /* And this is the operations vector for our replay cache */
203 const krb5_rc_ops mod_auth_kerb_rc_ops = {
204   0,
205   "dfl",
206   krb5_rc_dfl_init,
207   krb5_rc_dfl_recover,
208   krb5_rc_dfl_destroy,
209   krb5_rc_dfl_close,
210   mod_auth_kerb_rc_store,
211   krb5_rc_dfl_expunge,
212   krb5_rc_dfl_get_span,
213   krb5_rc_dfl_get_name,
214   krb5_rc_dfl_resolve
215 };
216 #endif
217
218
219 /*************************************************************************** 
220  Auth Configuration Initialization
221  ***************************************************************************/
222 static void *kerb_dir_create_config(MK_POOL *p, char *d)
223 {
224         kerb_auth_config *rec;
225
226         rec = (kerb_auth_config *) ap_pcalloc(p, sizeof(kerb_auth_config));
227         ((kerb_auth_config *)rec)->krb_verify_kdc = 1;
228         ((kerb_auth_config *)rec)->krb_service_name = "HTTP";
229         ((kerb_auth_config *)rec)->krb_authoritative = 1;
230 #ifdef KRB5
231         ((kerb_auth_config *)rec)->krb_method_k5pass = 1;
232         ((kerb_auth_config *)rec)->krb_method_gssapi = 1;
233 #endif
234 #ifdef KRB4
235         ((kerb_auth_config *)rec)->krb_method_k4pass = 1;
236 #endif
237         return rec;
238 }
239
240 static const char*
241 krb5_save_realms(cmd_parms *cmd, kerb_auth_config *sec, char *arg)
242 {
243    sec->krb_auth_realms= ap_pstrdup(cmd->pool, arg);
244    return NULL;
245 }
246
247 void log_rerror(const char *file, int line, int level, int status,
248                 const request_rec *r, const char *fmt, ...)
249 {
250    char errstr[1024];
251    va_list ap;
252
253    va_start(ap, fmt);
254    vsnprintf(errstr, sizeof(errstr), fmt, ap);
255    va_end(ap);
256
257    
258 #ifdef STANDARD20_MODULE_STUFF
259    ap_log_rerror(file, line, level | APLOG_NOERRNO, status, r, "%s", errstr);
260 #else
261    ap_log_rerror(file, line, level | APLOG_NOERRNO, r, "%s", errstr);
262 #endif
263 }
264
265 #ifdef KRB4
266 /*************************************************************************** 
267  Username/Password Validation for Krb4
268  ***************************************************************************/
269 static int
270 verify_krb4_user(request_rec *r, char *name, char *instance, char *realm,
271                  char *password, char *linstance, char *srvtab, int krb_verify_kdc)
272 {
273    int ret;
274    char *phost;
275    unsigned long addr;
276    struct hostent *hp;
277    const char *hostname;
278    KTEXT_ST ticket;
279    AUTH_DAT authdata;
280    char lrealm[REALM_SZ];
281
282    ret = krb_get_pw_in_tkt(name, instance, realm, "krbtgt", realm, 
283                            DEFAULT_TKT_LIFE, password);
284    if (ret) {
285       log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
286                  "Cannot get krb4 ticket: krb_get_pw_in_tkt() failed: %s",
287                  krb_get_err_text(ret));
288       return ret;
289    }
290
291    if (!krb_verify_kdc)
292       return ret;
293
294    hostname = ap_get_server_name(r);
295
296    hp = gethostbyname(hostname);
297    if (hp == NULL) {
298       dest_tkt();
299       log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
300                  "Cannot verify krb4 ticket: gethostbyname() failed: %s",
301                  hstrerror(h_errno));
302       return h_errno;
303    }
304    memcpy(&addr, hp->h_addr, sizeof(addr));
305
306    phost = krb_get_phost((char *)hostname);
307
308    krb_get_lrealm(lrealm, 1);
309
310    ret = krb_mk_req(&ticket, linstance, phost, lrealm, 0);
311    if (ret) {
312       log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
313                  "Cannot verify krb4 ticket: krb_mk_req() failed: %s",
314                  krb_get_err_text(ret));
315       dest_tkt();
316       return ret;
317    }
318
319    ret = krb_rd_req(&ticket, linstance, phost, addr, &authdata, srvtab);
320    if (ret) {
321       log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
322                  "Cannot verify krb4 ticket: krb_rd_req() failed: %s",
323                  krb_get_err_text(ret));
324       dest_tkt();
325    }
326
327    return ret;
328 }
329
330 static int
331 krb4_cache_cleanup(void *data)
332 {
333    char *tkt_file = (char *) data;
334    
335    krb_set_tkt_string(tkt_file);
336    dest_tkt();
337    return OK;
338 }
339
340 static int 
341 authenticate_user_krb4pwd(request_rec *r,
342                           kerb_auth_config *conf,
343                           const char *auth_line)
344 {
345    int ret;
346    const char *sent_pw;
347    const char *sent_name;
348    char *sent_instance;
349    char tkt_file[32];
350    char *tkt_file_p = NULL;
351    int fd;
352    const char *realms;
353    const char *realm;
354    char *user;
355    char lrealm[REALM_SZ];
356    int all_principals_unkown;
357
358    sent_pw = ap_pbase64decode(r->pool, auth_line);
359    sent_name = ap_getword (r->pool, &sent_pw, ':');
360
361    /* do not allow user to override realm setting of server */
362    if (strchr(sent_name, '@')) {
363       log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
364                  "specifying realm in user name is prohibited");
365       return HTTP_UNAUTHORIZED;
366    }
367
368    sent_instance = strchr(sent_name, '.');
369    if (sent_instance)
370       *sent_instance++ = '\0'; 
371
372    snprintf(tkt_file, sizeof(tkt_file), "/tmp/apache_tkt_XXXXXX");
373    fd = mkstemp(tkt_file);
374    if (fd < 0) {
375       log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
376                  "Cannot create krb4 ccache: mkstemp() failed: %s",
377                  strerror(errno));
378       return HTTP_INTERNAL_SERVER_ERROR;
379    }
380
381    tkt_file_p = ap_pstrdup(r->pool, tkt_file);
382    ap_register_cleanup(r->pool, tkt_file_p,
383                        krb4_cache_cleanup, ap_null_cleanup);
384
385    krb_set_tkt_string(tkt_file);
386
387    all_principals_unkown = 1;
388    realms = conf->krb_auth_realms;
389    do {
390       memset(lrealm, 0, sizeof(lrealm));
391       realm = NULL;
392       if (realms)
393          realm = ap_getword_white(r->pool, &realms);
394
395       if (realm == NULL) {
396          ret = krb_get_lrealm(lrealm, 1);
397          if (ret)
398             break;
399          realm = lrealm;
400       }
401
402       ret = verify_krb4_user(r, (char *)sent_name, 
403                              (sent_instance) ? sent_instance : "",
404                              (char *)realm, (char *)sent_pw,
405                              conf->krb_service_name,
406                              conf->krb_4_srvtab, conf->krb_verify_kdc);
407       if (!conf->krb_authoritative && ret) {
408          /* if we're not authoritative, we allow authentication to pass on
409           * to another modules if (and only if) the user is not known to us */
410          if (all_principals_unkown && ret != KDC_PR_UNKNOWN)
411             all_principals_unkown = 0;
412       }
413
414       if (ret == 0)
415          break;
416    } while (realms && *realms);
417
418    if (ret) {
419       /* XXX log only in the verify_krb4_user() call */
420       log_rerror(APLOG_MARK, APLOG_ERR, 0, r, "Verifying krb4 password failed");
421       ret = (!conf->krb_authoritative && all_principals_unkown == 1 && ret == KDC_PR_UNKNOWN) ?
422                  DECLINED : HTTP_UNAUTHORIZED;
423       goto end;
424    }
425
426    user = ap_pstrdup(r->pool, sent_name);
427    if (sent_instance)
428       user = ap_pstrcat(r->pool, user, ".", sent_instance, NULL);
429    user = ap_pstrcat(r->pool, user, "@", realm, NULL);
430
431    MK_USER = user;
432    MK_AUTH_TYPE = "Basic";
433    ap_table_setn(r->subprocess_env, "KRBTKFILE", tkt_file_p);
434
435    if (!conf->krb_save_credentials)
436       krb4_cache_cleanup(tkt_file);
437
438 end:
439    if (ret)
440       krb4_cache_cleanup(tkt_file);
441    close(fd);
442    tf_close();
443
444    return ret;
445 }
446 #endif /* KRB4 */
447
448 #ifdef KRB5
449 /*************************************************************************** 
450  Username/Password Validation for Krb5
451  ***************************************************************************/
452 static krb5_error_code
453 verify_krb5_init_creds(krb5_context context, krb5_creds *creds,
454                        krb5_principal ap_req_server, krb5_keytab ap_req_keytab)
455 {
456    krb5_error_code ret;
457    krb5_data req;
458    krb5_ccache local_ccache = NULL;
459    krb5_creds *new_creds = NULL;
460    krb5_auth_context auth_context = NULL;
461    krb5_keytab keytab = NULL;
462
463    krb5_data_zero (&req);
464
465    if (ap_req_keytab == NULL) {
466       ret = krb5_kt_default (context, &keytab);
467       if (ret)
468          return ret;
469    } else
470       keytab = ap_req_keytab;
471
472    ret = krb5_cc_resolve(context, "MEMORY:", &local_ccache);
473    if (ret)
474       return ret;
475
476    ret = krb5_cc_initialize(context, local_ccache, creds->client);
477    if (ret)
478       goto end;
479
480    ret = krb5_cc_store_cred (context, local_ccache, creds);
481    if (ret)
482       goto end;
483
484    if (!krb5_principal_compare (context, ap_req_server, creds->server)) {
485       krb5_creds match_cred;
486
487       memset (&match_cred, 0, sizeof(match_cred));
488
489       match_cred.client = creds->client;
490       match_cred.server = ap_req_server;
491
492       ret = krb5_get_credentials (context, 0, local_ccache, 
493                                   &match_cred, &new_creds);
494       if (ret)
495          goto end;
496       creds = new_creds;
497    }
498
499    ret = krb5_mk_req_extended (context, &auth_context, 0, NULL, creds, &req);
500    if (ret)
501       goto end;
502
503    krb5_auth_con_free (context, auth_context);
504    ret = krb5_auth_con_init(context, &auth_context);
505    if (ret)
506       goto end;
507    krb5_auth_con_setflags(context, auth_context, KRB5_AUTH_CONTEXT_DO_SEQUENCE);
508
509    ret = krb5_rd_req (context, &auth_context, &req, ap_req_server,
510                       keytab, 0, NULL);
511
512 end:
513    krb5_free_data_contents(context, &req);
514    if (auth_context)
515       krb5_auth_con_free (context, auth_context);
516    if (new_creds)
517       krb5_free_creds (context, new_creds);
518    if (ap_req_keytab == NULL && keytab)
519       krb5_kt_close (context, keytab);
520    if (local_ccache)
521       krb5_cc_destroy (context, local_ccache);
522
523    return ret;
524 }
525
526 /* Inspired by krb5_verify_user from Heimdal */
527 static krb5_error_code
528 verify_krb5_user(request_rec *r, krb5_context context, krb5_principal principal,
529                  krb5_ccache ccache, const char *password, const char *service,
530                  krb5_keytab keytab, int krb_verify_kdc)
531 {
532    krb5_creds creds;
533    krb5_principal server = NULL;
534    krb5_error_code ret;
535
536    /* XXX error messages shouldn't be logged here (and in the while() loop in
537     * authenticate_user_krb5pwd() as weell), in order to avoid confusing log
538     * entries when using multiple realms */
539
540    memset(&creds, 0, sizeof(creds));
541
542    ret = krb5_get_init_creds_password(context, &creds, principal, 
543                                       (char *)password, NULL,
544                                       NULL, 0, NULL, NULL);
545    if (ret) {
546       log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
547                  "krb5_get_init_creds_password() failed: %s",
548                  krb5_get_err_text(context, ret));
549       return ret;
550    }
551
552    ret = krb5_sname_to_principal(context, ap_get_server_name(r), service, 
553                                  KRB5_NT_UNKNOWN, &server);
554    if (ret) {
555       log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
556                  "krb5_sname_to_principal() failed: %s",
557                  krb5_get_err_text(context, ret));
558       goto end;
559    }
560    /* XXX log_debug: lookig for <server_princ> in keytab */
561
562    /* XXX
563    {
564       char *realm;
565
566       krb5_get_default_realm(context, &realm);
567       log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
568                  "trying to verify password using key for %s/%s@%s",
569                  service, ap_get_server_name(r), realm);
570    }
571    */
572
573    if (krb_verify_kdc &&
574        (ret = verify_krb5_init_creds(context, &creds, server, keytab))) {
575        log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
576                   "failed to verify krb5 credentials: %s",
577                   krb5_get_err_text(context, ret));
578        goto end;
579    }
580
581    if (ccache) {
582       ret = krb5_cc_initialize(context, ccache, principal);
583       if (ret) {
584          log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
585                     "krb5_cc_initialize() failed: %s",
586                     krb5_get_err_text(context, ret));
587          goto end;
588       }
589
590       ret = krb5_cc_store_cred(context, ccache, &creds);
591       if (ret) {
592          log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
593                     "krb5_cc_store_cred() failed: %s",
594                     krb5_get_err_text(context, ret));
595          goto end;
596       }
597    }
598
599 end:
600    krb5_free_cred_contents(context, &creds);
601    if (server)
602       krb5_free_principal(context, server);
603
604    return ret;
605 }
606
607 static int
608 krb5_cache_cleanup(void *data)
609 {
610    krb5_context context;
611    krb5_ccache  cache;
612    krb5_error_code problem;
613    char *cache_name = (char *) data;
614
615    problem = krb5_init_context(&context);
616    if (problem) {
617       /* ap_log_error(APLOG_MARK, APLOG_ERR, 0, NULL, "krb5_init_context() failed"); */
618       return HTTP_INTERNAL_SERVER_ERROR;
619    }
620
621    problem = krb5_cc_resolve(context, cache_name, &cache);
622    if (problem) {
623       /* log_error(APLOG_MARK, APLOG_ERR, 0, NULL, 
624                 "krb5_cc_resolve() failed (%s: %s)",
625                 cache_name, krb5_get_err_text(context, problem)); */
626       return HTTP_INTERNAL_SERVER_ERROR;
627    }
628
629    krb5_cc_destroy(context, cache);
630    krb5_free_context(context);
631    return OK;
632 }
633
634 static int
635 create_krb5_ccache(krb5_context kcontext,
636                    request_rec *r,
637                    kerb_auth_config *conf,
638                    krb5_principal princ,
639                    krb5_ccache *ccache)
640 {
641    char *ccname;
642    int fd;
643    krb5_error_code problem;
644    int ret;
645    krb5_ccache tmp_ccache = NULL;
646
647    ccname = ap_psprintf(r->pool, "FILE:%s/krb5cc_apache_XXXXXX", P_tmpdir);
648    fd = mkstemp(ccname + strlen("FILE:"));
649    if (fd < 0) {
650       log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
651                  "mkstemp() failed: %s", strerror(errno));
652       ret = HTTP_INTERNAL_SERVER_ERROR;
653       goto end;
654    }
655    close(fd);
656
657    problem = krb5_cc_resolve(kcontext, ccname, &tmp_ccache);
658    if (problem) {
659       log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
660                  "krb5_cc_resolve() failed: %s",
661                  krb5_get_err_text(kcontext, problem));
662       ret = HTTP_INTERNAL_SERVER_ERROR;
663       unlink(ccname);
664       goto end;
665    }
666
667    problem = krb5_cc_initialize(kcontext, tmp_ccache, princ);
668    if (problem) {
669       log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
670                  "Cannot initialize krb5 ccache %s: krb5_cc_initialize() failed: %s",
671                  ccname, krb5_get_err_text(kcontext, problem));
672       ret = HTTP_INTERNAL_SERVER_ERROR;
673       goto end;
674    }
675
676    ap_table_setn(r->subprocess_env, "KRB5CCNAME", ccname);
677    ap_register_cleanup(r->pool, ccname,
678                        krb5_cache_cleanup, ap_null_cleanup);
679
680    *ccache = tmp_ccache;
681    tmp_ccache = NULL;
682
683    ret = OK;
684
685 end:
686    if (tmp_ccache)
687       krb5_cc_destroy(kcontext, tmp_ccache);
688
689    return ret;
690 }
691
692 static int
693 store_krb5_creds(krb5_context kcontext,
694                  request_rec *r,
695                  kerb_auth_config *conf,
696                  krb5_ccache delegated_cred)
697 {
698    char errstr[1024];
699    krb5_error_code problem;
700    krb5_principal princ;
701    krb5_ccache ccache;
702    int ret;
703
704    problem = krb5_cc_get_principal(kcontext, delegated_cred, &princ);
705    if (problem) {
706       snprintf(errstr, sizeof(errstr), "krb5_cc_get_principal() failed: %s",
707                krb5_get_err_text(kcontext, problem));
708       return HTTP_INTERNAL_SERVER_ERROR;
709    }
710
711    ret = create_krb5_ccache(kcontext, r, conf, princ, &ccache);
712    if (ret) {
713       krb5_free_principal(kcontext, princ);
714       return ret;
715    }
716
717 #ifdef HEIMDAL
718    problem = krb5_cc_copy_cache(kcontext, delegated_cred, ccache);
719 #else
720    problem = krb5_cc_copy_creds(kcontext, delegated_cred, ccache);
721 #endif
722    krb5_free_principal(kcontext, princ);
723    if (problem) {
724       snprintf(errstr, sizeof(errstr), "Failed to store credentials: %s",
725                krb5_get_err_text(kcontext, problem));
726       krb5_cc_destroy(kcontext, ccache);
727       return HTTP_INTERNAL_SERVER_ERROR;
728    }
729
730    krb5_cc_close(kcontext, ccache);
731    return OK;
732 }
733
734
735 int authenticate_user_krb5pwd(request_rec *r,
736                               kerb_auth_config *conf,
737                               const char *auth_line)
738 {
739    const char      *sent_pw = NULL; 
740    const char      *sent_name = NULL;
741    const char      *realms = NULL;
742    krb5_context    kcontext = NULL;
743    krb5_error_code code;
744    krb5_principal  client = NULL;
745    krb5_ccache     ccache = NULL;
746    krb5_keytab     keytab = NULL;
747    int             ret;
748    char            *name = NULL;
749    int             all_principals_unkown;
750    char            *ccname = NULL;
751    int             fd;
752
753    code = krb5_init_context(&kcontext);
754    if (code) {
755       log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
756                  "Cannot initialize Kerberos5 context (%d)", code);
757       return HTTP_INTERNAL_SERVER_ERROR;
758    }
759
760    sent_pw = ap_pbase64decode(r->pool, auth_line);
761    sent_name = ap_getword (r->pool, &sent_pw, ':');
762    /* do not allow user to override realm setting of server */
763    if (strchr(sent_name, '@')) {
764       log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
765                  "specifying realm in user name is prohibited");
766       ret = HTTP_UNAUTHORIZED;
767       goto end;
768    }
769
770    if (sent_pw == NULL || *sent_pw == '\0') {
771       log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
772                  "empty passwords are not accepted");
773       ret = HTTP_UNAUTHORIZED;
774       goto end;
775    }
776
777    code = krb5_cc_resolve(kcontext, "MEMORY:", &ccache);
778    if (code) {
779       log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
780                  "generating new memory ccache failed: %s",
781                  krb5_get_err_text(kcontext, code));
782       ret = HTTP_INTERNAL_SERVER_ERROR;
783       unlink(ccname);
784       goto end;
785    }
786
787    if (conf->krb_5_keytab)
788       krb5_kt_resolve(kcontext, conf->krb_5_keytab, &keytab);
789
790    all_principals_unkown = 1;
791    realms = conf->krb_auth_realms;
792    do {
793       if (realms && (code = krb5_set_default_realm(kcontext,
794                                            ap_getword_white(r->pool, &realms)))){
795          log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
796                     "krb5_set_default_realm() failed: %s",
797                     krb5_get_err_text(kcontext, code));
798          continue;
799       }
800
801       if (client) {
802          krb5_free_principal(kcontext, client);
803          client = NULL;
804       }
805       code = krb5_parse_name(kcontext, sent_name, &client);
806       if (code) {
807          log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
808                     "krb5_parse_name() failed: %s",
809                     krb5_get_err_text(kcontext, code));
810          continue;
811       }
812
813       code = verify_krb5_user(r, kcontext, client, ccache, sent_pw, 
814                               conf->krb_service_name, 
815                               keytab, conf->krb_verify_kdc);
816       if (!conf->krb_authoritative && code) {
817          /* if we're not authoritative, we allow authentication to pass on
818           * to another modules if (and only if) the user is not known to us */
819          if (all_principals_unkown && code != KRB5KDC_ERR_C_PRINCIPAL_UNKNOWN)
820             all_principals_unkown = 0;
821       }
822
823       if (code == 0)
824          break;
825
826       /* ap_getword_white() used above shifts the parameter, so it's not
827          needed to touch the realms variable */
828    } while (realms && *realms);
829
830    memset((char *)sent_pw, 0, strlen(sent_pw));
831
832    if (code) {
833       if (!conf->krb_authoritative && all_principals_unkown == 1 && code == KRB5KDC_ERR_C_PRINCIPAL_UNKNOWN)
834          ret = DECLINED;
835       else
836          ret = HTTP_UNAUTHORIZED;
837
838       goto end;
839    }
840
841    code = krb5_unparse_name(kcontext, client, &name);
842    if (code) {
843       log_rerror(APLOG_MARK, APLOG_ERR, 0, r, "krb5_unparse_name() failed: %s",
844                  krb5_get_err_text(kcontext, code));
845       ret = HTTP_UNAUTHORIZED;
846       goto end;
847    }
848    MK_USER = ap_pstrdup (r->pool, name);
849    MK_AUTH_TYPE = "Basic";
850    free(name);
851
852    if (conf->krb_save_credentials)
853       store_krb5_creds(kcontext, r, conf, ccache);
854
855    ret = OK;
856
857 end:
858    if (client)
859       krb5_free_principal(kcontext, client);
860    if (ccache)
861       krb5_cc_destroy(kcontext, ccache);
862    if (keytab)
863       krb5_kt_close(kcontext, keytab);
864    krb5_free_context(kcontext);
865
866    return ret;
867 }
868
869 /*********************************************************************
870  * GSSAPI Authentication
871  ********************************************************************/
872
873 static const char *
874 get_gss_error(MK_POOL *p, OM_uint32 err_maj, OM_uint32 err_min, char *prefix)
875 {
876    OM_uint32 maj_stat, min_stat; 
877    OM_uint32 msg_ctx = 0;
878    gss_buffer_desc status_string;
879    char *err_msg;
880    size_t len;
881
882    err_msg = ap_pstrdup(p, prefix);
883    do {
884       maj_stat = gss_display_status (&min_stat,
885                                      err_maj,
886                                      GSS_C_GSS_CODE,
887                                      GSS_C_NO_OID,
888                                      &msg_ctx,
889                                      &status_string);
890       if (GSS_ERROR(maj_stat))
891          break;
892       err_msg = ap_pstrcat(p, err_msg, ": ", (char*) status_string.value, NULL);
893       gss_release_buffer(&min_stat, &status_string);
894       
895       maj_stat = gss_display_status (&min_stat,
896                                      err_min,
897                                      GSS_C_MECH_CODE,
898                                      GSS_C_NULL_OID,
899                                      &msg_ctx,
900                                      &status_string);
901       if (!GSS_ERROR(maj_stat)) {
902          err_msg = ap_pstrcat(p, err_msg,
903                               " (", (char*) status_string.value, ")", NULL);
904          gss_release_buffer(&min_stat, &status_string);
905       }
906    } while (!GSS_ERROR(maj_stat) && msg_ctx != 0);
907
908    return err_msg;
909 }
910
911 static int
912 store_gss_creds(request_rec *r, kerb_auth_config *conf, char *princ_name,
913                 gss_cred_id_t delegated_cred)
914 {
915    OM_uint32 maj_stat, min_stat;
916    krb5_principal princ = NULL;
917    krb5_ccache ccache = NULL;
918    krb5_error_code problem;
919    krb5_context context;
920    int ret = HTTP_INTERNAL_SERVER_ERROR;
921
922    problem = krb5_init_context(&context);
923    if (problem) {
924       log_rerror(APLOG_MARK, APLOG_ERR, 0, r, "Cannot initialize krb5 context");
925       return HTTP_INTERNAL_SERVER_ERROR;
926    }
927
928    problem = krb5_parse_name(context, princ_name, &princ);
929    if (problem) {
930       log_rerror(APLOG_MARK, APLOG_ERR, 0, r, 
931          "Cannot parse delegated username (%s)", krb5_get_err_text(context, problem));
932       goto end;
933    }
934
935    problem = create_krb5_ccache(context, r, conf, princ, &ccache);
936    if (problem) {
937       log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
938          "Cannot create krb5 ccache (%s)", krb5_get_err_text(context, problem));
939       goto end;
940    }
941
942    maj_stat = gss_krb5_copy_ccache(&min_stat, delegated_cred, ccache);
943    if (GSS_ERROR(maj_stat)) {
944       log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
945          "Cannot store delegated credential (%s)", 
946          get_gss_error(r->pool, maj_stat, min_stat, "gss_krb5_copy_ccache"));
947       goto end;
948    }
949
950    krb5_cc_close(context, ccache);
951    ccache = NULL;
952    ret = 0;
953
954 end:
955    if (princ)
956       krb5_free_principal(context, princ);
957    if (ccache)
958       krb5_cc_destroy(context, ccache);
959    krb5_free_context(context);
960    return ret;
961 }
962
963 static int
964 get_gss_creds(request_rec *r,
965               kerb_auth_config *conf,
966               gss_cred_id_t *server_creds)
967 {
968    gss_buffer_desc input_token = GSS_C_EMPTY_BUFFER;
969    OM_uint32 major_status, minor_status, minor_status2;
970    gss_name_t server_name = GSS_C_NO_NAME;
971    char buf[1024];
972
973    snprintf(buf, sizeof(buf), "%s@%s", conf->krb_service_name,
974          ap_get_server_name(r));
975
976    input_token.value = buf;
977    input_token.length = strlen(buf) + 1;
978
979    major_status = gss_import_name(&minor_status, &input_token,
980                                   GSS_C_NT_HOSTBASED_SERVICE,
981                                   &server_name);
982    if (GSS_ERROR(major_status)) {
983       log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
984                  "%s", get_gss_error(r->pool, major_status, minor_status,
985                  "gss_import_name() failed"));
986       return HTTP_INTERNAL_SERVER_ERROR;
987    }
988    
989    major_status = gss_acquire_cred(&minor_status, server_name, GSS_C_INDEFINITE,
990                                    GSS_C_NO_OID_SET, GSS_C_ACCEPT,
991                                    server_creds, NULL, NULL);
992    gss_release_name(&minor_status2, &server_name);
993    if (GSS_ERROR(major_status)) {
994       log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
995                  "%s", get_gss_error(r->pool, major_status, minor_status,
996                                      "gss_acquire_cred() failed"));
997       return HTTP_INTERNAL_SERVER_ERROR;
998    }
999
1000 #ifndef HEIMDAL
1001    /*
1002     * With MIT Kerberos 5 1.3.x the gss_cred_id_t is the same as
1003     * krb5_gss_cred_id_t and krb5_gss_cred_id_rec contains a pointer to
1004     * the replay cache.
1005     * This allows us to override the replay cache function vector with
1006     * our own one.
1007     * Note that this is a dirty hack to get things working and there may
1008     * well be unknown side-effects.
1009     */
1010    if (memcmp(((krb5_gss_cred_id_t) *server_creds)->rcache->ops->type, "dfl", 3) == 0)
1011       /* Override the rcache operations */
1012       ((krb5_gss_cred_id_t) *server_creds)->rcache->ops = &mod_auth_kerb_rc_ops;
1013 #if 0
1014    else
1015       /* rcache did not point to default rcache structure, return error */
1016       return HTTP_INTERNAL_SERVER_ERROR;
1017 #endif
1018 #endif
1019    
1020    return 0;
1021 }
1022
1023 static int
1024 cmp_gss_type(gss_buffer_t token, gss_OID oid)
1025 {
1026    unsigned char *p;
1027    size_t len;
1028
1029    if (token->length == 0)
1030       return GSS_S_DEFECTIVE_TOKEN;
1031
1032    /* XXX if (token->value == NTLMSSP) log_debug("NTLM mechanism used"); */
1033
1034    p = token->value;
1035    if (*p++ != 0x60)
1036       return GSS_S_DEFECTIVE_TOKEN;
1037    len = *p++;
1038    if (len & 0x80) {
1039       if ((len & 0x7f) > 4)
1040          return GSS_S_DEFECTIVE_TOKEN;
1041       p += len & 0x7f;
1042    }
1043    if (*p++ != 0x06)
1044       return GSS_S_DEFECTIVE_TOKEN;
1045
1046    if (((OM_uint32) *p++) != oid->length)
1047       return GSS_S_DEFECTIVE_TOKEN;
1048
1049    return memcmp(p, oid->elements, oid->length);
1050 }
1051
1052 static int
1053 authenticate_user_gss(request_rec *r, kerb_auth_config *conf,
1054                       const char *auth_line, char **negotiate_ret_value)
1055 {
1056   OM_uint32 major_status, minor_status, minor_status2;
1057   gss_buffer_desc input_token = GSS_C_EMPTY_BUFFER;
1058   gss_buffer_desc output_token = GSS_C_EMPTY_BUFFER;
1059   const char *auth_param = NULL;
1060   int ret;
1061   gss_name_t client_name = GSS_C_NO_NAME;
1062   gss_cred_id_t delegated_cred = GSS_C_NO_CREDENTIAL;
1063   OM_uint32 (*accept_sec_token)();
1064   gss_OID_desc spnego_oid;
1065   gss_ctx_id_t context = GSS_C_NO_CONTEXT;
1066   gss_cred_id_t server_creds = GSS_C_NO_CREDENTIAL;
1067
1068   *negotiate_ret_value = "\0";
1069
1070   spnego_oid.length = 6;
1071   spnego_oid.elements = (void *)"\x2b\x06\x01\x05\x05\x02";
1072
1073   if (conf->krb_5_keytab) {
1074      char *ktname;
1075      /* we don't use the ap_* calls here, since the string passed to putenv()
1076       * will become part of the enviroment and shouldn't be free()ed by apache
1077       */
1078      ktname = malloc(strlen("KRB5_KTNAME=") + strlen(conf->krb_5_keytab) + 1);
1079      if (ktname == NULL) {
1080         log_rerror(APLOG_MARK, APLOG_ERR, 0, r, "malloc() failed: not enough memory");
1081         ret = HTTP_INTERNAL_SERVER_ERROR;
1082         goto end;
1083      }
1084      sprintf(ktname, "KRB5_KTNAME=%s", conf->krb_5_keytab);
1085      putenv(ktname);
1086   }
1087
1088   ret = get_gss_creds(r, conf, &server_creds);
1089   if (ret)
1090      goto end;
1091
1092   /* ap_getword() shifts parameter */
1093   auth_param = ap_getword_white(r->pool, &auth_line);
1094   if (auth_param == NULL) {
1095      log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
1096                 "No Authorization parameter in request from client");
1097      ret = HTTP_UNAUTHORIZED;
1098      goto end;
1099   }
1100
1101   input_token.length = ap_base64decode_len(auth_param) + 1;
1102   input_token.value = ap_pcalloc(r->connection->pool, input_token.length);
1103   if (input_token.value == NULL) {
1104      log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
1105                 "ap_pcalloc() failed (not enough memory)");
1106      ret = HTTP_INTERNAL_SERVER_ERROR;
1107      goto end;
1108   }
1109   input_token.length = ap_base64decode(input_token.value, auth_param);
1110
1111   accept_sec_token = (cmp_gss_type(&input_token, &spnego_oid) == 0) ?
1112                         gss_accept_sec_context_spnego : gss_accept_sec_context;
1113
1114   major_status = accept_sec_token(&minor_status,
1115                                   &context,
1116                                   server_creds,
1117                                   &input_token,
1118                                   GSS_C_NO_CHANNEL_BINDINGS,
1119                                   &client_name,
1120                                   NULL,
1121                                   &output_token,
1122                                   NULL,
1123                                   NULL,
1124                                   &delegated_cred);
1125   if (output_token.length) {
1126      char *token = NULL;
1127      size_t len;
1128      
1129      len = ap_base64encode_len(output_token.length) + 1;
1130      token = ap_pcalloc(r->connection->pool, len + 1);
1131      if (token == NULL) {
1132         log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
1133                    "ap_pcalloc() failed (not enough memory)");
1134         ret = HTTP_INTERNAL_SERVER_ERROR;
1135         gss_release_buffer(&minor_status2, &output_token);
1136         goto end;
1137      }
1138      ap_base64encode(token, output_token.value, output_token.length);
1139      token[len] = '\0';
1140      *negotiate_ret_value = token;
1141      gss_release_buffer(&minor_status2, &output_token);
1142   }
1143
1144   if (GSS_ERROR(major_status)) {
1145      log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
1146                 "%s", get_gss_error(r->pool, major_status, minor_status,
1147                                     "gss_accept_sec_context() failed"));
1148      /* Don't offer the Negotiate method again if call to GSS layer failed */
1149      *negotiate_ret_value = NULL;
1150      ret = HTTP_UNAUTHORIZED;
1151      goto end;
1152   }
1153
1154 #if 0
1155   /* This is a _Kerberos_ module so multiple authentication rounds aren't
1156    * supported. If we wanted a generic GSS authentication we would have to do
1157    * some magic with exporting context etc. */
1158   if (major_status & GSS_S_CONTINUE_NEEDED) {
1159      ret = HTTP_UNAUTHORIZED;
1160      goto end;
1161   }
1162 #endif
1163
1164   major_status = gss_display_name(&minor_status, client_name, &output_token, NULL);
1165   gss_release_name(&minor_status, &client_name); 
1166   if (GSS_ERROR(major_status)) {
1167     log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
1168                "%s", get_gss_error(r->pool, major_status, minor_status,
1169                                    "gss_export_name() failed"));
1170     ret = HTTP_INTERNAL_SERVER_ERROR;
1171     goto end;
1172   }
1173
1174   MK_AUTH_TYPE = "Negotiate";
1175   MK_USER = ap_pstrdup(r->pool, output_token.value);
1176
1177   if (conf->krb_save_credentials && delegated_cred != GSS_C_NO_CREDENTIAL)
1178      store_gss_creds(r, conf, (char *)output_token.value, delegated_cred);
1179
1180   if (*negotiate_ret_value)
1181      set_kerb_auth_headers(r, conf, 0, 0, *negotiate_ret_value);
1182
1183   gss_release_buffer(&minor_status, &output_token);
1184
1185   ret = OK;
1186
1187 end:
1188   if (delegated_cred)
1189      gss_release_cred(&minor_status, &delegated_cred);
1190
1191   if (output_token.length) 
1192      gss_release_buffer(&minor_status, &output_token);
1193
1194   if (client_name != GSS_C_NO_NAME)
1195      gss_release_name(&minor_status, &client_name);
1196
1197   if (server_creds != GSS_C_NO_CREDENTIAL)
1198      gss_release_cred(&minor_status, &server_creds);
1199
1200   if (context != GSS_C_NO_CONTEXT)
1201      gss_delete_sec_context(&minor_status, &context, GSS_C_NO_BUFFER);
1202
1203   return ret;
1204 }
1205 #endif /* KRB5 */
1206
1207 static int
1208 already_succeeded(request_rec *r)
1209 {
1210    if (ap_is_initial_req(r) || MK_AUTH_TYPE == NULL)
1211       return 0;
1212    if (strcmp(MK_AUTH_TYPE, "Negotiate") ||
1213        (strcmp(MK_AUTH_TYPE, "Basic") && strchr(MK_USER, '@')))
1214       return 1;
1215    return 0;
1216 }
1217
1218 static void
1219 set_kerb_auth_headers(request_rec *r, const kerb_auth_config *conf,
1220                       int use_krb4, int use_krb5pwd, char *negotiate_ret_value)
1221 {
1222    const char *auth_name = NULL;
1223    int set_basic = 0;
1224    char *negoauth_param;
1225    const char *header_name = 
1226       (r->proxyreq == PROXYREQ_PROXY) ? "Proxy-Authenticate" : "WWW-Authenticate";
1227
1228    /* get the user realm specified in .htaccess */
1229    auth_name = ap_auth_name(r);
1230
1231    /* XXX should the WWW-Authenticate header be cleared first? */
1232 #ifdef KRB5
1233    if (negotiate_ret_value != NULL && conf->krb_method_gssapi) {
1234       negoauth_param = (*negotiate_ret_value == '\0') ? "Negotiate" :
1235                   ap_pstrcat(r->pool, "Negotiate ", negotiate_ret_value, NULL);
1236       ap_table_add(r->err_headers_out, header_name, negoauth_param);
1237    }
1238    if (use_krb5pwd && conf->krb_method_k5pass) {
1239       ap_table_add(r->err_headers_out, header_name,
1240                    ap_pstrcat(r->pool, "Basic realm=\"", auth_name, "\"", NULL));
1241       set_basic = 1;
1242    }
1243 #endif
1244
1245 #ifdef KRB4
1246    if (use_krb4 && conf->krb_method_k4pass && !set_basic)
1247       ap_table_add(r->err_headers_out, header_name,
1248                   ap_pstrcat(r->pool, "Basic realm=\"", auth_name, "\"", NULL));
1249 #endif
1250 }
1251
1252 int kerb_authenticate_user(request_rec *r)
1253 {
1254    kerb_auth_config *conf = 
1255       (kerb_auth_config *) ap_get_module_config(r->per_dir_config,
1256                                                 &auth_kerb_module);
1257    const char *auth_type = NULL;
1258    const char *auth_line = NULL;
1259    const char *type = NULL;
1260    int use_krb5 = 0, use_krb4 = 0;
1261    int ret;
1262    static int last_return = HTTP_UNAUTHORIZED;
1263    char *negotiate_ret_value = NULL;
1264
1265    /* get the type specified in .htaccess */
1266    type = ap_auth_type(r);
1267
1268    if (type && strcasecmp(type, "Kerberos") == 0)
1269       use_krb5 = use_krb4 = 1;
1270    else if(type && strcasecmp(type, "KerberosV5") == 0)
1271       use_krb4 = 0;
1272    else if(type && strcasecmp(type, "KerberosV4") == 0)
1273       use_krb5 = 0;
1274    else
1275       return DECLINED;
1276
1277    /* get what the user sent us in the HTTP header */
1278    auth_line = MK_TABLE_GET(r->headers_in, "Authorization");
1279    if (!auth_line) {
1280        auth_line = MK_TABLE_GET(r->headers_in, "Proxy-Authorization");
1281        if (!auth_line) {
1282                set_kerb_auth_headers(r, conf, use_krb4, use_krb5,
1283                                      (use_krb5) ? "\0" : NULL);
1284                return HTTP_UNAUTHORIZED;
1285        }
1286    }
1287    auth_type = ap_getword_white(r->pool, &auth_line);
1288
1289    if (already_succeeded(r))
1290       return last_return;
1291
1292    ret = HTTP_UNAUTHORIZED;
1293
1294 #ifdef KRB5
1295    if (use_krb5 && conf->krb_method_gssapi &&
1296        strcasecmp(auth_type, "Negotiate") == 0) {
1297       ret = authenticate_user_gss(r, conf, auth_line, &negotiate_ret_value);
1298    } else if (use_krb5 && conf->krb_method_k5pass &&
1299               strcasecmp(auth_type, "Basic") == 0) {
1300        ret = authenticate_user_krb5pwd(r, conf, auth_line);
1301    }
1302 #endif
1303
1304 #ifdef KRB4
1305    if (ret == HTTP_UNAUTHORIZED && use_krb4 && conf->krb_method_k4pass &&
1306        strcasecmp(auth_type, "Basic") == 0)
1307       ret = authenticate_user_krb4pwd(r, conf, auth_line);
1308 #endif
1309
1310    if (ret == HTTP_UNAUTHORIZED)
1311       set_kerb_auth_headers(r, conf, use_krb4, use_krb5, negotiate_ret_value);
1312
1313    /* XXX log_debug: if ret==OK, log(user XY authenticated) */
1314
1315    last_return = ret;
1316    return ret;
1317 }
1318
1319
1320 /*************************************************************************** 
1321  Module Setup/Configuration
1322  ***************************************************************************/
1323 #ifndef STANDARD20_MODULE_STUFF
1324 module MODULE_VAR_EXPORT auth_kerb_module = {
1325         STANDARD_MODULE_STUFF,
1326         NULL,                           /*      module initializer            */
1327         kerb_dir_create_config,         /*      per-directory config creator  */
1328         NULL,                           /*      per-directory config merger   */
1329         NULL,                           /*      per-server    config creator  */
1330         NULL,                           /*      per-server    config merger   */
1331         kerb_auth_cmds,                 /*      command table                 */
1332         NULL,                           /* [ 9] content handlers              */
1333         NULL,                           /* [ 2] URI-to-filename translation   */
1334         kerb_authenticate_user,         /* [ 5] check/validate user_id        */
1335         NULL,                           /* [ 6] check user_id is valid *here* */
1336         NULL,                           /* [ 4] check access by host address  */
1337         NULL,                           /* [ 7] MIME type checker/setter      */
1338         NULL,                           /* [ 8] fixups                        */
1339         NULL,                           /* [10] logger                        */
1340         NULL,                           /* [ 3] header parser                 */
1341         NULL,                           /*      process initialization        */
1342         NULL,                           /*      process exit/cleanup          */
1343         NULL                            /* [ 1] post read_request handling    */
1344 };
1345 #else
1346 static int
1347 kerb_init_handler(apr_pool_t *p, apr_pool_t *plog,
1348                   apr_pool_t *ptemp, server_rec *s)
1349 {
1350    ap_add_version_component(p, "mod_auth_kerb/" MODAUTHKERB_VERSION);
1351    return OK;
1352 }
1353
1354 void kerb_register_hooks(apr_pool_t *p)
1355 {
1356    ap_hook_post_config(kerb_init_handler, NULL, NULL, APR_HOOK_MIDDLE);
1357    ap_hook_check_user_id(kerb_authenticate_user, NULL, NULL, APR_HOOK_MIDDLE);
1358 }
1359
1360 module AP_MODULE_DECLARE_DATA auth_kerb_module =
1361 {
1362    STANDARD20_MODULE_STUFF,
1363    kerb_dir_create_config,      /* create per-dir    conf structures  */
1364    NULL,                        /* merge  per-dir    conf structures  */
1365    NULL,                        /* create per-server conf structures  */
1366    NULL,                        /* merge  per-server conf structures  */
1367    kerb_auth_cmds,              /* table of configuration directives  */
1368    kerb_register_hooks          /* register hooks                     */
1369 };
1370 #endif