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