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