accepted ticket [1707336]: Include valid options when calling krb5_get_init_creds_passw
[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_get_init_creds_opt options;
685    krb5_error_code ret;
686    krb5_ccache ret_ccache = NULL;
687    char *name = NULL;
688
689    /* XXX error messages shouldn't be logged here (and in the while() loop in
690     * authenticate_user_krb5pwd() as weell), in order to avoid confusing log
691     * entries when using multiple realms */
692
693    memset(&creds, 0, sizeof(creds));
694
695    ret = krb5_unparse_name(context, principal, &name);
696    if (ret == 0) {
697       log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
698                  "Trying to get TGT for user %s", name);
699       free(name);
700    }
701
702    krb5_get_init_creds_opt_init(&options);
703    ret = krb5_get_init_creds_password(context, &creds, principal, 
704                                       (char *)password, NULL,
705                                       NULL, 0, NULL, &options);
706    if (ret) {
707       log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
708                  "krb5_get_init_creds_password() failed: %s",
709                  krb5_get_err_text(context, ret));
710       goto end;
711    }
712
713    /* XXX
714    {
715       char *realm;
716
717       krb5_get_default_realm(context, &realm);
718       log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
719                  "trying to verify password using key for %s/%s@%s",
720                  service, ap_get_server_name(r), realm);
721    }
722    */
723
724    if (krb_verify_kdc &&
725        (ret = verify_krb5_init_creds(r, context, &creds, server, keytab))) {
726        log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
727                   "failed to verify krb5 credentials: %s",
728                   krb5_get_err_text(context, ret));
729        goto end;
730    }
731
732 #ifdef HAVE_KRB5_CC_NEW_UNIQUE
733    ret = krb5_cc_new_unique(context, "MEMORY", NULL, &ret_ccache);
734 #else
735    ret = krb5_cc_resolve(context, "MEMORY:", &ret_ccache);
736 #endif
737
738    if (ret) {
739       log_rerror(APLOG_MARK, APLOG_ERR, 0, r, 
740                  "generating new memory ccache failed: %s",
741                  krb5_get_err_text(context, ret));
742       goto end;
743    }
744
745    ret = krb5_cc_initialize(context, ret_ccache, principal);
746    if (ret) {
747       log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
748                  "krb5_cc_initialize() failed: %s",
749                  krb5_get_err_text(context, ret));
750       goto end;
751    }
752
753    ret = krb5_cc_store_cred(context, ret_ccache, &creds);
754    if (ret) {
755       log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
756                  "krb5_cc_store_cred() failed: %s",
757                  krb5_get_err_text(context, ret));
758       goto end;
759    }
760    *ccache = ret_ccache;
761    ret_ccache = NULL;
762
763 end:
764    krb5_free_cred_contents(context, &creds);
765    if (ret_ccache)
766       krb5_cc_destroy(context, ret_ccache);
767
768    return ret;
769 }
770
771 static int
772 krb5_cache_cleanup(void *data)
773 {
774    krb5_context context;
775    krb5_ccache  cache;
776    krb5_error_code problem;
777    char *cache_name = (char *) data;
778
779    problem = krb5_init_context(&context);
780    if (problem) {
781       /* ap_log_error(APLOG_MARK, APLOG_ERR, 0, NULL, "krb5_init_context() failed"); */
782       return HTTP_INTERNAL_SERVER_ERROR;
783    }
784
785    problem = krb5_cc_resolve(context, cache_name, &cache);
786    if (problem) {
787       /* log_error(APLOG_MARK, APLOG_ERR, 0, NULL, 
788                 "krb5_cc_resolve() failed (%s: %s)",
789                 cache_name, krb5_get_err_text(context, problem)); */
790       return HTTP_INTERNAL_SERVER_ERROR;
791    }
792
793    krb5_cc_destroy(context, cache);
794    krb5_free_context(context);
795    return OK;
796 }
797
798 static int
799 create_krb5_ccache(krb5_context kcontext,
800                    request_rec *r,
801                    kerb_auth_config *conf,
802                    krb5_principal princ,
803                    krb5_ccache *ccache)
804 {
805    char *ccname;
806    int fd;
807    krb5_error_code problem;
808    int ret;
809    krb5_ccache tmp_ccache = NULL;
810
811    ccname = apr_psprintf(r->pool, "FILE:%s/krb5cc_apache_XXXXXX", P_tmpdir);
812    fd = mkstemp(ccname + strlen("FILE:"));
813    if (fd < 0) {
814       log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
815                  "mkstemp() failed: %s", strerror(errno));
816       ret = HTTP_INTERNAL_SERVER_ERROR;
817       goto end;
818    }
819    close(fd);
820
821    problem = krb5_cc_resolve(kcontext, ccname, &tmp_ccache);
822    if (problem) {
823       log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
824                  "krb5_cc_resolve() failed: %s",
825                  krb5_get_err_text(kcontext, problem));
826       ret = HTTP_INTERNAL_SERVER_ERROR;
827       unlink(ccname);
828       goto end;
829    }
830
831    problem = krb5_cc_initialize(kcontext, tmp_ccache, princ);
832    if (problem) {
833       log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
834                  "Cannot initialize krb5 ccache %s: krb5_cc_initialize() failed: %s",
835                  ccname, krb5_get_err_text(kcontext, problem));
836       ret = HTTP_INTERNAL_SERVER_ERROR;
837       goto end;
838    }
839
840    apr_table_setn(r->subprocess_env, "KRB5CCNAME", ccname);
841    apr_pool_cleanup_register(r->pool, ccname, krb5_cache_cleanup,
842                              apr_pool_cleanup_null);
843
844    *ccache = tmp_ccache;
845    tmp_ccache = NULL;
846
847    ret = OK;
848
849 end:
850    if (tmp_ccache)
851       krb5_cc_destroy(kcontext, tmp_ccache);
852
853    return ret;
854 }
855
856 static int
857 store_krb5_creds(krb5_context kcontext,
858                  request_rec *r,
859                  kerb_auth_config *conf,
860                  krb5_ccache delegated_cred)
861 {
862    char errstr[1024];
863    krb5_error_code problem;
864    krb5_principal princ;
865    krb5_ccache ccache;
866    int ret;
867
868    problem = krb5_cc_get_principal(kcontext, delegated_cred, &princ);
869    if (problem) {
870       snprintf(errstr, sizeof(errstr), "krb5_cc_get_principal() failed: %s",
871                krb5_get_err_text(kcontext, problem));
872       return HTTP_INTERNAL_SERVER_ERROR;
873    }
874
875    ret = create_krb5_ccache(kcontext, r, conf, princ, &ccache);
876    if (ret) {
877       krb5_free_principal(kcontext, princ);
878       return ret;
879    }
880
881 #ifdef HEIMDAL
882    problem = krb5_cc_copy_cache(kcontext, delegated_cred, ccache);
883 #else
884    problem = krb5_cc_copy_creds(kcontext, delegated_cred, ccache);
885 #endif
886    krb5_free_principal(kcontext, princ);
887    if (problem) {
888       snprintf(errstr, sizeof(errstr), "Failed to store credentials: %s",
889                krb5_get_err_text(kcontext, problem));
890       krb5_cc_destroy(kcontext, ccache);
891       return HTTP_INTERNAL_SERVER_ERROR;
892    }
893
894    krb5_cc_close(kcontext, ccache);
895    return OK;
896 }
897
898
899 static int
900 authenticate_user_krb5pwd(request_rec *r,
901                           kerb_auth_config *conf,
902                           const char *auth_line)
903 {
904    const char      *sent_pw = NULL; 
905    const char      *sent_name = NULL;
906    const char      *realms = NULL;
907    const char      *realm = NULL;
908    krb5_context    kcontext = NULL;
909    krb5_error_code code;
910    krb5_principal  client = NULL;
911    krb5_principal  server = NULL;
912    krb5_ccache     ccache = NULL;
913    krb5_keytab     keytab = NULL;
914    int             ret;
915    char            *name = NULL;
916    int             all_principals_unkown;
917    char            *p = NULL;
918
919    //temporary fix for KrbServiceName Any, use default SERVICE_NAME
920    if (conf->krb_service_name && strcmp(conf->krb_service_name,"Any") == 0)
921       snprintf(conf->krb_service_name, 5,"%s",SERVICE_NAME);
922
923    code = krb5_init_context(&kcontext);
924    if (code) {
925       log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
926                  "Cannot initialize Kerberos5 context (%d)", code);
927       return HTTP_INTERNAL_SERVER_ERROR;
928    }
929
930    sent_pw = ap_pbase64decode(r->pool, auth_line);
931    sent_name = ap_getword_nulls_nc (r->pool, (char **) &sent_pw, ':');
932
933    if (sent_pw == NULL || *sent_pw == '\0') {
934       log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
935                  "empty passwords are not accepted");
936       ret = HTTP_UNAUTHORIZED;
937       goto end;
938    }
939
940    if (conf->krb_5_keytab)
941       krb5_kt_resolve(kcontext, conf->krb_5_keytab, &keytab);
942
943    if (conf->krb_service_name && strchr(conf->krb_service_name, '/') != NULL)
944       ret = krb5_parse_name (kcontext, conf->krb_service_name, &server);
945    else
946       ret = krb5_sname_to_principal(kcontext, ap_get_server_name(r),
947                                     (conf->krb_service_name) ? conf->krb_service_name : SERVICE_NAME,
948                                     KRB5_NT_SRV_HST, &server);
949
950    if (ret) {
951       log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
952                  "Error parsing server name (%s): %s",
953                  (conf->krb_service_name) ? conf->krb_service_name : SERVICE_NAME,
954                  krb5_get_err_text(kcontext, ret));
955       ret = HTTP_UNAUTHORIZED;
956       goto end;
957    }
958
959    code = krb5_unparse_name(kcontext, server, &name);
960    if (code) {
961       log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
962                  "krb5_unparse_name() failed: %s",
963                  krb5_get_err_text(kcontext, code));
964       ret = HTTP_UNAUTHORIZED;
965       goto end;
966    }
967    log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, "Using %s as server principal for password verification", name);
968    free(name);
969    name = NULL;
970
971    p = strchr(sent_name, '@');
972    if (p) {
973       *p++ = '\0';
974       if (conf->krb_auth_realms && !ap_find_token(r->pool, conf->krb_auth_realms, p)) {
975          log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
976                     "Specified realm `%s' not allowed by configuration", p);
977          ret = HTTP_UNAUTHORIZED;
978          goto end;
979       }
980    }
981
982    realms = (p) ? p : conf->krb_auth_realms;
983    all_principals_unkown = 1;
984    do {
985       name = (char *) sent_name;
986       if (realms && (realm = ap_getword_white(r->pool, &realms)))
987          name = apr_psprintf(r->pool, "%s@%s", sent_name, realm);
988
989       if (client) {
990          krb5_free_principal(kcontext, client);
991          client = NULL;
992       }
993
994       code = krb5_parse_name(kcontext, name, &client);
995       if (code) {
996          log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
997                     "krb5_parse_name() failed: %s",
998                     krb5_get_err_text(kcontext, code));
999          continue;
1000       }
1001
1002       code = verify_krb5_user(r, kcontext, client, sent_pw,
1003                               server, keytab, conf->krb_verify_kdc, &ccache);
1004       if (!conf->krb_authoritative && code) {
1005          /* if we're not authoritative, we allow authentication to pass on
1006           * to another modules if (and only if) the user is not known to us */
1007          if (all_principals_unkown && code != KRB5KDC_ERR_C_PRINCIPAL_UNKNOWN)
1008             all_principals_unkown = 0;
1009       }
1010
1011       if (code == 0)
1012          break;
1013
1014       /* ap_getword_white() used above shifts the parameter, so it's not
1015          needed to touch the realms variable */
1016    } while (realms && *realms);
1017
1018    memset((char *)sent_pw, 0, strlen(sent_pw));
1019
1020    if (code) {
1021       if (!conf->krb_authoritative && all_principals_unkown == 1 && code == KRB5KDC_ERR_C_PRINCIPAL_UNKNOWN)
1022          ret = DECLINED;
1023       else
1024          ret = HTTP_UNAUTHORIZED;
1025
1026       goto end;
1027    }
1028
1029    code = krb5_unparse_name(kcontext, client, &name);
1030    if (code) {
1031       log_rerror(APLOG_MARK, APLOG_ERR, 0, r, "krb5_unparse_name() failed: %s",
1032                  krb5_get_err_text(kcontext, code));
1033       ret = HTTP_UNAUTHORIZED;
1034       goto end;
1035    }
1036    MK_USER = apr_pstrdup (r->pool, name);
1037    MK_AUTH_TYPE = "Basic";
1038    free(name);
1039
1040    if (conf->krb_save_credentials)
1041       store_krb5_creds(kcontext, r, conf, ccache);
1042
1043    ret = OK;
1044
1045 end:
1046    log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
1047               "kerb_authenticate_user_krb5pwd ret=%d user=%s authtype=%s",
1048               ret, (MK_USER)?MK_USER:"(NULL)", (MK_AUTH_TYPE)?MK_AUTH_TYPE:"(NULL)");
1049    if (client)
1050       krb5_free_principal(kcontext, client);
1051    if (server)
1052       krb5_free_principal(kcontext, server);
1053    if (ccache)
1054       krb5_cc_destroy(kcontext, ccache);
1055    if (keytab)
1056       krb5_kt_close(kcontext, keytab);
1057    krb5_free_context(kcontext);
1058
1059    return ret;
1060 }
1061
1062 /*********************************************************************
1063  * GSSAPI Authentication
1064  ********************************************************************/
1065
1066 static const char *
1067 get_gss_error(request_rec *r, OM_uint32 err_maj, OM_uint32 err_min, char *prefix)
1068 {
1069    OM_uint32 maj_stat, min_stat; 
1070    OM_uint32 msg_ctx = 0;
1071    gss_buffer_desc status_string;
1072    char *err_msg;
1073
1074    log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
1075               "GSS-API major_status:%8.8x, minor_status:%8.8x",
1076               err_maj, err_min);
1077
1078    err_msg = apr_pstrdup(r->pool, prefix);
1079    do {
1080       maj_stat = gss_display_status (&min_stat,
1081                                      err_maj,
1082                                      GSS_C_GSS_CODE,
1083                                      GSS_C_NO_OID,
1084                                      &msg_ctx,
1085                                      &status_string);
1086       if (!GSS_ERROR(maj_stat)) {
1087          err_msg = apr_pstrcat(r->pool, err_msg, ": ",
1088                                (char*) status_string.value, NULL);
1089          gss_release_buffer(&min_stat, &status_string);
1090       }
1091    } while (!GSS_ERROR(maj_stat) && msg_ctx != 0);
1092
1093    msg_ctx = 0;
1094    err_msg = apr_pstrcat(r->pool, err_msg, " (", NULL);
1095    do {
1096       maj_stat = gss_display_status (&min_stat,
1097                                      err_min,
1098                                      GSS_C_MECH_CODE,
1099                                      GSS_C_NULL_OID,
1100                                      &msg_ctx,
1101                                      &status_string);
1102       if (!GSS_ERROR(maj_stat)) {
1103          err_msg = apr_pstrcat(r->pool, err_msg, ", ",
1104                                (char *) status_string.value, NULL);
1105          gss_release_buffer(&min_stat, &status_string);
1106       }
1107    } while (!GSS_ERROR(maj_stat) && msg_ctx != 0);
1108    err_msg = apr_pstrcat(r->pool, err_msg, ")", NULL);
1109
1110    return err_msg;
1111 }
1112
1113 static int
1114 store_gss_creds(request_rec *r, kerb_auth_config *conf, char *princ_name,
1115                 gss_cred_id_t delegated_cred)
1116 {
1117    OM_uint32 maj_stat, min_stat;
1118    krb5_principal princ = NULL;
1119    krb5_ccache ccache = NULL;
1120    krb5_error_code problem;
1121    krb5_context context;
1122    int ret = HTTP_INTERNAL_SERVER_ERROR;
1123
1124    problem = krb5_init_context(&context);
1125    if (problem) {
1126       log_rerror(APLOG_MARK, APLOG_ERR, 0, r, "Cannot initialize krb5 context");
1127       return HTTP_INTERNAL_SERVER_ERROR;
1128    }
1129
1130    problem = krb5_parse_name(context, princ_name, &princ);
1131    if (problem) {
1132       log_rerror(APLOG_MARK, APLOG_ERR, 0, r, 
1133          "Cannot parse delegated username (%s)", krb5_get_err_text(context, problem));
1134       goto end;
1135    }
1136
1137    problem = create_krb5_ccache(context, r, conf, princ, &ccache);
1138    if (problem) {
1139       log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
1140          "Cannot create krb5 ccache (%s)", krb5_get_err_text(context, problem));
1141       goto end;
1142    }
1143
1144    maj_stat = gss_krb5_copy_ccache(&min_stat, delegated_cred, ccache);
1145    if (GSS_ERROR(maj_stat)) {
1146       log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
1147          "Cannot store delegated credential (%s)", 
1148          get_gss_error(r, maj_stat, min_stat, "gss_krb5_copy_ccache"));
1149       goto end;
1150    }
1151
1152    krb5_cc_close(context, ccache);
1153    ccache = NULL;
1154    ret = 0;
1155
1156 end:
1157    if (princ)
1158       krb5_free_principal(context, princ);
1159    if (ccache)
1160       krb5_cc_destroy(context, ccache);
1161    krb5_free_context(context);
1162    return ret;
1163 }
1164
1165 static int
1166 get_gss_creds(request_rec *r,
1167               kerb_auth_config *conf,
1168               gss_cred_id_t *server_creds)
1169 {
1170    gss_buffer_desc token = GSS_C_EMPTY_BUFFER;
1171    OM_uint32 major_status, minor_status, minor_status2;
1172    gss_name_t server_name = GSS_C_NO_NAME;
1173    char buf[1024];
1174    int have_server_princ;
1175
1176
1177    have_server_princ = conf->krb_service_name && strchr(conf->krb_service_name, '/') != NULL;
1178    if (have_server_princ)
1179       strncpy(buf, conf->krb_service_name, sizeof(buf));
1180    else if (conf->krb_service_name && strcmp(conf->krb_service_name,"Any") == 0) {      
1181       *server_creds = GSS_C_NO_CREDENTIAL;
1182       return 0;
1183    }
1184    else
1185       snprintf(buf, sizeof(buf), "%s@%s",
1186                (conf->krb_service_name) ? conf->krb_service_name : SERVICE_NAME,
1187                ap_get_server_name(r));
1188
1189    token.value = buf;
1190    token.length = strlen(buf) + 1;
1191
1192    major_status = gss_import_name(&minor_status, &token,
1193                                   (have_server_princ) ? GSS_KRB5_NT_PRINCIPAL_NAME : GSS_C_NT_HOSTBASED_SERVICE,
1194                                   &server_name);
1195    memset(&token, 0, sizeof(token));
1196    if (GSS_ERROR(major_status)) {
1197       log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
1198                  "%s", get_gss_error(r, major_status, minor_status,
1199                  "gss_import_name() failed"));
1200       return HTTP_INTERNAL_SERVER_ERROR;
1201    }
1202
1203    major_status = gss_display_name(&minor_status, server_name, &token, NULL);
1204    if (GSS_ERROR(major_status)) {
1205       /* Perhaps we could just ignore this error but it's safer to give up now,
1206          I think */
1207       log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
1208                  "%s", get_gss_error(r, major_status, minor_status,
1209                                      "gss_display_name() failed"));
1210       return HTTP_INTERNAL_SERVER_ERROR;
1211    }
1212
1213    log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, "Acquiring creds for %s",
1214               token.value);
1215    gss_release_buffer(&minor_status, &token);
1216    
1217    major_status = gss_acquire_cred(&minor_status, server_name, GSS_C_INDEFINITE,
1218                                    GSS_C_NO_OID_SET, GSS_C_ACCEPT,
1219                                    server_creds, NULL, NULL);
1220    gss_release_name(&minor_status2, &server_name);
1221    if (GSS_ERROR(major_status)) {
1222       log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
1223                  "%s", get_gss_error(r, major_status, minor_status,
1224                                      "gss_acquire_cred() failed"));
1225       return HTTP_INTERNAL_SERVER_ERROR;
1226    }
1227
1228 #ifndef HEIMDAL
1229    /*
1230     * With MIT Kerberos 5 1.3.x the gss_cred_id_t is the same as
1231     * krb5_gss_cred_id_t and krb5_gss_cred_id_rec contains a pointer to
1232     * the replay cache.
1233     * This allows us to override the replay cache function vector with
1234     * our own one.
1235     * Note that this is a dirty hack to get things working and there may
1236     * well be unknown side-effects.
1237     */
1238    {
1239       krb5_gss_cred_id_t gss_creds = (krb5_gss_cred_id_t) *server_creds;
1240
1241       /* First we try to verify we are linked with 1.3.x to prevent from
1242          crashing when linked with 1.4.x */
1243       if (gss_creds && (gss_creds->usage == GSS_C_ACCEPT)) {
1244          if (gss_creds->rcache && gss_creds->rcache->ops &&
1245              gss_creds->rcache->ops->type &&  
1246              memcmp(gss_creds->rcache->ops->type, "dfl", 3) == 0)
1247           /* Override the rcache operations */
1248          gss_creds->rcache->ops = &mod_auth_kerb_rc_ops;
1249       }
1250    }
1251 #endif
1252    
1253    return 0;
1254 }
1255
1256 static int
1257 cmp_gss_type(gss_buffer_t token, gss_OID oid)
1258 {
1259    unsigned char *p;
1260    size_t len;
1261
1262    if (token->length == 0)
1263       return GSS_S_DEFECTIVE_TOKEN;
1264
1265    p = token->value;
1266    if (*p++ != 0x60)
1267       return GSS_S_DEFECTIVE_TOKEN;
1268    len = *p++;
1269    if (len & 0x80) {
1270       if ((len & 0x7f) > 4)
1271          return GSS_S_DEFECTIVE_TOKEN;
1272       p += len & 0x7f;
1273    }
1274    if (*p++ != 0x06)
1275       return GSS_S_DEFECTIVE_TOKEN;
1276
1277    if (((OM_uint32) *p++) != oid->length)
1278       return GSS_S_DEFECTIVE_TOKEN;
1279
1280    return memcmp(p, oid->elements, oid->length);
1281 }
1282
1283 static int
1284 authenticate_user_gss(request_rec *r, kerb_auth_config *conf,
1285                       const char *auth_line, char **negotiate_ret_value)
1286 {
1287   OM_uint32 major_status, minor_status, minor_status2;
1288   gss_buffer_desc input_token = GSS_C_EMPTY_BUFFER;
1289   gss_buffer_desc output_token = GSS_C_EMPTY_BUFFER;
1290   const char *auth_param = NULL;
1291   int ret;
1292   gss_name_t client_name = GSS_C_NO_NAME;
1293   gss_cred_id_t delegated_cred = GSS_C_NO_CREDENTIAL;
1294   OM_uint32 (KRB5_LIB_FUNCTION *accept_sec_token)
1295                          (OM_uint32 *, gss_ctx_id_t *, const gss_cred_id_t,
1296                          const gss_buffer_t, const gss_channel_bindings_t,
1297                          gss_name_t *, gss_OID *, gss_buffer_t, OM_uint32 *,
1298                          OM_uint32 *, gss_cred_id_t *);
1299   gss_OID_desc spnego_oid;
1300   gss_ctx_id_t context = GSS_C_NO_CONTEXT;
1301   gss_cred_id_t server_creds = GSS_C_NO_CREDENTIAL;
1302   OM_uint32 ret_flags = 0;
1303
1304   *negotiate_ret_value = "\0";
1305
1306   spnego_oid.length = 6;
1307   spnego_oid.elements = (void *)"\x2b\x06\x01\x05\x05\x02";
1308
1309   if (conf->krb_5_keytab) {
1310      char *ktname;
1311      /* we don't use the ap_* calls here, since the string passed to putenv()
1312       * will become part of the enviroment and shouldn't be free()ed by apache
1313       */
1314      ktname = malloc(strlen("KRB5_KTNAME=") + strlen(conf->krb_5_keytab) + 1);
1315      if (ktname == NULL) {
1316         log_rerror(APLOG_MARK, APLOG_ERR, 0, r, "malloc() failed: not enough memory");
1317         ret = HTTP_INTERNAL_SERVER_ERROR;
1318         goto end;
1319      }
1320      sprintf(ktname, "KRB5_KTNAME=%s", conf->krb_5_keytab);
1321      putenv(ktname);
1322 #ifdef HEIMDAL
1323      /* Seems to be also supported by latest MIT */
1324      gsskrb5_register_acceptor_identity(conf->krb_5_keytab);
1325 #endif
1326   }
1327
1328   ret = get_gss_creds(r, conf, &server_creds);
1329   if (ret)
1330      goto end;
1331
1332   /* ap_getword() shifts parameter */
1333   auth_param = ap_getword_white(r->pool, &auth_line);
1334   if (auth_param == NULL) {
1335      log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
1336                 "No Authorization parameter in request from client");
1337      ret = HTTP_UNAUTHORIZED;
1338      goto end;
1339   }
1340
1341   input_token.length = apr_base64_decode_len(auth_param) + 1;
1342   input_token.value = apr_pcalloc(r->connection->pool, input_token.length);
1343   if (input_token.value == NULL) {
1344      log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
1345                 "ap_pcalloc() failed (not enough memory)");
1346      ret = HTTP_INTERNAL_SERVER_ERROR;
1347      goto end;
1348   }
1349   input_token.length = apr_base64_decode(input_token.value, auth_param);
1350
1351 #ifdef GSSAPI_SUPPORTS_SPNEGO
1352   accept_sec_token = gss_accept_sec_context;
1353 #else
1354   accept_sec_token = (cmp_gss_type(&input_token, &spnego_oid) == 0) ?
1355                         gss_accept_sec_context_spnego : gss_accept_sec_context;
1356 #endif
1357
1358   log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, "Verifying client data using %s",
1359              (accept_sec_token == gss_accept_sec_context)
1360                ? "KRB5 GSS-API"
1361                : "SPNEGO GSS-API");
1362
1363   major_status = accept_sec_token(&minor_status,
1364                                   &context,
1365                                   server_creds,
1366                                   &input_token,
1367                                   GSS_C_NO_CHANNEL_BINDINGS,
1368                                   &client_name,
1369                                   NULL,
1370                                   &output_token,
1371                                   &ret_flags,
1372                                   NULL,
1373                                   &delegated_cred);
1374   log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
1375              "Client %s us their credential",
1376              (ret_flags & GSS_C_DELEG_FLAG) ? "sent" : "didn't send");
1377   if (output_token.length) {
1378      char *token = NULL;
1379      size_t len;
1380      
1381      len = apr_base64_encode_len(output_token.length) + 1;
1382      token = apr_pcalloc(r->connection->pool, len + 1);
1383      if (token == NULL) {
1384         log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
1385                    "ap_pcalloc() failed (not enough memory)");
1386         ret = HTTP_INTERNAL_SERVER_ERROR;
1387         gss_release_buffer(&minor_status2, &output_token);
1388         goto end;
1389      }
1390      apr_base64_encode(token, output_token.value, output_token.length);
1391      token[len] = '\0';
1392      *negotiate_ret_value = token;
1393      log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
1394                 "GSS-API token of length %d bytes will be sent back",
1395                 output_token.length);
1396      gss_release_buffer(&minor_status2, &output_token);
1397      set_kerb_auth_headers(r, conf, 0, 0, *negotiate_ret_value);
1398   }
1399
1400   if (GSS_ERROR(major_status)) {
1401      if (input_token.length > 7 && memcmp(input_token.value, "NTLMSSP", 7) == 0)
1402         log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
1403                   "Warning: received token seems to be NTLM, which isn't supported by the Kerberos module. Check your IE configuration.");
1404
1405      log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
1406                 "%s", get_gss_error(r, major_status, minor_status,
1407                                     "gss_accept_sec_context() failed"));
1408      /* Don't offer the Negotiate method again if call to GSS layer failed */
1409      *negotiate_ret_value = NULL;
1410      ret = HTTP_UNAUTHORIZED;
1411      goto end;
1412   }
1413
1414 #if 0
1415   /* This is a _Kerberos_ module so multiple authentication rounds aren't
1416    * supported. If we wanted a generic GSS authentication we would have to do
1417    * some magic with exporting context etc. */
1418   if (major_status & GSS_S_CONTINUE_NEEDED) {
1419      ret = HTTP_UNAUTHORIZED;
1420      goto end;
1421   }
1422 #endif
1423
1424   major_status = gss_display_name(&minor_status, client_name, &output_token, NULL);
1425   gss_release_name(&minor_status, &client_name); 
1426   if (GSS_ERROR(major_status)) {
1427     log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
1428                "%s", get_gss_error(r, major_status, minor_status,
1429                                    "gss_display_name() failed"));
1430     ret = HTTP_INTERNAL_SERVER_ERROR;
1431     goto end;
1432   }
1433
1434   MK_AUTH_TYPE = MECH_NEGOTIATE;
1435   MK_USER = apr_pstrdup(r->pool, output_token.value);
1436
1437   if (conf->krb_save_credentials && delegated_cred != GSS_C_NO_CREDENTIAL)
1438      store_gss_creds(r, conf, (char *)output_token.value, delegated_cred);
1439   
1440   gss_release_buffer(&minor_status, &output_token);
1441
1442   ret = OK;
1443
1444 end:
1445   if (delegated_cred)
1446      gss_release_cred(&minor_status, &delegated_cred);
1447
1448   if (output_token.length) 
1449      gss_release_buffer(&minor_status, &output_token);
1450
1451   if (client_name != GSS_C_NO_NAME)
1452      gss_release_name(&minor_status, &client_name);
1453
1454   if (server_creds != GSS_C_NO_CREDENTIAL)
1455      gss_release_cred(&minor_status, &server_creds);
1456
1457   if (context != GSS_C_NO_CONTEXT)
1458      gss_delete_sec_context(&minor_status, &context, GSS_C_NO_BUFFER);
1459
1460   return ret;
1461 }
1462
1463 static int
1464 do_krb5_an_to_ln(request_rec *r) {
1465   krb5_error_code code;
1466   int ret = HTTP_INTERNAL_SERVER_ERROR;
1467   char *MK_USER_LNAME = NULL;
1468   krb5_context    kcontext = NULL;
1469   krb5_principal client = NULL;
1470   
1471   code = krb5_init_context(&kcontext);
1472    if (code) {
1473       log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
1474                  "Cannot initialize Kerberos5 context (%d)", code);
1475       goto end;
1476    }
1477   
1478   code = krb5_parse_name(kcontext, MK_USER, &client);
1479       if (code) {
1480          log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
1481                     "krb5_parse_name() failed: %s",
1482                     krb5_get_err_text(kcontext, code));
1483            goto end;
1484   }
1485   MK_USER_LNAME = apr_pcalloc(r->pool, strlen(MK_USER)+1);
1486   if (MK_USER_LNAME == NULL) {
1487      log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
1488                 "ap_pcalloc() failed (not enough memory)");
1489      goto end;
1490   }
1491     code = krb5_aname_to_localname(kcontext, client, strlen(MK_USER), MK_USER_LNAME);
1492     if (code) {
1493                   if (code != KRB5_LNAME_NOTRANS) {
1494                         log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
1495                                    "krb5_aname_to_localname() failed: %s",
1496                                    krb5_get_err_text(kcontext, code));
1497
1498                   }
1499                   else {
1500                         log_rerror(APLOG_MARK, APLOG_NOTICE, 0, r,
1501                                    "krb5_aname_to_localname() found no "
1502                                    "mapping for principal %s",
1503                                    MK_USER);
1504                   }
1505           }
1506     else {
1507     log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
1508               "kerb_authenticate_a_name_to_local_name %s -> %s",
1509               (MK_USER)?MK_USER:"(NULL)", (MK_USER_LNAME)?MK_USER_LNAME:"(NULL)");
1510           MK_USER = apr_pstrdup(r->pool, MK_USER_LNAME);
1511           ret = OK;
1512           }
1513         end:
1514           if (client)
1515              krb5_free_principal(kcontext, client);
1516           if (kcontext)
1517              krb5_free_context(kcontext);
1518           return ret;
1519 }
1520
1521
1522 #endif /* KRB5 */
1523
1524 static krb5_conn_data *
1525 already_succeeded(request_rec *r, char *auth_line)
1526 {
1527    krb5_conn_data *conn_data;
1528    const char keyname[1024];
1529
1530    snprintf(keyname, sizeof(keyname) - 1,
1531         "mod_auth_kerb::connection::%s::%ld", r->connection->remote_ip, 
1532         r->connection->id);
1533
1534    if (apr_pool_userdata_get(&conn_data, keyname, r->connection->pool) != 0)
1535         return NULL;
1536
1537    if(conn_data) {
1538         if(strcmp(conn_data->authline, auth_line) == 0) {
1539                 log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, "matched previous auth request");
1540                 return conn_data;
1541         }
1542    }
1543    return NULL;
1544 }
1545
1546 static void
1547 set_kerb_auth_headers(request_rec *r, const kerb_auth_config *conf,
1548                       int use_krb4, int use_krb5pwd, char *negotiate_ret_value)
1549 {
1550    const char *auth_name = NULL;
1551    int set_basic = 0;
1552    char *negoauth_param;
1553    const char *header_name = 
1554       (r->proxyreq == PROXYREQ_PROXY) ? "Proxy-Authenticate" : "WWW-Authenticate";
1555
1556    /* get the user realm specified in .htaccess */
1557    auth_name = ap_auth_name(r);
1558
1559    /* XXX should the WWW-Authenticate header be cleared first?
1560     * apache in the proxy mode should retain client's authN headers? */
1561 #ifdef KRB5
1562    if (negotiate_ret_value != NULL && conf->krb_method_gssapi) {
1563       negoauth_param = (*negotiate_ret_value == '\0') ? MECH_NEGOTIATE :
1564                   apr_pstrcat(r->pool, MECH_NEGOTIATE " ", negotiate_ret_value, NULL);
1565       apr_table_add(r->err_headers_out, header_name, negoauth_param);
1566    }
1567    if ((use_krb5pwd && conf->krb_method_k5pass) || conf->krb_delegate_basic) {
1568       apr_table_add(r->err_headers_out, header_name,
1569                    apr_pstrcat(r->pool, "Basic realm=\"", auth_name, "\"", NULL));
1570       set_basic = 1;
1571    }
1572 #endif
1573
1574 #ifdef KRB4
1575    if (!set_basic && 
1576        ((use_krb4 && conf->krb_method_k4pass) || conf->krb_delegate_basic))
1577       apr_table_add(r->err_headers_out, header_name,
1578                   apr_pstrcat(r->pool, "Basic realm=\"", auth_name, "\"", NULL));
1579 #endif
1580 }
1581
1582 static int
1583 kerb_authenticate_user(request_rec *r)
1584 {
1585    kerb_auth_config *conf = 
1586       (kerb_auth_config *) ap_get_module_config(r->per_dir_config,
1587                                                 &auth_kerb_module);
1588    krb5_conn_data *prevauth = NULL;
1589    const char *auth_type = NULL;
1590    const char *auth_line = NULL;
1591    const char *type = NULL;
1592    int use_krb5 = 0, use_krb4 = 0;
1593    int ret;
1594    static int last_return = HTTP_UNAUTHORIZED;
1595    char *negotiate_ret_value = NULL;
1596    char keyname[1024];
1597
1598    /* get the type specified in .htaccess */
1599    type = ap_auth_type(r);
1600
1601    log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
1602               "kerb_authenticate_user entered with user %s and auth_type %s",
1603               (MK_USER)?MK_USER:"(NULL)",type?type:"(NULL)");
1604
1605    if (type && strcasecmp(type, "Kerberos") == 0)
1606       use_krb5 = use_krb4 = 1;
1607    else if(type && strcasecmp(type, "KerberosV5") == 0)
1608       use_krb5 = 1;
1609    else if(type && strcasecmp(type, "KerberosV4") == 0)
1610       use_krb4 = 1;
1611    else
1612       return DECLINED;
1613
1614 #if 0
1615    if (conf->krb_ssl_preauthentication) {
1616       const char *ssl_client_verify = ssl_var_lookup(r->pool, r->server,
1617                 r->connection, r, "SSL_CLIENT_VERIFY");
1618
1619       if (ssl_client_verify && strcmp(ssl_client_verify, "SUCCESS") == 0)
1620          return OK;
1621    }
1622 #endif
1623
1624    /* get what the user sent us in the HTTP header */
1625    auth_line = MK_TABLE_GET(r->headers_in, (r->proxyreq == PROXYREQ_PROXY)
1626                                             ? "Proxy-Authorization"
1627                                             : "Authorization");
1628    if (!auth_line) {
1629       set_kerb_auth_headers(r, conf, use_krb4, use_krb5, 
1630                             (use_krb5) ? "\0" : NULL);
1631       return HTTP_UNAUTHORIZED;
1632    }
1633    auth_type = ap_getword_white(r->pool, &auth_line);
1634
1635    /* If we are delegating Basic to other modules, DECLINE the request */
1636    if (conf->krb_delegate_basic &&
1637 #ifdef KRB5
1638        !conf->krb_method_k5pass &&
1639 #endif
1640 #ifdef KRB4
1641        !conf->krb_method_k4pass &&
1642 #endif
1643        (strcasecmp(auth_type, "Basic") == 0))
1644        return DECLINED;
1645
1646    if ( (prevauth = already_succeeded(r, auth_line)) == NULL) {
1647      ret = HTTP_UNAUTHORIZED;
1648
1649 #ifdef KRB5
1650    if (use_krb5 && conf->krb_method_gssapi &&
1651        strcasecmp(auth_type, MECH_NEGOTIATE) == 0) {
1652       ret = authenticate_user_gss(r, conf, auth_line, &negotiate_ret_value);
1653    } else if (use_krb5 && conf->krb_method_k5pass &&
1654               strcasecmp(auth_type, "Basic") == 0) {
1655        ret = authenticate_user_krb5pwd(r, conf, auth_line);
1656    }
1657 #endif
1658
1659 #ifdef KRB4
1660    if (ret == HTTP_UNAUTHORIZED && use_krb4 && conf->krb_method_k4pass &&
1661        strcasecmp(auth_type, "Basic") == 0)
1662       ret = authenticate_user_krb4pwd(r, conf, auth_line);
1663 #endif
1664
1665    if (ret == HTTP_UNAUTHORIZED)
1666       set_kerb_auth_headers(r, conf, use_krb4, use_krb5, negotiate_ret_value);
1667
1668    } else {
1669         ret = prevauth->last_return;
1670         MK_USER = prevauth->user;
1671         MK_AUTH_TYPE = prevauth->mech;
1672    }
1673
1674    /*
1675     * save who was auth'd, if it's not already stashed.
1676     */
1677      if(!prevauth) {
1678        prevauth = (krb5_conn_data *) apr_pcalloc(r->connection->pool, sizeof(krb5_conn_data));
1679        prevauth->user = apr_pstrdup(r->connection->pool, MK_USER);
1680        prevauth->authline = apr_pstrdup(r->connection->pool, auth_line);
1681        prevauth->mech = apr_pstrdup(r->connection->pool, auth_type);
1682        prevauth->last_return = ret;
1683        snprintf(keyname, sizeof(keyname) - 1,
1684            "mod_auth_kerb::connection::%s::%ld", 
1685            r->connection->remote_ip, r->connection->id);
1686        apr_pool_userdata_set(prevauth, keyname, NULL, r->connection->pool);
1687    }
1688
1689      if (ret == OK && conf->krb5_do_auth_to_local)
1690        ret = do_krb5_an_to_ln(r);
1691    
1692    /* XXX log_debug: if ret==OK, log(user XY authenticated) */
1693
1694    last_return = ret;
1695    return ret;
1696 }
1697
1698 int
1699 have_rcache_type(const char *type)
1700 {
1701    krb5_error_code ret;
1702    krb5_context context;
1703    krb5_rcache id = NULL;
1704    int found;
1705
1706    ret = krb5_init_context(&context);
1707    if (ret)
1708       return 0;
1709
1710    ret = krb5_rc_resolve_full(context, &id, "none:");
1711    found = (ret == 0);
1712
1713    if (ret == 0)
1714       krb5_rc_destroy(context, id);
1715    krb5_free_context(context);
1716
1717    return found;
1718 }
1719
1720 /*************************************************************************** 
1721  Module Setup/Configuration
1722  ***************************************************************************/
1723 #ifndef STANDARD20_MODULE_STUFF
1724 static void
1725 kerb_module_init(server_rec *dummy, pool *p)
1726 {
1727 #ifndef HEIMDAL
1728    /* Suppress the MIT replay cache.  Requires MIT Kerberos 1.4.0 or later.
1729       1.3.x are covered by the hack overiding the replay calls */
1730    if (getenv("KRB5RCACHETYPE") == NULL && have_rcache_type("none"))
1731       putenv(strdup("KRB5RCACHETYPE=none"));
1732 #endif
1733 }
1734
1735 module MODULE_VAR_EXPORT auth_kerb_module = {
1736         STANDARD_MODULE_STUFF,
1737         kerb_module_init,               /*      module initializer            */
1738         kerb_dir_create_config,         /*      per-directory config creator  */
1739         NULL,                           /*      per-directory config merger   */
1740         NULL,                           /*      per-server    config creator  */
1741         NULL,                           /*      per-server    config merger   */
1742         kerb_auth_cmds,                 /*      command table                 */
1743         NULL,                           /* [ 9] content handlers              */
1744         NULL,                           /* [ 2] URI-to-filename translation   */
1745         kerb_authenticate_user,         /* [ 5] check/validate user_id        */
1746         NULL,                           /* [ 6] check user_id is valid *here* */
1747         NULL,                           /* [ 4] check access by host address  */
1748         NULL,                           /* [ 7] MIME type checker/setter      */
1749         NULL,                           /* [ 8] fixups                        */
1750         NULL,                           /* [10] logger                        */
1751         NULL,                           /* [ 3] header parser                 */
1752         NULL,                           /*      process initialization        */
1753         NULL,                           /*      process exit/cleanup          */
1754         NULL                            /* [ 1] post read_request handling    */
1755 #ifdef EAPI
1756        ,NULL,                           /* EAPI: add_module                   */
1757         NULL,                           /* EAPI: remove_module                */
1758         NULL,                           /* EAPI: rewrite_command              */
1759         NULL                            /* EAPI: new_connection               */
1760 #endif
1761 };
1762 #else
1763 static int
1764 kerb_init_handler(apr_pool_t *p, apr_pool_t *plog,
1765                   apr_pool_t *ptemp, server_rec *s)
1766 {
1767    ap_add_version_component(p, "mod_auth_kerb/" MODAUTHKERB_VERSION);
1768 #ifndef HEIMDAL
1769    /* Suppress the MIT replay cache.  Requires MIT Kerberos 1.4.0 or later.
1770       1.3.x are covered by the hack overiding the replay calls */
1771    if (getenv("KRB5RCACHETYPE") == NULL && have_rcache_type("none"))
1772       putenv(strdup("KRB5RCACHETYPE=none"));
1773 #endif
1774    
1775    return OK;
1776 }
1777
1778 static void
1779 kerb_register_hooks(apr_pool_t *p)
1780 {
1781    ap_hook_post_config(kerb_init_handler, NULL, NULL, APR_HOOK_MIDDLE);
1782    ap_hook_check_user_id(kerb_authenticate_user, NULL, NULL, APR_HOOK_MIDDLE);
1783 }
1784
1785 module AP_MODULE_DECLARE_DATA auth_kerb_module =
1786 {
1787    STANDARD20_MODULE_STUFF,
1788    kerb_dir_create_config,      /* create per-dir    conf structures  */
1789    NULL,                        /* merge  per-dir    conf structures  */
1790    NULL,                        /* create per-server conf structures  */
1791    NULL,                        /* merge  per-server conf structures  */
1792    kerb_auth_cmds,              /* table of configuration directives  */
1793    kerb_register_hooks          /* register hooks                     */
1794 };
1795 #endif