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