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