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