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