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