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