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