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