e49f8e10febfe6de2acf611fee91b21a398ee38f
[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  * Copyright (c) 2004 Masarykova universita
15  * (Masaryk University, Brno, Czech Republic)
16  * All rights reserved.
17  *
18  * Redistribution and use in source and binary forms, with or without
19  * modification, are permitted provided that the following conditions are met:
20  *
21  * 1. Redistributions of source code must retain the above copyright notice,
22  *    this list of conditions and the following disclaimer.
23  *
24  * 2. Redistributions in binary form must reproduce the above copyright
25  *    notice, this list of conditions and the following disclaimer in the
26  *    documentation and/or other materials provided with the distribution.
27  *
28  * 3. Neither the name of the University nor the names of its contributors may
29  *    be used to endorse or promote products derived from this software
30  *    without specific prior written permission.
31  *
32  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
33  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
34  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
35  * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
36  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
37  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
38  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
39  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
40  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
41  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
42  * POSSIBILITY OF SUCH DAMAGE.
43  */
44
45 #ident "$Id$"
46
47 #include "config.h"
48
49 #include <stdlib.h>
50 #include <stdio.h>
51 #include <stdarg.h>
52
53 #define MODAUTHKERB_VERSION "5.0-rc6"
54
55 #include <httpd.h>
56 #include <http_config.h>
57 #include <http_core.h>
58 #include <http_log.h>
59 #include <http_protocol.h>
60 #include <http_request.h>
61
62 #ifdef STANDARD20_MODULE_STUFF
63 #include <ap_compat.h>
64 #include <apr_strings.h>
65 #include <apr_base64.h>
66 #endif
67
68 #ifdef KRB5
69 #include <krb5.h>
70 #ifdef HEIMDAL
71 #  include <gssapi.h>
72 #else
73 #  include <gssapi/gssapi.h>
74 #  include <gssapi/gssapi_generic.h>
75 #  include <gssapi/gssapi_krb5.h>
76 #  define GSS_C_NT_USER_NAME gss_nt_user_name
77 #  define GSS_C_NT_HOSTBASED_SERVICE gss_nt_service_name
78 #  define krb5_get_err_text(context,code) error_message(code)
79 #endif
80 #include "spnegokrb5.h"
81 #endif /* KRB5 */
82
83 #ifdef KRB4
84 /* Prevent warning about closesocket redefinition (Apache's ap_config.h and 
85  * MIT Kerberos' port-sockets.h both define it as close) */
86 #ifdef closesocket
87 #  undef closesocket
88 #endif
89 #include <krb.h>
90 #include <netdb.h> /* gethostbyname() */
91 #endif /* KRB4 */
92
93 #ifdef WIN32
94 #define vsnprintf _vsnprintf
95 #define snprintf _snprintf
96 #else
97 /* XXX remove dependency on unistd.h ??? */
98 #include <unistd.h>
99 #endif
100
101 #ifdef STANDARD20_MODULE_STUFF
102 module AP_MODULE_DECLARE_DATA auth_kerb_module;
103 #else
104 module auth_kerb_module;
105 #endif
106
107 /*************************************************************************** 
108  Macros To Ease Compatibility
109  ***************************************************************************/
110 #ifdef STANDARD20_MODULE_STUFF
111 #define MK_POOL apr_pool_t
112 #define MK_TABLE_GET apr_table_get
113 #define MK_USER r->user
114 #define MK_AUTH_TYPE r->ap_auth_type
115 #else
116 #define MK_POOL pool
117 #define MK_TABLE_GET ap_table_get
118 #define MK_USER r->connection->user
119 #define MK_AUTH_TYPE r->connection->ap_auth_type
120 #define PROXYREQ_PROXY STD_PROXY
121 #endif
122
123 /*************************************************************************** 
124  Auth Configuration Structure
125  ***************************************************************************/
126 typedef struct {
127         char *krb_auth_realms;
128         int krb_save_credentials;
129         int krb_verify_kdc;
130         char *krb_service_name;
131         int krb_authoritative;
132         int krb_delegate_basic;
133 #ifdef KRB5
134         char *krb_5_keytab;
135         int krb_method_gssapi;
136         int krb_method_k5pass;
137 #endif
138 #ifdef KRB4
139         char *krb_4_srvtab;
140         int krb_method_k4pass;
141 #endif
142 } kerb_auth_config;
143
144 static void
145 set_kerb_auth_headers(request_rec *r, const kerb_auth_config *conf,
146                       int use_krb4, int use_krb5pwd, char *negotiate_ret_value);
147
148 static const char*
149 krb5_save_realms(cmd_parms *cmd, kerb_auth_config *sec, char *arg);
150
151 #ifdef STANDARD20_MODULE_STUFF
152 #define command(name, func, var, type, usage)           \
153   AP_INIT_ ## type (name, func,                         \
154         (void*)APR_XtOffsetOf(kerb_auth_config, var),   \
155         OR_AUTHCFG | RSRC_CONF, usage)
156 #else
157 #define command(name, func, var, type, usage)           \
158   { name, func,                                         \
159     (void*)XtOffsetOf(kerb_auth_config, var),           \
160     OR_AUTHCFG | RSRC_CONF, type, usage }
161 #endif
162
163 static const command_rec kerb_auth_cmds[] = {
164    command("KrbAuthRealms", krb5_save_realms, krb_auth_realms,
165      RAW_ARGS, "Realms to attempt authentication against (can be multiple)."),
166
167    command("KrbAuthRealm", krb5_save_realms, krb_auth_realms,
168      RAW_ARGS, "Alias for KrbAuthRealms."),
169
170    command("KrbSaveCredentials", ap_set_flag_slot, krb_save_credentials,
171      FLAG, "Save and store credentials/tickets retrieved during auth."),
172
173    command("KrbVerifyKDC", ap_set_flag_slot, krb_verify_kdc,
174      FLAG, "Verify tickets against keytab to prevent KDC spoofing attacks."),
175
176    command("KrbServiceName", ap_set_string_slot, krb_service_name,
177      TAKE1, "Service name to be used by Apache for authentication."),
178
179    command("KrbAuthoritative", ap_set_flag_slot, krb_authoritative,
180      FLAG, "Set to 'off' to allow access control to be passed along to lower modules iff the UserID is not known to this module."),
181
182    command("KrbDelegateBasic", ap_set_flag_slot, krb_delegate_basic,
183      FLAG, "Always offer Basic authentication regardless of KrbMethodK5Pass and pass on authentication to lower modules if Basic headers arrive."),
184
185 #ifdef KRB5
186    command("Krb5Keytab", ap_set_file_slot, krb_5_keytab,
187      TAKE1, "Location of Kerberos V5 keytab file."),
188
189    command("KrbMethodNegotiate", ap_set_flag_slot, krb_method_gssapi,
190      FLAG, "Enable Negotiate authentication method."),
191
192    command("KrbMethodK5Passwd", ap_set_flag_slot, krb_method_k5pass,
193      FLAG, "Enable Kerberos V5 password authentication."),
194 #endif 
195
196 #ifdef KRB4
197    command("Krb4Srvtab", ap_set_file_slot, krb_4_srvtab,
198      TAKE1, "Location of Kerberos V4 srvtab file."),
199
200    command("KrbMethodK4Passwd", ap_set_flag_slot, krb_method_k4pass,
201      FLAG, "Enable Kerberos V4 password authentication."),
202 #endif
203
204    { NULL }
205 };
206
207 #ifdef WIN32
208 int
209 mkstemp(char *template)
210 {
211     int start, i;
212     pid_t val;
213     val = getpid();
214     start = strlen(template) - 1;
215     while(template[start] == 'X') {
216         template[start] = '0' + val % 10;
217         val /= 10;
218         start--;
219     }
220     
221     do{
222         int fd;
223         fd = open(template, O_RDWR | O_CREAT | O_EXCL, 0600);
224         if(fd >= 0 || errno != EEXIST)
225             return fd;
226         i = start + 1;
227         do{
228             if(template[i] == 0)
229                 return -1;
230             template[i]++;
231             if(template[i] == '9' + 1)
232                 template[i] = 'a';
233             if(template[i] <= 'z')
234                 break;
235             template[i] = 'a';
236             i++;
237         }while(1);
238     }while(1);
239 }
240 #endif
241
242 #if defined(KRB5) && !defined(HEIMDAL)
243 /* Needed to work around problems with replay caches */
244 #include "mit-internals.h"
245
246 /* This is our replacement krb5_rc_store function */
247 static krb5_error_code
248 mod_auth_kerb_rc_store(krb5_context context, krb5_rcache rcache,
249                        krb5_donot_replay_internal *donot_replay)
250 {
251    return 0;
252 }
253
254 /* And this is the operations vector for our replay cache */
255 const krb5_rc_ops_internal mod_auth_kerb_rc_ops = {
256   0,
257   "dfl",
258   krb5_rc_dfl_init,
259   krb5_rc_dfl_recover,
260   krb5_rc_dfl_destroy,
261   krb5_rc_dfl_close,
262   mod_auth_kerb_rc_store,
263   krb5_rc_dfl_expunge,
264   krb5_rc_dfl_get_span,
265   krb5_rc_dfl_get_name,
266   krb5_rc_dfl_resolve
267 };
268 #endif
269
270
271 /*************************************************************************** 
272  Auth Configuration Initialization
273  ***************************************************************************/
274 static void *kerb_dir_create_config(MK_POOL *p, char *d)
275 {
276         kerb_auth_config *rec;
277
278         rec = (kerb_auth_config *) ap_pcalloc(p, sizeof(kerb_auth_config));
279         ((kerb_auth_config *)rec)->krb_verify_kdc = 1;
280         ((kerb_auth_config *)rec)->krb_service_name = "HTTP";
281         ((kerb_auth_config *)rec)->krb_authoritative = 1;
282         ((kerb_auth_config *)rec)->krb_delegate_basic = 0;
283 #ifdef KRB5
284         ((kerb_auth_config *)rec)->krb_method_k5pass = 1;
285         ((kerb_auth_config *)rec)->krb_method_gssapi = 1;
286 #endif
287 #ifdef KRB4
288         ((kerb_auth_config *)rec)->krb_method_k4pass = 1;
289 #endif
290         return rec;
291 }
292
293 static const char*
294 krb5_save_realms(cmd_parms *cmd, kerb_auth_config *sec, char *arg)
295 {
296    sec->krb_auth_realms= ap_pstrdup(cmd->pool, arg);
297    return NULL;
298 }
299
300 void log_rerror(const char *file, int line, int level, int status,
301                 const request_rec *r, const char *fmt, ...)
302 {
303    char errstr[1024];
304    va_list ap;
305
306    va_start(ap, fmt);
307    vsnprintf(errstr, sizeof(errstr), fmt, ap);
308    va_end(ap);
309
310    
311 #ifdef STANDARD20_MODULE_STUFF
312    ap_log_rerror(file, line, level | APLOG_NOERRNO, status, r, "%s", errstr);
313 #else
314    ap_log_rerror(file, line, level | APLOG_NOERRNO, r, "%s", errstr);
315 #endif
316 }
317
318 #ifdef KRB4
319 /*************************************************************************** 
320  Username/Password Validation for Krb4
321  ***************************************************************************/
322 static int
323 verify_krb4_user(request_rec *r, char *name, char *instance, char *realm,
324                  char *password, char *linstance, char *srvtab, int krb_verify_kdc)
325 {
326    int ret;
327    char *phost;
328    unsigned long addr;
329    struct hostent *hp;
330    const char *hostname;
331    KTEXT_ST ticket;
332    AUTH_DAT authdata;
333    char lrealm[REALM_SZ];
334
335    ret = krb_get_pw_in_tkt(name, instance, realm, "krbtgt", realm, 
336                            DEFAULT_TKT_LIFE, password);
337    if (ret) {
338       log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
339                  "Cannot get krb4 ticket: krb_get_pw_in_tkt() failed: %s",
340                  krb_get_err_text(ret));
341       return ret;
342    }
343
344    if (!krb_verify_kdc)
345       return ret;
346
347    hostname = ap_get_server_name(r);
348
349    hp = gethostbyname(hostname);
350    if (hp == NULL) {
351       dest_tkt();
352       log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
353                  "Cannot verify krb4 ticket: gethostbyname() failed: %s",
354                  hstrerror(h_errno));
355       return h_errno;
356    }
357    memcpy(&addr, hp->h_addr, sizeof(addr));
358
359    phost = krb_get_phost((char *)hostname);
360
361    krb_get_lrealm(lrealm, 1);
362
363    ret = krb_mk_req(&ticket, linstance, phost, lrealm, 0);
364    if (ret) {
365       log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
366                  "Cannot verify krb4 ticket: krb_mk_req() failed: %s",
367                  krb_get_err_text(ret));
368       dest_tkt();
369       return ret;
370    }
371
372    ret = krb_rd_req(&ticket, linstance, phost, addr, &authdata, srvtab);
373    if (ret) {
374       log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
375                  "Cannot verify krb4 ticket: krb_rd_req() failed: %s",
376                  krb_get_err_text(ret));
377       dest_tkt();
378    }
379
380    return ret;
381 }
382
383 static int
384 krb4_cache_cleanup(void *data)
385 {
386    char *tkt_file = (char *) data;
387    
388    krb_set_tkt_string(tkt_file);
389    dest_tkt();
390    return OK;
391 }
392
393 static int 
394 authenticate_user_krb4pwd(request_rec *r,
395                           kerb_auth_config *conf,
396                           const char *auth_line)
397 {
398    int ret;
399    const char *sent_pw;
400    const char *sent_name;
401    char *sent_instance;
402    char tkt_file[32];
403    char *tkt_file_p = NULL;
404    int fd;
405    const char *realms;
406    const char *realm;
407    char *user;
408    char lrealm[REALM_SZ];
409    int all_principals_unkown;
410
411    sent_pw = ap_pbase64decode(r->pool, auth_line);
412    sent_name = ap_getword (r->pool, &sent_pw, ':');
413
414    /* do not allow user to override realm setting of server */
415    if (strchr(sent_name, '@')) {
416       log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
417                  "specifying realm in user name is prohibited");
418       return HTTP_UNAUTHORIZED;
419    }
420
421    sent_instance = strchr(sent_name, '.');
422    if (sent_instance)
423       *sent_instance++ = '\0'; 
424
425    snprintf(tkt_file, sizeof(tkt_file), "/tmp/apache_tkt_XXXXXX");
426    fd = mkstemp(tkt_file);
427    if (fd < 0) {
428       log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
429                  "Cannot create krb4 ccache: mkstemp() failed: %s",
430                  strerror(errno));
431       return HTTP_INTERNAL_SERVER_ERROR;
432    }
433
434    tkt_file_p = ap_pstrdup(r->pool, tkt_file);
435    ap_register_cleanup(r->pool, tkt_file_p,
436                        krb4_cache_cleanup, ap_null_cleanup);
437
438    krb_set_tkt_string(tkt_file);
439
440    all_principals_unkown = 1;
441    realms = conf->krb_auth_realms;
442    do {
443       memset(lrealm, 0, sizeof(lrealm));
444       realm = NULL;
445       if (realms)
446          realm = ap_getword_white(r->pool, &realms);
447
448       if (realm == NULL) {
449          ret = krb_get_lrealm(lrealm, 1);
450          if (ret)
451             break;
452          realm = lrealm;
453       }
454
455       ret = verify_krb4_user(r, (char *)sent_name, 
456                              (sent_instance) ? sent_instance : "",
457                              (char *)realm, (char *)sent_pw,
458                              conf->krb_service_name,
459                              conf->krb_4_srvtab, conf->krb_verify_kdc);
460       if (!conf->krb_authoritative && ret) {
461          /* if we're not authoritative, we allow authentication to pass on
462           * to another modules if (and only if) the user is not known to us */
463          if (all_principals_unkown && ret != KDC_PR_UNKNOWN)
464             all_principals_unkown = 0;
465       }
466
467       if (ret == 0)
468          break;
469    } while (realms && *realms);
470
471    if (ret) {
472       /* XXX log only in the verify_krb4_user() call */
473       log_rerror(APLOG_MARK, APLOG_ERR, 0, r, "Verifying krb4 password failed");
474       ret = (!conf->krb_authoritative && all_principals_unkown == 1 && ret == KDC_PR_UNKNOWN) ?
475                  DECLINED : HTTP_UNAUTHORIZED;
476       goto end;
477    }
478
479    user = ap_pstrdup(r->pool, sent_name);
480    if (sent_instance)
481       user = ap_pstrcat(r->pool, user, ".", sent_instance, NULL);
482    user = ap_pstrcat(r->pool, user, "@", realm, NULL);
483
484    MK_USER = user;
485    MK_AUTH_TYPE = "Basic";
486    ap_table_setn(r->subprocess_env, "KRBTKFILE", tkt_file_p);
487
488    if (!conf->krb_save_credentials)
489       krb4_cache_cleanup(tkt_file);
490
491 end:
492    if (ret)
493       krb4_cache_cleanup(tkt_file);
494    close(fd);
495    tf_close();
496
497    return ret;
498 }
499 #endif /* KRB4 */
500
501 #ifdef KRB5
502 /*************************************************************************** 
503  Username/Password Validation for Krb5
504  ***************************************************************************/
505
506 /* MIT kerberos uses replay cache checks even during credential verification
507  * (i.e. in krb5_verify_init_creds()), which is obviosuly useless. In order to
508  * avoid problems with multiple apache processes accessing the same rcache file
509  * we had to use this call instead, which is only a bit modified version of
510  * krb5_verify_init_creds() */
511 static krb5_error_code
512 verify_krb5_init_creds(krb5_context context, krb5_creds *creds,
513                        krb5_principal ap_req_server, krb5_keytab ap_req_keytab)
514 {
515    krb5_error_code ret;
516    krb5_data req;
517    krb5_ccache local_ccache = NULL;
518    krb5_creds *new_creds = NULL;
519    krb5_auth_context auth_context = NULL;
520    krb5_keytab keytab = NULL;
521
522    memset(&req, 0, sizeof(req));
523
524    if (ap_req_keytab == NULL) {
525       ret = krb5_kt_default (context, &keytab);
526       if (ret)
527          return ret;
528    } else
529       keytab = ap_req_keytab;
530
531    ret = krb5_cc_resolve(context, "MEMORY:", &local_ccache);
532    if (ret)
533       return ret;
534
535    ret = krb5_cc_initialize(context, local_ccache, creds->client);
536    if (ret)
537       goto end;
538
539    ret = krb5_cc_store_cred (context, local_ccache, creds);
540    if (ret)
541       goto end;
542
543    if (!krb5_principal_compare (context, ap_req_server, creds->server)) {
544       krb5_creds match_cred;
545
546       memset (&match_cred, 0, sizeof(match_cred));
547
548       match_cred.client = creds->client;
549       match_cred.server = ap_req_server;
550
551       ret = krb5_get_credentials (context, 0, local_ccache, 
552                                   &match_cred, &new_creds);
553       if (ret)
554          goto end;
555       creds = new_creds;
556    }
557
558    ret = krb5_mk_req_extended (context, &auth_context, 0, NULL, creds, &req);
559    if (ret)
560       goto end;
561
562    krb5_auth_con_free (context, auth_context);
563    auth_context = NULL;
564    ret = krb5_auth_con_init(context, &auth_context);
565    if (ret)
566       goto end;
567    /* use KRB5_AUTH_CONTEXT_DO_SEQUENCE to skip replay cache checks */
568    krb5_auth_con_setflags(context, auth_context, KRB5_AUTH_CONTEXT_DO_SEQUENCE);
569
570    ret = krb5_rd_req (context, &auth_context, &req, ap_req_server,
571                       keytab, 0, NULL);
572
573 end:
574 #ifdef HEIMDAL
575    /* XXX Do I ever want to support Heimdal 0.4 ??? */
576    krb5_data_free(&req);
577 #else
578    krb5_free_data_contents(context, &req);
579 #endif
580    if (auth_context)
581       krb5_auth_con_free (context, auth_context);
582    if (new_creds)
583       krb5_free_creds (context, new_creds);
584    if (ap_req_keytab == NULL && keytab)
585       krb5_kt_close (context, keytab);
586    if (local_ccache)
587       krb5_cc_destroy (context, local_ccache);
588
589    return ret;
590 }
591
592 /* Inspired by krb5_verify_user from Heimdal */
593 static krb5_error_code
594 verify_krb5_user(request_rec *r, krb5_context context, krb5_principal principal,
595                  const char *password, const char *service, krb5_keytab keytab,
596                  int krb_verify_kdc, krb5_ccache *ccache)
597 {
598    krb5_creds creds;
599    krb5_principal server = NULL;
600    krb5_error_code ret;
601    krb5_ccache ret_ccache = NULL;
602
603    /* XXX error messages shouldn't be logged here (and in the while() loop in
604     * authenticate_user_krb5pwd() as weell), in order to avoid confusing log
605     * entries when using multiple realms */
606
607    memset(&creds, 0, sizeof(creds));
608
609    ret = krb5_get_init_creds_password(context, &creds, principal, 
610                                       (char *)password, NULL,
611                                       NULL, 0, NULL, NULL);
612    if (ret) {
613       log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
614                  "krb5_get_init_creds_password() failed: %s",
615                  krb5_get_err_text(context, ret));
616       return ret;
617    }
618
619    ret = krb5_sname_to_principal(context, ap_get_server_name(r), service, 
620                                  KRB5_NT_SRV_HST, &server);
621    if (ret) {
622       log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
623                  "krb5_sname_to_principal() failed: %s",
624                  krb5_get_err_text(context, ret));
625       goto end;
626    }
627    /* XXX log_debug: lookig for <server_princ> in keytab */
628
629    /* XXX
630    {
631       char *realm;
632
633       krb5_get_default_realm(context, &realm);
634       log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
635                  "trying to verify password using key for %s/%s@%s",
636                  service, ap_get_server_name(r), realm);
637    }
638    */
639
640    if (krb_verify_kdc &&
641        (ret = verify_krb5_init_creds(context, &creds, server, keytab))) {
642        log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
643                   "failed to verify krb5 credentials: %s",
644                   krb5_get_err_text(context, ret));
645        goto end;
646    }
647
648    ret = krb5_cc_resolve(context, "MEMORY:", &ret_ccache);
649    if (ret) {
650       log_rerror(APLOG_MARK, APLOG_ERR, 0, r, 
651                  "generating new memory ccache failed: %s",
652                  krb5_get_err_text(context, ret));
653       goto end;
654    }
655
656    ret = krb5_cc_initialize(context, ret_ccache, principal);
657    if (ret) {
658       log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
659                  "krb5_cc_initialize() failed: %s",
660                  krb5_get_err_text(context, ret));
661       goto end;
662    }
663
664    ret = krb5_cc_store_cred(context, ret_ccache, &creds);
665    if (ret) {
666       log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
667                  "krb5_cc_store_cred() failed: %s",
668                  krb5_get_err_text(context, ret));
669       goto end;
670    }
671    *ccache = ret_ccache;
672    ret_ccache = NULL;
673
674 end:
675    krb5_free_cred_contents(context, &creds);
676    if (server)
677       krb5_free_principal(context, server);
678    if (ret_ccache)
679       krb5_cc_destroy(context, ret_ccache);
680
681    return ret;
682 }
683
684 static int
685 krb5_cache_cleanup(void *data)
686 {
687    krb5_context context;
688    krb5_ccache  cache;
689    krb5_error_code problem;
690    char *cache_name = (char *) data;
691
692    problem = krb5_init_context(&context);
693    if (problem) {
694       /* ap_log_error(APLOG_MARK, APLOG_ERR, 0, NULL, "krb5_init_context() failed"); */
695       return HTTP_INTERNAL_SERVER_ERROR;
696    }
697
698    problem = krb5_cc_resolve(context, cache_name, &cache);
699    if (problem) {
700       /* log_error(APLOG_MARK, APLOG_ERR, 0, NULL, 
701                 "krb5_cc_resolve() failed (%s: %s)",
702                 cache_name, krb5_get_err_text(context, problem)); */
703       return HTTP_INTERNAL_SERVER_ERROR;
704    }
705
706    krb5_cc_destroy(context, cache);
707    krb5_free_context(context);
708    return OK;
709 }
710
711 static int
712 create_krb5_ccache(krb5_context kcontext,
713                    request_rec *r,
714                    kerb_auth_config *conf,
715                    krb5_principal princ,
716                    krb5_ccache *ccache)
717 {
718    char *ccname;
719    int fd;
720    krb5_error_code problem;
721    int ret;
722    krb5_ccache tmp_ccache = NULL;
723
724    ccname = ap_psprintf(r->pool, "FILE:%s/krb5cc_apache_XXXXXX", P_tmpdir);
725    fd = mkstemp(ccname + strlen("FILE:"));
726    if (fd < 0) {
727       log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
728                  "mkstemp() failed: %s", strerror(errno));
729       ret = HTTP_INTERNAL_SERVER_ERROR;
730       goto end;
731    }
732    close(fd);
733
734    problem = krb5_cc_resolve(kcontext, ccname, &tmp_ccache);
735    if (problem) {
736       log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
737                  "krb5_cc_resolve() failed: %s",
738                  krb5_get_err_text(kcontext, problem));
739       ret = HTTP_INTERNAL_SERVER_ERROR;
740       unlink(ccname);
741       goto end;
742    }
743
744    problem = krb5_cc_initialize(kcontext, tmp_ccache, princ);
745    if (problem) {
746       log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
747                  "Cannot initialize krb5 ccache %s: krb5_cc_initialize() failed: %s",
748                  ccname, krb5_get_err_text(kcontext, problem));
749       ret = HTTP_INTERNAL_SERVER_ERROR;
750       goto end;
751    }
752
753    ap_table_setn(r->subprocess_env, "KRB5CCNAME", ccname);
754    ap_register_cleanup(r->pool, ccname,
755                        krb5_cache_cleanup, ap_null_cleanup);
756
757    *ccache = tmp_ccache;
758    tmp_ccache = NULL;
759
760    ret = OK;
761
762 end:
763    if (tmp_ccache)
764       krb5_cc_destroy(kcontext, tmp_ccache);
765
766    return ret;
767 }
768
769 static int
770 store_krb5_creds(krb5_context kcontext,
771                  request_rec *r,
772                  kerb_auth_config *conf,
773                  krb5_ccache delegated_cred)
774 {
775    char errstr[1024];
776    krb5_error_code problem;
777    krb5_principal princ;
778    krb5_ccache ccache;
779    int ret;
780
781    problem = krb5_cc_get_principal(kcontext, delegated_cred, &princ);
782    if (problem) {
783       snprintf(errstr, sizeof(errstr), "krb5_cc_get_principal() failed: %s",
784                krb5_get_err_text(kcontext, problem));
785       return HTTP_INTERNAL_SERVER_ERROR;
786    }
787
788    ret = create_krb5_ccache(kcontext, r, conf, princ, &ccache);
789    if (ret) {
790       krb5_free_principal(kcontext, princ);
791       return ret;
792    }
793
794 #ifdef HEIMDAL
795    problem = krb5_cc_copy_cache(kcontext, delegated_cred, ccache);
796 #else
797    problem = krb5_cc_copy_creds(kcontext, delegated_cred, ccache);
798 #endif
799    krb5_free_principal(kcontext, princ);
800    if (problem) {
801       snprintf(errstr, sizeof(errstr), "Failed to store credentials: %s",
802                krb5_get_err_text(kcontext, problem));
803       krb5_cc_destroy(kcontext, ccache);
804       return HTTP_INTERNAL_SERVER_ERROR;
805    }
806
807    krb5_cc_close(kcontext, ccache);
808    return OK;
809 }
810
811
812 int authenticate_user_krb5pwd(request_rec *r,
813                               kerb_auth_config *conf,
814                               const char *auth_line)
815 {
816    const char      *sent_pw = NULL; 
817    const char      *sent_name = NULL;
818    const char      *realms = NULL;
819    krb5_context    kcontext = NULL;
820    krb5_error_code code;
821    krb5_principal  client = NULL;
822    krb5_ccache     ccache = NULL;
823    krb5_keytab     keytab = NULL;
824    int             ret;
825    char            *name = NULL;
826    int             all_principals_unkown;
827
828    code = krb5_init_context(&kcontext);
829    if (code) {
830       log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
831                  "Cannot initialize Kerberos5 context (%d)", code);
832       return HTTP_INTERNAL_SERVER_ERROR;
833    }
834
835    sent_pw = ap_pbase64decode(r->pool, auth_line);
836    sent_name = ap_getword (r->pool, &sent_pw, ':');
837    /* do not allow user to override realm setting of server */
838    if (strchr(sent_name, '@')) {
839       log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
840                  "specifying realm in user name is prohibited");
841       ret = HTTP_UNAUTHORIZED;
842       goto end;
843    }
844
845    if (sent_pw == NULL || *sent_pw == '\0') {
846       log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
847                  "empty passwords are not accepted");
848       ret = HTTP_UNAUTHORIZED;
849       goto end;
850    }
851
852    if (conf->krb_5_keytab)
853       krb5_kt_resolve(kcontext, conf->krb_5_keytab, &keytab);
854
855    all_principals_unkown = 1;
856    realms = conf->krb_auth_realms;
857    do {
858       if (realms && (code = krb5_set_default_realm(kcontext,
859                                            ap_getword_white(r->pool, &realms)))){
860          log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
861                     "krb5_set_default_realm() failed: %s",
862                     krb5_get_err_text(kcontext, code));
863          continue;
864       }
865
866       if (client) {
867          krb5_free_principal(kcontext, client);
868          client = NULL;
869       }
870       code = krb5_parse_name(kcontext, sent_name, &client);
871       if (code) {
872          log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
873                     "krb5_parse_name() failed: %s",
874                     krb5_get_err_text(kcontext, code));
875          continue;
876       }
877
878       code = verify_krb5_user(r, kcontext, client, sent_pw, 
879                               conf->krb_service_name, 
880                               keytab, conf->krb_verify_kdc, &ccache);
881       if (!conf->krb_authoritative && code) {
882          /* if we're not authoritative, we allow authentication to pass on
883           * to another modules if (and only if) the user is not known to us */
884          if (all_principals_unkown && code != KRB5KDC_ERR_C_PRINCIPAL_UNKNOWN)
885             all_principals_unkown = 0;
886       }
887
888       if (code == 0)
889          break;
890
891       /* ap_getword_white() used above shifts the parameter, so it's not
892          needed to touch the realms variable */
893    } while (realms && *realms);
894
895    memset((char *)sent_pw, 0, strlen(sent_pw));
896
897    if (code) {
898       if (!conf->krb_authoritative && all_principals_unkown == 1 && code == KRB5KDC_ERR_C_PRINCIPAL_UNKNOWN)
899          ret = DECLINED;
900       else
901          ret = HTTP_UNAUTHORIZED;
902
903       goto end;
904    }
905
906    code = krb5_unparse_name(kcontext, client, &name);
907    if (code) {
908       log_rerror(APLOG_MARK, APLOG_ERR, 0, r, "krb5_unparse_name() failed: %s",
909                  krb5_get_err_text(kcontext, code));
910       ret = HTTP_UNAUTHORIZED;
911       goto end;
912    }
913    MK_USER = ap_pstrdup (r->pool, name);
914    MK_AUTH_TYPE = "Basic";
915    free(name);
916
917    if (conf->krb_save_credentials)
918       store_krb5_creds(kcontext, r, conf, ccache);
919
920    ret = OK;
921
922 end:
923    log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
924               "kerb_authenticate_user_krb5pwd ret=%d user=%s authtype=%s",
925               ret, (MK_USER)?MK_USER:"(NULL)", MK_AUTH_TYPE);
926    if (client)
927       krb5_free_principal(kcontext, client);
928    if (ccache)
929       krb5_cc_destroy(kcontext, ccache);
930    if (keytab)
931       krb5_kt_close(kcontext, keytab);
932    krb5_free_context(kcontext);
933
934    return ret;
935 }
936
937 /*********************************************************************
938  * GSSAPI Authentication
939  ********************************************************************/
940
941 static const char *
942 get_gss_error(MK_POOL *p, OM_uint32 err_maj, OM_uint32 err_min, char *prefix)
943 {
944    OM_uint32 maj_stat, min_stat; 
945    OM_uint32 msg_ctx = 0;
946    gss_buffer_desc status_string;
947    char *err_msg;
948
949    err_msg = ap_pstrdup(p, prefix);
950    do {
951       maj_stat = gss_display_status (&min_stat,
952                                      err_maj,
953                                      GSS_C_GSS_CODE,
954                                      GSS_C_NO_OID,
955                                      &msg_ctx,
956                                      &status_string);
957       if (GSS_ERROR(maj_stat))
958          break;
959       err_msg = ap_pstrcat(p, err_msg, ": ", (char*) status_string.value, NULL);
960       gss_release_buffer(&min_stat, &status_string);
961       
962       maj_stat = gss_display_status (&min_stat,
963                                      err_min,
964                                      GSS_C_MECH_CODE,
965                                      GSS_C_NULL_OID,
966                                      &msg_ctx,
967                                      &status_string);
968       if (!GSS_ERROR(maj_stat)) {
969          err_msg = ap_pstrcat(p, err_msg,
970                               " (", (char*) status_string.value, ")", NULL);
971          gss_release_buffer(&min_stat, &status_string);
972       }
973    } while (!GSS_ERROR(maj_stat) && msg_ctx != 0);
974
975    return err_msg;
976 }
977
978 static int
979 store_gss_creds(request_rec *r, kerb_auth_config *conf, char *princ_name,
980                 gss_cred_id_t delegated_cred)
981 {
982    OM_uint32 maj_stat, min_stat;
983    krb5_principal princ = NULL;
984    krb5_ccache ccache = NULL;
985    krb5_error_code problem;
986    krb5_context context;
987    int ret = HTTP_INTERNAL_SERVER_ERROR;
988
989    problem = krb5_init_context(&context);
990    if (problem) {
991       log_rerror(APLOG_MARK, APLOG_ERR, 0, r, "Cannot initialize krb5 context");
992       return HTTP_INTERNAL_SERVER_ERROR;
993    }
994
995    problem = krb5_parse_name(context, princ_name, &princ);
996    if (problem) {
997       log_rerror(APLOG_MARK, APLOG_ERR, 0, r, 
998          "Cannot parse delegated username (%s)", krb5_get_err_text(context, problem));
999       goto end;
1000    }
1001
1002    problem = create_krb5_ccache(context, r, conf, princ, &ccache);
1003    if (problem) {
1004       log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
1005          "Cannot create krb5 ccache (%s)", krb5_get_err_text(context, problem));
1006       goto end;
1007    }
1008
1009    maj_stat = gss_krb5_copy_ccache(&min_stat, delegated_cred, ccache);
1010    if (GSS_ERROR(maj_stat)) {
1011       log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
1012          "Cannot store delegated credential (%s)", 
1013          get_gss_error(r->pool, maj_stat, min_stat, "gss_krb5_copy_ccache"));
1014       goto end;
1015    }
1016
1017    krb5_cc_close(context, ccache);
1018    ccache = NULL;
1019    ret = 0;
1020
1021 end:
1022    if (princ)
1023       krb5_free_principal(context, princ);
1024    if (ccache)
1025       krb5_cc_destroy(context, ccache);
1026    krb5_free_context(context);
1027    return ret;
1028 }
1029
1030 static int
1031 get_gss_creds(request_rec *r,
1032               kerb_auth_config *conf,
1033               gss_cred_id_t *server_creds)
1034 {
1035    gss_buffer_desc token = GSS_C_EMPTY_BUFFER;
1036    OM_uint32 major_status, minor_status, minor_status2;
1037    gss_name_t server_name = GSS_C_NO_NAME;
1038    char buf[1024];
1039
1040    snprintf(buf, sizeof(buf), "%s@%s", conf->krb_service_name,
1041             ap_get_server_name(r));
1042
1043    token.value = buf;
1044    token.length = strlen(buf) + 1;
1045
1046    major_status = gss_import_name(&minor_status, &token,
1047                                   GSS_C_NT_HOSTBASED_SERVICE,
1048                                   &server_name);
1049    memset(&token, 0, sizeof(token));
1050    if (GSS_ERROR(major_status)) {
1051       log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
1052                  "%s", get_gss_error(r->pool, major_status, minor_status,
1053                  "gss_import_name() failed"));
1054       return HTTP_INTERNAL_SERVER_ERROR;
1055    }
1056
1057    major_status = gss_display_name(&minor_status, server_name, &token, NULL);
1058    if (GSS_ERROR(major_status)) {
1059       /* Perhaps we could just ignore this error but it's safer to give up now,
1060          I think */
1061       log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
1062                  "%s", get_gss_error(r->pool, major_status, minor_status,
1063                                      "gss_display_name() failed"));
1064       return HTTP_INTERNAL_SERVER_ERROR;
1065    }
1066
1067    log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, "Acquiring creds for %s",
1068               token.value);
1069    gss_release_buffer(&minor_status, &token);
1070    
1071    major_status = gss_acquire_cred(&minor_status, server_name, GSS_C_INDEFINITE,
1072                                    GSS_C_NO_OID_SET, GSS_C_ACCEPT,
1073                                    server_creds, NULL, NULL);
1074    gss_release_name(&minor_status2, &server_name);
1075    if (GSS_ERROR(major_status)) {
1076       log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
1077                  "%s", get_gss_error(r->pool, major_status, minor_status,
1078                                      "gss_acquire_cred() failed"));
1079       return HTTP_INTERNAL_SERVER_ERROR;
1080    }
1081
1082 #ifndef HEIMDAL
1083    /*
1084     * With MIT Kerberos 5 1.3.x the gss_cred_id_t is the same as
1085     * krb5_gss_cred_id_t and krb5_gss_cred_id_rec contains a pointer to
1086     * the replay cache.
1087     * This allows us to override the replay cache function vector with
1088     * our own one.
1089     * Note that this is a dirty hack to get things working and there may
1090     * well be unknown side-effects.
1091     */
1092    {
1093       krb5_gss_cred_id_t gss_creds = (krb5_gss_cred_id_t) *server_creds;
1094
1095       if (gss_creds && gss_creds->rcache && gss_creds->rcache->ops &&
1096           gss_creds->rcache->ops->type &&  
1097           memcmp(gss_creds->rcache->ops->type, "dfl", 3) == 0)
1098           /* Override the rcache operations */
1099          gss_creds->rcache->ops = &mod_auth_kerb_rc_ops;
1100    }
1101 #endif
1102    
1103    return 0;
1104 }
1105
1106 static int
1107 cmp_gss_type(gss_buffer_t token, gss_OID oid)
1108 {
1109    unsigned char *p;
1110    size_t len;
1111
1112    if (token->length == 0)
1113       return GSS_S_DEFECTIVE_TOKEN;
1114
1115    p = token->value;
1116    if (*p++ != 0x60)
1117       return GSS_S_DEFECTIVE_TOKEN;
1118    len = *p++;
1119    if (len & 0x80) {
1120       if ((len & 0x7f) > 4)
1121          return GSS_S_DEFECTIVE_TOKEN;
1122       p += len & 0x7f;
1123    }
1124    if (*p++ != 0x06)
1125       return GSS_S_DEFECTIVE_TOKEN;
1126
1127    if (((OM_uint32) *p++) != oid->length)
1128       return GSS_S_DEFECTIVE_TOKEN;
1129
1130    return memcmp(p, oid->elements, oid->length);
1131 }
1132
1133 static int
1134 authenticate_user_gss(request_rec *r, kerb_auth_config *conf,
1135                       const char *auth_line, char **negotiate_ret_value)
1136 {
1137   OM_uint32 major_status, minor_status, minor_status2;
1138   gss_buffer_desc input_token = GSS_C_EMPTY_BUFFER;
1139   gss_buffer_desc output_token = GSS_C_EMPTY_BUFFER;
1140   const char *auth_param = NULL;
1141   int ret;
1142   gss_name_t client_name = GSS_C_NO_NAME;
1143   gss_cred_id_t delegated_cred = GSS_C_NO_CREDENTIAL;
1144   OM_uint32 
1145      (*accept_sec_token)(OM_uint32 *, gss_ctx_id_t *, const gss_cred_id_t,
1146                          const gss_buffer_t, const gss_channel_bindings_t,
1147                          gss_name_t *, gss_OID *, gss_buffer_t, OM_uint32 *,
1148                          OM_uint32 *, gss_cred_id_t *);
1149   gss_OID_desc spnego_oid;
1150   gss_ctx_id_t context = GSS_C_NO_CONTEXT;
1151   gss_cred_id_t server_creds = GSS_C_NO_CREDENTIAL;
1152
1153   *negotiate_ret_value = "\0";
1154
1155   spnego_oid.length = 6;
1156   spnego_oid.elements = (void *)"\x2b\x06\x01\x05\x05\x02";
1157
1158   if (conf->krb_5_keytab) {
1159      char *ktname;
1160      /* we don't use the ap_* calls here, since the string passed to putenv()
1161       * will become part of the enviroment and shouldn't be free()ed by apache
1162       */
1163      ktname = malloc(strlen("KRB5_KTNAME=") + strlen(conf->krb_5_keytab) + 1);
1164      if (ktname == NULL) {
1165         log_rerror(APLOG_MARK, APLOG_ERR, 0, r, "malloc() failed: not enough memory");
1166         ret = HTTP_INTERNAL_SERVER_ERROR;
1167         goto end;
1168      }
1169      sprintf(ktname, "KRB5_KTNAME=%s", conf->krb_5_keytab);
1170      putenv(ktname);
1171   }
1172
1173   ret = get_gss_creds(r, conf, &server_creds);
1174   if (ret)
1175      goto end;
1176
1177   /* ap_getword() shifts parameter */
1178   auth_param = ap_getword_white(r->pool, &auth_line);
1179   if (auth_param == NULL) {
1180      log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
1181                 "No Authorization parameter in request from client");
1182      ret = HTTP_UNAUTHORIZED;
1183      goto end;
1184   }
1185
1186   input_token.length = ap_base64decode_len(auth_param) + 1;
1187   input_token.value = ap_pcalloc(r->connection->pool, input_token.length);
1188   if (input_token.value == NULL) {
1189      log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
1190                 "ap_pcalloc() failed (not enough memory)");
1191      ret = HTTP_INTERNAL_SERVER_ERROR;
1192      goto end;
1193   }
1194   input_token.length = ap_base64decode(input_token.value, auth_param);
1195
1196   accept_sec_token = (cmp_gss_type(&input_token, &spnego_oid) == 0) ?
1197                         gss_accept_sec_context_spnego : gss_accept_sec_context;
1198
1199   /* pridat: Read client Negotiate data of length XXX, prefix YYY */
1200   log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, "Verifying client data using %s",
1201              (accept_sec_token == gss_accept_sec_context)
1202                ? "KRB5 GSS-API"
1203                : "SPNEGO GSS-API");
1204
1205   major_status = accept_sec_token(&minor_status,
1206                                   &context,
1207                                   server_creds,
1208                                   &input_token,
1209                                   GSS_C_NO_CHANNEL_BINDINGS,
1210                                   &client_name,
1211                                   NULL,
1212                                   &output_token,
1213                                   NULL,
1214                                   NULL,
1215                                   &delegated_cred);
1216   log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
1217              "Verification returned code %d", major_status);
1218   if (output_token.length) {
1219      char *token = NULL;
1220      size_t len;
1221      
1222      len = ap_base64encode_len(output_token.length) + 1;
1223      token = ap_pcalloc(r->connection->pool, len + 1);
1224      if (token == NULL) {
1225         log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
1226                    "ap_pcalloc() failed (not enough memory)");
1227         ret = HTTP_INTERNAL_SERVER_ERROR;
1228         gss_release_buffer(&minor_status2, &output_token);
1229         goto end;
1230      }
1231      ap_base64encode(token, output_token.value, output_token.length);
1232      token[len] = '\0';
1233      *negotiate_ret_value = token;
1234      log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
1235                 "GSS-API token of length %d bytes will be sent back",
1236                 output_token.length);
1237      gss_release_buffer(&minor_status2, &output_token);
1238   }
1239
1240   if (GSS_ERROR(major_status)) {
1241      if (input_token.length > 7 && memcmp(input_token.value, "NTLMSSP", 7) == 0)
1242         log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
1243                   "Warning: received token seems to be NTLM, which isn't supported by the Kerberos module. Check your IE configuration.");
1244
1245      log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
1246                 "%s", get_gss_error(r->pool, major_status, minor_status,
1247                                     "gss_accept_sec_context() failed"));
1248      /* Don't offer the Negotiate method again if call to GSS layer failed */
1249      *negotiate_ret_value = NULL;
1250      ret = HTTP_UNAUTHORIZED;
1251      goto end;
1252   }
1253
1254 #if 0
1255   /* This is a _Kerberos_ module so multiple authentication rounds aren't
1256    * supported. If we wanted a generic GSS authentication we would have to do
1257    * some magic with exporting context etc. */
1258   if (major_status & GSS_S_CONTINUE_NEEDED) {
1259      ret = HTTP_UNAUTHORIZED;
1260      goto end;
1261   }
1262 #endif
1263
1264   major_status = gss_display_name(&minor_status, client_name, &output_token, NULL);
1265   gss_release_name(&minor_status, &client_name); 
1266   if (GSS_ERROR(major_status)) {
1267     log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
1268                "%s", get_gss_error(r->pool, major_status, minor_status,
1269                                    "gss_export_name() failed"));
1270     ret = HTTP_INTERNAL_SERVER_ERROR;
1271     goto end;
1272   }
1273
1274   MK_AUTH_TYPE = "Negotiate";
1275   MK_USER = ap_pstrdup(r->pool, output_token.value);
1276
1277   if (conf->krb_save_credentials && delegated_cred != GSS_C_NO_CREDENTIAL)
1278      store_gss_creds(r, conf, (char *)output_token.value, delegated_cred);
1279
1280   if (*negotiate_ret_value)
1281      set_kerb_auth_headers(r, conf, 0, 0, *negotiate_ret_value);
1282
1283   gss_release_buffer(&minor_status, &output_token);
1284
1285   ret = OK;
1286
1287 end:
1288   if (delegated_cred)
1289      gss_release_cred(&minor_status, &delegated_cred);
1290
1291   if (output_token.length) 
1292      gss_release_buffer(&minor_status, &output_token);
1293
1294   if (client_name != GSS_C_NO_NAME)
1295      gss_release_name(&minor_status, &client_name);
1296
1297   if (server_creds != GSS_C_NO_CREDENTIAL)
1298      gss_release_cred(&minor_status, &server_creds);
1299
1300   if (context != GSS_C_NO_CONTEXT)
1301      gss_delete_sec_context(&minor_status, &context, GSS_C_NO_BUFFER);
1302
1303   return ret;
1304 }
1305 #endif /* KRB5 */
1306
1307 static int
1308 already_succeeded(request_rec *r)
1309 {
1310    if (ap_is_initial_req(r) || MK_AUTH_TYPE == NULL)
1311       return 0;
1312    if (strcmp(MK_AUTH_TYPE, "Negotiate") ||
1313        (strcmp(MK_AUTH_TYPE, "Basic") && strchr(MK_USER, '@')))
1314       return 1;
1315    return 0;
1316 }
1317
1318 static void
1319 set_kerb_auth_headers(request_rec *r, const kerb_auth_config *conf,
1320                       int use_krb4, int use_krb5pwd, char *negotiate_ret_value)
1321 {
1322    const char *auth_name = NULL;
1323    int set_basic = 0;
1324    char *negoauth_param;
1325    const char *header_name = 
1326       (r->proxyreq == PROXYREQ_PROXY) ? "Proxy-Authenticate" : "WWW-Authenticate";
1327
1328    /* get the user realm specified in .htaccess */
1329    auth_name = ap_auth_name(r);
1330
1331    /* XXX should the WWW-Authenticate header be cleared first?
1332     * apache in the proxy mode should retain client's authN headers? */
1333 #ifdef KRB5
1334    if (negotiate_ret_value != NULL && conf->krb_method_gssapi) {
1335       negoauth_param = (*negotiate_ret_value == '\0') ? "Negotiate" :
1336                   ap_pstrcat(r->pool, "Negotiate ", negotiate_ret_value, NULL);
1337       ap_table_add(r->err_headers_out, header_name, negoauth_param);
1338    }
1339    if ((use_krb5pwd && conf->krb_method_k5pass) || conf->krb_delegate_basic) {
1340       ap_table_add(r->err_headers_out, header_name,
1341                    ap_pstrcat(r->pool, "Basic realm=\"", auth_name, "\"", NULL));
1342       set_basic = 1;
1343    }
1344 #endif
1345
1346 #ifdef KRB4
1347    if (!set_basic && 
1348        ((use_krb4 && conf->krb_method_k4pass) || conf->krb_delegate_basic))
1349       ap_table_add(r->err_headers_out, header_name,
1350                   ap_pstrcat(r->pool, "Basic realm=\"", auth_name, "\"", NULL));
1351 #endif
1352 }
1353
1354 int kerb_authenticate_user(request_rec *r)
1355 {
1356    kerb_auth_config *conf = 
1357       (kerb_auth_config *) ap_get_module_config(r->per_dir_config,
1358                                                 &auth_kerb_module);
1359    const char *auth_type = NULL;
1360    const char *auth_line = NULL;
1361    const char *type = NULL;
1362    int use_krb5 = 0, use_krb4 = 0;
1363    int ret;
1364    static int last_return = HTTP_UNAUTHORIZED;
1365    char *negotiate_ret_value = NULL;
1366
1367    /* get the type specified in .htaccess */
1368    type = ap_auth_type(r);
1369
1370    log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
1371               "kerb_authenticate_user entered with user %s and auth_type %s",
1372               (MK_USER)?MK_USER:"(NULL)",type?type:"(NULL)");
1373
1374    if (type && strcasecmp(type, "Kerberos") == 0)
1375       use_krb5 = use_krb4 = 1;
1376    else if(type && strcasecmp(type, "KerberosV5") == 0)
1377       use_krb5 = 1;
1378    else if(type && strcasecmp(type, "KerberosV4") == 0)
1379       use_krb4 = 1;
1380    else
1381       return DECLINED;
1382
1383    /* get what the user sent us in the HTTP header */
1384    auth_line = MK_TABLE_GET(r->headers_in, (r->proxyreq == PROXYREQ_PROXY)
1385                                             ? "Proxy-Authorization"
1386                                             : "Authorization");
1387    if (!auth_line) {
1388       set_kerb_auth_headers(r, conf, use_krb4, use_krb5, 
1389                             (use_krb5) ? "\0" : NULL);
1390       return HTTP_UNAUTHORIZED;
1391    }
1392    auth_type = ap_getword_white(r->pool, &auth_line);
1393
1394    /* If we are delegating Basic to other modules, DECLINE the request */
1395    if (conf->krb_delegate_basic &&
1396 #ifdef KRB5
1397        !conf->krb_method_k5pass &&
1398 #endif
1399 #ifdef KRB4
1400        !conf->krb_method_k4pass &&
1401 #endif
1402        (strcasecmp(auth_type, "Basic") == 0))
1403        return DECLINED;
1404
1405    if (already_succeeded(r))
1406       return last_return;
1407
1408    ret = HTTP_UNAUTHORIZED;
1409
1410 #ifdef KRB5
1411    if (use_krb5 && conf->krb_method_gssapi &&
1412        strcasecmp(auth_type, "Negotiate") == 0) {
1413       ret = authenticate_user_gss(r, conf, auth_line, &negotiate_ret_value);
1414    } else if (use_krb5 && conf->krb_method_k5pass &&
1415               strcasecmp(auth_type, "Basic") == 0) {
1416        ret = authenticate_user_krb5pwd(r, conf, auth_line);
1417    }
1418 #endif
1419
1420 #ifdef KRB4
1421    if (ret == HTTP_UNAUTHORIZED && use_krb4 && conf->krb_method_k4pass &&
1422        strcasecmp(auth_type, "Basic") == 0)
1423       ret = authenticate_user_krb4pwd(r, conf, auth_line);
1424 #endif
1425
1426    if (ret == HTTP_UNAUTHORIZED)
1427       set_kerb_auth_headers(r, conf, use_krb4, use_krb5, negotiate_ret_value);
1428
1429    /* XXX log_debug: if ret==OK, log(user XY authenticated) */
1430
1431    last_return = ret;
1432    return ret;
1433 }
1434
1435
1436 /*************************************************************************** 
1437  Module Setup/Configuration
1438  ***************************************************************************/
1439 #ifndef STANDARD20_MODULE_STUFF
1440 module MODULE_VAR_EXPORT auth_kerb_module = {
1441         STANDARD_MODULE_STUFF,
1442         NULL,                           /*      module initializer            */
1443         kerb_dir_create_config,         /*      per-directory config creator  */
1444         NULL,                           /*      per-directory config merger   */
1445         NULL,                           /*      per-server    config creator  */
1446         NULL,                           /*      per-server    config merger   */
1447         kerb_auth_cmds,                 /*      command table                 */
1448         NULL,                           /* [ 9] content handlers              */
1449         NULL,                           /* [ 2] URI-to-filename translation   */
1450         kerb_authenticate_user,         /* [ 5] check/validate user_id        */
1451         NULL,                           /* [ 6] check user_id is valid *here* */
1452         NULL,                           /* [ 4] check access by host address  */
1453         NULL,                           /* [ 7] MIME type checker/setter      */
1454         NULL,                           /* [ 8] fixups                        */
1455         NULL,                           /* [10] logger                        */
1456         NULL,                           /* [ 3] header parser                 */
1457         NULL,                           /*      process initialization        */
1458         NULL,                           /*      process exit/cleanup          */
1459         NULL                            /* [ 1] post read_request handling    */
1460 #ifdef EAPI
1461        ,NULL,                           /* EAPI: add_module                   */
1462         NULL,                           /* EAPI: remove_module                */
1463         NULL,                           /* EAPI: rewrite_command              */
1464         NULL                            /* EAPI: new_connection               */
1465 #endif
1466 };
1467 #else
1468 static int
1469 kerb_init_handler(apr_pool_t *p, apr_pool_t *plog,
1470                   apr_pool_t *ptemp, server_rec *s)
1471 {
1472    ap_add_version_component(p, "mod_auth_kerb/" MODAUTHKERB_VERSION);
1473    return OK;
1474 }
1475
1476 void kerb_register_hooks(apr_pool_t *p)
1477 {
1478    ap_hook_post_config(kerb_init_handler, NULL, NULL, APR_HOOK_MIDDLE);
1479    ap_hook_check_user_id(kerb_authenticate_user, NULL, NULL, APR_HOOK_MIDDLE);
1480 }
1481
1482 module AP_MODULE_DECLARE_DATA auth_kerb_module =
1483 {
1484    STANDARD20_MODULE_STUFF,
1485    kerb_dir_create_config,      /* create per-dir    conf structures  */
1486    NULL,                        /* merge  per-dir    conf structures  */
1487    NULL,                        /* create per-server conf structures  */
1488    NULL,                        /* merge  per-server conf structures  */
1489    kerb_auth_cmds,              /* table of configuration directives  */
1490    kerb_register_hooks          /* register hooks                     */
1491 };
1492 #endif