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