- removed unused compatibility macros
[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 #ifdef KRB5
140         char *krb_5_keytab;
141         int krb_method_gssapi;
142         int krb_method_k5pass;
143 #endif
144 #ifdef KRB4
145         char *krb_4_srvtab;
146         int krb_method_k4pass;
147 #endif
148 } kerb_auth_config;
149
150 static const char*
151 krb5_save_realms(cmd_parms *cmd, kerb_auth_config *sec, char *arg);
152
153 #ifdef APXS1
154 #define command(name, func, var, type, usage)           \
155   { name, func,                                         \
156     (void*)XtOffsetOf(kerb_auth_config, var),           \
157     OR_AUTHCFG, type, usage }
158 #else
159 #define command(name, func, var, type, usage)           \
160   AP_INIT_ ## type (name, func,                         \
161         (void*)APR_XtOffsetOf(kerb_auth_config, var),   \
162         OR_AUTHCFG, usage)
163 #endif
164
165 static const command_rec kerb_auth_cmds[] = {
166    command("KrbAuthRealms", krb5_save_realms, krb_auth_realms,
167      RAW_ARGS, "Realms to attempt authentication against (can be multiple)."),
168
169    command("KrbAuthRealm", krb5_save_realms, krb_auth_realms,
170      RAW_ARGS, "Alias for KrbAuthRealms."),
171
172    command("KrbSaveCredentials", ap_set_flag_slot, krb_save_credentials,
173      FLAG, "Save and store credentials/tickets retrieved during auth."),
174
175 #ifdef KRB5
176    command("Krb5Keytab", ap_set_file_slot, krb_5_keytab,
177      TAKE1, "Location of Kerberos V5 keytab file."),
178
179    command("KrbMethodNegotiate", ap_set_flag_slot, krb_method_gssapi,
180      FLAG, "Enable Negotiate authentication method."),
181
182    command("KrbMethodK5Pass", ap_set_flag_slot, krb_method_k5pass,
183      FLAG, "Enable Kerberos V5 password authentication."),
184 #endif 
185
186 #ifdef KRB4
187    command("Krb4Srvtab", ap_set_file_slot, krb_4_srvtab,
188      TAKE1, "Location of Kerberos V4 srvtab file."),
189
190    command("KrbMethodK4Pass", ap_set_flag_slot, krb_method_k4pass,
191      FLAG, "Enable Kerberos V4 password authentication."),
192 #endif
193
194    { NULL }
195 };
196
197 #ifdef KRB5
198 typedef struct {
199    gss_ctx_id_t context;
200    gss_cred_id_t server_creds;
201 } gss_connection_t;
202
203 static gss_connection_t *gss_connection = NULL;
204 #endif
205
206
207 /*************************************************************************** 
208  Auth Configuration Initialization
209  ***************************************************************************/
210 static void *kerb_dir_create_config(MK_POOL *p, char *d)
211 {
212         kerb_auth_config *rec;
213
214         rec = (kerb_auth_config *) ap_pcalloc(p, sizeof(kerb_auth_config));
215 #ifdef KRB5
216         ((kerb_auth_config *)rec)->krb_method_k5pass = 1;
217         ((kerb_auth_config *)rec)->krb_method_gssapi = 1;
218 #endif
219 #ifdef KRB4
220         ((kerb_auth_config *)rec)->krb_method_k4pass = 1;
221 #endif
222         return rec;
223 }
224
225 static const char*
226 krb5_save_realms(cmd_parms *cmd, kerb_auth_config *sec, char *arg)
227 {
228    sec->krb_auth_realms= ap_pstrdup(cmd->pool, arg);
229    return NULL;
230 }
231
232 void log_rerror(const char *file, int line, int level, int status,
233                 const request_rec *r, const char *fmt, ...)
234 {
235    char errstr[1024];
236    char errnostr[1024];
237    va_list ap;
238
239    va_start(ap, fmt);
240    vsnprintf(errstr, sizeof(errstr), fmt, ap);
241    va_end(ap);
242
243    errnostr[0] = '\0';
244    if (errno)
245       snprintf(errnostr, sizeof(errnostr), "%s: (%s)", errstr, strerror(errno));
246    else
247       snprintf(errnostr, sizeof(errnostr), "%s", errstr);
248    
249 #ifdef APXS1
250    ap_log_rerror(file, line, level | APLOG_NOERRNO, r, "%s", errnostr);
251 #else
252    ap_log_rerror(file, line, level | APLOG_NOERRNO, status, r, "%s", errnostr);
253 #endif
254 }
255
256 #ifdef KRB4
257 /*************************************************************************** 
258  Username/Password Validation for Krb4
259  ***************************************************************************/
260 static int
261 verify_krb4_user(request_rec *r, char *name, char *instance, char *realm,
262                  char *password, char *linstance, char *srvtab)
263 {
264    int ret;
265    char *phost;
266    unsigned long addr;
267    struct hostent *hp;
268    const char *hostname;
269    KTEXT_ST ticket;
270    AUTH_DAT authdata;
271    char lrealm[REALM_SZ];
272
273    ret = krb_get_pw_in_tkt(name, instance, realm, "krbtgt", realm, 
274                            DEFAULT_TKT_LIFE, password);
275    if (ret) {
276       log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
277                  "Cannot get krb4 ticket: krb_get_pw_in_tkt() failed: %s",
278                  krb_get_err_text(ret));
279       return ret;
280    }
281
282    hostname = ap_get_server_name(r);
283
284    hp = gethostbyname(hostname);
285    if (hp == NULL) {
286       dest_tkt();
287       log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
288                  "Cannot verify krb4 ticket: gethostbyname() failed: %s",
289                  hstrerror(h_errno));
290       return h_errno;
291    }
292    memcpy(&addr, hp->h_addr, sizeof(addr));
293
294    phost = krb_get_phost((char *)hostname);
295
296    krb_get_lrealm(lrealm, 1);
297
298    ret = krb_mk_req(&ticket, linstance, phost, lrealm, 0);
299    if (ret) {
300       log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
301                  "Cannot verify krb4 ticket: krb_mk_req() failed: %s",
302                  krb_get_err_text(ret));
303       dest_tkt();
304       return ret;
305    }
306
307    ret = krb_rd_req(&ticket, linstance, phost, addr, &authdata, srvtab);
308    if (ret) {
309       log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
310                  "Cannot verify krb4 ticket: krb_rd_req() failed: %s",
311                  krb_get_err_text(ret));
312       dest_tkt();
313    }
314
315    return ret;
316 }
317
318 static int
319 krb4_cache_cleanup(void *data)
320 {
321    char *tkt_file = (char *) data;
322    
323    krb_set_tkt_string(tkt_file);
324    dest_tkt();
325    return OK;
326 }
327
328 static int 
329 authenticate_user_krb4pwd(request_rec *r,
330                           kerb_auth_config *conf,
331                           const char *auth_line)
332 {
333    int ret;
334    const char *sent_pw;
335    const char *sent_name;
336    char *sent_instance;
337    char tkt_file[32];
338    char *tkt_file_p = NULL;
339    int fd;
340    const char *realms;
341    const char *realm;
342    char *user;
343    char lrealm[REALM_SZ];
344
345    sent_pw = ap_pbase64decode(r->pool, auth_line);
346    sent_name = ap_getword (r->pool, &sent_pw, ':');
347
348    /* do not allow user to override realm setting of server */
349    if (strchr(sent_name, '@')) {
350       log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
351                  "specifying realm in user name is prohibited");
352       return HTTP_UNAUTHORIZED;
353    }
354
355    sent_instance = strchr(sent_name, '.');
356    if (sent_instance)
357       *sent_instance++ = '\0'; 
358
359    snprintf(tkt_file, sizeof(tkt_file), "/tmp/apache_tkt_XXXXXX");
360    fd = mkstemp(tkt_file);
361    if (fd < 0) {
362       log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
363                  "Cannot create krb4 ccache: mkstemp() failed: %s",
364                  strerror(errno));
365       return HTTP_INTERNAL_SERVER_ERROR;
366    }
367
368    tkt_file_p = ap_pstrdup(r->pool, tkt_file);
369    ap_register_cleanup(r->pool, tkt_file_p,
370                        krb4_cache_cleanup, ap_null_cleanup);
371
372    krb_set_tkt_string(tkt_file);
373
374    realms = conf->krb_auth_realms;
375    do {
376       memset(lrealm, 0, sizeof(lrealm));
377       realm = NULL;
378       if (realms)
379          realm = ap_getword_white(r->pool, &realms);
380
381       if (realm == NULL) {
382          ret = krb_get_lrealm(lrealm, 1);
383          realm = lrealm;
384       }
385       if (realm == NULL || *realm == '\0')
386          break;
387
388       ret = verify_krb4_user(r, (char *)sent_name, 
389                              (sent_instance) ? sent_instance : "",
390                              (char *)realm, (char *)sent_pw, "khttp",
391                              conf->krb_4_srvtab);
392       if (ret == 0)
393          break;
394    } while (realms && *realms);
395
396    if (ret) {
397       log_rerror(APLOG_MARK, APLOG_ERR, 0, r, "Verifying krb4 password failed");
398       ret = HTTP_UNAUTHORIZED;
399       goto end;
400    }
401
402    user = ap_pstrdup(r->pool, sent_name);
403    if (sent_instance)
404       user = ap_pstrcat(r->pool, user, ".", sent_instance, NULL);
405    user = ap_pstrcat(r->pool, user, "@", realm, NULL);
406
407    MK_USER = user;
408    MK_AUTH_TYPE = "Basic";
409    ap_table_setn(r->subprocess_env, "KRBTKFILE", tkt_file_p);
410
411    if (!conf->krb_save_credentials)
412       krb4_cache_cleanup(tkt_file);
413
414 end:
415    if (ret)
416       krb4_cache_cleanup(tkt_file);
417    close(fd);
418    tf_close();
419
420    return ret;
421 }
422 #endif /* KRB4 */
423
424 #ifdef KRB5
425 /*************************************************************************** 
426  Username/Password Validation for Krb5
427  ***************************************************************************/
428 /* Inspired by krb5_verify_user from Heimdal */
429 static krb5_error_code
430 verify_krb5_user(request_rec *r, krb5_context context, krb5_principal principal,
431                  krb5_ccache ccache, const char *password, const char *service,
432                  krb5_keytab keytab)
433 {
434    krb5_creds creds;
435    krb5_principal server = NULL;
436    krb5_error_code ret;
437    krb5_verify_init_creds_opt opt;
438
439    memset(&creds, 0, sizeof(creds));
440
441    ret = krb5_get_init_creds_password(context, &creds, principal, 
442                                       (char *)password, krb5_prompter_posix,
443                                       NULL, 0, NULL, NULL);
444    if (ret)
445       return ret;
446
447    ret = krb5_sname_to_principal(context, ap_get_server_name(r), service, 
448                                  KRB5_NT_SRV_HST, &server);
449    if (ret)
450       goto end;
451
452    krb5_verify_init_creds_opt_init(&opt);
453    krb5_verify_init_creds_opt_set_ap_req_nofail(&opt, 1);
454
455    ret = krb5_verify_init_creds(context, &creds, server, keytab, NULL, &opt);
456    if (ret)
457       goto end;
458
459    if (ccache) {
460       ret = krb5_cc_initialize(context, ccache, principal);
461       if (ret == 0)
462          ret = krb5_cc_store_cred(context, ccache, &creds);
463    }
464
465 end:
466    krb5_free_cred_contents(context, &creds);
467    if (server)
468       krb5_free_principal(context, server);
469    return ret;
470 }
471
472 static int
473 krb5_cache_cleanup(void *data)
474 {
475    krb5_context context;
476    krb5_ccache  cache;
477    krb5_error_code problem;
478    char *cache_name = (char *) data;
479
480    problem = krb5_init_context(&context);
481    if (problem) {
482       /* ap_log_error(APLOG_MARK, APLOG_ERR, 0, NULL, "krb5_init_context() failed"); */
483       return HTTP_INTERNAL_SERVER_ERROR;
484    }
485
486    problem = krb5_cc_resolve(context, cache_name, &cache);
487    if (problem) {
488       /* log_error(APLOG_MARK, APLOG_ERR, 0, NULL, 
489                 "krb5_cc_resolve() failed (%s: %s)",
490                 cache_name, krb5_get_err_text(context, problem)); */
491       return HTTP_INTERNAL_SERVER_ERROR;
492    }
493
494    krb5_cc_destroy(context, cache);
495    krb5_free_context(context);
496    return OK;
497 }
498
499 static int
500 create_krb5_ccache(krb5_context kcontext,
501                    request_rec *r,
502                    kerb_auth_config *conf,
503                    krb5_principal princ,
504                    krb5_ccache *ccache)
505 {
506    char *ccname;
507    krb5_error_code problem;
508    int ret;
509    krb5_ccache tmp_ccache = NULL;
510
511 #ifdef HAVE_KRB5_CC_GEN_NEW
512    problem = krb5_cc_gen_new(kcontext, &krb5_fcc_ops, &tmp_ccache);
513 #else
514    /* only older MIT seem to not have the krb5_cc_gen_new() call, so we use
515     * MIT specific call here */
516    problem = krb5_fcc_generate_new(kcontext, &tmp_ccache);
517    /* krb5_fcc_generate_new() doesn't set KRB5_TC_OPENCLOSE, which makes 
518       krb5_cc_initialize() fail */
519    krb5_fcc_set_flags(kcontext, tmp_ccache, KRB5_TC_OPENCLOSE);
520 #endif
521    if (problem) {
522       log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
523                  "Cannot create file for new krb5 ccache: %s",
524                  krb5_get_err_text(kcontext, problem));
525       ret = HTTP_INTERNAL_SERVER_ERROR;
526       goto end;
527    }
528
529    ccname = ap_pstrdup(r->pool, krb5_cc_get_name(kcontext, tmp_ccache));
530
531    problem = krb5_cc_initialize(kcontext, tmp_ccache, princ);
532    if (problem) {
533       log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
534                  "Cannot initialize krb5 ccache %s: krb5_cc_initialize() failed: %s",
535                  ccname, krb5_get_err_text(kcontext, problem));
536       ret = HTTP_INTERNAL_SERVER_ERROR;
537       goto end;
538    }
539
540    ap_table_setn(r->subprocess_env, "KRB5CCNAME", ccname);
541    ap_register_cleanup(r->pool, ccname,
542                        krb5_cache_cleanup, ap_null_cleanup);
543
544    *ccache = tmp_ccache;
545    tmp_ccache = NULL;
546
547    ret = OK;
548
549 end:
550    if (tmp_ccache)
551       krb5_cc_destroy(kcontext, tmp_ccache);
552
553    return ret;
554 }
555
556 static int
557 store_krb5_creds(krb5_context kcontext,
558                  request_rec *r,
559                  kerb_auth_config *conf,
560                  krb5_ccache delegated_cred)
561 {
562    char errstr[1024];
563    krb5_error_code problem;
564    krb5_principal princ;
565    krb5_ccache ccache;
566    int ret;
567
568    problem = krb5_cc_get_principal(kcontext, delegated_cred, &princ);
569    if (problem) {
570       snprintf(errstr, sizeof(errstr), "krb5_cc_get_principal() failed: %s",
571                krb5_get_err_text(kcontext, problem));
572       return HTTP_INTERNAL_SERVER_ERROR;
573    }
574
575    ret = create_krb5_ccache(kcontext, r, conf, princ, &ccache);
576    if (ret) {
577       krb5_free_principal(kcontext, princ);
578       return ret;
579    }
580
581 #ifdef HEIMDAL
582    problem = krb5_cc_copy_cache(kcontext, delegated_cred, ccache);
583 #else
584    problem = krb5_cc_copy_creds(kcontext, delegated_cred, ccache);
585 #endif
586    krb5_free_principal(kcontext, princ);
587    if (problem) {
588       snprintf(errstr, sizeof(errstr), "Failed to store credentials: %s",
589                krb5_get_err_text(kcontext, problem));
590       krb5_cc_destroy(kcontext, ccache);
591       return HTTP_INTERNAL_SERVER_ERROR;
592    }
593
594    krb5_cc_close(kcontext, ccache);
595    return OK;
596 }
597
598
599 int authenticate_user_krb5pwd(request_rec *r,
600                               kerb_auth_config *conf,
601                               const char *auth_line)
602 {
603    const char      *sent_pw = NULL; 
604    const char      *sent_name = NULL;
605    const char      *realms = NULL;
606    krb5_context    kcontext = NULL;
607    krb5_error_code code;
608    krb5_principal  client = NULL;
609    krb5_ccache     ccache = NULL;
610    krb5_keytab     keytab = NULL;
611    int             ret;
612    char *name = NULL;
613
614    code = krb5_init_context(&kcontext);
615    if (code) {
616       log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
617                  "Cannot initialize Kerberos5 context (%d)", code);
618       return HTTP_INTERNAL_SERVER_ERROR;
619    }
620
621    sent_pw = ap_pbase64decode(r->pool, auth_line);
622    sent_name = ap_getword (r->pool, &sent_pw, ':');
623    /* do not allow user to override realm setting of server */
624    if (strchr(sent_name, '@')) {
625       log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
626                  "specifying realm in user name is prohibited");
627       ret = HTTP_UNAUTHORIZED;
628       goto end;
629    } 
630
631 #ifdef HAVE_KRB5_CC_GEN_NEW
632    code = krb5_cc_gen_new(kcontext, &krb5_mcc_ops, &ccache);
633 #else
634    /* only older MIT seem to not have the krb5_cc_gen_new() call, so we use
635     * MIT specific call here */
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
865   if (gss_connection == NULL) {
866      gss_connection = ap_pcalloc(r->connection->pool, sizeof(*gss_connection));
867      if (gss_connection == NULL) {
868         log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
869                    "ap_pcalloc() failed (not enough memory)");
870         ret = HTTP_INTERNAL_SERVER_ERROR;
871         goto end;
872      }
873      memset(gss_connection, 0, sizeof(*gss_connection));
874      ap_register_cleanup(r->connection->pool, gss_connection, cleanup_gss_connection, ap_null_cleanup);
875   }
876
877   if (conf->krb_5_keytab) {
878      char *ktname;
879      /* we don't use the ap_* calls here, since the string passed to putenv()
880       * will become part of the enviroment and shouldn't be free()ed by apache
881       */
882      ktname = malloc(strlen("KRB5_KTNAME=") + strlen(conf->krb_5_keytab) + 1);
883      if (ktname == NULL) {
884         log_rerror(APLOG_MARK, APLOG_ERR, 0, r, "malloc() failed: not enough memory");
885         ret = HTTP_INTERNAL_SERVER_ERROR;
886         goto end;
887      }
888      sprintf(ktname, "KRB5_KTNAME=%s", conf->krb_5_keytab);
889      putenv(ktname);
890   }
891
892   if (gss_connection->server_creds == GSS_C_NO_CREDENTIAL) {
893      ret = get_gss_creds(r, conf, &gss_connection->server_creds);
894      if (ret)
895         goto end;
896   }
897
898   /* ap_getword() shifts parameter */
899   auth_param = ap_getword_white(r->pool, &auth_line);
900   if (auth_param == NULL) {
901      log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
902                 "No Authorization parameter in request from client");
903      ret = HTTP_UNAUTHORIZED;
904      goto end;
905   }
906
907   input_token.length = ap_base64decode_len(auth_param) + 1;
908   input_token.value = ap_pcalloc(r->connection->pool, input_token.length);
909   if (input_token.value == NULL) {
910      log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
911                 "ap_pcalloc() failed (not enough memory)");
912      ret = HTTP_INTERNAL_SERVER_ERROR;
913      goto end;
914   }
915   input_token.length = ap_base64decode(input_token.value, auth_param);
916
917 #if 0 
918   major_status = gss_accept_sec_context(
919 #else
920   major_status = gss_accept_sec_context_spnego(
921 #endif
922                                         &minor_status,
923                                         &gss_connection->context,
924                                         gss_connection->server_creds,
925                                         &input_token,
926                                         GSS_C_NO_CHANNEL_BINDINGS,
927                                         &client_name,
928                                         NULL,
929                                         &output_token,
930                                         NULL,
931                                         NULL,
932                                         &delegated_cred);
933   if (output_token.length) {
934      char *token = NULL;
935      size_t len;
936      
937      len = ap_base64encode_len(output_token.length) + 1;
938      token = ap_pcalloc(r->connection->pool, len + 1);
939      if (token == NULL) {
940         log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
941                    "ap_pcalloc() failed (not enough memory)");
942         ret = HTTP_INTERNAL_SERVER_ERROR;
943         gss_release_buffer(&minor_status2, &output_token);
944         goto end;
945      }
946      ap_base64encode(token, output_token.value, output_token.length);
947      token[len] = '\0';
948      ap_table_set(r->err_headers_out, "WWW-Authenticate",
949                   ap_pstrcat(r->pool, "Negotiate ", token, NULL));
950      gss_release_buffer(&minor_status2, &output_token);
951   }
952
953   if (GSS_ERROR(major_status)) {
954      log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
955                 "%s", get_gss_error(r->pool, minor_status,
956                                     "gss_accept_sec_context() failed"));
957      ret = HTTP_UNAUTHORIZED;
958      goto end;
959   }
960
961   if (major_status & GSS_S_CONTINUE_NEEDED) {
962      /* Some GSSAPI mechanism (eg GSI from Globus) may require multiple 
963       * iterations to establish authentication */
964      ret = HTTP_UNAUTHORIZED;
965      goto end;
966   }
967
968   major_status = gss_display_name(&minor_status, client_name, &output_token, NULL);
969   gss_release_name(&minor_status, &client_name); 
970   if (GSS_ERROR(major_status)) {
971     log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
972                "%s", get_gss_error(r->pool, minor_status, 
973                                    "gss_export_name() failed"));
974     ret = HTTP_INTERNAL_SERVER_ERROR;
975     goto end;
976   }
977
978   MK_AUTH_TYPE = "Negotiate";
979   MK_USER = ap_pstrdup(r->pool, output_token.value);
980
981   if (conf->krb_save_credentials && delegated_cred != GSS_C_NO_CREDENTIAL)
982      store_gss_creds(r, conf, (char *)output_token.value, delegated_cred);
983
984   gss_release_buffer(&minor_status, &output_token);
985
986   ret = OK;
987
988 end:
989   if (delegated_cred)
990      gss_release_cred(&minor_status, &delegated_cred);
991
992   if (output_token.length) 
993      gss_release_buffer(&minor_status, &output_token);
994
995   if (client_name != GSS_C_NO_NAME)
996      gss_release_name(&minor_status, &client_name);
997
998   cleanup_gss_connection(gss_connection);
999
1000   return ret;
1001 }
1002 #endif /* KRB5 */
1003
1004 static int
1005 already_succeeded(request_rec *r)
1006 {
1007    if (ap_is_initial_req(r) || MK_AUTH_TYPE == NULL)
1008       return 0;
1009    if (strcmp(MK_AUTH_TYPE, "Negotiate") ||
1010        (strcmp(MK_AUTH_TYPE, "Basic") && strchr(MK_USER, '@')))
1011       return 1;
1012    return 0;
1013 }
1014
1015 static void
1016 note_kerb_auth_failure(request_rec *r, const kerb_auth_config *conf,
1017                        int use_krb4, int use_krb5)
1018 {
1019    const char *auth_name = NULL;
1020    int set_basic = 0;
1021
1022    /* get the user realm specified in .htaccess */
1023    auth_name = ap_auth_name(r);
1024
1025    /* XXX should the WWW-Authenticate header be cleared first? */
1026 #ifdef KRB5
1027    if (use_krb5 && conf->krb_method_gssapi)
1028       ap_table_add(r->err_headers_out, "WWW-Authenticate", "Negotiate");
1029    if (use_krb5 && conf->krb_method_k5pass) {
1030       ap_table_add(r->err_headers_out, "WWW-Authenticate",
1031                    ap_pstrcat(r->pool, "Basic realm=\"", auth_name, "\"", NULL));
1032       set_basic = 1;
1033    }
1034 #endif
1035
1036 #ifdef KRB4
1037    if (use_krb4 && conf->krb_method_k4pass && !set_basic)
1038       ap_table_add(r->err_headers_out, "WWW-Authenticate",
1039                    ap_pstrcat(r->pool, "Basic realm=\"", auth_name, "\"", NULL));
1040 #endif
1041 }
1042
1043 int kerb_authenticate_user(request_rec *r)
1044 {
1045    kerb_auth_config *conf = 
1046       (kerb_auth_config *) ap_get_module_config(r->per_dir_config,
1047                                                 &auth_kerb_module);
1048    const char *auth_type = NULL;
1049    const char *auth_line = NULL;
1050    const char *type = NULL;
1051    int use_krb5 = 0, use_krb4 = 0;
1052    int ret;
1053    static int last_return = HTTP_UNAUTHORIZED;
1054
1055    /* get the type specified in .htaccess */
1056    type = ap_auth_type(r);
1057
1058    if (type && strcasecmp(type, "Kerberos") == 0)
1059       use_krb5 = use_krb4 = 1;
1060    else if(type && strcasecmp(type, "KerberosV5") == 0)
1061       use_krb4 = 0;
1062    else if(type && strcasecmp(type, "KerberosV4") == 0)
1063       use_krb5 = 0;
1064    else
1065       return DECLINED;
1066
1067    /* get what the user sent us in the HTTP header */
1068    auth_line = MK_TABLE_GET(r->headers_in, "Authorization");
1069    if (!auth_line) {
1070       note_kerb_auth_failure(r, conf, use_krb4, use_krb5);
1071       return HTTP_UNAUTHORIZED;
1072    }
1073    auth_type = ap_getword_white(r->pool, &auth_line);
1074
1075    if (already_succeeded(r))
1076       return last_return;
1077
1078    ret = HTTP_UNAUTHORIZED;
1079
1080 #ifdef KRB5
1081    if (use_krb5 && conf->krb_method_gssapi &&
1082        strcasecmp(auth_type, "Negotiate") == 0) {
1083       ret = authenticate_user_gss(r, conf, auth_line);
1084    } else if (use_krb5 && conf->krb_method_k5pass &&
1085               strcasecmp(auth_type, "Basic") == 0) {
1086        ret = authenticate_user_krb5pwd(r, conf, auth_line);
1087    }
1088 #endif
1089
1090 #ifdef KRB4
1091    if (ret == HTTP_UNAUTHORIZED && use_krb4 && conf->krb_method_k4pass &&
1092        strcasecmp(auth_type, "Basic") == 0)
1093       ret = authenticate_user_krb4pwd(r, conf, auth_line);
1094 #endif
1095
1096    if (ret == HTTP_UNAUTHORIZED)
1097       note_kerb_auth_failure(r, conf, use_krb4, use_krb5);
1098
1099    last_return = ret;
1100    return ret;
1101 }
1102
1103
1104 /*************************************************************************** 
1105  Module Setup/Configuration
1106  ***************************************************************************/
1107 #ifdef APXS1
1108 module MODULE_VAR_EXPORT auth_kerb_module = {
1109         STANDARD_MODULE_STUFF,
1110         NULL,                           /*      module initializer            */
1111         kerb_dir_create_config,         /*      per-directory config creator  */
1112         NULL,                           /*      per-directory config merger   */
1113         NULL,                           /*      per-server    config creator  */
1114         NULL,                           /*      per-server    config merger   */
1115         kerb_auth_cmds,                 /*      command table                 */
1116         NULL,                           /* [ 9] content handlers              */
1117         NULL,                           /* [ 2] URI-to-filename translation   */
1118         kerb_authenticate_user,         /* [ 5] check/validate user_id        */
1119         NULL,                           /* [ 6] check user_id is valid *here* */
1120         NULL,                           /* [ 4] check access by host address  */
1121         NULL,                           /* [ 7] MIME type checker/setter      */
1122         NULL,                           /* [ 8] fixups                        */
1123         NULL,                           /* [10] logger                        */
1124         NULL,                           /* [ 3] header parser                 */
1125         NULL,                           /*      process initialization        */
1126         NULL,                           /*      process exit/cleanup          */
1127         NULL                            /* [ 1] post read_request handling    */
1128 };
1129 #else
1130 static int
1131 kerb_init_handler(apr_pool_t *p, apr_pool_t *plog,
1132                   apr_pool_t *ptemp, server_rec *s)
1133 {
1134    ap_add_version_component(p, "mod_auth_kerb/" MODAUTHKERB_VERSION);
1135    return OK;
1136 }
1137
1138 void kerb_register_hooks(apr_pool_t *p)
1139 {
1140    ap_hook_post_config(kerb_init_handler, NULL, NULL, APR_HOOK_MIDDLE);
1141    ap_hook_check_user_id(kerb_authenticate_user, NULL, NULL, APR_HOOK_MIDDLE);
1142 }
1143
1144 module AP_MODULE_DECLARE_DATA auth_kerb_module =
1145 {
1146    STANDARD20_MODULE_STUFF,
1147    kerb_dir_create_config,      /* create per-dir    conf structures  */
1148    NULL,                        /* merge  per-dir    conf structures  */
1149    NULL,                        /* create per-server conf structures  */
1150    NULL,                        /* merge  per-server conf structures  */
1151    kerb_auth_cmds,              /* table of configuration directives  */
1152    kerb_register_hooks          /* register hooks                     */
1153 };
1154 #endif