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