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