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