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