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