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