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