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