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