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