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