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