Added option KrbVerifyKDC to optinaly disable the verification of KDC
[mod_auth_kerb.cvs/.git] / src / mod_auth_kerb.c
1 /*
2  * Daniel Kouril <kouril@users.sourceforge.net>
3  *
4  * Source and Documentation can be found at:
5  * http://modauthkerb.sourceforge.net/
6  *
7  * Based on work by
8  *   James E. Robinson, III <james@ncstate.net>
9  *   Daniel Henninger <daniel@ncsu.edu>
10  *   Ludek Sulak <xsulak@fi.muni.cz>
11  */
12
13 /* ====================================================================
14  * The Apache Software License, Version 1.1
15  *
16  * Copyright (c) 2000-2003 The Apache Software Foundation.  All rights
17  * reserved.
18  *
19  * Redistribution and use in source and binary forms, with or without
20  * modification, are permitted provided that the following conditions
21  * are met:
22  *
23  * 1. Redistributions of source code must retain the above copyright
24  *    notice, this list of conditions and the following disclaimer.
25  *
26  * 2. Redistributions in binary form must reproduce the above copyright
27  *    notice, this list of conditions and the following disclaimer in
28  *    the documentation and/or other materials provided with the
29  *    distribution.
30  *
31  * 3. The end-user documentation included with the redistribution,
32  *    if any, must include the following acknowledgment:
33  *       "This product includes software developed by the
34  *        Apache Software Foundation (http://www.apache.org/)."
35  *    Alternately, this acknowledgment may appear in the software itself,
36  *    if and wherever such third-party acknowledgments normally appear.
37  *
38  * 4. The names "Apache" and "Apache Software Foundation" must
39  *    not be used to endorse or promote products derived from this
40  *    software without prior written permission. For written
41  *    permission, please contact apache@apache.org.
42  *
43  * 5. Products derived from this software may not be called "Apache",
44  *    nor may "Apache" appear in their name, without prior written
45  *    permission of the Apache Software Foundation.
46  *
47  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
48  * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
49  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
50  * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
51  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
52  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
53  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
54  * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
55  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
56  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
57  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
58  * SUCH DAMAGE.
59  * ====================================================================
60  *
61  * This software consists of voluntary contributions made by many
62  * individuals on behalf of the Apache Software Foundation.  For more
63  * information on the Apache Software Foundation, please see
64  * <http://www.apache.org/>.
65  *
66  * Portions of this software are based upon public domain software
67  * originally written at the National Center for Supercomputing Applications,
68  * University of Illinois, Urbana-Champaign.
69  */
70
71 #ident "$Id$"
72
73 #include "config.h"
74
75 #define MODAUTHKERB_VERSION "5.0-rc2"
76
77 #ifndef APXS1
78 #include "ap_compat.h"
79 #include "apr_strings.h"
80 #endif
81 #include "httpd.h"
82 #include "http_config.h"
83 #include "http_core.h"
84 #include "http_log.h"
85 #include "http_protocol.h"
86 #include "http_request.h"
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 #  define GSS_C_NT_USER_NAME gss_nt_user_name
96 #  define GSS_C_NT_HOSTBASED_SERVICE gss_nt_service_name
97 #  define krb5_get_err_text(context,code) error_message(code)
98 #endif
99 #endif /* KRB5 */
100
101 #ifdef KRB4
102 /*Prevent warning about closesocket redefinition (Apache's ap_config.h and 
103  * MIT Kerberos' port-sockets.h both define it as close) */
104 #ifdef closesocket
105 #  undef closesocket
106 #endif
107 #include <krb.h>
108 #include <netdb.h> /* gethostbyname() */
109 #endif /* KRB4 */
110
111 #ifdef APXS1
112 module auth_kerb_module;
113 #else
114 module AP_MODULE_DECLARE_DATA auth_kerb_module;
115 #endif
116
117 /*************************************************************************** 
118  Macros To Ease Compatibility
119  ***************************************************************************/
120 #ifdef APXS1
121 #define MK_POOL pool
122 #define MK_TABLE_GET ap_table_get
123 #define MK_USER r->connection->user
124 #define MK_AUTH_TYPE r->connection->ap_auth_type
125 #else
126 #define MK_POOL apr_pool_t
127 #define MK_TABLE_GET apr_table_get
128 #define MK_USER r->user
129 #define MK_AUTH_TYPE r->ap_auth_type
130 #endif /* APXS1 */
131
132
133 /*************************************************************************** 
134  Auth Configuration Structure
135  ***************************************************************************/
136 typedef struct {
137         char *krb_auth_realms;
138         int krb_save_credentials;
139         int krb_verify_kdc;
140 #ifdef KRB5
141         char *krb_5_keytab;
142         int krb_method_gssapi;
143         int krb_method_k5pass;
144 #endif
145 #ifdef KRB4
146         char *krb_4_srvtab;
147         int krb_method_k4pass;
148 #endif
149 } kerb_auth_config;
150
151 static const char*
152 krb5_save_realms(cmd_parms *cmd, kerb_auth_config *sec, char *arg);
153
154 #ifdef APXS1
155 #define command(name, func, var, type, usage)           \
156   { name, func,                                         \
157     (void*)XtOffsetOf(kerb_auth_config, var),           \
158     OR_AUTHCFG, type, usage }
159 #else
160 #define command(name, func, var, type, usage)           \
161   AP_INIT_ ## type (name, func,                         \
162         (void*)APR_XtOffsetOf(kerb_auth_config, var),   \
163         OR_AUTHCFG, usage)
164 #endif
165
166 static const command_rec kerb_auth_cmds[] = {
167    command("KrbAuthRealms", krb5_save_realms, krb_auth_realms,
168      RAW_ARGS, "Realms to attempt authentication against (can be multiple)."),
169
170    command("KrbAuthRealm", krb5_save_realms, krb_auth_realms,
171      RAW_ARGS, "Alias for KrbAuthRealms."),
172
173    command("KrbSaveCredentials", ap_set_flag_slot, krb_save_credentials,
174      FLAG, "Save and store credentials/tickets retrieved during auth."),
175
176    command("KrbVerifyKDC", ap_set_flag_slot, krb_verify_kdc,
177      FLAG, "Verify tickets against keytab to prevent KDC spoofing attacks."),
178
179 #ifdef KRB5
180    command("Krb5Keytab", ap_set_file_slot, krb_5_keytab,
181      TAKE1, "Location of Kerberos V5 keytab file."),
182
183    command("KrbMethodNegotiate", ap_set_flag_slot, krb_method_gssapi,
184      FLAG, "Enable Negotiate authentication method."),
185
186    command("KrbMethodK5Pass", ap_set_flag_slot, krb_method_k5pass,
187      FLAG, "Enable Kerberos V5 password authentication."),
188 #endif 
189
190 #ifdef KRB4
191    command("Krb4Srvtab", ap_set_file_slot, krb_4_srvtab,
192      TAKE1, "Location of Kerberos V4 srvtab file."),
193
194    command("KrbMethodK4Pass", ap_set_flag_slot, krb_method_k4pass,
195      FLAG, "Enable Kerberos V4 password authentication."),
196 #endif
197
198    { NULL }
199 };
200
201 #ifdef KRB5
202 typedef struct {
203    gss_ctx_id_t context;
204    gss_cred_id_t server_creds;
205 } gss_connection_t;
206
207 static gss_connection_t *gss_connection = NULL;
208 #endif
209
210
211 /*************************************************************************** 
212  Auth Configuration Initialization
213  ***************************************************************************/
214 static void *kerb_dir_create_config(MK_POOL *p, char *d)
215 {
216         kerb_auth_config *rec;
217
218         rec = (kerb_auth_config *) ap_pcalloc(p, sizeof(kerb_auth_config));
219         ((kerb_auth_config *)rec)->krb_verify_kdc = 1;
220 #ifdef KRB5
221         ((kerb_auth_config *)rec)->krb_method_k5pass = 1;
222         ((kerb_auth_config *)rec)->krb_method_gssapi = 1;
223 #endif
224 #ifdef KRB4
225         ((kerb_auth_config *)rec)->krb_method_k4pass = 1;
226 #endif
227         return rec;
228 }
229
230 static const char*
231 krb5_save_realms(cmd_parms *cmd, kerb_auth_config *sec, char *arg)
232 {
233    sec->krb_auth_realms= ap_pstrdup(cmd->pool, arg);
234    return NULL;
235 }
236
237 void log_rerror(const char *file, int line, int level, int status,
238                 const request_rec *r, const char *fmt, ...)
239 {
240    char errstr[1024];
241    char errnostr[1024];
242    va_list ap;
243
244    va_start(ap, fmt);
245    vsnprintf(errstr, sizeof(errstr), fmt, ap);
246    va_end(ap);
247
248    errnostr[0] = '\0';
249    if (errno)
250       snprintf(errnostr, sizeof(errnostr), "%s: (%s)", errstr, strerror(errno));
251    else
252       snprintf(errnostr, sizeof(errnostr), "%s", errstr);
253    
254 #ifdef APXS1
255    ap_log_rerror(file, line, level | APLOG_NOERRNO, r, "%s", errnostr);
256 #else
257    ap_log_rerror(file, line, level | APLOG_NOERRNO, status, r, "%s", errnostr);
258 #endif
259 }
260
261 #ifdef KRB4
262 /*************************************************************************** 
263  Username/Password Validation for Krb4
264  ***************************************************************************/
265 static int
266 verify_krb4_user(request_rec *r, char *name, char *instance, char *realm,
267                  char *password, char *linstance, char *srvtab, int krb_verify_kdc)
268 {
269    int ret;
270    char *phost;
271    unsigned long addr;
272    struct hostent *hp;
273    const char *hostname;
274    KTEXT_ST ticket;
275    AUTH_DAT authdata;
276    char lrealm[REALM_SZ];
277
278    ret = krb_get_pw_in_tkt(name, instance, realm, "krbtgt", realm, 
279                            DEFAULT_TKT_LIFE, password);
280    if (ret) {
281       log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
282                  "Cannot get krb4 ticket: krb_get_pw_in_tkt() failed: %s",
283                  krb_get_err_text(ret));
284       return ret;
285    }
286
287    if (!krb_verify_kdc)
288       return ret;
289
290    hostname = ap_get_server_name(r);
291
292    hp = gethostbyname(hostname);
293    if (hp == NULL) {
294       dest_tkt();
295       log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
296                  "Cannot verify krb4 ticket: gethostbyname() failed: %s",
297                  hstrerror(h_errno));
298       return h_errno;
299    }
300    memcpy(&addr, hp->h_addr, sizeof(addr));
301
302    phost = krb_get_phost((char *)hostname);
303
304    krb_get_lrealm(lrealm, 1);
305
306    ret = krb_mk_req(&ticket, linstance, phost, lrealm, 0);
307    if (ret) {
308       log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
309                  "Cannot verify krb4 ticket: krb_mk_req() failed: %s",
310                  krb_get_err_text(ret));
311       dest_tkt();
312       return ret;
313    }
314
315    ret = krb_rd_req(&ticket, linstance, phost, addr, &authdata, srvtab);
316    if (ret) {
317       log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
318                  "Cannot verify krb4 ticket: krb_rd_req() failed: %s",
319                  krb_get_err_text(ret));
320       dest_tkt();
321    }
322
323    return ret;
324 }
325
326 static int
327 krb4_cache_cleanup(void *data)
328 {
329    char *tkt_file = (char *) data;
330    
331    krb_set_tkt_string(tkt_file);
332    dest_tkt();
333    return OK;
334 }
335
336 static int 
337 authenticate_user_krb4pwd(request_rec *r,
338                           kerb_auth_config *conf,
339                           const char *auth_line)
340 {
341    int ret;
342    const char *sent_pw;
343    const char *sent_name;
344    char *sent_instance;
345    char tkt_file[32];
346    char *tkt_file_p = NULL;
347    int fd;
348    const char *realms;
349    const char *realm;
350    char *user;
351    char lrealm[REALM_SZ];
352
353    sent_pw = ap_pbase64decode(r->pool, auth_line);
354    sent_name = ap_getword (r->pool, &sent_pw, ':');
355
356    /* do not allow user to override realm setting of server */
357    if (strchr(sent_name, '@')) {
358       log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
359                  "specifying realm in user name is prohibited");
360       return HTTP_UNAUTHORIZED;
361    }
362
363    sent_instance = strchr(sent_name, '.');
364    if (sent_instance)
365       *sent_instance++ = '\0'; 
366
367    snprintf(tkt_file, sizeof(tkt_file), "/tmp/apache_tkt_XXXXXX");
368    fd = mkstemp(tkt_file);
369    if (fd < 0) {
370       log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
371                  "Cannot create krb4 ccache: mkstemp() failed: %s",
372                  strerror(errno));
373       return HTTP_INTERNAL_SERVER_ERROR;
374    }
375
376    tkt_file_p = ap_pstrdup(r->pool, tkt_file);
377    ap_register_cleanup(r->pool, tkt_file_p,
378                        krb4_cache_cleanup, ap_null_cleanup);
379
380    krb_set_tkt_string(tkt_file);
381
382    realms = conf->krb_auth_realms;
383    do {
384       memset(lrealm, 0, sizeof(lrealm));
385       realm = NULL;
386       if (realms)
387          realm = ap_getword_white(r->pool, &realms);
388
389       if (realm == NULL) {
390          ret = krb_get_lrealm(lrealm, 1);
391          realm = lrealm;
392       }
393       if (realm == NULL || *realm == '\0')
394          break;
395
396       ret = verify_krb4_user(r, (char *)sent_name, 
397                              (sent_instance) ? sent_instance : "",
398                              (char *)realm, (char *)sent_pw, "khttp",
399                              conf->krb_4_srvtab, conf->krb_verify_kdc);
400       if (ret == 0)
401          break;
402    } while (realms && *realms);
403
404    if (ret) {
405       log_rerror(APLOG_MARK, APLOG_ERR, 0, r, "Verifying krb4 password failed");
406       ret = HTTP_UNAUTHORIZED;
407       goto end;
408    }
409
410    user = ap_pstrdup(r->pool, sent_name);
411    if (sent_instance)
412       user = ap_pstrcat(r->pool, user, ".", sent_instance, NULL);
413    user = ap_pstrcat(r->pool, user, "@", realm, NULL);
414
415    MK_USER = user;
416    MK_AUTH_TYPE = "Basic";
417    ap_table_setn(r->subprocess_env, "KRBTKFILE", tkt_file_p);
418
419    if (!conf->krb_save_credentials)
420       krb4_cache_cleanup(tkt_file);
421
422 end:
423    if (ret)
424       krb4_cache_cleanup(tkt_file);
425    close(fd);
426    tf_close();
427
428    return ret;
429 }
430 #endif /* KRB4 */
431
432 #ifdef KRB5
433 /*************************************************************************** 
434  Username/Password Validation for Krb5
435  ***************************************************************************/
436 /* Inspired by krb5_verify_user from Heimdal */
437 static krb5_error_code
438 verify_krb5_user(request_rec *r, krb5_context context, krb5_principal principal,
439                  krb5_ccache ccache, const char *password, const char *service,
440                  krb5_keytab keytab, int krb_verify_kdc)
441 {
442    krb5_creds creds;
443    krb5_principal server = NULL;
444    krb5_error_code ret;
445    krb5_verify_init_creds_opt opt;
446
447    memset(&creds, 0, sizeof(creds));
448
449    ret = krb5_get_init_creds_password(context, &creds, principal, 
450                                       (char *)password, krb5_prompter_posix,
451                                       NULL, 0, NULL, NULL);
452    if (ret)
453       return ret;
454
455    ret = krb5_sname_to_principal(context, ap_get_server_name(r), service, 
456                                  KRB5_NT_SRV_HST, &server);
457    if (ret)
458       goto end;
459
460    krb5_verify_init_creds_opt_init(&opt);
461    krb5_verify_init_creds_opt_set_ap_req_nofail(&opt, krb_verify_kdc);
462
463    ret = krb5_verify_init_creds(context, &creds, server, keytab, NULL, &opt);
464    if (ret)
465       goto end;
466
467    if (ccache) {
468       ret = krb5_cc_initialize(context, ccache, principal);
469       if (ret == 0)
470          ret = krb5_cc_store_cred(context, ccache, &creds);
471    }
472
473 end:
474    krb5_free_cred_contents(context, &creds);
475    if (server)
476       krb5_free_principal(context, server);
477    return ret;
478 }
479
480 static int
481 krb5_cache_cleanup(void *data)
482 {
483    krb5_context context;
484    krb5_ccache  cache;
485    krb5_error_code problem;
486    char *cache_name = (char *) data;
487
488    problem = krb5_init_context(&context);
489    if (problem) {
490       /* ap_log_error(APLOG_MARK, APLOG_ERR, 0, NULL, "krb5_init_context() failed"); */
491       return HTTP_INTERNAL_SERVER_ERROR;
492    }
493
494    problem = krb5_cc_resolve(context, cache_name, &cache);
495    if (problem) {
496       /* log_error(APLOG_MARK, APLOG_ERR, 0, NULL, 
497                 "krb5_cc_resolve() failed (%s: %s)",
498                 cache_name, krb5_get_err_text(context, problem)); */
499       return HTTP_INTERNAL_SERVER_ERROR;
500    }
501
502    krb5_cc_destroy(context, cache);
503    krb5_free_context(context);
504    return OK;
505 }
506
507 static int
508 create_krb5_ccache(krb5_context kcontext,
509                    request_rec *r,
510                    kerb_auth_config *conf,
511                    krb5_principal princ,
512                    krb5_ccache *ccache)
513 {
514    char *ccname;
515    krb5_error_code problem;
516    int ret;
517    krb5_ccache tmp_ccache = NULL;
518
519 #ifdef HAVE_KRB5_CC_GEN_NEW
520    problem = krb5_cc_gen_new(kcontext, &krb5_fcc_ops, &tmp_ccache);
521 #else
522    /* only older MIT seem to not have the krb5_cc_gen_new() call, so we use
523     * MIT specific call here */
524    problem = krb5_fcc_generate_new(kcontext, &tmp_ccache);
525    /* krb5_fcc_generate_new() doesn't set KRB5_TC_OPENCLOSE, which makes 
526       krb5_cc_initialize() fail */
527    krb5_fcc_set_flags(kcontext, tmp_ccache, KRB5_TC_OPENCLOSE);
528 #endif
529    if (problem) {
530       log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
531                  "Cannot create file for new krb5 ccache: %s",
532                  krb5_get_err_text(kcontext, problem));
533       ret = HTTP_INTERNAL_SERVER_ERROR;
534       goto end;
535    }
536
537    ccname = ap_pstrdup(r->pool, krb5_cc_get_name(kcontext, tmp_ccache));
538
539    problem = krb5_cc_initialize(kcontext, tmp_ccache, princ);
540    if (problem) {
541       log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
542                  "Cannot initialize krb5 ccache %s: krb5_cc_initialize() failed: %s",
543                  ccname, krb5_get_err_text(kcontext, problem));
544       ret = HTTP_INTERNAL_SERVER_ERROR;
545       goto end;
546    }
547
548    ap_table_setn(r->subprocess_env, "KRB5CCNAME", ccname);
549    ap_register_cleanup(r->pool, ccname,
550                        krb5_cache_cleanup, ap_null_cleanup);
551
552    *ccache = tmp_ccache;
553    tmp_ccache = NULL;
554
555    ret = OK;
556
557 end:
558    if (tmp_ccache)
559       krb5_cc_destroy(kcontext, tmp_ccache);
560
561    return ret;
562 }
563
564 static int
565 store_krb5_creds(krb5_context kcontext,
566                  request_rec *r,
567                  kerb_auth_config *conf,
568                  krb5_ccache delegated_cred)
569 {
570    char errstr[1024];
571    krb5_error_code problem;
572    krb5_principal princ;
573    krb5_ccache ccache;
574    int ret;
575
576    problem = krb5_cc_get_principal(kcontext, delegated_cred, &princ);
577    if (problem) {
578       snprintf(errstr, sizeof(errstr), "krb5_cc_get_principal() failed: %s",
579                krb5_get_err_text(kcontext, problem));
580       return HTTP_INTERNAL_SERVER_ERROR;
581    }
582
583    ret = create_krb5_ccache(kcontext, r, conf, princ, &ccache);
584    if (ret) {
585       krb5_free_principal(kcontext, princ);
586       return ret;
587    }
588
589 #ifdef HEIMDAL
590    problem = krb5_cc_copy_cache(kcontext, delegated_cred, ccache);
591 #else
592    problem = krb5_cc_copy_creds(kcontext, delegated_cred, ccache);
593 #endif
594    krb5_free_principal(kcontext, princ);
595    if (problem) {
596       snprintf(errstr, sizeof(errstr), "Failed to store credentials: %s",
597                krb5_get_err_text(kcontext, problem));
598       krb5_cc_destroy(kcontext, ccache);
599       return HTTP_INTERNAL_SERVER_ERROR;
600    }
601
602    krb5_cc_close(kcontext, ccache);
603    return OK;
604 }
605
606
607 int authenticate_user_krb5pwd(request_rec *r,
608                               kerb_auth_config *conf,
609                               const char *auth_line)
610 {
611    const char      *sent_pw = NULL; 
612    const char      *sent_name = NULL;
613    const char      *realms = NULL;
614    krb5_context    kcontext = NULL;
615    krb5_error_code code;
616    krb5_principal  client = NULL;
617    krb5_ccache     ccache = NULL;
618    krb5_keytab     keytab = NULL;
619    int             ret;
620    char *name = NULL;
621
622    code = krb5_init_context(&kcontext);
623    if (code) {
624       log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
625                  "Cannot initialize Kerberos5 context (%d)", code);
626       return HTTP_INTERNAL_SERVER_ERROR;
627    }
628
629    sent_pw = ap_pbase64decode(r->pool, auth_line);
630    sent_name = ap_getword (r->pool, &sent_pw, ':');
631    /* do not allow user to override realm setting of server */
632    if (strchr(sent_name, '@')) {
633       log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
634                  "specifying realm in user name is prohibited");
635       ret = HTTP_UNAUTHORIZED;
636       goto end;
637    } 
638
639 #ifdef HAVE_KRB5_CC_GEN_NEW
640    code = krb5_cc_gen_new(kcontext, &krb5_mcc_ops, &ccache);
641 #else
642    /* only older MIT seem to not have the krb5_cc_gen_new() call, so we use
643     * MIT specific call here */
644    code = krb5_mcc_generate_new(kcontext, &ccache);
645 #endif
646    if (code) {
647       log_rerror(APLOG_MARK, APLOG_ERR, 0, r, 
648                  "Cannot generate new ccache: %s",
649                  krb5_get_err_text(kcontext, code));
650       ret = HTTP_INTERNAL_SERVER_ERROR;
651       goto end;
652    }
653
654    if (conf->krb_5_keytab)
655       krb5_kt_resolve(kcontext, conf->krb_5_keytab, &keytab);
656
657    realms = conf->krb_auth_realms;
658    do {
659       if (realms && (code = krb5_set_default_realm(kcontext,
660                                            ap_getword_white(r->pool, &realms))))
661          continue;
662
663       if (client) {
664          krb5_free_principal(kcontext, client);
665          client = NULL;
666       }
667       code = krb5_parse_name(kcontext, sent_name, &client);
668       if (code)
669          continue;
670
671       code = verify_krb5_user(r, kcontext, client, ccache, sent_pw, "khttp",
672                               keytab, conf->krb_verify_kdc);
673       if (code == 0)
674          break;
675
676       /* ap_getword_white() used above shifts the parameter, so it's not
677          needed to touch the realms variable */
678    } while (realms && *realms);
679
680    memset((char *)sent_pw, 0, strlen(sent_pw));
681
682    if (code) {
683       log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
684                  "Verifying krb5 password failed: %s",
685                  krb5_get_err_text(kcontext, code));
686       ret = HTTP_UNAUTHORIZED;
687       goto end;
688    }
689
690    code = krb5_unparse_name(kcontext, client, &name);
691    if (code) {
692       log_rerror(APLOG_MARK, APLOG_ERR, 0, r, "krb5_unparse_name() failed: %s",
693                  krb5_get_err_text(kcontext, code));
694       ret = HTTP_UNAUTHORIZED;
695       goto end;
696    }
697    MK_USER = ap_pstrdup (r->pool, name);
698    MK_AUTH_TYPE = "Basic";
699    free(name);
700
701    if (conf->krb_save_credentials)
702       store_krb5_creds(kcontext, r, conf, ccache);
703
704    ret = OK;
705
706 end:
707    if (client)
708       krb5_free_principal(kcontext, client);
709    if (ccache)
710       krb5_cc_destroy(kcontext, ccache);
711    if (keytab)
712       krb5_kt_close(kcontext, keytab);
713    krb5_free_context(kcontext);
714
715    return ret;
716 }
717
718 /*********************************************************************
719  * GSSAPI Authentication
720  ********************************************************************/
721
722 static const char *
723 get_gss_error(MK_POOL *p, OM_uint32 error_status, char *prefix)
724 {
725    OM_uint32 maj_stat, min_stat;
726    OM_uint32 msg_ctx = 0;
727    gss_buffer_desc status_string;
728    char buf[1024];
729    size_t len;
730
731    snprintf(buf, sizeof(buf), "%s", prefix);
732    len = strlen(buf);
733    do {
734       maj_stat = gss_display_status (&min_stat,
735                                      error_status,
736                                      GSS_C_MECH_CODE,
737                                      GSS_C_NO_OID,
738                                      &msg_ctx,
739                                      &status_string);
740       if (sizeof(buf) > len + status_string.length + 1) {
741          sprintf(buf+len, ": %s", (char*) status_string.value);
742          len += status_string.length;
743       }
744       gss_release_buffer(&min_stat, &status_string);
745    } while (!GSS_ERROR(maj_stat) && msg_ctx != 0);
746
747    return (ap_pstrdup(p, buf));
748 }
749
750 static int
751 cleanup_gss_connection(void *data)
752 {
753    OM_uint32 minor_status;
754    gss_connection_t *gss_conn = (gss_connection_t *)data;
755
756    if (data == NULL)
757       return OK;
758    if (gss_conn->context != GSS_C_NO_CONTEXT)
759       gss_delete_sec_context(&minor_status, &gss_conn->context,
760                              GSS_C_NO_BUFFER);
761    if (gss_conn->server_creds != GSS_C_NO_CREDENTIAL)
762       gss_release_cred(&minor_status, &gss_conn->server_creds);
763
764    gss_connection = NULL;
765
766    return OK;
767 }
768
769 static int
770 store_gss_creds(request_rec *r, kerb_auth_config *conf, char *princ_name,
771                 gss_cred_id_t delegated_cred)
772 {
773    OM_uint32 maj_stat, min_stat;
774    krb5_principal princ = NULL;
775    krb5_ccache ccache = NULL;
776    krb5_error_code problem;
777    krb5_context context;
778    int ret = HTTP_INTERNAL_SERVER_ERROR;
779
780    problem = krb5_init_context(&context);
781    if (problem) {
782       log_rerror(APLOG_MARK, APLOG_ERR, 0, r, "Cannot initialize krb5 context");
783       return HTTP_INTERNAL_SERVER_ERROR;
784    }
785
786    problem = krb5_parse_name(context, princ_name, &princ);
787    if (problem) {
788       log_rerror(APLOG_MARK, APLOG_ERR, 0, r, 
789          "Cannot parse delegated username (%s)", krb5_get_err_text(context, problem));
790       goto end;
791    }
792
793    problem = create_krb5_ccache(context, r, conf, princ, &ccache);
794    if (problem) {
795       log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
796          "Cannot create krb5 ccache (%s)", krb5_get_err_text(context, problem));
797       goto end;
798    }
799
800    maj_stat = gss_krb5_copy_ccache(&min_stat, delegated_cred, ccache);
801    if (GSS_ERROR(maj_stat)) {
802       log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
803          "Cannot store delegated credential (%s)", 
804          get_gss_error(r->pool, min_stat, "gss_krb5_copy_ccache"));
805       goto end;
806    }
807
808    krb5_cc_close(context, ccache);
809    ccache = NULL;
810    ret = 0;
811
812 end:
813    if (princ)
814       krb5_free_principal(context, princ);
815    if (ccache)
816       krb5_cc_destroy(context, ccache);
817    krb5_free_context(context);
818    return ret;
819 }
820
821 static int
822 get_gss_creds(request_rec *r,
823               kerb_auth_config *conf,
824               gss_cred_id_t *server_creds)
825 {
826    gss_buffer_desc input_token = GSS_C_EMPTY_BUFFER;
827    OM_uint32 major_status, minor_status, minor_status2;
828    gss_name_t server_name = GSS_C_NO_NAME;
829    char buf[1024];
830
831    snprintf(buf, sizeof(buf), "%s/%s", "khttp", ap_get_server_name(r));
832
833    input_token.value = buf;
834    input_token.length = strlen(buf) + 1;
835
836    major_status = gss_import_name(&minor_status, &input_token,
837                                   GSS_C_NT_USER_NAME,
838                                   &server_name);
839    if (GSS_ERROR(major_status)) {
840       log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
841                  "%s", get_gss_error(r->pool, minor_status,
842                  "gss_import_name() failed"));
843       return HTTP_INTERNAL_SERVER_ERROR;
844    }
845    
846    major_status = gss_acquire_cred(&minor_status, server_name, GSS_C_INDEFINITE,
847                                    GSS_C_NO_OID_SET, GSS_C_ACCEPT,
848                                    server_creds, NULL, NULL);
849    gss_release_name(&minor_status2, &server_name);
850    if (GSS_ERROR(major_status)) {
851       log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
852                  "%s", get_gss_error(r->pool, minor_status,
853                                      "gss_acquire_cred() failed"));
854       return HTTP_INTERNAL_SERVER_ERROR;
855    }
856    
857    return 0;
858 }
859
860 static int
861 authenticate_user_gss(request_rec *r,
862                       kerb_auth_config *conf,
863                       const char *auth_line)
864 {
865   OM_uint32 major_status, minor_status, minor_status2;
866   gss_buffer_desc input_token = GSS_C_EMPTY_BUFFER;
867   gss_buffer_desc output_token = GSS_C_EMPTY_BUFFER;
868   const char *auth_param = NULL;
869   int ret;
870   gss_name_t client_name = GSS_C_NO_NAME;
871   gss_cred_id_t delegated_cred = GSS_C_NO_CREDENTIAL;
872
873   if (gss_connection == NULL) {
874      gss_connection = ap_pcalloc(r->connection->pool, sizeof(*gss_connection));
875      if (gss_connection == NULL) {
876         log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
877                    "ap_pcalloc() failed (not enough memory)");
878         ret = HTTP_INTERNAL_SERVER_ERROR;
879         goto end;
880      }
881      memset(gss_connection, 0, sizeof(*gss_connection));
882      ap_register_cleanup(r->connection->pool, gss_connection, cleanup_gss_connection, ap_null_cleanup);
883   }
884
885   if (conf->krb_5_keytab) {
886      char *ktname;
887      /* we don't use the ap_* calls here, since the string passed to putenv()
888       * will become part of the enviroment and shouldn't be free()ed by apache
889       */
890      ktname = malloc(strlen("KRB5_KTNAME=") + strlen(conf->krb_5_keytab) + 1);
891      if (ktname == NULL) {
892         log_rerror(APLOG_MARK, APLOG_ERR, 0, r, "malloc() failed: not enough memory");
893         ret = HTTP_INTERNAL_SERVER_ERROR;
894         goto end;
895      }
896      sprintf(ktname, "KRB5_KTNAME=%s", conf->krb_5_keytab);
897      putenv(ktname);
898   }
899
900   if (gss_connection->server_creds == GSS_C_NO_CREDENTIAL) {
901      ret = get_gss_creds(r, conf, &gss_connection->server_creds);
902      if (ret)
903         goto end;
904   }
905
906   /* ap_getword() shifts parameter */
907   auth_param = ap_getword_white(r->pool, &auth_line);
908   if (auth_param == NULL) {
909      log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
910                 "No Authorization parameter in request from client");
911      ret = HTTP_UNAUTHORIZED;
912      goto end;
913   }
914
915   input_token.length = ap_base64decode_len(auth_param) + 1;
916   input_token.value = ap_pcalloc(r->connection->pool, input_token.length);
917   if (input_token.value == NULL) {
918      log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
919                 "ap_pcalloc() failed (not enough memory)");
920      ret = HTTP_INTERNAL_SERVER_ERROR;
921      goto end;
922   }
923   input_token.length = ap_base64decode(input_token.value, auth_param);
924
925 #if 0 
926   major_status = gss_accept_sec_context(
927 #else
928   major_status = gss_accept_sec_context_spnego(
929 #endif
930                                         &minor_status,
931                                         &gss_connection->context,
932                                         gss_connection->server_creds,
933                                         &input_token,
934                                         GSS_C_NO_CHANNEL_BINDINGS,
935                                         &client_name,
936                                         NULL,
937                                         &output_token,
938                                         NULL,
939                                         NULL,
940                                         &delegated_cred);
941   if (output_token.length) {
942      char *token = NULL;
943      size_t len;
944      
945      len = ap_base64encode_len(output_token.length) + 1;
946      token = ap_pcalloc(r->connection->pool, len + 1);
947      if (token == NULL) {
948         log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
949                    "ap_pcalloc() failed (not enough memory)");
950         ret = HTTP_INTERNAL_SERVER_ERROR;
951         gss_release_buffer(&minor_status2, &output_token);
952         goto end;
953      }
954      ap_base64encode(token, output_token.value, output_token.length);
955      token[len] = '\0';
956      ap_table_set(r->err_headers_out, "WWW-Authenticate",
957                   ap_pstrcat(r->pool, "Negotiate ", token, NULL));
958      gss_release_buffer(&minor_status2, &output_token);
959   }
960
961   if (GSS_ERROR(major_status)) {
962      log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
963                 "%s", get_gss_error(r->pool, minor_status,
964                                     "gss_accept_sec_context() failed"));
965      ret = HTTP_UNAUTHORIZED;
966      goto end;
967   }
968
969   if (major_status & GSS_S_CONTINUE_NEEDED) {
970      /* Some GSSAPI mechanism (eg GSI from Globus) may require multiple 
971       * iterations to establish authentication */
972      ret = HTTP_UNAUTHORIZED;
973      goto end;
974   }
975
976   major_status = gss_display_name(&minor_status, client_name, &output_token, NULL);
977   gss_release_name(&minor_status, &client_name); 
978   if (GSS_ERROR(major_status)) {
979     log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
980                "%s", get_gss_error(r->pool, minor_status, 
981                                    "gss_export_name() failed"));
982     ret = HTTP_INTERNAL_SERVER_ERROR;
983     goto end;
984   }
985
986   MK_AUTH_TYPE = "Negotiate";
987   MK_USER = ap_pstrdup(r->pool, output_token.value);
988
989   if (conf->krb_save_credentials && delegated_cred != GSS_C_NO_CREDENTIAL)
990      store_gss_creds(r, conf, (char *)output_token.value, delegated_cred);
991
992   gss_release_buffer(&minor_status, &output_token);
993
994   ret = OK;
995
996 end:
997   if (delegated_cred)
998      gss_release_cred(&minor_status, &delegated_cred);
999
1000   if (output_token.length) 
1001      gss_release_buffer(&minor_status, &output_token);
1002
1003   if (client_name != GSS_C_NO_NAME)
1004      gss_release_name(&minor_status, &client_name);
1005
1006   cleanup_gss_connection(gss_connection);
1007
1008   return ret;
1009 }
1010 #endif /* KRB5 */
1011
1012 static int
1013 already_succeeded(request_rec *r)
1014 {
1015    if (ap_is_initial_req(r) || MK_AUTH_TYPE == NULL)
1016       return 0;
1017    if (strcmp(MK_AUTH_TYPE, "Negotiate") ||
1018        (strcmp(MK_AUTH_TYPE, "Basic") && strchr(MK_USER, '@')))
1019       return 1;
1020    return 0;
1021 }
1022
1023 static void
1024 note_kerb_auth_failure(request_rec *r, const kerb_auth_config *conf,
1025                        int use_krb4, int use_krb5)
1026 {
1027    const char *auth_name = NULL;
1028    int set_basic = 0;
1029
1030    /* get the user realm specified in .htaccess */
1031    auth_name = ap_auth_name(r);
1032
1033    /* XXX should the WWW-Authenticate header be cleared first? */
1034 #ifdef KRB5
1035    if (use_krb5 && conf->krb_method_gssapi)
1036       ap_table_add(r->err_headers_out, "WWW-Authenticate", "Negotiate");
1037    if (use_krb5 && conf->krb_method_k5pass) {
1038       ap_table_add(r->err_headers_out, "WWW-Authenticate",
1039                    ap_pstrcat(r->pool, "Basic realm=\"", auth_name, "\"", NULL));
1040       set_basic = 1;
1041    }
1042 #endif
1043
1044 #ifdef KRB4
1045    if (use_krb4 && conf->krb_method_k4pass && !set_basic)
1046       ap_table_add(r->err_headers_out, "WWW-Authenticate",
1047                    ap_pstrcat(r->pool, "Basic realm=\"", auth_name, "\"", NULL));
1048 #endif
1049 }
1050
1051 int kerb_authenticate_user(request_rec *r)
1052 {
1053    kerb_auth_config *conf = 
1054       (kerb_auth_config *) ap_get_module_config(r->per_dir_config,
1055                                                 &auth_kerb_module);
1056    const char *auth_type = NULL;
1057    const char *auth_line = NULL;
1058    const char *type = NULL;
1059    int use_krb5 = 0, use_krb4 = 0;
1060    int ret;
1061    static int last_return = HTTP_UNAUTHORIZED;
1062
1063    /* get the type specified in .htaccess */
1064    type = ap_auth_type(r);
1065
1066    if (type && strcasecmp(type, "Kerberos") == 0)
1067       use_krb5 = use_krb4 = 1;
1068    else if(type && strcasecmp(type, "KerberosV5") == 0)
1069       use_krb4 = 0;
1070    else if(type && strcasecmp(type, "KerberosV4") == 0)
1071       use_krb5 = 0;
1072    else
1073       return DECLINED;
1074
1075    /* get what the user sent us in the HTTP header */
1076    auth_line = MK_TABLE_GET(r->headers_in, "Authorization");
1077    if (!auth_line) {
1078       note_kerb_auth_failure(r, conf, use_krb4, use_krb5);
1079       return HTTP_UNAUTHORIZED;
1080    }
1081    auth_type = ap_getword_white(r->pool, &auth_line);
1082
1083    if (already_succeeded(r))
1084       return last_return;
1085
1086    ret = HTTP_UNAUTHORIZED;
1087
1088 #ifdef KRB5
1089    if (use_krb5 && conf->krb_method_gssapi &&
1090        strcasecmp(auth_type, "Negotiate") == 0) {
1091       ret = authenticate_user_gss(r, conf, auth_line);
1092    } else if (use_krb5 && conf->krb_method_k5pass &&
1093               strcasecmp(auth_type, "Basic") == 0) {
1094        ret = authenticate_user_krb5pwd(r, conf, auth_line);
1095    }
1096 #endif
1097
1098 #ifdef KRB4
1099    if (ret == HTTP_UNAUTHORIZED && use_krb4 && conf->krb_method_k4pass &&
1100        strcasecmp(auth_type, "Basic") == 0)
1101       ret = authenticate_user_krb4pwd(r, conf, auth_line);
1102 #endif
1103
1104    if (ret == HTTP_UNAUTHORIZED)
1105       note_kerb_auth_failure(r, conf, use_krb4, use_krb5);
1106
1107    last_return = ret;
1108    return ret;
1109 }
1110
1111
1112 /*************************************************************************** 
1113  Module Setup/Configuration
1114  ***************************************************************************/
1115 #ifdef APXS1
1116 module MODULE_VAR_EXPORT auth_kerb_module = {
1117         STANDARD_MODULE_STUFF,
1118         NULL,                           /*      module initializer            */
1119         kerb_dir_create_config,         /*      per-directory config creator  */
1120         NULL,                           /*      per-directory config merger   */
1121         NULL,                           /*      per-server    config creator  */
1122         NULL,                           /*      per-server    config merger   */
1123         kerb_auth_cmds,                 /*      command table                 */
1124         NULL,                           /* [ 9] content handlers              */
1125         NULL,                           /* [ 2] URI-to-filename translation   */
1126         kerb_authenticate_user,         /* [ 5] check/validate user_id        */
1127         NULL,                           /* [ 6] check user_id is valid *here* */
1128         NULL,                           /* [ 4] check access by host address  */
1129         NULL,                           /* [ 7] MIME type checker/setter      */
1130         NULL,                           /* [ 8] fixups                        */
1131         NULL,                           /* [10] logger                        */
1132         NULL,                           /* [ 3] header parser                 */
1133         NULL,                           /*      process initialization        */
1134         NULL,                           /*      process exit/cleanup          */
1135         NULL                            /* [ 1] post read_request handling    */
1136 };
1137 #else
1138 static int
1139 kerb_init_handler(apr_pool_t *p, apr_pool_t *plog,
1140                   apr_pool_t *ptemp, server_rec *s)
1141 {
1142    ap_add_version_component(p, "mod_auth_kerb/" MODAUTHKERB_VERSION);
1143    return OK;
1144 }
1145
1146 void kerb_register_hooks(apr_pool_t *p)
1147 {
1148    ap_hook_post_config(kerb_init_handler, NULL, NULL, APR_HOOK_MIDDLE);
1149    ap_hook_check_user_id(kerb_authenticate_user, NULL, NULL, APR_HOOK_MIDDLE);
1150 }
1151
1152 module AP_MODULE_DECLARE_DATA auth_kerb_module =
1153 {
1154    STANDARD20_MODULE_STUFF,
1155    kerb_dir_create_config,      /* create per-dir    conf structures  */
1156    NULL,                        /* merge  per-dir    conf structures  */
1157    NULL,                        /* create per-server conf structures  */
1158    NULL,                        /* merge  per-server conf structures  */
1159    kerb_auth_cmds,              /* table of configuration directives  */
1160    kerb_register_hooks          /* register hooks                     */
1161 };
1162 #endif