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