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