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