Home | History | Annotate | Line # | Download | only in pam_krb5
pam_krb5.c revision 1.26.26.1
      1 /*	$NetBSD: pam_krb5.c,v 1.26.26.1 2020/04/08 14:07:15 martin Exp $	*/
      2 
      3 /*-
      4  * This pam_krb5 module contains code that is:
      5  *   Copyright (c) Derrick J. Brashear, 1996. All rights reserved.
      6  *   Copyright (c) Frank Cusack, 1999-2001. All rights reserved.
      7  *   Copyright (c) Jacques A. Vidrine, 2000-2001. All rights reserved.
      8  *   Copyright (c) Nicolas Williams, 2001. All rights reserved.
      9  *   Copyright (c) Perot Systems Corporation, 2001. All rights reserved.
     10  *   Copyright (c) Mark R V Murray, 2001.  All rights reserved.
     11  *   Copyright (c) Networks Associates Technology, Inc., 2002-2005.
     12  *       All rights reserved.
     13  *
     14  * Portions of this software were developed for the FreeBSD Project by
     15  * ThinkSec AS and NAI Labs, the Security Research Division of Network
     16  * Associates, Inc.  under DARPA/SPAWAR contract N66001-01-C-8035
     17  * ("CBOSS"), as part of the DARPA CHATS research program.
     18  *
     19  * Redistribution and use in source and binary forms, with or without
     20  * modification, are permitted provided that the following conditions
     21  * are met:
     22  * 1. Redistributions of source code must retain the above copyright
     23  *    notices, and the entire permission notice in its entirety,
     24  *    including the disclaimer of warranties.
     25  * 2. Redistributions in binary form must reproduce the above copyright
     26  *    notice, this list of conditions and the following disclaimer in the
     27  *    documentation and/or other materials provided with the distribution.
     28  * 3. The name of the author may not be used to endorse or promote
     29  *    products derived from this software without specific prior
     30  *    written permission.
     31  *
     32  * ALTERNATIVELY, this product may be distributed under the terms of
     33  * the GNU Public License, in which case the provisions of the GPL are
     34  * required INSTEAD OF the above restrictions.  (This clause is
     35  * necessary due to a potential bad interaction between the GPL and
     36  * the restrictions contained in a BSD-style copyright.)
     37  *
     38  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED
     39  * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
     40  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
     41  * DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT,
     42  * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
     43  * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
     44  * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     45  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
     46  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
     47  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
     48  * OF THE POSSIBILITY OF SUCH DAMAGE.
     49  *
     50  */
     51 
     52 #include <sys/cdefs.h>
     53 #ifdef __FreeBSD__
     54 __FBSDID("$FreeBSD: src/lib/libpam/modules/pam_krb5/pam_krb5.c,v 1.22 2005/01/24 16:49:50 rwatson Exp $");
     55 #else
     56 __RCSID("$NetBSD: pam_krb5.c,v 1.26.26.1 2020/04/08 14:07:15 martin Exp $");
     57 #endif
     58 
     59 #include <sys/types.h>
     60 #include <sys/stat.h>
     61 #include <errno.h>
     62 #include <limits.h>
     63 #include <pwd.h>
     64 #include <stdio.h>
     65 #include <stdlib.h>
     66 #include <string.h>
     67 #include <syslog.h>
     68 #include <unistd.h>
     69 
     70 #include <krb5/krb5.h>
     71 #include <krb5/com_err.h>
     72 #include <krb5/parse_time.h>
     73 
     74 #define	PAM_SM_AUTH
     75 #define	PAM_SM_ACCOUNT
     76 #define	PAM_SM_PASSWORD
     77 
     78 #include <security/pam_appl.h>
     79 #include <security/pam_modules.h>
     80 #include <security/pam_mod_misc.h>
     81 #include <security/openpam.h>
     82 
     83 #define	COMPAT_HEIMDAL
     84 /* #define	COMPAT_MIT */
     85 
     86 static void	log_krb5(krb5_context, krb5_error_code, struct syslog_data *,
     87     const char *, ...) __printflike(4, 5);
     88 static int	verify_krb_v5_tgt(krb5_context, krb5_ccache, char *, int);
     89 static void	cleanup_cache(pam_handle_t *, void *, int);
     90 static const	char *compat_princ_component(krb5_context, krb5_principal, int);
     91 static void	compat_free_data_contents(krb5_context, krb5_data *);
     92 
     93 #define USER_PROMPT		"Username: "
     94 #define PASSWORD_PROMPT		"%s's password:"
     95 #define NEW_PASSWORD_PROMPT	"New Password:"
     96 
     97 #define PAM_OPT_CCACHE		"ccache"
     98 #define PAM_OPT_DEBUG		"debug"
     99 #define PAM_OPT_FORWARDABLE	"forwardable"
    100 #define PAM_OPT_RENEWABLE	"renewable"
    101 #define PAM_OPT_NO_CCACHE	"no_ccache"
    102 #define PAM_OPT_REUSE_CCACHE	"reuse_ccache"
    103 
    104 /*
    105  * authentication management
    106  */
    107 PAM_EXTERN int
    108 pam_sm_authenticate(pam_handle_t *pamh, int flags __unused,
    109     int argc __unused, const char *argv[] __unused)
    110 {
    111 	krb5_error_code krbret;
    112 	krb5_context pam_context;
    113 	krb5_creds creds;
    114 	krb5_principal princ;
    115 	krb5_ccache ccache;
    116 	krb5_get_init_creds_opt *opts = NULL;
    117 	struct passwd *pwd, pwres;
    118 	int retval;
    119 	const void *ccache_data;
    120 	const char *user, *pass;
    121 	const void *sourceuser, *service;
    122 	char *principal, *princ_name, *ccache_name, luser[32], *srvdup;
    123 	char password_prompt[80];
    124 	char pwbuf[1024];
    125 	const char *rtime;
    126 
    127 	princ_name = NULL;
    128 	retval = pam_get_user(pamh, &user, USER_PROMPT);
    129 	if (retval != PAM_SUCCESS)
    130 		return (retval);
    131 
    132 	PAM_LOG("Got user: %s", user);
    133 
    134 	retval = pam_get_item(pamh, PAM_RUSER, &sourceuser);
    135 	if (retval != PAM_SUCCESS)
    136 		return (retval);
    137 
    138 	PAM_LOG("Got ruser: %s", (const char *)sourceuser);
    139 
    140 	service = NULL;
    141 	pam_get_item(pamh, PAM_SERVICE, &service);
    142 	if (service == NULL)
    143 		service = "unknown";
    144 
    145 	PAM_LOG("Got service: %s", (const char *)service);
    146 
    147 	krbret = krb5_init_context(&pam_context);
    148 	if (krbret != 0) {
    149 		PAM_VERBOSE_ERROR("Kerberos 5 error");
    150 		return (PAM_SERVICE_ERR);
    151 	}
    152 
    153 	PAM_LOG("Context initialised");
    154 
    155 	krbret = krb5_get_init_creds_opt_alloc(pam_context, &opts);
    156 	if (krbret != 0) {
    157 		PAM_VERBOSE_ERROR("Kerberos 5 error");
    158 		return (PAM_SERVICE_ERR);
    159 	}
    160 
    161 	if (openpam_get_option(pamh, PAM_OPT_FORWARDABLE))
    162 		krb5_get_init_creds_opt_set_forwardable(opts, 1);
    163 
    164 	if ((rtime = openpam_get_option(pamh, PAM_OPT_RENEWABLE)) != NULL) {
    165 		krb5_deltat renew;
    166 		char rbuf[80], *rp;
    167 
    168 		if (*rtime) {
    169 			(void)strlcpy(rbuf, rtime, sizeof(rbuf));
    170 			rtime = rbuf;
    171 			for (rp = rbuf; *rp; rp++)
    172 				if (*rp == '_')
    173 					*rp = ' ';
    174 		}
    175 		else
    176 			rtime = "1 month";
    177 		renew = parse_time(rtime, "s");
    178 		krb5_get_init_creds_opt_set_renew_life(opts, renew);
    179 	}
    180 
    181 
    182 
    183 	PAM_LOG("Credentials initialised");
    184 
    185 	krbret = krb5_cc_register(pam_context, &krb5_mcc_ops, FALSE);
    186 	if (krbret != 0 && krbret != KRB5_CC_TYPE_EXISTS) {
    187 		PAM_VERBOSE_ERROR("Kerberos 5 error");
    188 		retval = PAM_SERVICE_ERR;
    189 		goto cleanup3;
    190 	}
    191 
    192 	PAM_LOG("Done krb5_cc_register()");
    193 
    194 	/* Get principal name */
    195 	if (openpam_get_option(pamh, PAM_OPT_AUTH_AS_SELF))
    196 		asprintf(&principal, "%s/%s", (const char *)sourceuser, user);
    197 	else
    198 		principal = strdup(user);
    199 
    200 	PAM_LOG("Created principal: %s", principal);
    201 
    202 	krbret = krb5_parse_name(pam_context, principal, &princ);
    203 	free(principal);
    204 	if (krbret != 0) {
    205 		log_krb5(pam_context, krbret, NULL, "krb5_parse_name");
    206 		PAM_VERBOSE_ERROR("Kerberos 5 error");
    207 		retval = PAM_SERVICE_ERR;
    208 		goto cleanup3;
    209 	}
    210 
    211 	PAM_LOG("Done krb5_parse_name()");
    212 
    213 	/* Now convert the principal name into something human readable */
    214 	krbret = krb5_unparse_name(pam_context, princ, &princ_name);
    215 	if (krbret != 0) {
    216 		log_krb5(pam_context, krbret, NULL, "krb5_unparse_name");
    217 		PAM_VERBOSE_ERROR("Kerberos 5 error");
    218 		retval = PAM_SERVICE_ERR;
    219 		goto cleanup2;
    220 	}
    221 
    222 	PAM_LOG("Got principal: %s", princ_name);
    223 
    224 	/* Get password */
    225 	(void) snprintf(password_prompt, sizeof(password_prompt),
    226 	    PASSWORD_PROMPT, princ_name);
    227 	retval = pam_get_authtok(pamh, PAM_AUTHTOK, &pass, password_prompt);
    228 	if (retval != PAM_SUCCESS)
    229 		goto cleanup2;
    230 
    231 	PAM_LOG("Got password");
    232 
    233 	/* Verify the local user exists (AFTER getting the password) */
    234 	if (strchr(user, '@')) {
    235 		/* get a local account name for this principal */
    236 		krbret = krb5_aname_to_localname(pam_context, princ,
    237 		    sizeof(luser), luser);
    238 		if (krbret != 0) {
    239 			PAM_VERBOSE_ERROR("Kerberos 5 error");
    240 			log_krb5(pam_context, krbret, NULL,
    241 			    "krb5_aname_to_localname");
    242 			retval = PAM_USER_UNKNOWN;
    243 			goto cleanup2;
    244 		}
    245 
    246 		retval = pam_set_item(pamh, PAM_USER, luser);
    247 		if (retval != PAM_SUCCESS)
    248 			goto cleanup2;
    249 
    250 		PAM_LOG("PAM_USER Redone");
    251 	}
    252 
    253 	if (getpwnam_r(user, &pwres, pwbuf, sizeof(pwbuf), &pwd) != 0 ||
    254 	    pwd == NULL) {
    255 		retval = PAM_USER_UNKNOWN;
    256 		goto cleanup2;
    257 	}
    258 
    259 	PAM_LOG("Done getpwnam_r()");
    260 
    261 	/* Get a TGT */
    262 	memset(&creds, 0, sizeof(krb5_creds));
    263 	krbret = krb5_get_init_creds_password(pam_context, &creds, princ,
    264 	    pass, NULL, pamh, 0, NULL, opts);
    265 	if (krbret != 0) {
    266 		PAM_VERBOSE_ERROR("Kerberos 5 error");
    267 		log_krb5(pam_context, krbret, NULL,
    268 		    "krb5_get_init_creds_password");
    269 		retval = PAM_AUTH_ERR;
    270 		goto cleanup2;
    271 	}
    272 
    273 	PAM_LOG("Got TGT");
    274 
    275 	/* Generate a temporary cache */
    276 	krbret = krb5_cc_new_unique(pam_context, "MEMORY", NULL, &ccache);
    277 	if (krbret != 0) {
    278 		PAM_VERBOSE_ERROR("Kerberos 5 error");
    279 		log_krb5(pam_context, krbret, NULL, "krb5_cc_gen_new");
    280 		retval = PAM_SERVICE_ERR;
    281 		goto cleanup;
    282 	}
    283 	krbret = krb5_cc_initialize(pam_context, ccache, princ);
    284 	if (krbret != 0) {
    285 		PAM_VERBOSE_ERROR("Kerberos 5 error");
    286 		log_krb5(pam_context, krbret, NULL, "krb5_cc_initialize");
    287 		retval = PAM_SERVICE_ERR;
    288 		goto cleanup;
    289 	}
    290 	krbret = krb5_cc_store_cred(pam_context, ccache, &creds);
    291 	if (krbret != 0) {
    292 		PAM_VERBOSE_ERROR("Kerberos 5 error");
    293 		log_krb5(pam_context, krbret, NULL, "krb5_cc_store_cred");
    294 		krb5_cc_destroy(pam_context, ccache);
    295 		retval = PAM_SERVICE_ERR;
    296 		goto cleanup;
    297 	}
    298 
    299 	PAM_LOG("Credentials stashed");
    300 
    301 	/* Verify them */
    302 	if ((srvdup = strdup(service)) == NULL) {
    303 		retval = PAM_BUF_ERR;
    304 		goto cleanup;
    305 	}
    306 	krbret = verify_krb_v5_tgt(pam_context, ccache, srvdup,
    307 	    openpam_get_option(pamh, PAM_OPT_DEBUG) ? 1 : 0);
    308 	free(srvdup);
    309 	if (krbret == -1) {
    310 		PAM_VERBOSE_ERROR("Kerberos 5 error");
    311 		krb5_cc_destroy(pam_context, ccache);
    312 		retval = PAM_AUTH_ERR;
    313 		goto cleanup;
    314 	}
    315 
    316 	PAM_LOG("Credentials stash verified");
    317 
    318 	retval = pam_get_data(pamh, "ccache", &ccache_data);
    319 	if (retval == PAM_SUCCESS) {
    320 		krb5_cc_destroy(pam_context, ccache);
    321 		PAM_VERBOSE_ERROR("Kerberos 5 error");
    322 		retval = PAM_AUTH_ERR;
    323 		goto cleanup;
    324 	}
    325 
    326 	PAM_LOG("Credentials stash not pre-existing");
    327 
    328 	asprintf(&ccache_name, "%s:%s", krb5_cc_get_type(pam_context,
    329 		ccache), krb5_cc_get_name(pam_context, ccache));
    330 	if (ccache_name == NULL) {
    331 		PAM_VERBOSE_ERROR("Kerberos 5 error");
    332 		retval = PAM_BUF_ERR;
    333 		goto cleanup;
    334 	}
    335 	retval = pam_set_data(pamh, "ccache", ccache_name, cleanup_cache);
    336 	if (retval != 0) {
    337 		krb5_cc_destroy(pam_context, ccache);
    338 		PAM_VERBOSE_ERROR("Kerberos 5 error");
    339 		retval = PAM_SERVICE_ERR;
    340 		goto cleanup;
    341 	}
    342 
    343 	PAM_LOG("Credentials stash saved");
    344 
    345 cleanup:
    346 	krb5_free_cred_contents(pam_context, &creds);
    347 	PAM_LOG("Done cleanup");
    348 cleanup2:
    349 	krb5_free_principal(pam_context, princ);
    350 	PAM_LOG("Done cleanup2");
    351 cleanup3:
    352 	if (princ_name)
    353 		free(princ_name);
    354 
    355 	if (opts)
    356 		krb5_get_init_creds_opt_free(pam_context, opts);
    357 
    358 	krb5_free_context(pam_context);
    359 
    360 	PAM_LOG("Done cleanup3");
    361 
    362 	if (retval != PAM_SUCCESS)
    363 		PAM_VERBOSE_ERROR("Kerberos 5 refuses you");
    364 
    365 	return (retval);
    366 }
    367 
    368 PAM_EXTERN int
    369 pam_sm_setcred(pam_handle_t *pamh, int flags,
    370     int argc __unused, const char *argv[] __unused)
    371 {
    372 
    373 	krb5_error_code krbret;
    374 	krb5_context pam_context;
    375 	krb5_principal princ;
    376 	krb5_creds creds;
    377 	krb5_ccache ccache_temp, ccache_perm;
    378 	krb5_cc_cursor cursor;
    379 	struct passwd *pwd = NULL, pwres;
    380 	int retval;
    381 	const char *cache_name, *q;
    382 	const void *user;
    383 	const void *cache_data;
    384 	char *cache_name_buf = NULL, *p, *cache_name_buf2 = NULL;
    385 	char pwbuf[1024];
    386 
    387 	uid_t euid;
    388 	gid_t egid;
    389 
    390 	if (flags & PAM_DELETE_CRED)
    391 		return (PAM_SUCCESS); /* XXX */
    392 
    393 	if (!(flags & (PAM_REFRESH_CRED|PAM_REINITIALIZE_CRED|PAM_ESTABLISH_CRED)))
    394 		return (PAM_SERVICE_ERR);
    395 
    396 	/* If a persistent cache isn't desired, stop now. */
    397 	if (openpam_get_option(pamh, PAM_OPT_NO_CCACHE))
    398 		return (PAM_SUCCESS);
    399 
    400 	PAM_LOG("Establishing credentials");
    401 
    402 	/* Get username */
    403 	retval = pam_get_item(pamh, PAM_USER, &user);
    404 	if (retval != PAM_SUCCESS)
    405 		return (retval);
    406 
    407 	PAM_LOG("Got user: %s", (const char *)user);
    408 
    409 	krbret = krb5_init_context(&pam_context);
    410 	if (krbret != 0) {
    411 		PAM_LOG("Error krb5_init_context() failed");
    412 		return (PAM_SERVICE_ERR);
    413 	}
    414 
    415 	PAM_LOG("Context initialised");
    416 
    417 	euid = geteuid();	/* Usually 0 */
    418 	egid = getegid();
    419 
    420 	PAM_LOG("Got euid, egid: %d %d", euid, egid);
    421 
    422 	/* Retrieve the temporary cache */
    423 	retval = pam_get_data(pamh, "ccache", &cache_data);
    424 	if (retval != PAM_SUCCESS) {
    425 		retval = PAM_CRED_UNAVAIL;
    426 		goto cleanup3;
    427 	}
    428 	krbret = krb5_cc_resolve(pam_context, cache_data, &ccache_temp);
    429 	if (krbret != 0) {
    430 		log_krb5(pam_context, krbret, NULL, "krb5_cc_resolve(\"%s\")",
    431 		    (const char *)cache_data);
    432 		retval = PAM_SERVICE_ERR;
    433 		goto cleanup3;
    434 	}
    435 
    436 	/* Get the uid. This should exist. */
    437 	if (getpwnam_r(user, &pwres, pwbuf, sizeof(pwbuf), &pwd) != 0 ||
    438 	    pwd == NULL) {
    439 		retval = PAM_USER_UNKNOWN;
    440 		goto cleanup3;
    441 	}
    442 
    443 	PAM_LOG("Done getpwnam_r()");
    444 
    445 	/* Avoid following a symlink as root */
    446 	if (setegid(pwd->pw_gid)) {
    447 		retval = PAM_SERVICE_ERR;
    448 		goto cleanup3;
    449 	}
    450 	if (seteuid(pwd->pw_uid)) {
    451 		retval = PAM_SERVICE_ERR;
    452 		goto cleanup3;
    453 	}
    454 
    455 	PAM_LOG("Done setegid() & seteuid()");
    456 
    457 	if (flags & (PAM_REFRESH_CRED|PAM_REINITIALIZE_CRED)) {
    458                 cache_name = getenv("KRB5CCNAME");
    459                 if (!cache_name)
    460                 	goto cleanup3;
    461 	} else {
    462 		size_t len = PATH_MAX + 16;
    463 		/* Get the cache name */
    464 		cache_name = openpam_get_option(pamh, PAM_OPT_CCACHE);
    465 		if (cache_name == NULL) {
    466 			asprintf(&cache_name_buf, "FILE:/tmp/krb5cc_%d", pwd->pw_uid);
    467 			cache_name = cache_name_buf;
    468 		}
    469 
    470 		cache_name_buf2 = p = calloc(len, sizeof(char));
    471 		q = cache_name;
    472 
    473 		if (p == NULL) {
    474 			PAM_LOG("Error malloc(): failure");
    475 			retval = PAM_BUF_ERR;
    476 			goto cleanup3;
    477 		}
    478 		cache_name = p;
    479 
    480 		/* convert %u and %p */
    481 		while (*q) {
    482 			int l;
    483 			if (*q == '%') {
    484 				q++;
    485 				if (*q == 'u') {
    486 					l = snprintf(p, len, "%d", pwd->pw_uid);
    487 				}
    488 				else if (*q == 'p') {
    489 					l = snprintf(p, len, "%d", getpid());
    490 				}
    491 				else {
    492 					/* Not a special token */
    493 					if (!len)
    494 						goto truncated;
    495 					*p = '%';
    496 					l = 1;
    497 					q--;
    498 				}
    499 				if ((size_t)l > len) {
    500 truncated:				PAM_LOG("string truncation failure");
    501 					retval = PAM_BUF_ERR;
    502 					goto cleanup3;
    503 				}
    504 				q++;
    505 			}
    506 			else {
    507 				if (!len)
    508 					goto truncated;
    509 				*p = *q++;
    510 				l = 1;
    511 			}
    512 			p += l;
    513 			len -= (size_t)l;
    514 		}
    515 		if (!len)
    516 			goto truncated;
    517 		*p = '\0';
    518 	}
    519 
    520 	PAM_LOG("Got cache_name: %s", cache_name);
    521 
    522 	/* Initialize the new ccache */
    523 	krbret = krb5_cc_get_principal(pam_context, ccache_temp, &princ);
    524 	if (krbret != 0) {
    525 		log_krb5(pam_context, krbret, NULL, "krb5_cc_get_principal");
    526 		retval = PAM_SERVICE_ERR;
    527 		goto cleanup3;
    528 	}
    529 	krbret = krb5_cc_resolve(pam_context, cache_name, &ccache_perm);
    530 	if (krbret != 0) {
    531 		log_krb5(pam_context, krbret, NULL, "krb5_cc_resolve");
    532 		retval = PAM_SERVICE_ERR;
    533 		goto cleanup2;
    534 	}
    535 
    536 	krbret = krb5_cc_initialize(pam_context, ccache_perm, princ);
    537 	if (krbret != 0) {
    538 		log_krb5(pam_context, krbret, NULL, "krb5_cc_initialize");
    539 		retval = PAM_SERVICE_ERR;
    540 		goto cleanup2;
    541 	}
    542 
    543 	PAM_LOG("Cache initialised");
    544 
    545 	/* Prepare for iteration over creds */
    546 	krbret = krb5_cc_start_seq_get(pam_context, ccache_temp, &cursor);
    547 	if (krbret != 0) {
    548 		log_krb5(pam_context, krbret, NULL, "krb5_cc_start_seq_get");
    549 		krb5_cc_destroy(pam_context, ccache_perm);
    550 		retval = PAM_SERVICE_ERR;
    551 		goto cleanup2;
    552 	}
    553 
    554 	PAM_LOG("Prepared for iteration");
    555 
    556 	/* Copy the creds (should be two of them) */
    557 	while ((krbret = krb5_cc_next_cred(pam_context, ccache_temp,
    558 				&cursor, &creds)) == 0) {
    559 
    560 		krbret = krb5_cc_store_cred(pam_context, ccache_perm, &creds);
    561 		if (krbret != 0) {
    562 			log_krb5(pam_context, krbret, NULL,
    563 			    "krb5_cc_store_cred");
    564 			krb5_cc_destroy(pam_context, ccache_perm);
    565 			krb5_free_cred_contents(pam_context, &creds);
    566 			retval = PAM_SERVICE_ERR;
    567 			goto cleanup2;
    568 		}
    569 
    570 		krb5_free_cred_contents(pam_context, &creds);
    571 		PAM_LOG("Iteration");
    572 	}
    573 
    574 	krb5_cc_end_seq_get(pam_context, ccache_temp, &cursor);
    575 
    576 	PAM_LOG("Done iterating");
    577 
    578 	if (flags & PAM_ESTABLISH_CRED) {
    579 		if (strstr(cache_name, "FILE:") == cache_name) {
    580 			if (chown(&cache_name[5], pwd->pw_uid, pwd->pw_gid) == -1) {
    581 				PAM_LOG("Error chown(): %s", strerror(errno));
    582 				krb5_cc_destroy(pam_context, ccache_perm);
    583 				retval = PAM_SERVICE_ERR;
    584 				goto cleanup2;
    585 			}
    586 			PAM_LOG("Done chown()");
    587 
    588 			if (chmod(&cache_name[5], (S_IRUSR | S_IWUSR)) == -1) {
    589 				PAM_LOG("Error chmod(): %s", strerror(errno));
    590 				krb5_cc_destroy(pam_context, ccache_perm);
    591 				retval = PAM_SERVICE_ERR;
    592 				goto cleanup2;
    593 			}
    594 			PAM_LOG("Done chmod()");
    595 		}
    596 	}
    597 
    598 	krb5_cc_close(pam_context, ccache_perm);
    599 
    600 	PAM_LOG("Cache closed");
    601 
    602 	retval = pam_setenv(pamh, "KRB5CCNAME", cache_name, 1);
    603 	if (retval != PAM_SUCCESS) {
    604 		PAM_LOG("Error pam_setenv(): %s", pam_strerror(pamh, retval));
    605 		retval = PAM_SERVICE_ERR;
    606 		goto cleanup2;
    607 	}
    608 
    609 	PAM_LOG("Environment done: KRB5CCNAME=%s", cache_name);
    610 
    611 cleanup2:
    612 	krb5_free_principal(pam_context, princ);
    613 	PAM_LOG("Done cleanup2");
    614 cleanup3:
    615 	krb5_free_context(pam_context);
    616 	PAM_LOG("Done cleanup3");
    617 
    618 	seteuid(euid);
    619 	setegid(egid);
    620 
    621 	PAM_LOG("Done seteuid() & setegid()");
    622 
    623 	if (cache_name_buf != NULL)
    624 		free(cache_name_buf);
    625 	if (cache_name_buf2 != NULL)
    626 		free(cache_name_buf2);
    627 
    628 	return (retval);
    629 }
    630 
    631 /*
    632  * account management
    633  */
    634 PAM_EXTERN int
    635 pam_sm_acct_mgmt(pam_handle_t *pamh, int flags __unused,
    636     int argc __unused, const char *argv[] __unused)
    637 {
    638 	krb5_error_code krbret;
    639 	krb5_context pam_context;
    640 	krb5_ccache ccache;
    641 	krb5_principal princ;
    642 	int retval;
    643 	const void *user;
    644 	const void *ccache_name;
    645 
    646 	retval = pam_get_item(pamh, PAM_USER, &user);
    647 	if (retval != PAM_SUCCESS)
    648 		return (retval);
    649 
    650 	PAM_LOG("Got user: %s", (const char *)user);
    651 
    652 	retval = pam_get_data(pamh, "ccache", &ccache_name);
    653 	if (retval != PAM_SUCCESS)
    654 		return (PAM_SUCCESS);
    655 
    656 	PAM_LOG("Got credentials");
    657 
    658 	krbret = krb5_init_context(&pam_context);
    659 	if (krbret != 0) {
    660 		PAM_LOG("Error krb5_init_context() failed");
    661 		return (PAM_PERM_DENIED);
    662 	}
    663 
    664 	PAM_LOG("Context initialised");
    665 
    666 	krbret = krb5_cc_resolve(pam_context, (const char *)ccache_name, &ccache);
    667 	if (krbret != 0) {
    668 		log_krb5(pam_context, krbret, NULL, "krb5_cc_resolve(\"%s\")",
    669 		    (const char *)ccache_name);
    670 		krb5_free_context(pam_context);
    671 		return (PAM_PERM_DENIED);
    672 	}
    673 
    674 	PAM_LOG("Got ccache %s", (const char *)ccache_name);
    675 
    676 
    677 	krbret = krb5_cc_get_principal(pam_context, ccache, &princ);
    678 	if (krbret != 0) {
    679 		log_krb5(pam_context, krbret, NULL, "krb5_cc_get_principal");
    680 		retval = PAM_PERM_DENIED;;
    681 		goto cleanup;
    682 	}
    683 
    684 	PAM_LOG("Got principal");
    685 
    686 	if (krb5_kuserok(pam_context, princ, (const char *)user))
    687 		retval = PAM_SUCCESS;
    688 	else
    689 		retval = PAM_PERM_DENIED;
    690 	krb5_free_principal(pam_context, princ);
    691 
    692 	PAM_LOG("Done kuserok()");
    693 
    694 cleanup:
    695 	krb5_free_context(pam_context);
    696 	PAM_LOG("Done cleanup");
    697 
    698 	return (retval);
    699 
    700 }
    701 
    702 /*
    703  * password management
    704  */
    705 PAM_EXTERN int
    706 pam_sm_chauthtok(pam_handle_t *pamh, int flags,
    707     int argc __unused, const char *argv[] __unused)
    708 {
    709 	krb5_error_code krbret;
    710 	krb5_context pam_context;
    711 	krb5_creds creds;
    712 	krb5_principal princ;
    713 	krb5_get_init_creds_opt *opts;
    714 	krb5_data result_code_string, result_string;
    715 	int result_code, retval;
    716 	const char *pass;
    717 	const void *user;
    718 	char *princ_name, *passdup;
    719 	char password_prompt[80];
    720 
    721 	princ_name = NULL;
    722 	if (flags & PAM_PRELIM_CHECK) {
    723 		/* Nothing to do here. */
    724 		return (PAM_SUCCESS);
    725 	}
    726 
    727 	if (!(flags & PAM_UPDATE_AUTHTOK)) {
    728 		PAM_LOG("Illegal flags argument");
    729 		return (PAM_ABORT);
    730 	}
    731 
    732 	retval = pam_get_item(pamh, PAM_USER, &user);
    733 	if (retval != PAM_SUCCESS)
    734 		return (retval);
    735 
    736 	PAM_LOG("Got user: %s", (const char *)user);
    737 
    738 	krbret = krb5_init_context(&pam_context);
    739 	if (krbret != 0) {
    740 		PAM_LOG("Error krb5_init_context() failed");
    741 		return (PAM_SERVICE_ERR);
    742 	}
    743 
    744 	PAM_LOG("Context initialised");
    745 
    746 	krbret = krb5_get_init_creds_opt_alloc(pam_context, &opts);
    747 	if (krbret != 0) {
    748 		PAM_LOG("Error krb5_init_context() failed");
    749 		return (PAM_SERVICE_ERR);
    750 	}
    751 
    752 	krb5_get_init_creds_opt_set_tkt_life(opts, 300);
    753 	krb5_get_init_creds_opt_set_forwardable(opts, FALSE);
    754 	krb5_get_init_creds_opt_set_proxiable(opts, FALSE);
    755 
    756 	PAM_LOG("Credentials options initialised");
    757 
    758 	/* Get principal name */
    759 	krbret = krb5_parse_name(pam_context, (const char *)user, &princ);
    760 	if (krbret != 0) {
    761 		log_krb5(pam_context, krbret, NULL, "krb5_parse_name");
    762 		retval = PAM_USER_UNKNOWN;
    763 		goto cleanup3;
    764 	}
    765 
    766 	/* Now convert the principal name into something human readable */
    767 	krbret = krb5_unparse_name(pam_context, princ, &princ_name);
    768 	if (krbret != 0) {
    769 		log_krb5(pam_context, krbret, NULL, "krb5_unparse_name");
    770 		retval = PAM_SERVICE_ERR;
    771 		goto cleanup2;
    772 	}
    773 
    774 	PAM_LOG("Got principal: %s", princ_name);
    775 
    776 	/* Get password */
    777 	(void) snprintf(password_prompt, sizeof(password_prompt),
    778 	    PASSWORD_PROMPT, princ_name);
    779 	retval = pam_get_authtok(pamh, PAM_OLDAUTHTOK, &pass, password_prompt);
    780 	if (retval != PAM_SUCCESS)
    781 		goto cleanup2;
    782 
    783 	PAM_LOG("Got password");
    784 
    785 	memset(&creds, 0, sizeof(krb5_creds));
    786 	krbret = krb5_get_init_creds_password(pam_context, &creds, princ,
    787 	    pass, NULL, pamh, 0, "kadmin/changepw", opts);
    788 	if (krbret != 0) {
    789 		log_krb5(pam_context, krbret, NULL,
    790 		    "krb5_get_init_creds_password");
    791 		retval = PAM_AUTH_ERR;
    792 		goto cleanup2;
    793 	}
    794 
    795 	PAM_LOG("Credentials established");
    796 
    797 	/* Now get the new password */
    798 	for (;;) {
    799 		retval = pam_get_authtok(pamh,
    800 		    PAM_AUTHTOK, &pass, NEW_PASSWORD_PROMPT);
    801 		if (retval != PAM_TRY_AGAIN)
    802 			break;
    803 		pam_error(pamh, "Mismatch; try again, EOF to quit.");
    804 	}
    805 	if (retval != PAM_SUCCESS)
    806 		goto cleanup;
    807 
    808 	PAM_LOG("Got new password");
    809 
    810 	/* Change it */
    811 	if ((passdup = strdup(pass)) == NULL) {
    812 		retval = PAM_BUF_ERR;
    813 		goto cleanup;
    814 	}
    815 
    816 	krb5_data_zero(&result_code_string);
    817 	krb5_data_zero(&result_string);
    818 
    819 	krbret = krb5_set_password(pam_context, &creds, passdup, princ,
    820 	    &result_code, &result_code_string, &result_string);
    821 	free(passdup);
    822 	if (krbret != 0) {
    823 		log_krb5(pam_context, krbret, NULL, "Unable to set password");
    824 		retval = PAM_AUTHTOK_ERR;
    825 		goto cleanup;
    826 	}
    827 	if (result_code) {
    828 		pam_info(pamh, "%s%s%.*s",
    829 		    krb5_passwd_result_to_string(pam_context, result_code),
    830 		    result_string.length > 0 ? ": " : "",
    831 		    (int)result_string.length,
    832 		    result_string.length > 0 ? (char *)result_string.data : "");
    833 		retval = PAM_AUTHTOK_ERR;
    834 	} else {
    835 		PAM_LOG("Password changed");
    836 	}
    837 
    838 	krb5_data_free(&result_string);
    839 	krb5_data_free(&result_code_string);
    840 
    841 cleanup:
    842 	krb5_free_cred_contents(pam_context, &creds);
    843 	PAM_LOG("Done cleanup");
    844 cleanup2:
    845 	krb5_free_principal(pam_context, princ);
    846 	PAM_LOG("Done cleanup2");
    847 cleanup3:
    848 	if (princ_name)
    849 		free(princ_name);
    850 
    851 	if (opts)
    852 		krb5_get_init_creds_opt_free(pam_context, opts);
    853 
    854 	krb5_free_context(pam_context);
    855 
    856 	PAM_LOG("Done cleanup3");
    857 
    858 	return (retval);
    859 }
    860 
    861 PAM_MODULE_ENTRY("pam_krb5");
    862 
    863 static void
    864 log_krb5(krb5_context ctx, krb5_error_code err,
    865     struct syslog_data *data, const char *fmt, ...)
    866 {
    867 	char b1[1024], b2[1024];
    868 	const char *errtxt;
    869 	va_list ap;
    870 
    871 	va_start(ap, fmt);
    872 	vsnprintf(b1, sizeof(b1), fmt, ap);
    873 	va_end(ap);
    874 	if (ctx)
    875 		errtxt = krb5_get_error_message(ctx, err);
    876 	else
    877 		errtxt = NULL;
    878 	if (errtxt != NULL) {
    879 		snprintf(b2, sizeof(b2), "%s", errtxt);
    880 		krb5_free_error_message(ctx, errtxt);
    881 	} else {
    882 		snprintf(b2, sizeof(b2), "unknown %d", (int)err);
    883 	}
    884 	if (data)
    885 		syslog_r(LOG_DEBUG, data, "%s (%s)", b1, b2);
    886 	else
    887 		PAM_LOG("%s (%s)", b1, b2);
    888 }
    889 
    890 /*
    891  * This routine with some modification is from the MIT V5B6 appl/bsd/login.c
    892  * Modified by Sam Hartman <hartmans (at) mit.edu> to support PAM services
    893  * for Debian.
    894  *
    895  * Verify the Kerberos ticket-granting ticket just retrieved for the
    896  * user.  If the Kerberos server doesn't respond, assume the user is
    897  * trying to fake us out (since we DID just get a TGT from what is
    898  * supposedly our KDC).  If the host/<host> service is unknown (i.e.,
    899  * the local keytab doesn't have it), and we cannot find another
    900  * service we do have, let her in.
    901  *
    902  * Returns 1 for confirmation, -1 for failure, 0 for uncertainty.
    903  */
    904 /* ARGSUSED */
    905 static int
    906 verify_krb_v5_tgt(krb5_context context, krb5_ccache ccache,
    907     char *pam_service, int debug)
    908 {
    909 	krb5_error_code retval;
    910 	krb5_principal princ;
    911 	krb5_keyblock *keyblock;
    912 	krb5_data packet;
    913 	krb5_auth_context auth_context = NULL;
    914 	char phost[BUFSIZ];
    915 	const char *services[3], **service;
    916 	struct syslog_data data = SYSLOG_DATA_INIT;
    917 
    918 	packet.data = 0;
    919 
    920 	if (debug)
    921 		openlog_r("pam_krb5", LOG_PID, LOG_AUTHPRIV, &data);
    922 
    923 	/* If possible we want to try and verify the ticket we have
    924 	 * received against a keytab.  We will try multiple service
    925 	 * principals, including at least the host principal and the PAM
    926 	 * service principal.  The host principal is preferred because access
    927 	 * to that key is generally sufficient to compromise root, while the
    928 	 * service key for this PAM service may be less carefully guarded.
    929 	 * It is important to check the keytab first before the KDC so we do
    930 	 * not get spoofed by a fake KDC.
    931 	 */
    932 	services[0] = "host";
    933 	services[1] = pam_service;
    934 	services[2] = NULL;
    935 	keyblock = 0;
    936 	retval = -1;
    937 	for (service = &services[0]; *service != NULL; service++) {
    938 		retval = krb5_sname_to_principal(context, NULL, *service,
    939 		    KRB5_NT_SRV_HST, &princ);
    940 		if (retval != 0 && debug)
    941 			log_krb5(context, retval, &data,
    942 			    "pam_krb5: verify_krb_v5_tgt: "
    943 			    "krb5_sname_to_principal");
    944 		if (retval != 0)
    945 			return -1;
    946 
    947 		/* Extract the name directly. */
    948 		strncpy(phost, compat_princ_component(context, princ, 1),
    949 		    BUFSIZ);
    950 		phost[BUFSIZ - 1] = '\0';
    951 
    952 		/*
    953 		 * Do we have service/<host> keys?
    954 		 * (use default/configured keytab, kvno IGNORE_VNO to get the
    955 		 * first match, and ignore enctype.)
    956 		 */
    957 		retval = krb5_kt_read_service_key(context, NULL, princ, 0, 0,
    958 		    &keyblock);
    959 		if (retval != 0)
    960 			continue;
    961 		break;
    962 	}
    963 	if (retval != 0) {	/* failed to find key */
    964 		/* Keytab or service key does not exist */
    965 		if (debug)
    966 			log_krb5(context, retval, &data,
    967 			    "pam_krb5: verify_krb_v5_tgt: "
    968 			    "krb5_kt_read_service_key");
    969 		retval = 0;
    970 		goto cleanup;
    971 	}
    972 	if (keyblock)
    973 		krb5_free_keyblock(context, keyblock);
    974 
    975 	/* Talk to the kdc and construct the ticket. */
    976 	auth_context = NULL;
    977 	retval = krb5_mk_req(context, &auth_context, 0, *service, phost,
    978 		NULL, ccache, &packet);
    979 	if (auth_context) {
    980 		krb5_auth_con_free(context, auth_context);
    981 		auth_context = NULL;	/* setup for rd_req */
    982 	}
    983 	if (retval) {
    984 		if (debug)
    985 			log_krb5(context, retval, &data,
    986 			    "pam_krb5: verify_krb_v5_tgt: "
    987 			    "krb5_mk_req");
    988 		retval = -1;
    989 		goto cleanup;
    990 	}
    991 
    992 	/* Try to use the ticket. */
    993 	retval = krb5_rd_req(context, &auth_context, &packet, princ, NULL,
    994 	    NULL, NULL);
    995 	if (retval) {
    996 		if (debug)
    997 			log_krb5(context, retval, &data,
    998 			    "pam_krb5: verify_krb_v5_tgt: "
    999 			    "krb5_rd_req");
   1000 		retval = -1;
   1001 	}
   1002 	else
   1003 		retval = 1;
   1004 
   1005 cleanup:
   1006 	if (debug)
   1007 		closelog_r(&data);
   1008 	if (packet.data)
   1009 		compat_free_data_contents(context, &packet);
   1010 	if (auth_context) {
   1011 		krb5_auth_con_free(context, auth_context);
   1012 		auth_context = NULL;	/* setup for rd_req */
   1013 	}
   1014 	krb5_free_principal(context, princ);
   1015 	return retval;
   1016 }
   1017 
   1018 /* Free the memory for cache_name. Called by pam_end() */
   1019 /* ARGSUSED */
   1020 static void
   1021 cleanup_cache(pam_handle_t *pamh __unused, void *data, int pam_end_status __unused)
   1022 {
   1023 	krb5_context pam_context;
   1024 	krb5_ccache ccache;
   1025 	krb5_error_code krbret;
   1026 
   1027 	if (krb5_init_context(&pam_context))
   1028 		return;
   1029 
   1030 	krbret = krb5_cc_resolve(pam_context, data, &ccache);
   1031 	if (krbret == 0)
   1032 		krb5_cc_destroy(pam_context, ccache);
   1033 	krb5_free_context(pam_context);
   1034 	free(data);
   1035 }
   1036 
   1037 #ifdef COMPAT_HEIMDAL
   1038 #ifdef COMPAT_MIT
   1039 #error This cannot be MIT and Heimdal compatible!
   1040 #endif
   1041 #endif
   1042 
   1043 #ifndef COMPAT_HEIMDAL
   1044 #ifndef COMPAT_MIT
   1045 #error One of COMPAT_MIT and COMPAT_HEIMDAL must be specified!
   1046 #endif
   1047 #endif
   1048 
   1049 #ifdef COMPAT_HEIMDAL
   1050 /* ARGSUSED */
   1051 static const char *
   1052 compat_princ_component(krb5_context context __unused, krb5_principal princ, int n)
   1053 {
   1054 	return princ->name.name_string.val[n];
   1055 }
   1056 
   1057 /* ARGSUSED */
   1058 static void
   1059 compat_free_data_contents(krb5_context context __unused, krb5_data * data)
   1060 {
   1061 	krb5_xfree(data->data);
   1062 }
   1063 #endif
   1064 
   1065 #ifdef COMPAT_MIT
   1066 static const char *
   1067 compat_princ_component(krb5_context context, krb5_principal princ, int n)
   1068 {
   1069 	return krb5_princ_component(context, princ, n)->data;
   1070 }
   1071 
   1072 static void
   1073 compat_free_data_contents(krb5_context context, krb5_data * data)
   1074 {
   1075 	krb5_free_data_contents(context, data);
   1076 }
   1077 #endif
   1078