Home | History | Annotate | Line # | Download | only in pam_krb5
pam_krb5.c revision 1.17
      1 /*	$NetBSD: pam_krb5.c,v 1.17 2006/11/03 18:04:20 christos 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.17 2006/11/03 18:04:20 christos 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 
     73 #define	PAM_SM_AUTH
     74 #define	PAM_SM_ACCOUNT
     75 #define	PAM_SM_PASSWORD
     76 
     77 #include <security/pam_appl.h>
     78 #include <security/pam_modules.h>
     79 #include <security/pam_mod_misc.h>
     80 #include <security/openpam.h>
     81 
     82 #define	COMPAT_HEIMDAL
     83 /* #define	COMPAT_MIT */
     84 
     85 static int	verify_krb_v5_tgt(krb5_context, krb5_ccache, char *, int);
     86 static void	cleanup_cache(pam_handle_t *, void *, int);
     87 static const	char *compat_princ_component(krb5_context, krb5_principal, int);
     88 static void	compat_free_data_contents(krb5_context, krb5_data *);
     89 
     90 #define USER_PROMPT		"Username: "
     91 #define PASSWORD_PROMPT		"%s's Password:"
     92 #define NEW_PASSWORD_PROMPT	"New Password:"
     93 
     94 #define PAM_OPT_CCACHE		"ccache"
     95 #define PAM_OPT_DEBUG		"debug"
     96 #define PAM_OPT_FORWARDABLE	"forwardable"
     97 #define PAM_OPT_NO_CCACHE	"no_ccache"
     98 #define PAM_OPT_REUSE_CCACHE	"reuse_ccache"
     99 
    100 /*
    101  * authentication management
    102  */
    103 PAM_EXTERN int
    104 pam_sm_authenticate(pam_handle_t *pamh, int flags __unused,
    105     int argc __unused, const char *argv[] __unused)
    106 {
    107 	krb5_error_code krbret;
    108 	krb5_context pam_context;
    109 	krb5_creds creds;
    110 	krb5_principal princ;
    111 	krb5_ccache ccache;
    112 	krb5_get_init_creds_opt opts;
    113 	struct passwd *pwd, pwres;
    114 	int retval;
    115 	void *ccache_data;
    116 	const char *user, *pass;
    117 	const void *sourceuser, *service;
    118 	char *principal, *princ_name, *ccache_name, luser[32], *srvdup;
    119 	char password_prompt[80];
    120 	char pwbuf[1024];
    121 
    122 	princ_name = NULL;
    123 	retval = pam_get_user(pamh, &user, USER_PROMPT);
    124 	if (retval != PAM_SUCCESS)
    125 		return (retval);
    126 
    127 	PAM_LOG("Got user: %s", user);
    128 
    129 	retval = pam_get_item(pamh, PAM_RUSER, &sourceuser);
    130 	if (retval != PAM_SUCCESS)
    131 		return (retval);
    132 
    133 	PAM_LOG("Got ruser: %s", (const char *)sourceuser);
    134 
    135 	service = NULL;
    136 	pam_get_item(pamh, PAM_SERVICE, &service);
    137 	if (service == NULL)
    138 		service = "unknown";
    139 
    140 	PAM_LOG("Got service: %s", (const char *)service);
    141 
    142 	krbret = krb5_init_context(&pam_context);
    143 	if (krbret != 0) {
    144 		PAM_VERBOSE_ERROR("Kerberos 5 error");
    145 		return (PAM_SERVICE_ERR);
    146 	}
    147 
    148 	PAM_LOG("Context initialised");
    149 
    150 	krb5_get_init_creds_opt_init(&opts);
    151 
    152 	if (openpam_get_option(pamh, PAM_OPT_FORWARDABLE))
    153 		krb5_get_init_creds_opt_set_forwardable(&opts, 1);
    154 
    155 	PAM_LOG("Credentials initialised");
    156 
    157 	krbret = krb5_cc_register(pam_context, &krb5_mcc_ops, FALSE);
    158 	if (krbret != 0 && krbret != KRB5_CC_TYPE_EXISTS) {
    159 		PAM_VERBOSE_ERROR("Kerberos 5 error");
    160 		retval = PAM_SERVICE_ERR;
    161 		goto cleanup3;
    162 	}
    163 
    164 	PAM_LOG("Done krb5_cc_register()");
    165 
    166 	/* Get principal name */
    167 	if (openpam_get_option(pamh, PAM_OPT_AUTH_AS_SELF))
    168 		asprintf(&principal, "%s/%s", (const char *)sourceuser, user);
    169 	else
    170 		principal = strdup(user);
    171 
    172 	PAM_LOG("Created principal: %s", principal);
    173 
    174 	krbret = krb5_parse_name(pam_context, principal, &princ);
    175 	free(principal);
    176 	if (krbret != 0) {
    177 		PAM_LOG("Error krb5_parse_name(): %s",
    178 		    krb5_get_err_text(pam_context, krbret));
    179 		PAM_VERBOSE_ERROR("Kerberos 5 error");
    180 		retval = PAM_SERVICE_ERR;
    181 		goto cleanup3;
    182 	}
    183 
    184 	PAM_LOG("Done krb5_parse_name()");
    185 
    186 	/* Now convert the principal name into something human readable */
    187 	krbret = krb5_unparse_name(pam_context, princ, &princ_name);
    188 	if (krbret != 0) {
    189 		PAM_LOG("Error krb5_unparse_name(): %s",
    190 		    krb5_get_err_text(pam_context, krbret));
    191 		PAM_VERBOSE_ERROR("Kerberos 5 error");
    192 		retval = PAM_SERVICE_ERR;
    193 		goto cleanup2;
    194 	}
    195 
    196 	PAM_LOG("Got principal: %s", princ_name);
    197 
    198 	/* Get password */
    199 	(void) snprintf(password_prompt, sizeof(password_prompt),
    200 	    PASSWORD_PROMPT, princ_name);
    201 	retval = pam_get_authtok(pamh, PAM_AUTHTOK, &pass, password_prompt);
    202 	if (retval != PAM_SUCCESS)
    203 		goto cleanup2;
    204 
    205 	PAM_LOG("Got password");
    206 
    207 	/* Verify the local user exists (AFTER getting the password) */
    208 	if (strchr(user, '@')) {
    209 		/* get a local account name for this principal */
    210 		krbret = krb5_aname_to_localname(pam_context, princ,
    211 		    sizeof(luser), luser);
    212 		if (krbret != 0) {
    213 			PAM_VERBOSE_ERROR("Kerberos 5 error");
    214 			PAM_LOG("Error krb5_aname_to_localname(): %s",
    215 			    krb5_get_err_text(pam_context, krbret));
    216 			retval = PAM_USER_UNKNOWN;
    217 			goto cleanup2;
    218 		}
    219 
    220 		retval = pam_set_item(pamh, PAM_USER, luser);
    221 		if (retval != PAM_SUCCESS)
    222 			goto cleanup2;
    223 
    224 		PAM_LOG("PAM_USER Redone");
    225 	}
    226 
    227 	if (getpwnam_r(user, &pwres, pwbuf, sizeof(pwbuf), &pwd) != 0 ||
    228 	    pwd == NULL) {
    229 		retval = PAM_USER_UNKNOWN;
    230 		goto cleanup2;
    231 	}
    232 
    233 	PAM_LOG("Done getpwnam_r()");
    234 
    235 	/* Get a TGT */
    236 	memset(&creds, 0, sizeof(krb5_creds));
    237 	krbret = krb5_get_init_creds_password(pam_context, &creds, princ,
    238 	    pass, NULL, pamh, 0, NULL, &opts);
    239 	if (krbret != 0) {
    240 		PAM_VERBOSE_ERROR("Kerberos 5 error");
    241 		PAM_LOG("Error krb5_get_init_creds_password(): %s",
    242 		    krb5_get_err_text(pam_context, krbret));
    243 		retval = PAM_AUTH_ERR;
    244 		goto cleanup2;
    245 	}
    246 
    247 	PAM_LOG("Got TGT");
    248 
    249 	/* Generate a temporary cache */
    250 	krbret = krb5_cc_gen_new(pam_context, &krb5_mcc_ops, &ccache);
    251 	if (krbret != 0) {
    252 		PAM_VERBOSE_ERROR("Kerberos 5 error");
    253 		PAM_LOG("Error krb5_cc_gen_new(): %s",
    254 		    krb5_get_err_text(pam_context, krbret));
    255 		retval = PAM_SERVICE_ERR;
    256 		goto cleanup;
    257 	}
    258 	krbret = krb5_cc_initialize(pam_context, ccache, princ);
    259 	if (krbret != 0) {
    260 		PAM_VERBOSE_ERROR("Kerberos 5 error");
    261 		PAM_LOG("Error krb5_cc_initialize(): %s",
    262 		    krb5_get_err_text(pam_context, krbret));
    263 		retval = PAM_SERVICE_ERR;
    264 		goto cleanup;
    265 	}
    266 	krbret = krb5_cc_store_cred(pam_context, ccache, &creds);
    267 	if (krbret != 0) {
    268 		PAM_VERBOSE_ERROR("Kerberos 5 error");
    269 		PAM_LOG("Error krb5_cc_store_cred(): %s",
    270 		    krb5_get_err_text(pam_context, krbret));
    271 		krb5_cc_destroy(pam_context, ccache);
    272 		retval = PAM_SERVICE_ERR;
    273 		goto cleanup;
    274 	}
    275 
    276 	PAM_LOG("Credentials stashed");
    277 
    278 	/* Verify them */
    279 	if ((srvdup = strdup(service)) == NULL) {
    280 		retval = PAM_BUF_ERR;
    281 		goto cleanup;
    282 	}
    283 	krbret = verify_krb_v5_tgt(pam_context, ccache, srvdup,
    284 	    openpam_get_option(pamh, PAM_OPT_DEBUG) ? 1 : 0);
    285 	free(srvdup);
    286 	if (krbret == -1) {
    287 		PAM_VERBOSE_ERROR("Kerberos 5 error");
    288 		krb5_cc_destroy(pam_context, ccache);
    289 		retval = PAM_AUTH_ERR;
    290 		goto cleanup;
    291 	}
    292 
    293 	PAM_LOG("Credentials stash verified");
    294 
    295 	retval = pam_get_data(pamh, "ccache", &ccache_data);
    296 	if (retval == PAM_SUCCESS) {
    297 		krb5_cc_destroy(pam_context, ccache);
    298 		PAM_VERBOSE_ERROR("Kerberos 5 error");
    299 		retval = PAM_AUTH_ERR;
    300 		goto cleanup;
    301 	}
    302 
    303 	PAM_LOG("Credentials stash not pre-existing");
    304 
    305 	asprintf(&ccache_name, "%s:%s", krb5_cc_get_type(pam_context,
    306 		ccache), krb5_cc_get_name(pam_context, ccache));
    307 	if (ccache_name == NULL) {
    308 		PAM_VERBOSE_ERROR("Kerberos 5 error");
    309 		retval = PAM_BUF_ERR;
    310 		goto cleanup;
    311 	}
    312 	retval = pam_set_data(pamh, "ccache", ccache_name, cleanup_cache);
    313 	if (retval != 0) {
    314 		krb5_cc_destroy(pam_context, ccache);
    315 		PAM_VERBOSE_ERROR("Kerberos 5 error");
    316 		retval = PAM_SERVICE_ERR;
    317 		goto cleanup;
    318 	}
    319 
    320 	PAM_LOG("Credentials stash saved");
    321 
    322 cleanup:
    323 	krb5_free_cred_contents(pam_context, &creds);
    324 	PAM_LOG("Done cleanup");
    325 cleanup2:
    326 	krb5_free_principal(pam_context, princ);
    327 	PAM_LOG("Done cleanup2");
    328 cleanup3:
    329 	if (princ_name)
    330 		free(princ_name);
    331 
    332 	krb5_free_context(pam_context);
    333 
    334 	PAM_LOG("Done cleanup3");
    335 
    336 	if (retval != PAM_SUCCESS)
    337 		PAM_VERBOSE_ERROR("Kerberos 5 refuses you");
    338 
    339 	return (retval);
    340 }
    341 
    342 PAM_EXTERN int
    343 pam_sm_setcred(pam_handle_t *pamh, int flags,
    344     int argc __unused, const char *argv[] __unused)
    345 {
    346 
    347 	krb5_error_code krbret;
    348 	krb5_context pam_context;
    349 	krb5_principal princ;
    350 	krb5_creds creds;
    351 	krb5_ccache ccache_temp, ccache_perm;
    352 	krb5_cc_cursor cursor;
    353 	struct passwd *pwd = NULL, pwres;
    354 	int retval;
    355 	const char *cache_name, *q;
    356 	const void *user;
    357 	void *cache_data;
    358 	char *cache_name_buf = NULL, *p, *cache_name_buf2 = NULL;
    359 	char pwbuf[1024];
    360 
    361 	uid_t euid;
    362 	gid_t egid;
    363 
    364 	if (flags & PAM_DELETE_CRED)
    365 		return (PAM_SUCCESS); /* XXX */
    366 
    367 	if (!(flags & (PAM_REFRESH_CRED|PAM_REINITIALIZE_CRED|PAM_ESTABLISH_CRED)))
    368 		return (PAM_SERVICE_ERR);
    369 
    370 	/* If a persistent cache isn't desired, stop now. */
    371 	if (openpam_get_option(pamh, PAM_OPT_NO_CCACHE))
    372 		return (PAM_SUCCESS);
    373 
    374 	PAM_LOG("Establishing credentials");
    375 
    376 	/* Get username */
    377 	retval = pam_get_item(pamh, PAM_USER, &user);
    378 	if (retval != PAM_SUCCESS)
    379 		return (retval);
    380 
    381 	PAM_LOG("Got user: %s", (const char *)user);
    382 
    383 	krbret = krb5_init_context(&pam_context);
    384 	if (krbret != 0) {
    385 		PAM_LOG("Error krb5_init_context() failed");
    386 		return (PAM_SERVICE_ERR);
    387 	}
    388 
    389 	PAM_LOG("Context initialised");
    390 
    391 	euid = geteuid();	/* Usually 0 */
    392 	egid = getegid();
    393 
    394 	PAM_LOG("Got euid, egid: %d %d", euid, egid);
    395 
    396 	/* Retrieve the temporary cache */
    397 	retval = pam_get_data(pamh, "ccache", &cache_data);
    398 	if (retval != PAM_SUCCESS) {
    399 		retval = PAM_CRED_UNAVAIL;
    400 		goto cleanup3;
    401 	}
    402 	krbret = krb5_cc_resolve(pam_context, cache_data, &ccache_temp);
    403 	if (krbret != 0) {
    404 		PAM_LOG("Error krb5_cc_resolve(\"%s\"): %s", (const char *)cache_data,
    405 		    krb5_get_err_text(pam_context, krbret));
    406 		retval = PAM_SERVICE_ERR;
    407 		goto cleanup3;
    408 	}
    409 
    410 	/* Get the uid. This should exist. */
    411 	if (getpwnam_r(user, &pwres, pwbuf, sizeof(pwbuf), &pwd) != 0 ||
    412 	    pwd == NULL) {
    413 		retval = PAM_USER_UNKNOWN;
    414 		goto cleanup3;
    415 	}
    416 
    417 	PAM_LOG("Done getpwnam_r()");
    418 
    419 	/* Avoid following a symlink as root */
    420 	if (setegid(pwd->pw_gid)) {
    421 		retval = PAM_SERVICE_ERR;
    422 		goto cleanup3;
    423 	}
    424 	if (seteuid(pwd->pw_uid)) {
    425 		retval = PAM_SERVICE_ERR;
    426 		goto cleanup3;
    427 	}
    428 
    429 	PAM_LOG("Done setegid() & seteuid()");
    430 
    431 	if (flags & (PAM_REFRESH_CRED|PAM_REINITIALIZE_CRED)) {
    432                 cache_name = getenv("KRB5CCNAME");
    433                 if (!cache_name)
    434                 	goto cleanup3;
    435 	} else {
    436 		/* Get the cache name */
    437 		cache_name = openpam_get_option(pamh, PAM_OPT_CCACHE);
    438 		if (cache_name == NULL) {
    439 			asprintf(&cache_name_buf, "FILE:/tmp/krb5cc_%d", pwd->pw_uid);
    440 			cache_name = cache_name_buf;
    441 		}
    442 
    443 		/* XXX potential overflow */
    444 		cache_name_buf2 = p = calloc(PATH_MAX + 16, sizeof(char));
    445 		q = cache_name;
    446 
    447 		if (p == NULL) {
    448 			PAM_LOG("Error malloc(): failure");
    449 			retval = PAM_BUF_ERR;
    450 			goto cleanup3;
    451 		}
    452 		cache_name = p;
    453 
    454 		/* convert %u and %p */
    455 		while (*q) {
    456 			if (*q == '%') {
    457 				q++;
    458 				if (*q == 'u') {
    459 					sprintf(p, "%d", pwd->pw_uid);
    460 					p += strlen(p);
    461 				}
    462 				else if (*q == 'p') {
    463 					sprintf(p, "%d", getpid());
    464 					p += strlen(p);
    465 				}
    466 				else {
    467 					/* Not a special token */
    468 					*p++ = '%';
    469 					q--;
    470 				}
    471 				q++;
    472 			}
    473 			else {
    474 				*p++ = *q++;
    475 			}
    476 		}
    477 	}
    478 
    479 	PAM_LOG("Got cache_name: %s", cache_name);
    480 
    481 	/* Initialize the new ccache */
    482 	krbret = krb5_cc_get_principal(pam_context, ccache_temp, &princ);
    483 	if (krbret != 0) {
    484 		PAM_LOG("Error krb5_cc_get_principal(): %s",
    485 		    krb5_get_err_text(pam_context, krbret));
    486 		retval = PAM_SERVICE_ERR;
    487 		goto cleanup3;
    488 	}
    489 	krbret = krb5_cc_resolve(pam_context, cache_name, &ccache_perm);
    490 	if (krbret != 0) {
    491 		PAM_LOG("Error krb5_cc_resolve(): %s",
    492 		    krb5_get_err_text(pam_context, krbret));
    493 		retval = PAM_SERVICE_ERR;
    494 		goto cleanup2;
    495 	}
    496 
    497 	krbret = krb5_cc_initialize(pam_context, ccache_perm, princ);
    498 	if (krbret != 0) {
    499 		PAM_LOG("Error krb5_cc_initialize(): %s",
    500 		    krb5_get_err_text(pam_context, krbret));
    501 		retval = PAM_SERVICE_ERR;
    502 		goto cleanup2;
    503 	}
    504 
    505 	PAM_LOG("Cache initialised");
    506 
    507 	/* Prepare for iteration over creds */
    508 	krbret = krb5_cc_start_seq_get(pam_context, ccache_temp, &cursor);
    509 	if (krbret != 0) {
    510 		PAM_LOG("Error krb5_cc_start_seq_get(): %s",
    511 		    krb5_get_err_text(pam_context, krbret));
    512 		krb5_cc_destroy(pam_context, ccache_perm);
    513 		retval = PAM_SERVICE_ERR;
    514 		goto cleanup2;
    515 	}
    516 
    517 	PAM_LOG("Prepared for iteration");
    518 
    519 	/* Copy the creds (should be two of them) */
    520 	while ((krbret = krb5_cc_next_cred(pam_context, ccache_temp,
    521 				&cursor, &creds) == 0)) {
    522 
    523 		krbret = krb5_cc_store_cred(pam_context, ccache_perm, &creds);
    524 		if (krbret != 0) {
    525 			PAM_LOG("Error krb5_cc_store_cred(): %s",
    526 			    krb5_get_err_text(pam_context, krbret));
    527 			krb5_cc_destroy(pam_context, ccache_perm);
    528 			krb5_free_cred_contents(pam_context, &creds);
    529 			retval = PAM_SERVICE_ERR;
    530 			goto cleanup2;
    531 		}
    532 
    533 		krb5_free_cred_contents(pam_context, &creds);
    534 		PAM_LOG("Iteration");
    535 	}
    536 
    537 	krb5_cc_end_seq_get(pam_context, ccache_temp, &cursor);
    538 
    539 	PAM_LOG("Done iterating");
    540 
    541 	if (flags & PAM_ESTABLISH_CRED) {
    542 		if (strstr(cache_name, "FILE:") == cache_name) {
    543 			if (chown(&cache_name[5], pwd->pw_uid, pwd->pw_gid) == -1) {
    544 				PAM_LOG("Error chown(): %s", strerror(errno));
    545 				krb5_cc_destroy(pam_context, ccache_perm);
    546 				retval = PAM_SERVICE_ERR;
    547 				goto cleanup2;
    548 			}
    549 			PAM_LOG("Done chown()");
    550 
    551 			if (chmod(&cache_name[5], (S_IRUSR | S_IWUSR)) == -1) {
    552 				PAM_LOG("Error chmod(): %s", strerror(errno));
    553 				krb5_cc_destroy(pam_context, ccache_perm);
    554 				retval = PAM_SERVICE_ERR;
    555 				goto cleanup2;
    556 			}
    557 			PAM_LOG("Done chmod()");
    558 		}
    559 	}
    560 
    561 	krb5_cc_close(pam_context, ccache_perm);
    562 
    563 	PAM_LOG("Cache closed");
    564 
    565 	retval = pam_setenv(pamh, "KRB5CCNAME", cache_name, 1);
    566 	if (retval != PAM_SUCCESS) {
    567 		PAM_LOG("Error pam_setenv(): %s", pam_strerror(pamh, retval));
    568 		retval = PAM_SERVICE_ERR;
    569 		goto cleanup2;
    570 	}
    571 
    572 	PAM_LOG("Environment done: KRB5CCNAME=%s", cache_name);
    573 
    574 cleanup2:
    575 	krb5_free_principal(pam_context, princ);
    576 	PAM_LOG("Done cleanup2");
    577 cleanup3:
    578 	krb5_free_context(pam_context);
    579 	PAM_LOG("Done cleanup3");
    580 
    581 	seteuid(euid);
    582 	setegid(egid);
    583 
    584 	PAM_LOG("Done seteuid() & setegid()");
    585 
    586 	if (cache_name_buf != NULL)
    587 		free(cache_name_buf);
    588 	if (cache_name_buf2 != NULL)
    589 		free(cache_name_buf2);
    590 
    591 	return (retval);
    592 }
    593 
    594 /*
    595  * account management
    596  */
    597 PAM_EXTERN int
    598 pam_sm_acct_mgmt(pam_handle_t *pamh, int flags __unused,
    599     int argc __unused, const char *argv[] __unused)
    600 {
    601 	krb5_error_code krbret;
    602 	krb5_context pam_context;
    603 	krb5_ccache ccache;
    604 	krb5_principal princ;
    605 	int retval;
    606 	const void *user;
    607 	void *ccache_name;
    608 
    609 	retval = pam_get_item(pamh, PAM_USER, &user);
    610 	if (retval != PAM_SUCCESS)
    611 		return (retval);
    612 
    613 	PAM_LOG("Got user: %s", (const char *)user);
    614 
    615 	retval = pam_get_data(pamh, "ccache", &ccache_name);
    616 	if (retval != PAM_SUCCESS)
    617 		return (PAM_SUCCESS);
    618 
    619 	PAM_LOG("Got credentials");
    620 
    621 	krbret = krb5_init_context(&pam_context);
    622 	if (krbret != 0) {
    623 		PAM_LOG("Error krb5_init_context() failed");
    624 		return (PAM_PERM_DENIED);
    625 	}
    626 
    627 	PAM_LOG("Context initialised");
    628 
    629 	krbret = krb5_cc_resolve(pam_context, (const char *)ccache_name, &ccache);
    630 	if (krbret != 0) {
    631 		PAM_LOG("Error krb5_cc_resolve(\"%s\"): %s", (const char *)ccache_name,
    632 		    krb5_get_err_text(pam_context, krbret));
    633 		krb5_free_context(pam_context);
    634 		return (PAM_PERM_DENIED);
    635 	}
    636 
    637 	PAM_LOG("Got ccache %s", (const char *)ccache_name);
    638 
    639 
    640 	krbret = krb5_cc_get_principal(pam_context, ccache, &princ);
    641 	if (krbret != 0) {
    642 		PAM_LOG("Error krb5_cc_get_principal(): %s",
    643 		    krb5_get_err_text(pam_context, krbret));
    644 		retval = PAM_PERM_DENIED;;
    645 		goto cleanup;
    646 	}
    647 
    648 	PAM_LOG("Got principal");
    649 
    650 	if (krb5_kuserok(pam_context, princ, (const char *)user))
    651 		retval = PAM_SUCCESS;
    652 	else
    653 		retval = PAM_PERM_DENIED;
    654 	krb5_free_principal(pam_context, princ);
    655 
    656 	PAM_LOG("Done kuserok()");
    657 
    658 cleanup:
    659 	krb5_free_context(pam_context);
    660 	PAM_LOG("Done cleanup");
    661 
    662 	return (retval);
    663 
    664 }
    665 
    666 /*
    667  * password management
    668  */
    669 PAM_EXTERN int
    670 pam_sm_chauthtok(pam_handle_t *pamh, int flags,
    671     int argc __unused, const char *argv[] __unused)
    672 {
    673 	krb5_error_code krbret;
    674 	krb5_context pam_context;
    675 	krb5_creds creds;
    676 	krb5_principal princ;
    677 	krb5_get_init_creds_opt opts;
    678 	krb5_data result_code_string, result_string;
    679 	int result_code, retval;
    680 	const char *pass;
    681 	const void *user;
    682 	char *princ_name, *passdup;
    683 	char password_prompt[80];
    684 
    685 	princ_name = NULL;
    686 	if (flags & PAM_PRELIM_CHECK) {
    687 		/* Nothing to do here. */
    688 		return (PAM_SUCCESS);
    689 	}
    690 
    691 	if (!(flags & PAM_UPDATE_AUTHTOK)) {
    692 		PAM_LOG("Illegal flags argument");
    693 		return (PAM_ABORT);
    694 	}
    695 
    696 	retval = pam_get_item(pamh, PAM_USER, &user);
    697 	if (retval != PAM_SUCCESS)
    698 		return (retval);
    699 
    700 	PAM_LOG("Got user: %s", (const char *)user);
    701 
    702 	krbret = krb5_init_context(&pam_context);
    703 	if (krbret != 0) {
    704 		PAM_LOG("Error krb5_init_context() failed");
    705 		return (PAM_SERVICE_ERR);
    706 	}
    707 
    708 	PAM_LOG("Context initialised");
    709 
    710 	krb5_get_init_creds_opt_init(&opts);
    711 
    712 	krb5_get_init_creds_opt_set_tkt_life(&opts, 300);
    713 	krb5_get_init_creds_opt_set_forwardable(&opts, FALSE);
    714 	krb5_get_init_creds_opt_set_proxiable(&opts, FALSE);
    715 
    716 	PAM_LOG("Credentials options initialised");
    717 
    718 	/* Get principal name */
    719 	krbret = krb5_parse_name(pam_context, (const char *)user, &princ);
    720 	if (krbret != 0) {
    721 		PAM_LOG("Error krb5_parse_name(): %s",
    722 		    krb5_get_err_text(pam_context, krbret));
    723 		retval = PAM_USER_UNKNOWN;
    724 		goto cleanup3;
    725 	}
    726 
    727 	/* Now convert the principal name into something human readable */
    728 	krbret = krb5_unparse_name(pam_context, princ, &princ_name);
    729 	if (krbret != 0) {
    730 		PAM_LOG("Error krb5_unparse_name(): %s",
    731 		    krb5_get_err_text(pam_context, krbret));
    732 		retval = PAM_SERVICE_ERR;
    733 		goto cleanup2;
    734 	}
    735 
    736 	PAM_LOG("Got principal: %s", princ_name);
    737 
    738 	/* Get password */
    739 	(void) snprintf(password_prompt, sizeof(password_prompt),
    740 	    PASSWORD_PROMPT, princ_name);
    741 	retval = pam_get_authtok(pamh, PAM_OLDAUTHTOK, &pass, password_prompt);
    742 	if (retval != PAM_SUCCESS)
    743 		goto cleanup2;
    744 
    745 	PAM_LOG("Got password");
    746 
    747 	memset(&creds, 0, sizeof(krb5_creds));
    748 	krbret = krb5_get_init_creds_password(pam_context, &creds, princ,
    749 	    pass, NULL, pamh, 0, "kadmin/changepw", &opts);
    750 	if (krbret != 0) {
    751 		PAM_LOG("Error krb5_get_init_creds_password(): %s",
    752 		    krb5_get_err_text(pam_context, krbret));
    753 		retval = PAM_AUTH_ERR;
    754 		goto cleanup2;
    755 	}
    756 
    757 	PAM_LOG("Credentials established");
    758 
    759 	/* Now get the new password */
    760 	for (;;) {
    761 		retval = pam_get_authtok(pamh,
    762 		    PAM_AUTHTOK, &pass, NEW_PASSWORD_PROMPT);
    763 		if (retval != PAM_TRY_AGAIN)
    764 			break;
    765 		pam_error(pamh, "Mismatch; try again, EOF to quit.");
    766 	}
    767 	if (retval != PAM_SUCCESS)
    768 		goto cleanup;
    769 
    770 	PAM_LOG("Got new password");
    771 
    772 	/* Change it */
    773 	if ((passdup = strdup(pass)) == NULL) {
    774 		retval = PAM_BUF_ERR;
    775 		goto cleanup;
    776 	}
    777 
    778 	krb5_data_zero(&result_code_string);
    779 	krb5_data_zero(&result_string);
    780 
    781 	krbret = krb5_change_password(pam_context, &creds, passdup,
    782 	    &result_code, &result_code_string, &result_string);
    783 	free(passdup);
    784 	if (krbret != 0) {
    785 		pam_error(pamh, "Unable to set password: %s",
    786 		    krb5_get_err_text(pam_context, krbret));
    787 		retval = PAM_AUTHTOK_ERR;
    788 		goto cleanup;
    789 	}
    790 	if (result_code) {
    791 		pam_info(pamh, "%s%s%.*s",
    792 		    krb5_passwd_result_to_string(pam_context, result_code),
    793 		    result_string.length > 0 ? ": " : "",
    794 		    (int)result_string.length,
    795 		    result_string.length > 0 ? (char *)result_string.data : "");
    796 		retval = PAM_AUTHTOK_ERR;
    797 	} else {
    798 		PAM_LOG("Password changed");
    799 	}
    800 
    801 	krb5_data_free(&result_string);
    802 	krb5_data_free(&result_code_string);
    803 
    804 cleanup:
    805 	krb5_free_cred_contents(pam_context, &creds);
    806 	PAM_LOG("Done cleanup");
    807 cleanup2:
    808 	krb5_free_principal(pam_context, princ);
    809 	PAM_LOG("Done cleanup2");
    810 cleanup3:
    811 	if (princ_name)
    812 		free(princ_name);
    813 
    814 	krb5_free_context(pam_context);
    815 
    816 	PAM_LOG("Done cleanup3");
    817 
    818 	return (retval);
    819 }
    820 
    821 PAM_MODULE_ENTRY("pam_krb5");
    822 
    823 /*
    824  * This routine with some modification is from the MIT V5B6 appl/bsd/login.c
    825  * Modified by Sam Hartman <hartmans (at) mit.edu> to support PAM services
    826  * for Debian.
    827  *
    828  * Verify the Kerberos ticket-granting ticket just retrieved for the
    829  * user.  If the Kerberos server doesn't respond, assume the user is
    830  * trying to fake us out (since we DID just get a TGT from what is
    831  * supposedly our KDC).  If the host/<host> service is unknown (i.e.,
    832  * the local keytab doesn't have it), and we cannot find another
    833  * service we do have, let her in.
    834  *
    835  * Returns 1 for confirmation, -1 for failure, 0 for uncertainty.
    836  */
    837 /* ARGSUSED */
    838 static int
    839 verify_krb_v5_tgt(krb5_context context, krb5_ccache ccache,
    840     char *pam_service, int debug)
    841 {
    842 	krb5_error_code retval;
    843 	krb5_principal princ;
    844 	krb5_keyblock *keyblock;
    845 	krb5_data packet;
    846 	krb5_auth_context auth_context = NULL;
    847 	char phost[BUFSIZ];
    848 	const char *services[3], **service;
    849 	struct syslog_data data;
    850 
    851 	packet.data = 0;
    852 
    853 	if (debug)
    854 		openlog_r("pam_krb5", LOG_PID, LOG_AUTHPRIV, &data);
    855 
    856 	/* If possible we want to try and verify the ticket we have
    857 	 * received against a keytab.  We will try multiple service
    858 	 * principals, including at least the host principal and the PAM
    859 	 * service principal.  The host principal is preferred because access
    860 	 * to that key is generally sufficient to compromise root, while the
    861 	 * service key for this PAM service may be less carefully guarded.
    862 	 * It is important to check the keytab first before the KDC so we do
    863 	 * not get spoofed by a fake KDC.
    864 	 */
    865 	services[0] = "host";
    866 	services[1] = pam_service;
    867 	services[2] = NULL;
    868 	keyblock = 0;
    869 	retval = -1;
    870 	for (service = &services[0]; *service != NULL; service++) {
    871 		retval = krb5_sname_to_principal(context, NULL, *service,
    872 		    KRB5_NT_SRV_HST, &princ);
    873 		if (retval != 0) {
    874 			if (debug)
    875 				syslog_r(LOG_DEBUG, &data,
    876 				    "pam_krb5: verify_krb_v5_tgt(): %s: %s",
    877 				    "krb5_sname_to_principal()",
    878 				    krb5_get_err_text(context, retval));
    879 			return -1;
    880 		}
    881 
    882 		/* Extract the name directly. */
    883 		strncpy(phost, compat_princ_component(context, princ, 1),
    884 		    BUFSIZ);
    885 		phost[BUFSIZ - 1] = '\0';
    886 
    887 		/*
    888 		 * Do we have service/<host> keys?
    889 		 * (use default/configured keytab, kvno IGNORE_VNO to get the
    890 		 * first match, and ignore enctype.)
    891 		 */
    892 		retval = krb5_kt_read_service_key(context, NULL, princ, 0, 0,
    893 		    &keyblock);
    894 		if (retval != 0)
    895 			continue;
    896 		break;
    897 	}
    898 	if (retval != 0) {	/* failed to find key */
    899 		/* Keytab or service key does not exist */
    900 		if (debug)
    901 			syslog_r(LOG_DEBUG, &data,
    902 			    "pam_krb5: verify_krb_v5_tgt(): %s: %s",
    903 			    "krb5_kt_read_service_key()",
    904 			    krb5_get_err_text(context, retval));
    905 		retval = 0;
    906 		goto cleanup;
    907 	}
    908 	if (keyblock)
    909 		krb5_free_keyblock(context, keyblock);
    910 
    911 	/* Talk to the kdc and construct the ticket. */
    912 	auth_context = NULL;
    913 	retval = krb5_mk_req(context, &auth_context, 0, *service, phost,
    914 		NULL, ccache, &packet);
    915 	if (auth_context) {
    916 		krb5_auth_con_free(context, auth_context);
    917 		auth_context = NULL;	/* setup for rd_req */
    918 	}
    919 	if (retval) {
    920 		if (debug)
    921 			syslog_r(LOG_DEBUG, &data,
    922 			    "pam_krb5: verify_krb_v5_tgt(): %s: %s",
    923 			    "krb5_mk_req()",
    924 			    krb5_get_err_text(context, retval));
    925 		retval = -1;
    926 		goto cleanup;
    927 	}
    928 
    929 	/* Try to use the ticket. */
    930 	retval = krb5_rd_req(context, &auth_context, &packet, princ, NULL,
    931 	    NULL, NULL);
    932 	if (retval) {
    933 		if (debug)
    934 			syslog_r(LOG_DEBUG, &data,
    935 			    "pam_krb5: verify_krb_v5_tgt(): %s: %s",
    936 			    "krb5_rd_req()",
    937 			    krb5_get_err_text(context, retval));
    938 		retval = -1;
    939 	}
    940 	else
    941 		retval = 1;
    942 
    943 cleanup:
    944 	if (debug)
    945 		closelog_r(&data);
    946 	if (packet.data)
    947 		compat_free_data_contents(context, &packet);
    948 	if (auth_context) {
    949 		krb5_auth_con_free(context, auth_context);
    950 		auth_context = NULL;	/* setup for rd_req */
    951 	}
    952 	krb5_free_principal(context, princ);
    953 	return retval;
    954 }
    955 
    956 /* Free the memory for cache_name. Called by pam_end() */
    957 /* ARGSUSED */
    958 static void
    959 cleanup_cache(pam_handle_t *pamh __unused, void *data, int pam_end_status __unused)
    960 {
    961 	krb5_context pam_context;
    962 	krb5_ccache ccache;
    963 	krb5_error_code krbret;
    964 
    965 	if (krb5_init_context(&pam_context))
    966 		return;
    967 
    968 	krbret = krb5_cc_resolve(pam_context, data, &ccache);
    969 	if (krbret == 0)
    970 		krb5_cc_destroy(pam_context, ccache);
    971 	krb5_free_context(pam_context);
    972 	free(data);
    973 }
    974 
    975 #ifdef COMPAT_HEIMDAL
    976 #ifdef COMPAT_MIT
    977 #error This cannot be MIT and Heimdal compatible!
    978 #endif
    979 #endif
    980 
    981 #ifndef COMPAT_HEIMDAL
    982 #ifndef COMPAT_MIT
    983 #error One of COMPAT_MIT and COMPAT_HEIMDAL must be specified!
    984 #endif
    985 #endif
    986 
    987 #ifdef COMPAT_HEIMDAL
    988 /* ARGSUSED */
    989 static const char *
    990 compat_princ_component(krb5_context context __unused, krb5_principal princ, int n)
    991 {
    992 	return princ->name.name_string.val[n];
    993 }
    994 
    995 /* ARGSUSED */
    996 static void
    997 compat_free_data_contents(krb5_context context __unused, krb5_data * data)
    998 {
    999 	krb5_xfree(data->data);
   1000 }
   1001 #endif
   1002 
   1003 #ifdef COMPAT_MIT
   1004 static const char *
   1005 compat_princ_component(krb5_context context, krb5_principal princ, int n)
   1006 {
   1007 	return krb5_princ_component(context, princ, n)->data;
   1008 }
   1009 
   1010 static void
   1011 compat_free_data_contents(krb5_context context, krb5_data * data)
   1012 {
   1013 	krb5_free_data_contents(context, data);
   1014 }
   1015 #endif
   1016