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