really log minor GSS error messages
[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       if (GSS_ERROR(maj_stat))
783          break;
784       err_msg = ap_pstrcat(p, err_msg, ": ", (char*) status_string.value, NULL);
785       gss_release_buffer(&min_stat, &status_string);
786       
787       maj_stat = gss_display_status (&min_stat,
788                                      err_min,
789                                      GSS_C_MECH_CODE,
790                                      GSS_C_NULL_OID,
791                                      &msg_ctx,
792                                      &status_string);
793       if (!GSS_ERROR(maj_stat)) {
794          err_msg = ap_pstrcat(p, err_msg,
795                               " (", (char*) status_string.value, ")", NULL);
796          gss_release_buffer(&min_stat, &status_string);
797       }
798    } while (!GSS_ERROR(maj_stat) && msg_ctx != 0);
799
800    return err_msg;
801 }
802
803 static int
804 cleanup_gss_connection(void *data)
805 {
806    OM_uint32 minor_status;
807    gss_connection_t *gss_conn = (gss_connection_t *)data;
808
809    if (data == NULL)
810       return OK;
811    if (gss_conn->context != GSS_C_NO_CONTEXT)
812       gss_delete_sec_context(&minor_status, &gss_conn->context,
813                              GSS_C_NO_BUFFER);
814    if (gss_conn->server_creds != GSS_C_NO_CREDENTIAL)
815       gss_release_cred(&minor_status, &gss_conn->server_creds);
816
817    gss_connection = NULL;
818
819    return OK;
820 }
821
822 static int
823 store_gss_creds(request_rec *r, kerb_auth_config *conf, char *princ_name,
824                 gss_cred_id_t delegated_cred)
825 {
826    OM_uint32 maj_stat, min_stat;
827    krb5_principal princ = NULL;
828    krb5_ccache ccache = NULL;
829    krb5_error_code problem;
830    krb5_context context;
831    int ret = HTTP_INTERNAL_SERVER_ERROR;
832
833    problem = krb5_init_context(&context);
834    if (problem) {
835       log_rerror(APLOG_MARK, APLOG_ERR, 0, r, "Cannot initialize krb5 context");
836       return HTTP_INTERNAL_SERVER_ERROR;
837    }
838
839    problem = krb5_parse_name(context, princ_name, &princ);
840    if (problem) {
841       log_rerror(APLOG_MARK, APLOG_ERR, 0, r, 
842          "Cannot parse delegated username (%s)", krb5_get_err_text(context, problem));
843       goto end;
844    }
845
846    problem = create_krb5_ccache(context, r, conf, princ, &ccache);
847    if (problem) {
848       log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
849          "Cannot create krb5 ccache (%s)", krb5_get_err_text(context, problem));
850       goto end;
851    }
852
853    maj_stat = gss_krb5_copy_ccache(&min_stat, delegated_cred, ccache);
854    if (GSS_ERROR(maj_stat)) {
855       log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
856          "Cannot store delegated credential (%s)", 
857          get_gss_error(r->pool, maj_stat, min_stat, "gss_krb5_copy_ccache"));
858       goto end;
859    }
860
861    krb5_cc_close(context, ccache);
862    ccache = NULL;
863    ret = 0;
864
865 end:
866    if (princ)
867       krb5_free_principal(context, princ);
868    if (ccache)
869       krb5_cc_destroy(context, ccache);
870    krb5_free_context(context);
871    return ret;
872 }
873
874 static int
875 get_gss_creds(request_rec *r,
876               kerb_auth_config *conf,
877               gss_cred_id_t *server_creds)
878 {
879    gss_buffer_desc input_token = GSS_C_EMPTY_BUFFER;
880    OM_uint32 major_status, minor_status, minor_status2;
881    gss_name_t server_name = GSS_C_NO_NAME;
882    char buf[1024];
883
884    snprintf(buf, sizeof(buf), "%s/%s", conf->krb_service_name, ap_get_server_name(r));
885
886    input_token.value = buf;
887    input_token.length = strlen(buf) + 1;
888
889    major_status = gss_import_name(&minor_status, &input_token,
890                                   GSS_C_NT_USER_NAME,
891                                   &server_name);
892    if (GSS_ERROR(major_status)) {
893       log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
894                  "%s", get_gss_error(r->pool, major_status, minor_status,
895                  "gss_import_name() failed"));
896       return HTTP_INTERNAL_SERVER_ERROR;
897    }
898    
899    major_status = gss_acquire_cred(&minor_status, server_name, GSS_C_INDEFINITE,
900                                    GSS_C_NO_OID_SET, GSS_C_ACCEPT,
901                                    server_creds, NULL, NULL);
902    gss_release_name(&minor_status2, &server_name);
903    if (GSS_ERROR(major_status)) {
904       log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
905                  "%s", get_gss_error(r->pool, major_status, minor_status,
906                                      "gss_acquire_cred() failed"));
907       return HTTP_INTERNAL_SERVER_ERROR;
908    }
909    
910    return 0;
911 }
912
913 static int
914 cmp_gss_type(gss_buffer_t token, gss_OID oid)
915 {
916    unsigned char *p;
917    size_t len;
918
919    if (token->length == 0)
920       return GSS_S_DEFECTIVE_TOKEN;
921
922    p = token->value;
923    if (*p++ != 0x60)
924       return GSS_S_DEFECTIVE_TOKEN;
925    len = *p++;
926    if (len & 0x80) {
927       if ((len & 0x7f) > 4)
928          return GSS_S_DEFECTIVE_TOKEN;
929       p += len & 0x7f;
930    }
931    if (*p++ != 0x06)
932       return GSS_S_DEFECTIVE_TOKEN;
933
934    if (((OM_uint32) *p++) != oid->length)
935       return GSS_S_DEFECTIVE_TOKEN;
936
937    return memcmp(p, oid->elements, oid->length);
938 }
939
940 static int
941 authenticate_user_gss(request_rec *r, kerb_auth_config *conf,
942                       const char *auth_line, char **negotiate_ret_value)
943 {
944   OM_uint32 major_status, minor_status, minor_status2;
945   gss_buffer_desc input_token = GSS_C_EMPTY_BUFFER;
946   gss_buffer_desc output_token = GSS_C_EMPTY_BUFFER;
947   const char *auth_param = NULL;
948   int ret;
949   gss_name_t client_name = GSS_C_NO_NAME;
950   gss_cred_id_t delegated_cred = GSS_C_NO_CREDENTIAL;
951   OM_uint32 (*accept_sec_token)();
952   gss_OID_desc spnego_oid;
953
954   *negotiate_ret_value = (char *)EMPTY_STRING;
955
956   spnego_oid.length = 6;
957   spnego_oid.elements = (void *)"\x2b\x06\x01\x05\x05\x02";
958
959   if (gss_connection == NULL) {
960      gss_connection = ap_pcalloc(r->connection->pool, sizeof(*gss_connection));
961      if (gss_connection == NULL) {
962         log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
963                    "ap_pcalloc() failed (not enough memory)");
964         ret = HTTP_INTERNAL_SERVER_ERROR;
965         goto end;
966      }
967      memset(gss_connection, 0, sizeof(*gss_connection));
968      ap_register_cleanup(r->connection->pool, gss_connection, cleanup_gss_connection, ap_null_cleanup);
969   }
970
971   if (conf->krb_5_keytab) {
972      char *ktname;
973      /* we don't use the ap_* calls here, since the string passed to putenv()
974       * will become part of the enviroment and shouldn't be free()ed by apache
975       */
976      ktname = malloc(strlen("KRB5_KTNAME=") + strlen(conf->krb_5_keytab) + 1);
977      if (ktname == NULL) {
978         log_rerror(APLOG_MARK, APLOG_ERR, 0, r, "malloc() failed: not enough memory");
979         ret = HTTP_INTERNAL_SERVER_ERROR;
980         goto end;
981      }
982      sprintf(ktname, "KRB5_KTNAME=%s", conf->krb_5_keytab);
983      putenv(ktname);
984   }
985
986   if (gss_connection->server_creds == GSS_C_NO_CREDENTIAL) {
987      ret = get_gss_creds(r, conf, &gss_connection->server_creds);
988      if (ret)
989         goto end;
990   }
991
992   /* ap_getword() shifts parameter */
993   auth_param = ap_getword_white(r->pool, &auth_line);
994   if (auth_param == NULL) {
995      log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
996                 "No Authorization parameter in request from client");
997      ret = HTTP_UNAUTHORIZED;
998      goto end;
999   }
1000
1001   input_token.length = ap_base64decode_len(auth_param) + 1;
1002   input_token.value = ap_pcalloc(r->connection->pool, input_token.length);
1003   if (input_token.value == NULL) {
1004      log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
1005                 "ap_pcalloc() failed (not enough memory)");
1006      ret = HTTP_INTERNAL_SERVER_ERROR;
1007      goto end;
1008   }
1009   input_token.length = ap_base64decode(input_token.value, auth_param);
1010
1011   accept_sec_token = (cmp_gss_type(&input_token, &spnego_oid) == 0) ?
1012                         gss_accept_sec_context_spnego : gss_accept_sec_context;
1013
1014   major_status = accept_sec_token(&minor_status,
1015                                   &gss_connection->context,
1016                                   gss_connection->server_creds,
1017                                   &input_token,
1018                                   GSS_C_NO_CHANNEL_BINDINGS,
1019                                   &client_name,
1020                                   NULL,
1021                                   &output_token,
1022                                   NULL,
1023                                   NULL,
1024                                   &delegated_cred);
1025   if (output_token.length) {
1026      char *token = NULL;
1027      size_t len;
1028      
1029      len = ap_base64encode_len(output_token.length) + 1;
1030      token = ap_pcalloc(r->connection->pool, len + 1);
1031      if (token == NULL) {
1032         log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
1033                    "ap_pcalloc() failed (not enough memory)");
1034         ret = HTTP_INTERNAL_SERVER_ERROR;
1035         gss_release_buffer(&minor_status2, &output_token);
1036         goto end;
1037      }
1038      ap_base64encode(token, output_token.value, output_token.length);
1039      token[len] = '\0';
1040      *negotiate_ret_value = token;
1041      gss_release_buffer(&minor_status2, &output_token);
1042   }
1043
1044   if (GSS_ERROR(major_status)) {
1045      log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
1046                 "%s", get_gss_error(r->pool, major_status, minor_status,
1047                                     "gss_accept_sec_context() failed"));
1048      /* Don't offer the Negotiate method again if call to GSS layer failed */
1049      *negotiate_ret_value = NULL;
1050      ret = HTTP_UNAUTHORIZED;
1051      goto end;
1052   }
1053
1054   if (major_status & GSS_S_CONTINUE_NEEDED) {
1055      /* Some GSSAPI mechanism (eg GSI from Globus) may require multiple 
1056       * iterations to establish authentication */
1057      ret = HTTP_UNAUTHORIZED;
1058      goto end;
1059   }
1060
1061   major_status = gss_display_name(&minor_status, client_name, &output_token, NULL);
1062   gss_release_name(&minor_status, &client_name); 
1063   if (GSS_ERROR(major_status)) {
1064     log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
1065                "%s", get_gss_error(r->pool, major_status, minor_status,
1066                                    "gss_export_name() failed"));
1067     ret = HTTP_INTERNAL_SERVER_ERROR;
1068     goto end;
1069   }
1070
1071   MK_AUTH_TYPE = "Negotiate";
1072   MK_USER = ap_pstrdup(r->pool, output_token.value);
1073
1074   if (conf->krb_save_credentials && delegated_cred != GSS_C_NO_CREDENTIAL)
1075      store_gss_creds(r, conf, (char *)output_token.value, delegated_cred);
1076
1077   gss_release_buffer(&minor_status, &output_token);
1078
1079   ret = OK;
1080
1081 end:
1082   if (delegated_cred)
1083      gss_release_cred(&minor_status, &delegated_cred);
1084
1085   if (output_token.length) 
1086      gss_release_buffer(&minor_status, &output_token);
1087
1088   if (client_name != GSS_C_NO_NAME)
1089      gss_release_name(&minor_status, &client_name);
1090
1091   cleanup_gss_connection(gss_connection);
1092
1093   return ret;
1094 }
1095 #endif /* KRB5 */
1096
1097 static int
1098 already_succeeded(request_rec *r)
1099 {
1100    if (ap_is_initial_req(r) || MK_AUTH_TYPE == NULL)
1101       return 0;
1102    if (strcmp(MK_AUTH_TYPE, "Negotiate") ||
1103        (strcmp(MK_AUTH_TYPE, "Basic") && strchr(MK_USER, '@')))
1104       return 1;
1105    return 0;
1106 }
1107
1108 static void
1109 note_kerb_auth_failure(request_rec *r, const kerb_auth_config *conf,
1110                        int use_krb4, int use_krb5, char *negotiate_ret_value)
1111 {
1112    const char *auth_name = NULL;
1113    int set_basic = 0;
1114    char *negoauth_param;
1115
1116    /* get the user realm specified in .htaccess */
1117    auth_name = ap_auth_name(r);
1118
1119    /* XXX should the WWW-Authenticate header be cleared first? */
1120 #ifdef KRB5
1121    if (use_krb5 && conf->krb_method_gssapi && negotiate_ret_value != NULL) {
1122       negoauth_param = (*negotiate_ret_value == '\0') ? "Negotiate" :
1123                   ap_pstrcat(r->pool, "Negotiate ", negotiate_ret_value, NULL);
1124       ap_table_add(r->err_headers_out, "WWW-Authenticate", negoauth_param);
1125    }
1126    if (use_krb5 && conf->krb_method_k5pass) {
1127       ap_table_add(r->err_headers_out, "WWW-Authenticate",
1128                    ap_pstrcat(r->pool, "Basic realm=\"", auth_name, "\"", NULL));
1129       set_basic = 1;
1130    }
1131 #endif
1132
1133 #ifdef KRB4
1134    if (use_krb4 && conf->krb_method_k4pass && !set_basic)
1135       ap_table_add(r->err_headers_out, "WWW-Authenticate",
1136                    ap_pstrcat(r->pool, "Basic realm=\"", auth_name, "\"", NULL));
1137 #endif
1138 }
1139
1140 int kerb_authenticate_user(request_rec *r)
1141 {
1142    kerb_auth_config *conf = 
1143       (kerb_auth_config *) ap_get_module_config(r->per_dir_config,
1144                                                 &auth_kerb_module);
1145    const char *auth_type = NULL;
1146    const char *auth_line = NULL;
1147    const char *type = NULL;
1148    int use_krb5 = 0, use_krb4 = 0;
1149    int ret;
1150    static int last_return = HTTP_UNAUTHORIZED;
1151    char *negotiate_ret_value;
1152
1153    /* get the type specified in .htaccess */
1154    type = ap_auth_type(r);
1155
1156    if (type && strcasecmp(type, "Kerberos") == 0)
1157       use_krb5 = use_krb4 = 1;
1158    else if(type && strcasecmp(type, "KerberosV5") == 0)
1159       use_krb4 = 0;
1160    else if(type && strcasecmp(type, "KerberosV4") == 0)
1161       use_krb5 = 0;
1162    else
1163       return DECLINED;
1164
1165    /* get what the user sent us in the HTTP header */
1166    auth_line = MK_TABLE_GET(r->headers_in, "Authorization");
1167    if (!auth_line) {
1168       note_kerb_auth_failure(r, conf, use_krb4, use_krb5, "\0");
1169       return HTTP_UNAUTHORIZED;
1170    }
1171    auth_type = ap_getword_white(r->pool, &auth_line);
1172
1173    if (already_succeeded(r))
1174       return last_return;
1175
1176    ret = HTTP_UNAUTHORIZED;
1177
1178 #ifdef KRB5
1179    if (use_krb5 && conf->krb_method_gssapi &&
1180        strcasecmp(auth_type, "Negotiate") == 0) {
1181       ret = authenticate_user_gss(r, conf, auth_line, &negotiate_ret_value);
1182    } else if (use_krb5 && conf->krb_method_k5pass &&
1183               strcasecmp(auth_type, "Basic") == 0) {
1184        ret = authenticate_user_krb5pwd(r, conf, auth_line);
1185    }
1186 #endif
1187
1188 #ifdef KRB4
1189    if (ret == HTTP_UNAUTHORIZED && use_krb4 && conf->krb_method_k4pass &&
1190        strcasecmp(auth_type, "Basic") == 0)
1191       ret = authenticate_user_krb4pwd(r, conf, auth_line);
1192 #endif
1193
1194    if (ret == HTTP_UNAUTHORIZED)
1195       note_kerb_auth_failure(r, conf, use_krb4, use_krb5, negotiate_ret_value);
1196
1197    last_return = ret;
1198    return ret;
1199 }
1200
1201
1202 /*************************************************************************** 
1203  Module Setup/Configuration
1204  ***************************************************************************/
1205 #ifdef APXS1
1206 module MODULE_VAR_EXPORT auth_kerb_module = {
1207         STANDARD_MODULE_STUFF,
1208         NULL,                           /*      module initializer            */
1209         kerb_dir_create_config,         /*      per-directory config creator  */
1210         NULL,                           /*      per-directory config merger   */
1211         NULL,                           /*      per-server    config creator  */
1212         NULL,                           /*      per-server    config merger   */
1213         kerb_auth_cmds,                 /*      command table                 */
1214         NULL,                           /* [ 9] content handlers              */
1215         NULL,                           /* [ 2] URI-to-filename translation   */
1216         kerb_authenticate_user,         /* [ 5] check/validate user_id        */
1217         NULL,                           /* [ 6] check user_id is valid *here* */
1218         NULL,                           /* [ 4] check access by host address  */
1219         NULL,                           /* [ 7] MIME type checker/setter      */
1220         NULL,                           /* [ 8] fixups                        */
1221         NULL,                           /* [10] logger                        */
1222         NULL,                           /* [ 3] header parser                 */
1223         NULL,                           /*      process initialization        */
1224         NULL,                           /*      process exit/cleanup          */
1225         NULL                            /* [ 1] post read_request handling    */
1226 };
1227 #else
1228 static int
1229 kerb_init_handler(apr_pool_t *p, apr_pool_t *plog,
1230                   apr_pool_t *ptemp, server_rec *s)
1231 {
1232    ap_add_version_component(p, "mod_auth_kerb/" MODAUTHKERB_VERSION);
1233    return OK;
1234 }
1235
1236 void kerb_register_hooks(apr_pool_t *p)
1237 {
1238    ap_hook_post_config(kerb_init_handler, NULL, NULL, APR_HOOK_MIDDLE);
1239    ap_hook_check_user_id(kerb_authenticate_user, NULL, NULL, APR_HOOK_MIDDLE);
1240 }
1241
1242 module AP_MODULE_DECLARE_DATA auth_kerb_module =
1243 {
1244    STANDARD20_MODULE_STUFF,
1245    kerb_dir_create_config,      /* create per-dir    conf structures  */
1246    NULL,                        /* merge  per-dir    conf structures  */
1247    NULL,                        /* create per-server conf structures  */
1248    NULL,                        /* merge  per-server conf structures  */
1249    kerb_auth_cmds,              /* table of configuration directives  */
1250    kerb_register_hooks          /* register hooks                     */
1251 };
1252 #endif