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