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