2 * Daniel Kouril <kouril@users.sourceforge.net>
4 * Source and Documentation can be found at:
5 * http://modauthkerb.sourceforge.net/
8 * James E. Robinson, III <james@ncstate.net>
9 * Daniel Henninger <daniel@ncsu.edu>
10 * Ludek Sulak <xsulak@fi.muni.cz>
14 * Copyright (c) 2004 Masarykova universita
15 * (Masaryk University, Brno, Czech Republic)
16 * All rights reserved.
18 * Redistribution and use in source and binary forms, with or without
19 * modification, are permitted provided that the following conditions are met:
21 * 1. Redistributions of source code must retain the above copyright notice,
22 * this list of conditions and the following disclaimer.
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.
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.
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.
53 #define MODAUTHKERB_VERSION "5.0-rc6"
56 #include <http_config.h>
57 #include <http_core.h>
59 #include <http_protocol.h>
60 #include <http_request.h>
62 #ifdef STANDARD20_MODULE_STUFF
63 #include <ap_compat.h>
64 #include <apr_strings.h>
65 #include <apr_base64.h>
73 # include <gssapi/gssapi.h>
74 # include <gssapi/gssapi_generic.h>
75 # include <gssapi/gssapi_krb5.h>
76 # define GSS_C_NT_USER_NAME gss_nt_user_name
77 # define GSS_C_NT_HOSTBASED_SERVICE gss_nt_service_name
78 # define krb5_get_err_text(context,code) error_message(code)
80 #include "spnegokrb5.h"
84 /* Prevent warning about closesocket redefinition (Apache's ap_config.h and
85 * MIT Kerberos' port-sockets.h both define it as close) */
90 #include <netdb.h> /* gethostbyname() */
94 #define vsnprintf _vsnprintf
95 #define snprintf _snprintf
97 /* XXX remove dependency on unistd.h ??? */
101 #ifdef STANDARD20_MODULE_STUFF
102 module AP_MODULE_DECLARE_DATA auth_kerb_module;
104 module auth_kerb_module;
107 /***************************************************************************
108 Macros To Ease Compatibility
109 ***************************************************************************/
110 #ifdef STANDARD20_MODULE_STUFF
111 #define MK_POOL apr_pool_t
112 #define MK_TABLE_GET apr_table_get
113 #define MK_USER r->user
114 #define MK_AUTH_TYPE r->ap_auth_type
117 #define MK_TABLE_GET ap_table_get
118 #define MK_USER r->connection->user
119 #define MK_AUTH_TYPE r->connection->ap_auth_type
120 #define PROXYREQ_PROXY STD_PROXY
123 /***************************************************************************
124 Auth Configuration Structure
125 ***************************************************************************/
127 char *krb_auth_realms;
128 int krb_save_credentials;
130 char *krb_service_name;
131 int krb_authoritative;
132 int krb_delegate_basic;
135 int krb_method_gssapi;
136 int krb_method_k5pass;
140 int krb_method_k4pass;
145 set_kerb_auth_headers(request_rec *r, const kerb_auth_config *conf,
146 int use_krb4, int use_krb5pwd, char *negotiate_ret_value);
149 krb5_save_realms(cmd_parms *cmd, kerb_auth_config *sec, char *arg);
151 #ifdef STANDARD20_MODULE_STUFF
152 #define command(name, func, var, type, usage) \
153 AP_INIT_ ## type (name, func, \
154 (void*)APR_XtOffsetOf(kerb_auth_config, var), \
155 OR_AUTHCFG | RSRC_CONF, usage)
157 #define command(name, func, var, type, usage) \
159 (void*)XtOffsetOf(kerb_auth_config, var), \
160 OR_AUTHCFG | RSRC_CONF, type, usage }
163 static const command_rec kerb_auth_cmds[] = {
164 command("KrbAuthRealms", krb5_save_realms, krb_auth_realms,
165 RAW_ARGS, "Realms to attempt authentication against (can be multiple)."),
167 command("KrbAuthRealm", krb5_save_realms, krb_auth_realms,
168 RAW_ARGS, "Alias for KrbAuthRealms."),
170 command("KrbSaveCredentials", ap_set_flag_slot, krb_save_credentials,
171 FLAG, "Save and store credentials/tickets retrieved during auth."),
173 command("KrbVerifyKDC", ap_set_flag_slot, krb_verify_kdc,
174 FLAG, "Verify tickets against keytab to prevent KDC spoofing attacks."),
176 command("KrbServiceName", ap_set_string_slot, krb_service_name,
177 TAKE1, "Service name to be used by Apache for authentication."),
179 command("KrbAuthoritative", ap_set_flag_slot, krb_authoritative,
180 FLAG, "Set to 'off' to allow access control to be passed along to lower modules iff the UserID is not known to this module."),
182 command("KrbDelegateBasic", ap_set_flag_slot, krb_delegate_basic,
183 FLAG, "Always offer Basic authentication regardless of KrbMethodK5Pass and pass on authentication to lower modules if Basic headers arrive."),
186 command("Krb5Keytab", ap_set_file_slot, krb_5_keytab,
187 TAKE1, "Location of Kerberos V5 keytab file."),
189 command("KrbMethodNegotiate", ap_set_flag_slot, krb_method_gssapi,
190 FLAG, "Enable Negotiate authentication method."),
192 command("KrbMethodK5Passwd", ap_set_flag_slot, krb_method_k5pass,
193 FLAG, "Enable Kerberos V5 password authentication."),
197 command("Krb4Srvtab", ap_set_file_slot, krb_4_srvtab,
198 TAKE1, "Location of Kerberos V4 srvtab file."),
200 command("KrbMethodK4Passwd", ap_set_flag_slot, krb_method_k4pass,
201 FLAG, "Enable Kerberos V4 password authentication."),
209 mkstemp(char *template)
214 start = strlen(template) - 1;
215 while(template[start] == 'X') {
216 template[start] = '0' + val % 10;
223 fd = open(template, O_RDWR | O_CREAT | O_EXCL, 0600);
224 if(fd >= 0 || errno != EEXIST)
231 if(template[i] == '9' + 1)
233 if(template[i] <= 'z')
242 #if defined(KRB5) && !defined(HEIMDAL)
243 /* Needed to work around problems with replay caches */
244 #include "mit-internals.h"
246 /* This is our replacement krb5_rc_store function */
247 static krb5_error_code
248 mod_auth_kerb_rc_store(krb5_context context, krb5_rcache rcache,
249 krb5_donot_replay_internal *donot_replay)
254 /* And this is the operations vector for our replay cache */
255 const krb5_rc_ops_internal mod_auth_kerb_rc_ops = {
262 mod_auth_kerb_rc_store,
264 krb5_rc_dfl_get_span,
265 krb5_rc_dfl_get_name,
271 /***************************************************************************
272 Auth Configuration Initialization
273 ***************************************************************************/
274 static void *kerb_dir_create_config(MK_POOL *p, char *d)
276 kerb_auth_config *rec;
278 rec = (kerb_auth_config *) ap_pcalloc(p, sizeof(kerb_auth_config));
279 ((kerb_auth_config *)rec)->krb_verify_kdc = 1;
280 ((kerb_auth_config *)rec)->krb_service_name = "HTTP";
281 ((kerb_auth_config *)rec)->krb_authoritative = 1;
282 ((kerb_auth_config *)rec)->krb_delegate_basic = 0;
284 ((kerb_auth_config *)rec)->krb_method_k5pass = 1;
285 ((kerb_auth_config *)rec)->krb_method_gssapi = 1;
288 ((kerb_auth_config *)rec)->krb_method_k4pass = 1;
294 krb5_save_realms(cmd_parms *cmd, kerb_auth_config *sec, char *arg)
296 sec->krb_auth_realms= ap_pstrdup(cmd->pool, arg);
300 void log_rerror(const char *file, int line, int level, int status,
301 const request_rec *r, const char *fmt, ...)
307 vsnprintf(errstr, sizeof(errstr), fmt, ap);
311 #ifdef STANDARD20_MODULE_STUFF
312 ap_log_rerror(file, line, level | APLOG_NOERRNO, status, r, "%s", errstr);
314 ap_log_rerror(file, line, level | APLOG_NOERRNO, r, "%s", errstr);
319 /***************************************************************************
320 Username/Password Validation for Krb4
321 ***************************************************************************/
323 verify_krb4_user(request_rec *r, char *name, char *instance, char *realm,
324 char *password, char *linstance, char *srvtab, int krb_verify_kdc)
330 const char *hostname;
333 char lrealm[REALM_SZ];
335 ret = krb_get_pw_in_tkt(name, instance, realm, "krbtgt", realm,
336 DEFAULT_TKT_LIFE, password);
338 log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
339 "Cannot get krb4 ticket: krb_get_pw_in_tkt() failed: %s",
340 krb_get_err_text(ret));
347 hostname = ap_get_server_name(r);
349 hp = gethostbyname(hostname);
352 log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
353 "Cannot verify krb4 ticket: gethostbyname() failed: %s",
357 memcpy(&addr, hp->h_addr, sizeof(addr));
359 phost = krb_get_phost((char *)hostname);
361 krb_get_lrealm(lrealm, 1);
363 ret = krb_mk_req(&ticket, linstance, phost, lrealm, 0);
365 log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
366 "Cannot verify krb4 ticket: krb_mk_req() failed: %s",
367 krb_get_err_text(ret));
372 ret = krb_rd_req(&ticket, linstance, phost, addr, &authdata, srvtab);
374 log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
375 "Cannot verify krb4 ticket: krb_rd_req() failed: %s",
376 krb_get_err_text(ret));
384 krb4_cache_cleanup(void *data)
386 char *tkt_file = (char *) data;
388 krb_set_tkt_string(tkt_file);
394 authenticate_user_krb4pwd(request_rec *r,
395 kerb_auth_config *conf,
396 const char *auth_line)
400 const char *sent_name;
403 char *tkt_file_p = NULL;
408 char lrealm[REALM_SZ];
409 int all_principals_unkown;
411 sent_pw = ap_pbase64decode(r->pool, auth_line);
412 sent_name = ap_getword (r->pool, &sent_pw, ':');
414 /* do not allow user to override realm setting of server */
415 if (strchr(sent_name, '@')) {
416 log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
417 "specifying realm in user name is prohibited");
418 return HTTP_UNAUTHORIZED;
421 sent_instance = strchr(sent_name, '.');
423 *sent_instance++ = '\0';
425 snprintf(tkt_file, sizeof(tkt_file), "/tmp/apache_tkt_XXXXXX");
426 fd = mkstemp(tkt_file);
428 log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
429 "Cannot create krb4 ccache: mkstemp() failed: %s",
431 return HTTP_INTERNAL_SERVER_ERROR;
434 tkt_file_p = ap_pstrdup(r->pool, tkt_file);
435 ap_register_cleanup(r->pool, tkt_file_p,
436 krb4_cache_cleanup, ap_null_cleanup);
438 krb_set_tkt_string(tkt_file);
440 all_principals_unkown = 1;
441 realms = conf->krb_auth_realms;
443 memset(lrealm, 0, sizeof(lrealm));
446 realm = ap_getword_white(r->pool, &realms);
449 ret = krb_get_lrealm(lrealm, 1);
455 ret = verify_krb4_user(r, (char *)sent_name,
456 (sent_instance) ? sent_instance : "",
457 (char *)realm, (char *)sent_pw,
458 conf->krb_service_name,
459 conf->krb_4_srvtab, conf->krb_verify_kdc);
460 if (!conf->krb_authoritative && ret) {
461 /* if we're not authoritative, we allow authentication to pass on
462 * to another modules if (and only if) the user is not known to us */
463 if (all_principals_unkown && ret != KDC_PR_UNKNOWN)
464 all_principals_unkown = 0;
469 } while (realms && *realms);
472 /* XXX log only in the verify_krb4_user() call */
473 log_rerror(APLOG_MARK, APLOG_ERR, 0, r, "Verifying krb4 password failed");
474 ret = (!conf->krb_authoritative && all_principals_unkown == 1 && ret == KDC_PR_UNKNOWN) ?
475 DECLINED : HTTP_UNAUTHORIZED;
479 user = ap_pstrdup(r->pool, sent_name);
481 user = ap_pstrcat(r->pool, user, ".", sent_instance, NULL);
482 user = ap_pstrcat(r->pool, user, "@", realm, NULL);
485 MK_AUTH_TYPE = "Basic";
486 ap_table_setn(r->subprocess_env, "KRBTKFILE", tkt_file_p);
488 if (!conf->krb_save_credentials)
489 krb4_cache_cleanup(tkt_file);
493 krb4_cache_cleanup(tkt_file);
502 /***************************************************************************
503 Username/Password Validation for Krb5
504 ***************************************************************************/
506 /* MIT kerberos uses replay cache checks even during credential verification
507 * (i.e. in krb5_verify_init_creds()), which is obviosuly useless. In order to
508 * avoid problems with multiple apache processes accessing the same rcache file
509 * we had to use this call instead, which is only a bit modified version of
510 * krb5_verify_init_creds() */
511 static krb5_error_code
512 verify_krb5_init_creds(krb5_context context, krb5_creds *creds,
513 krb5_principal ap_req_server, krb5_keytab ap_req_keytab)
517 krb5_ccache local_ccache = NULL;
518 krb5_creds *new_creds = NULL;
519 krb5_auth_context auth_context = NULL;
520 krb5_keytab keytab = NULL;
522 memset(&req, 0, sizeof(req));
524 if (ap_req_keytab == NULL) {
525 ret = krb5_kt_default (context, &keytab);
529 keytab = ap_req_keytab;
531 ret = krb5_cc_resolve(context, "MEMORY:", &local_ccache);
535 ret = krb5_cc_initialize(context, local_ccache, creds->client);
539 ret = krb5_cc_store_cred (context, local_ccache, creds);
543 if (!krb5_principal_compare (context, ap_req_server, creds->server)) {
544 krb5_creds match_cred;
546 memset (&match_cred, 0, sizeof(match_cred));
548 match_cred.client = creds->client;
549 match_cred.server = ap_req_server;
551 ret = krb5_get_credentials (context, 0, local_ccache,
552 &match_cred, &new_creds);
558 ret = krb5_mk_req_extended (context, &auth_context, 0, NULL, creds, &req);
562 krb5_auth_con_free (context, auth_context);
564 ret = krb5_auth_con_init(context, &auth_context);
567 /* use KRB5_AUTH_CONTEXT_DO_SEQUENCE to skip replay cache checks */
568 krb5_auth_con_setflags(context, auth_context, KRB5_AUTH_CONTEXT_DO_SEQUENCE);
570 ret = krb5_rd_req (context, &auth_context, &req, ap_req_server,
575 /* XXX Do I ever want to support Heimdal 0.4 ??? */
576 krb5_data_free(&req);
578 krb5_free_data_contents(context, &req);
581 krb5_auth_con_free (context, auth_context);
583 krb5_free_creds (context, new_creds);
584 if (ap_req_keytab == NULL && keytab)
585 krb5_kt_close (context, keytab);
587 krb5_cc_destroy (context, local_ccache);
592 /* Inspired by krb5_verify_user from Heimdal */
593 static krb5_error_code
594 verify_krb5_user(request_rec *r, krb5_context context, krb5_principal principal,
595 const char *password, const char *service, krb5_keytab keytab,
596 int krb_verify_kdc, krb5_ccache *ccache)
599 krb5_principal server = NULL;
601 krb5_ccache ret_ccache = NULL;
603 /* XXX error messages shouldn't be logged here (and in the while() loop in
604 * authenticate_user_krb5pwd() as weell), in order to avoid confusing log
605 * entries when using multiple realms */
607 memset(&creds, 0, sizeof(creds));
609 ret = krb5_get_init_creds_password(context, &creds, principal,
610 (char *)password, NULL,
611 NULL, 0, NULL, NULL);
613 log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
614 "krb5_get_init_creds_password() failed: %s",
615 krb5_get_err_text(context, ret));
619 ret = krb5_sname_to_principal(context, ap_get_server_name(r), service,
620 KRB5_NT_SRV_HST, &server);
622 log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
623 "krb5_sname_to_principal() failed: %s",
624 krb5_get_err_text(context, ret));
627 /* XXX log_debug: lookig for <server_princ> in keytab */
633 krb5_get_default_realm(context, &realm);
634 log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
635 "trying to verify password using key for %s/%s@%s",
636 service, ap_get_server_name(r), realm);
640 if (krb_verify_kdc &&
641 (ret = verify_krb5_init_creds(context, &creds, server, keytab))) {
642 log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
643 "failed to verify krb5 credentials: %s",
644 krb5_get_err_text(context, ret));
648 ret = krb5_cc_resolve(context, "MEMORY:", &ret_ccache);
650 log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
651 "generating new memory ccache failed: %s",
652 krb5_get_err_text(context, ret));
656 ret = krb5_cc_initialize(context, ret_ccache, principal);
658 log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
659 "krb5_cc_initialize() failed: %s",
660 krb5_get_err_text(context, ret));
664 ret = krb5_cc_store_cred(context, ret_ccache, &creds);
666 log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
667 "krb5_cc_store_cred() failed: %s",
668 krb5_get_err_text(context, ret));
671 *ccache = ret_ccache;
675 krb5_free_cred_contents(context, &creds);
677 krb5_free_principal(context, server);
679 krb5_cc_destroy(context, ret_ccache);
685 krb5_cache_cleanup(void *data)
687 krb5_context context;
689 krb5_error_code problem;
690 char *cache_name = (char *) data;
692 problem = krb5_init_context(&context);
694 /* ap_log_error(APLOG_MARK, APLOG_ERR, 0, NULL, "krb5_init_context() failed"); */
695 return HTTP_INTERNAL_SERVER_ERROR;
698 problem = krb5_cc_resolve(context, cache_name, &cache);
700 /* log_error(APLOG_MARK, APLOG_ERR, 0, NULL,
701 "krb5_cc_resolve() failed (%s: %s)",
702 cache_name, krb5_get_err_text(context, problem)); */
703 return HTTP_INTERNAL_SERVER_ERROR;
706 krb5_cc_destroy(context, cache);
707 krb5_free_context(context);
712 create_krb5_ccache(krb5_context kcontext,
714 kerb_auth_config *conf,
715 krb5_principal princ,
720 krb5_error_code problem;
722 krb5_ccache tmp_ccache = NULL;
724 ccname = ap_psprintf(r->pool, "FILE:%s/krb5cc_apache_XXXXXX", P_tmpdir);
725 fd = mkstemp(ccname + strlen("FILE:"));
727 log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
728 "mkstemp() failed: %s", strerror(errno));
729 ret = HTTP_INTERNAL_SERVER_ERROR;
734 problem = krb5_cc_resolve(kcontext, ccname, &tmp_ccache);
736 log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
737 "krb5_cc_resolve() failed: %s",
738 krb5_get_err_text(kcontext, problem));
739 ret = HTTP_INTERNAL_SERVER_ERROR;
744 problem = krb5_cc_initialize(kcontext, tmp_ccache, princ);
746 log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
747 "Cannot initialize krb5 ccache %s: krb5_cc_initialize() failed: %s",
748 ccname, krb5_get_err_text(kcontext, problem));
749 ret = HTTP_INTERNAL_SERVER_ERROR;
753 ap_table_setn(r->subprocess_env, "KRB5CCNAME", ccname);
754 ap_register_cleanup(r->pool, ccname,
755 krb5_cache_cleanup, ap_null_cleanup);
757 *ccache = tmp_ccache;
764 krb5_cc_destroy(kcontext, tmp_ccache);
770 store_krb5_creds(krb5_context kcontext,
772 kerb_auth_config *conf,
773 krb5_ccache delegated_cred)
776 krb5_error_code problem;
777 krb5_principal princ;
781 problem = krb5_cc_get_principal(kcontext, delegated_cred, &princ);
783 snprintf(errstr, sizeof(errstr), "krb5_cc_get_principal() failed: %s",
784 krb5_get_err_text(kcontext, problem));
785 return HTTP_INTERNAL_SERVER_ERROR;
788 ret = create_krb5_ccache(kcontext, r, conf, princ, &ccache);
790 krb5_free_principal(kcontext, princ);
795 problem = krb5_cc_copy_cache(kcontext, delegated_cred, ccache);
797 problem = krb5_cc_copy_creds(kcontext, delegated_cred, ccache);
799 krb5_free_principal(kcontext, princ);
801 snprintf(errstr, sizeof(errstr), "Failed to store credentials: %s",
802 krb5_get_err_text(kcontext, problem));
803 krb5_cc_destroy(kcontext, ccache);
804 return HTTP_INTERNAL_SERVER_ERROR;
807 krb5_cc_close(kcontext, ccache);
812 int authenticate_user_krb5pwd(request_rec *r,
813 kerb_auth_config *conf,
814 const char *auth_line)
816 const char *sent_pw = NULL;
817 const char *sent_name = NULL;
818 const char *realms = NULL;
819 krb5_context kcontext = NULL;
820 krb5_error_code code;
821 krb5_principal client = NULL;
822 krb5_ccache ccache = NULL;
823 krb5_keytab keytab = NULL;
826 int all_principals_unkown;
828 code = krb5_init_context(&kcontext);
830 log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
831 "Cannot initialize Kerberos5 context (%d)", code);
832 return HTTP_INTERNAL_SERVER_ERROR;
835 sent_pw = ap_pbase64decode(r->pool, auth_line);
836 sent_name = ap_getword (r->pool, &sent_pw, ':');
837 /* do not allow user to override realm setting of server */
838 if (strchr(sent_name, '@')) {
839 log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
840 "specifying realm in user name is prohibited");
841 ret = HTTP_UNAUTHORIZED;
845 if (sent_pw == NULL || *sent_pw == '\0') {
846 log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
847 "empty passwords are not accepted");
848 ret = HTTP_UNAUTHORIZED;
852 if (conf->krb_5_keytab)
853 krb5_kt_resolve(kcontext, conf->krb_5_keytab, &keytab);
855 all_principals_unkown = 1;
856 realms = conf->krb_auth_realms;
858 if (realms && (code = krb5_set_default_realm(kcontext,
859 ap_getword_white(r->pool, &realms)))){
860 log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
861 "krb5_set_default_realm() failed: %s",
862 krb5_get_err_text(kcontext, code));
867 krb5_free_principal(kcontext, client);
870 code = krb5_parse_name(kcontext, sent_name, &client);
872 log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
873 "krb5_parse_name() failed: %s",
874 krb5_get_err_text(kcontext, code));
878 code = verify_krb5_user(r, kcontext, client, sent_pw,
879 conf->krb_service_name,
880 keytab, conf->krb_verify_kdc, &ccache);
881 if (!conf->krb_authoritative && code) {
882 /* if we're not authoritative, we allow authentication to pass on
883 * to another modules if (and only if) the user is not known to us */
884 if (all_principals_unkown && code != KRB5KDC_ERR_C_PRINCIPAL_UNKNOWN)
885 all_principals_unkown = 0;
891 /* ap_getword_white() used above shifts the parameter, so it's not
892 needed to touch the realms variable */
893 } while (realms && *realms);
895 memset((char *)sent_pw, 0, strlen(sent_pw));
898 if (!conf->krb_authoritative && all_principals_unkown == 1 && code == KRB5KDC_ERR_C_PRINCIPAL_UNKNOWN)
901 ret = HTTP_UNAUTHORIZED;
906 code = krb5_unparse_name(kcontext, client, &name);
908 log_rerror(APLOG_MARK, APLOG_ERR, 0, r, "krb5_unparse_name() failed: %s",
909 krb5_get_err_text(kcontext, code));
910 ret = HTTP_UNAUTHORIZED;
913 MK_USER = ap_pstrdup (r->pool, name);
914 MK_AUTH_TYPE = "Basic";
917 if (conf->krb_save_credentials)
918 store_krb5_creds(kcontext, r, conf, ccache);
923 log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
924 "kerb_authenticate_user_krb5pwd ret=%d user=%s authtype=%s",
925 ret, (MK_USER)?MK_USER:"(NULL)", MK_AUTH_TYPE);
927 krb5_free_principal(kcontext, client);
929 krb5_cc_destroy(kcontext, ccache);
931 krb5_kt_close(kcontext, keytab);
932 krb5_free_context(kcontext);
937 /*********************************************************************
938 * GSSAPI Authentication
939 ********************************************************************/
942 get_gss_error(MK_POOL *p, OM_uint32 err_maj, OM_uint32 err_min, char *prefix)
944 OM_uint32 maj_stat, min_stat;
945 OM_uint32 msg_ctx = 0;
946 gss_buffer_desc status_string;
949 err_msg = ap_pstrdup(p, prefix);
951 maj_stat = gss_display_status (&min_stat,
957 if (GSS_ERROR(maj_stat))
959 err_msg = ap_pstrcat(p, err_msg, ": ", (char*) status_string.value, NULL);
960 gss_release_buffer(&min_stat, &status_string);
962 maj_stat = gss_display_status (&min_stat,
968 if (!GSS_ERROR(maj_stat)) {
969 err_msg = ap_pstrcat(p, err_msg,
970 " (", (char*) status_string.value, ")", NULL);
971 gss_release_buffer(&min_stat, &status_string);
973 } while (!GSS_ERROR(maj_stat) && msg_ctx != 0);
979 store_gss_creds(request_rec *r, kerb_auth_config *conf, char *princ_name,
980 gss_cred_id_t delegated_cred)
982 OM_uint32 maj_stat, min_stat;
983 krb5_principal princ = NULL;
984 krb5_ccache ccache = NULL;
985 krb5_error_code problem;
986 krb5_context context;
987 int ret = HTTP_INTERNAL_SERVER_ERROR;
989 problem = krb5_init_context(&context);
991 log_rerror(APLOG_MARK, APLOG_ERR, 0, r, "Cannot initialize krb5 context");
992 return HTTP_INTERNAL_SERVER_ERROR;
995 problem = krb5_parse_name(context, princ_name, &princ);
997 log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
998 "Cannot parse delegated username (%s)", krb5_get_err_text(context, problem));
1002 problem = create_krb5_ccache(context, r, conf, princ, &ccache);
1004 log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
1005 "Cannot create krb5 ccache (%s)", krb5_get_err_text(context, problem));
1009 maj_stat = gss_krb5_copy_ccache(&min_stat, delegated_cred, ccache);
1010 if (GSS_ERROR(maj_stat)) {
1011 log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
1012 "Cannot store delegated credential (%s)",
1013 get_gss_error(r->pool, maj_stat, min_stat, "gss_krb5_copy_ccache"));
1017 krb5_cc_close(context, ccache);
1023 krb5_free_principal(context, princ);
1025 krb5_cc_destroy(context, ccache);
1026 krb5_free_context(context);
1031 get_gss_creds(request_rec *r,
1032 kerb_auth_config *conf,
1033 gss_cred_id_t *server_creds)
1035 gss_buffer_desc token = GSS_C_EMPTY_BUFFER;
1036 OM_uint32 major_status, minor_status, minor_status2;
1037 gss_name_t server_name = GSS_C_NO_NAME;
1040 snprintf(buf, sizeof(buf), "%s@%s", conf->krb_service_name,
1041 ap_get_server_name(r));
1044 token.length = strlen(buf) + 1;
1046 major_status = gss_import_name(&minor_status, &token,
1047 GSS_C_NT_HOSTBASED_SERVICE,
1049 memset(&token, 0, sizeof(token));
1050 if (GSS_ERROR(major_status)) {
1051 log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
1052 "%s", get_gss_error(r->pool, major_status, minor_status,
1053 "gss_import_name() failed"));
1054 return HTTP_INTERNAL_SERVER_ERROR;
1057 major_status = gss_display_name(&minor_status, server_name, &token, NULL);
1058 if (GSS_ERROR(major_status)) {
1059 /* Perhaps we could just ignore this error but it's safer to give up now,
1061 log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
1062 "%s", get_gss_error(r->pool, major_status, minor_status,
1063 "gss_display_name() failed"));
1064 return HTTP_INTERNAL_SERVER_ERROR;
1067 log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, "Acquiring creds for %s",
1069 gss_release_buffer(&minor_status, &token);
1071 major_status = gss_acquire_cred(&minor_status, server_name, GSS_C_INDEFINITE,
1072 GSS_C_NO_OID_SET, GSS_C_ACCEPT,
1073 server_creds, NULL, NULL);
1074 gss_release_name(&minor_status2, &server_name);
1075 if (GSS_ERROR(major_status)) {
1076 log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
1077 "%s", get_gss_error(r->pool, major_status, minor_status,
1078 "gss_acquire_cred() failed"));
1079 return HTTP_INTERNAL_SERVER_ERROR;
1084 * With MIT Kerberos 5 1.3.x the gss_cred_id_t is the same as
1085 * krb5_gss_cred_id_t and krb5_gss_cred_id_rec contains a pointer to
1087 * This allows us to override the replay cache function vector with
1089 * Note that this is a dirty hack to get things working and there may
1090 * well be unknown side-effects.
1093 krb5_gss_cred_id_t gss_creds = (krb5_gss_cred_id_t) *server_creds;
1095 if (gss_creds && gss_creds->rcache && gss_creds->rcache->ops &&
1096 gss_creds->rcache->ops->type &&
1097 memcmp(gss_creds->rcache->ops->type, "dfl", 3) == 0)
1098 /* Override the rcache operations */
1099 gss_creds->rcache->ops = &mod_auth_kerb_rc_ops;
1107 cmp_gss_type(gss_buffer_t token, gss_OID oid)
1112 if (token->length == 0)
1113 return GSS_S_DEFECTIVE_TOKEN;
1117 return GSS_S_DEFECTIVE_TOKEN;
1120 if ((len & 0x7f) > 4)
1121 return GSS_S_DEFECTIVE_TOKEN;
1125 return GSS_S_DEFECTIVE_TOKEN;
1127 if (((OM_uint32) *p++) != oid->length)
1128 return GSS_S_DEFECTIVE_TOKEN;
1130 return memcmp(p, oid->elements, oid->length);
1134 authenticate_user_gss(request_rec *r, kerb_auth_config *conf,
1135 const char *auth_line, char **negotiate_ret_value)
1137 OM_uint32 major_status, minor_status, minor_status2;
1138 gss_buffer_desc input_token = GSS_C_EMPTY_BUFFER;
1139 gss_buffer_desc output_token = GSS_C_EMPTY_BUFFER;
1140 const char *auth_param = NULL;
1142 gss_name_t client_name = GSS_C_NO_NAME;
1143 gss_cred_id_t delegated_cred = GSS_C_NO_CREDENTIAL;
1145 (*accept_sec_token)(OM_uint32 *, gss_ctx_id_t *, const gss_cred_id_t,
1146 const gss_buffer_t, const gss_channel_bindings_t,
1147 gss_name_t *, gss_OID *, gss_buffer_t, OM_uint32 *,
1148 OM_uint32 *, gss_cred_id_t *);
1149 gss_OID_desc spnego_oid;
1150 gss_ctx_id_t context = GSS_C_NO_CONTEXT;
1151 gss_cred_id_t server_creds = GSS_C_NO_CREDENTIAL;
1153 *negotiate_ret_value = "\0";
1155 spnego_oid.length = 6;
1156 spnego_oid.elements = (void *)"\x2b\x06\x01\x05\x05\x02";
1158 if (conf->krb_5_keytab) {
1160 /* we don't use the ap_* calls here, since the string passed to putenv()
1161 * will become part of the enviroment and shouldn't be free()ed by apache
1163 ktname = malloc(strlen("KRB5_KTNAME=") + strlen(conf->krb_5_keytab) + 1);
1164 if (ktname == NULL) {
1165 log_rerror(APLOG_MARK, APLOG_ERR, 0, r, "malloc() failed: not enough memory");
1166 ret = HTTP_INTERNAL_SERVER_ERROR;
1169 sprintf(ktname, "KRB5_KTNAME=%s", conf->krb_5_keytab);
1173 ret = get_gss_creds(r, conf, &server_creds);
1177 /* ap_getword() shifts parameter */
1178 auth_param = ap_getword_white(r->pool, &auth_line);
1179 if (auth_param == NULL) {
1180 log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
1181 "No Authorization parameter in request from client");
1182 ret = HTTP_UNAUTHORIZED;
1186 input_token.length = ap_base64decode_len(auth_param) + 1;
1187 input_token.value = ap_pcalloc(r->connection->pool, input_token.length);
1188 if (input_token.value == NULL) {
1189 log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
1190 "ap_pcalloc() failed (not enough memory)");
1191 ret = HTTP_INTERNAL_SERVER_ERROR;
1194 input_token.length = ap_base64decode(input_token.value, auth_param);
1196 accept_sec_token = (cmp_gss_type(&input_token, &spnego_oid) == 0) ?
1197 gss_accept_sec_context_spnego : gss_accept_sec_context;
1199 /* pridat: Read client Negotiate data of length XXX, prefix YYY */
1200 log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, "Verifying client data using %s",
1201 (accept_sec_token == gss_accept_sec_context)
1203 : "SPNEGO GSS-API");
1205 major_status = accept_sec_token(&minor_status,
1209 GSS_C_NO_CHANNEL_BINDINGS,
1216 log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
1217 "Verification returned code %d", major_status);
1218 if (output_token.length) {
1222 len = ap_base64encode_len(output_token.length) + 1;
1223 token = ap_pcalloc(r->connection->pool, len + 1);
1224 if (token == NULL) {
1225 log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
1226 "ap_pcalloc() failed (not enough memory)");
1227 ret = HTTP_INTERNAL_SERVER_ERROR;
1228 gss_release_buffer(&minor_status2, &output_token);
1231 ap_base64encode(token, output_token.value, output_token.length);
1233 *negotiate_ret_value = token;
1234 log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
1235 "GSS-API token of length %d bytes will be sent back",
1236 major_status, output_token.length);
1237 gss_release_buffer(&minor_status2, &output_token);
1240 if (GSS_ERROR(major_status)) {
1241 if (input_token.length > 7 && memcmp(input_token.value, "NTLMSSP", 7) == 0)
1242 log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
1243 "Warning: received token seems to be NTLM, which isn't supported by the Kerberos module. Check your IE configuration.");
1245 log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
1246 "%s", get_gss_error(r->pool, major_status, minor_status,
1247 "gss_accept_sec_context() failed"));
1248 /* Don't offer the Negotiate method again if call to GSS layer failed */
1249 *negotiate_ret_value = NULL;
1250 ret = HTTP_UNAUTHORIZED;
1255 /* This is a _Kerberos_ module so multiple authentication rounds aren't
1256 * supported. If we wanted a generic GSS authentication we would have to do
1257 * some magic with exporting context etc. */
1258 if (major_status & GSS_S_CONTINUE_NEEDED) {
1259 ret = HTTP_UNAUTHORIZED;
1264 major_status = gss_display_name(&minor_status, client_name, &output_token, NULL);
1265 gss_release_name(&minor_status, &client_name);
1266 if (GSS_ERROR(major_status)) {
1267 log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
1268 "%s", get_gss_error(r->pool, major_status, minor_status,
1269 "gss_export_name() failed"));
1270 ret = HTTP_INTERNAL_SERVER_ERROR;
1274 MK_AUTH_TYPE = "Negotiate";
1275 MK_USER = ap_pstrdup(r->pool, output_token.value);
1277 if (conf->krb_save_credentials && delegated_cred != GSS_C_NO_CREDENTIAL)
1278 store_gss_creds(r, conf, (char *)output_token.value, delegated_cred);
1280 if (*negotiate_ret_value)
1281 set_kerb_auth_headers(r, conf, 0, 0, *negotiate_ret_value);
1283 gss_release_buffer(&minor_status, &output_token);
1289 gss_release_cred(&minor_status, &delegated_cred);
1291 if (output_token.length)
1292 gss_release_buffer(&minor_status, &output_token);
1294 if (client_name != GSS_C_NO_NAME)
1295 gss_release_name(&minor_status, &client_name);
1297 if (server_creds != GSS_C_NO_CREDENTIAL)
1298 gss_release_cred(&minor_status, &server_creds);
1300 if (context != GSS_C_NO_CONTEXT)
1301 gss_delete_sec_context(&minor_status, &context, GSS_C_NO_BUFFER);
1308 already_succeeded(request_rec *r)
1310 if (ap_is_initial_req(r) || MK_AUTH_TYPE == NULL)
1312 if (strcmp(MK_AUTH_TYPE, "Negotiate") ||
1313 (strcmp(MK_AUTH_TYPE, "Basic") && strchr(MK_USER, '@')))
1319 set_kerb_auth_headers(request_rec *r, const kerb_auth_config *conf,
1320 int use_krb4, int use_krb5pwd, char *negotiate_ret_value)
1322 const char *auth_name = NULL;
1324 char *negoauth_param;
1325 const char *header_name =
1326 (r->proxyreq == PROXYREQ_PROXY) ? "Proxy-Authenticate" : "WWW-Authenticate";
1328 /* get the user realm specified in .htaccess */
1329 auth_name = ap_auth_name(r);
1331 /* XXX should the WWW-Authenticate header be cleared first?
1332 * apache in the proxy mode should retain client's authN headers? */
1334 if (negotiate_ret_value != NULL && conf->krb_method_gssapi) {
1335 negoauth_param = (*negotiate_ret_value == '\0') ? "Negotiate" :
1336 ap_pstrcat(r->pool, "Negotiate ", negotiate_ret_value, NULL);
1337 ap_table_add(r->err_headers_out, header_name, negoauth_param);
1339 if ((use_krb5pwd && conf->krb_method_k5pass) || conf->krb_delegate_basic) {
1340 ap_table_add(r->err_headers_out, header_name,
1341 ap_pstrcat(r->pool, "Basic realm=\"", auth_name, "\"", NULL));
1348 ((use_krb4 && conf->krb_method_k4pass) || conf->krb_delegate_basic))
1349 ap_table_add(r->err_headers_out, header_name,
1350 ap_pstrcat(r->pool, "Basic realm=\"", auth_name, "\"", NULL));
1354 int kerb_authenticate_user(request_rec *r)
1356 kerb_auth_config *conf =
1357 (kerb_auth_config *) ap_get_module_config(r->per_dir_config,
1359 const char *auth_type = NULL;
1360 const char *auth_line = NULL;
1361 const char *type = NULL;
1362 int use_krb5 = 0, use_krb4 = 0;
1364 static int last_return = HTTP_UNAUTHORIZED;
1365 char *negotiate_ret_value = NULL;
1367 /* get the type specified in .htaccess */
1368 type = ap_auth_type(r);
1370 log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
1371 "kerb_authenticate_user entered with user %s and auth_type %s",
1372 (MK_USER)?MK_USER:"(NULL)",type?type:"(NULL)");
1374 if (type && strcasecmp(type, "Kerberos") == 0)
1375 use_krb5 = use_krb4 = 1;
1376 else if(type && strcasecmp(type, "KerberosV5") == 0)
1378 else if(type && strcasecmp(type, "KerberosV4") == 0)
1383 /* get what the user sent us in the HTTP header */
1384 auth_line = MK_TABLE_GET(r->headers_in, (r->proxyreq == PROXYREQ_PROXY)
1385 ? "Proxy-Authorization"
1388 set_kerb_auth_headers(r, conf, use_krb4, use_krb5,
1389 (use_krb5) ? "\0" : NULL);
1390 return HTTP_UNAUTHORIZED;
1392 auth_type = ap_getword_white(r->pool, &auth_line);
1394 /* If we are delegating Basic to other modules, DECLINE the request */
1395 if (conf->krb_delegate_basic &&
1397 !conf->krb_method_k5pass &&
1400 !conf->krb_method_k4pass &&
1402 (strcasecmp(auth_type, "Basic") == 0))
1405 if (already_succeeded(r))
1408 ret = HTTP_UNAUTHORIZED;
1411 if (use_krb5 && conf->krb_method_gssapi &&
1412 strcasecmp(auth_type, "Negotiate") == 0) {
1413 ret = authenticate_user_gss(r, conf, auth_line, &negotiate_ret_value);
1414 } else if (use_krb5 && conf->krb_method_k5pass &&
1415 strcasecmp(auth_type, "Basic") == 0) {
1416 ret = authenticate_user_krb5pwd(r, conf, auth_line);
1421 if (ret == HTTP_UNAUTHORIZED && use_krb4 && conf->krb_method_k4pass &&
1422 strcasecmp(auth_type, "Basic") == 0)
1423 ret = authenticate_user_krb4pwd(r, conf, auth_line);
1426 if (ret == HTTP_UNAUTHORIZED)
1427 set_kerb_auth_headers(r, conf, use_krb4, use_krb5, negotiate_ret_value);
1429 /* XXX log_debug: if ret==OK, log(user XY authenticated) */
1436 /***************************************************************************
1437 Module Setup/Configuration
1438 ***************************************************************************/
1439 #ifndef STANDARD20_MODULE_STUFF
1440 module MODULE_VAR_EXPORT auth_kerb_module = {
1441 STANDARD_MODULE_STUFF,
1442 NULL, /* module initializer */
1443 kerb_dir_create_config, /* per-directory config creator */
1444 NULL, /* per-directory config merger */
1445 NULL, /* per-server config creator */
1446 NULL, /* per-server config merger */
1447 kerb_auth_cmds, /* command table */
1448 NULL, /* [ 9] content handlers */
1449 NULL, /* [ 2] URI-to-filename translation */
1450 kerb_authenticate_user, /* [ 5] check/validate user_id */
1451 NULL, /* [ 6] check user_id is valid *here* */
1452 NULL, /* [ 4] check access by host address */
1453 NULL, /* [ 7] MIME type checker/setter */
1454 NULL, /* [ 8] fixups */
1455 NULL, /* [10] logger */
1456 NULL, /* [ 3] header parser */
1457 NULL, /* process initialization */
1458 NULL, /* process exit/cleanup */
1459 NULL /* [ 1] post read_request handling */
1461 ,NULL, /* EAPI: add_module */
1462 NULL, /* EAPI: remove_module */
1463 NULL, /* EAPI: rewrite_command */
1464 NULL /* EAPI: new_connection */
1469 kerb_init_handler(apr_pool_t *p, apr_pool_t *plog,
1470 apr_pool_t *ptemp, server_rec *s)
1472 ap_add_version_component(p, "mod_auth_kerb/" MODAUTHKERB_VERSION);
1476 void kerb_register_hooks(apr_pool_t *p)
1478 ap_hook_post_config(kerb_init_handler, NULL, NULL, APR_HOOK_MIDDLE);
1479 ap_hook_check_user_id(kerb_authenticate_user, NULL, NULL, APR_HOOK_MIDDLE);
1482 module AP_MODULE_DECLARE_DATA auth_kerb_module =
1484 STANDARD20_MODULE_STUFF,
1485 kerb_dir_create_config, /* create per-dir conf structures */
1486 NULL, /* merge per-dir conf structures */
1487 NULL, /* create per-server conf structures */
1488 NULL, /* merge per-server conf structures */
1489 kerb_auth_cmds, /* table of configuration directives */
1490 kerb_register_hooks /* register hooks */