gssd.c revision 245089
1/*-
2 * Copyright (c) 2008 Isilon Inc http://www.isilon.com/
3 * Authors: Doug Rabson <dfr@rabson.org>
4 * Developed with Red Inc: Alfred Perlstein <alfred@freebsd.org>
5 *
6 * Redistribution and use in source and binary forms, with or without
7 * modification, are permitted provided that the following conditions
8 * are met:
9 * 1. Redistributions of source code must retain the above copyright
10 *    notice, this list of conditions and the following disclaimer.
11 * 2. Redistributions in binary form must reproduce the above copyright
12 *    notice, this list of conditions and the following disclaimer in the
13 *    documentation and/or other materials provided with the distribution.
14 *
15 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
16 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
19 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
20 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
21 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
22 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
23 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
24 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
25 * SUCH DAMAGE.
26 */
27
28#include <sys/cdefs.h>
29__FBSDID("$FreeBSD: stable/9/usr.sbin/gssd/gssd.c 245089 2013-01-06 01:41:14Z rmacklem $");
30
31#include <sys/param.h>
32#include <sys/stat.h>
33#include <sys/linker.h>
34#include <sys/module.h>
35#include <sys/queue.h>
36#include <sys/syslog.h>
37#include <ctype.h>
38#include <dirent.h>
39#include <err.h>
40#ifndef WITHOUT_KERBEROS
41#include <krb5.h>
42#endif
43#include <pwd.h>
44#include <stdio.h>
45#include <stdlib.h>
46#include <string.h>
47#include <unistd.h>
48#include <gssapi/gssapi.h>
49#include <rpc/rpc.h>
50#include <rpc/rpc_com.h>
51
52#include "gssd.h"
53
54#ifndef _PATH_GSS_MECH
55#define _PATH_GSS_MECH	"/etc/gss/mech"
56#endif
57#ifndef _PATH_GSSDSOCK
58#define _PATH_GSSDSOCK	"/var/run/gssd.sock"
59#endif
60
61struct gss_resource {
62	LIST_ENTRY(gss_resource) gr_link;
63	uint64_t	gr_id;	/* indentifier exported to kernel */
64	void*		gr_res;	/* GSS-API resource pointer */
65};
66LIST_HEAD(gss_resource_list, gss_resource) gss_resources;
67int gss_resource_count;
68uint32_t gss_next_id;
69uint32_t gss_start_time;
70int debug_level;
71static char ccfile_dirlist[PATH_MAX + 1], ccfile_substring[NAME_MAX + 1];
72static char pref_realm[1024];
73
74static void gssd_load_mech(void);
75static int find_ccache_file(const char *, uid_t, char *);
76static int is_a_valid_tgt_cache(const char *, uid_t, int *, time_t *);
77
78extern void gssd_1(struct svc_req *rqstp, SVCXPRT *transp);
79extern int gssd_syscall(char *path);
80
81int
82main(int argc, char **argv)
83{
84	/*
85	 * We provide an RPC service on a local-domain socket. The
86	 * kernel's GSS-API code will pass what it can't handle
87	 * directly to us.
88	 */
89	struct sockaddr_un sun;
90	int fd, oldmask, ch, debug;
91	SVCXPRT *xprt;
92
93	/*
94	 * Initialize the credential cache file name substring and the
95	 * search directory list.
96	 */
97	strlcpy(ccfile_substring, "krb5cc_", sizeof(ccfile_substring));
98	ccfile_dirlist[0] = '\0';
99	pref_realm[0] = '\0';
100	debug = 0;
101	while ((ch = getopt(argc, argv, "ds:c:r:")) != -1) {
102		switch (ch) {
103		case 'd':
104			debug_level++;
105			break;
106		case 's':
107#ifndef WITHOUT_KERBEROS
108			/*
109			 * Set the directory search list. This enables use of
110			 * find_ccache_file() to search the directories for a
111			 * suitable credentials cache file.
112			 */
113			strlcpy(ccfile_dirlist, optarg, sizeof(ccfile_dirlist));
114#else
115			errx(1, "This option not available when built"
116			    " without MK_KERBEROS\n");
117#endif
118			break;
119		case 'c':
120			/*
121			 * Specify a non-default credential cache file
122			 * substring.
123			 */
124			strlcpy(ccfile_substring, optarg,
125			    sizeof(ccfile_substring));
126			break;
127		case 'r':
128			/*
129			 * Set the preferred realm for the credential cache tgt.
130			 */
131			strlcpy(pref_realm, optarg, sizeof(pref_realm));
132			break;
133		default:
134			fprintf(stderr,
135			    "usage: %s [-d] [-s dir-list] [-c file-substring]"
136			    " [-r preferred-realm]\n", argv[0]);
137			exit(1);
138			break;
139		}
140	}
141
142	gssd_load_mech();
143
144	if (!debug_level)
145		daemon(0, 0);
146
147	memset(&sun, 0, sizeof sun);
148	sun.sun_family = AF_LOCAL;
149	unlink(_PATH_GSSDSOCK);
150	strcpy(sun.sun_path, _PATH_GSSDSOCK);
151	sun.sun_len = SUN_LEN(&sun);
152	fd = socket(AF_LOCAL, SOCK_STREAM, 0);
153	if (!fd) {
154		if (debug_level == 0) {
155			syslog(LOG_ERR, "Can't create local gssd socket");
156			exit(1);
157		}
158		err(1, "Can't create local gssd socket");
159	}
160	oldmask = umask(S_IXUSR|S_IRWXG|S_IRWXO);
161	if (bind(fd, (struct sockaddr *) &sun, sun.sun_len) < 0) {
162		if (debug_level == 0) {
163			syslog(LOG_ERR, "Can't bind local gssd socket");
164			exit(1);
165		}
166		err(1, "Can't bind local gssd socket");
167	}
168	umask(oldmask);
169	if (listen(fd, SOMAXCONN) < 0) {
170		if (debug_level == 0) {
171			syslog(LOG_ERR, "Can't listen on local gssd socket");
172			exit(1);
173		}
174		err(1, "Can't listen on local gssd socket");
175	}
176	xprt = svc_vc_create(fd, RPC_MAXDATASIZE, RPC_MAXDATASIZE);
177	if (!xprt) {
178		if (debug_level == 0) {
179			syslog(LOG_ERR,
180			    "Can't create transport for local gssd socket");
181			exit(1);
182		}
183		err(1, "Can't create transport for local gssd socket");
184	}
185	if (!svc_reg(xprt, GSSD, GSSDVERS, gssd_1, NULL)) {
186		if (debug_level == 0) {
187			syslog(LOG_ERR,
188			    "Can't register service for local gssd socket");
189			exit(1);
190		}
191		err(1, "Can't register service for local gssd socket");
192	}
193
194	LIST_INIT(&gss_resources);
195	gss_next_id = 1;
196	gss_start_time = time(0);
197
198	gssd_syscall(_PATH_GSSDSOCK);
199	svc_run();
200
201	return (0);
202}
203
204static void
205gssd_load_mech(void)
206{
207	FILE		*fp;
208	char		buf[256];
209	char		*p;
210	char		*name, *oid, *lib, *kobj;
211
212	fp = fopen(_PATH_GSS_MECH, "r");
213	if (!fp)
214		return;
215
216	while (fgets(buf, sizeof(buf), fp)) {
217		if (*buf == '#')
218			continue;
219		p = buf;
220		name = strsep(&p, "\t\n ");
221		if (p) while (isspace(*p)) p++;
222		oid = strsep(&p, "\t\n ");
223		if (p) while (isspace(*p)) p++;
224		lib = strsep(&p, "\t\n ");
225		if (p) while (isspace(*p)) p++;
226		kobj = strsep(&p, "\t\n ");
227		if (!name || !oid || !lib || !kobj)
228			continue;
229
230		if (strcmp(kobj, "-")) {
231			/*
232			 * Attempt to load the kernel module if its
233			 * not already present.
234			 */
235			if (modfind(kobj) < 0) {
236				if (kldload(kobj) < 0) {
237					fprintf(stderr,
238			"%s: can't find or load kernel module %s for %s\n",
239					    getprogname(), kobj, name);
240				}
241			}
242		}
243	}
244	fclose(fp);
245}
246
247static void *
248gssd_find_resource(uint64_t id)
249{
250	struct gss_resource *gr;
251
252	if (!id)
253		return (NULL);
254
255	LIST_FOREACH(gr, &gss_resources, gr_link)
256		if (gr->gr_id == id)
257			return (gr->gr_res);
258
259	return (NULL);
260}
261
262static uint64_t
263gssd_make_resource(void *res)
264{
265	struct gss_resource *gr;
266
267	if (!res)
268		return (0);
269
270	gr = malloc(sizeof(struct gss_resource));
271	if (!gr)
272		return (0);
273	gr->gr_id = (gss_next_id++) + ((uint64_t) gss_start_time << 32);
274	gr->gr_res = res;
275	LIST_INSERT_HEAD(&gss_resources, gr, gr_link);
276	gss_resource_count++;
277	if (debug_level > 1)
278		printf("%d resources allocated\n", gss_resource_count);
279
280	return (gr->gr_id);
281}
282
283static void
284gssd_delete_resource(uint64_t id)
285{
286	struct gss_resource *gr;
287
288	LIST_FOREACH(gr, &gss_resources, gr_link) {
289		if (gr->gr_id == id) {
290			LIST_REMOVE(gr, gr_link);
291			free(gr);
292			gss_resource_count--;
293			if (debug_level > 1)
294				printf("%d resources allocated\n",
295				    gss_resource_count);
296			return;
297		}
298	}
299}
300
301bool_t
302gssd_null_1_svc(void *argp, void *result, struct svc_req *rqstp)
303{
304
305	return (TRUE);
306}
307
308bool_t
309gssd_init_sec_context_1_svc(init_sec_context_args *argp, init_sec_context_res *result, struct svc_req *rqstp)
310{
311	gss_cred_id_t cred = GSS_C_NO_CREDENTIAL;
312	gss_ctx_id_t ctx = GSS_C_NO_CONTEXT;
313	gss_name_t name = GSS_C_NO_NAME;
314	char ccname[PATH_MAX + 5 + 1], *cp, *cp2;
315	int gotone;
316
317	memset(result, 0, sizeof(*result));
318	if (ccfile_dirlist[0] != '\0' && argp->cred == 0) {
319		/*
320		 * For the "-s" case and no credentials provided as an
321		 * argument, search the directory list for an appropriate
322		 * credential cache file. If the search fails, return failure.
323		 */
324		gotone = 0;
325		cp = ccfile_dirlist;
326		do {
327			cp2 = strchr(cp, ':');
328			if (cp2 != NULL)
329				*cp2 = '\0';
330			gotone = find_ccache_file(cp, argp->uid, ccname);
331			if (gotone != 0)
332				break;
333			if (cp2 != NULL)
334				*cp2++ = ':';
335			cp = cp2;
336		} while (cp != NULL && *cp != '\0');
337		if (gotone == 0) {
338			result->major_status = GSS_S_CREDENTIALS_EXPIRED;
339			return (TRUE);
340		}
341	} else {
342		/*
343		 * If there wasn't a "-s" option or the credentials have
344		 * been provided as an argument, do it the old way.
345		 * When credentials are provided, the uid should be root.
346		 */
347		if (argp->cred != 0 && argp->uid != 0) {
348			if (debug_level == 0)
349				syslog(LOG_ERR, "gss_init_sec_context:"
350				    " cred for non-root");
351			else
352				fprintf(stderr, "gss_init_sec_context:"
353				    " cred for non-root\n");
354		}
355		snprintf(ccname, sizeof(ccname), "FILE:/tmp/krb5cc_%d",
356		    (int) argp->uid);
357	}
358	setenv("KRB5CCNAME", ccname, TRUE);
359
360	if (argp->cred) {
361		cred = gssd_find_resource(argp->cred);
362		if (!cred) {
363			result->major_status = GSS_S_CREDENTIALS_EXPIRED;
364			return (TRUE);
365		}
366	}
367	if (argp->ctx) {
368		ctx = gssd_find_resource(argp->ctx);
369		if (!ctx) {
370			result->major_status = GSS_S_CONTEXT_EXPIRED;
371			return (TRUE);
372		}
373	}
374	if (argp->name) {
375		name = gssd_find_resource(argp->name);
376		if (!name) {
377			result->major_status = GSS_S_BAD_NAME;
378			return (TRUE);
379		}
380	}
381
382	result->major_status = gss_init_sec_context(&result->minor_status,
383	    cred, &ctx, name, argp->mech_type,
384	    argp->req_flags, argp->time_req, argp->input_chan_bindings,
385	    &argp->input_token, &result->actual_mech_type,
386	    &result->output_token, &result->ret_flags, &result->time_rec);
387
388	if (result->major_status == GSS_S_COMPLETE
389	    || result->major_status == GSS_S_CONTINUE_NEEDED) {
390		if (argp->ctx)
391			result->ctx = argp->ctx;
392		else
393			result->ctx = gssd_make_resource(ctx);
394	}
395
396	return (TRUE);
397}
398
399bool_t
400gssd_accept_sec_context_1_svc(accept_sec_context_args *argp, accept_sec_context_res *result, struct svc_req *rqstp)
401{
402	gss_ctx_id_t ctx = GSS_C_NO_CONTEXT;
403	gss_cred_id_t cred = GSS_C_NO_CREDENTIAL;
404	gss_name_t src_name;
405	gss_cred_id_t delegated_cred_handle;
406
407	memset(result, 0, sizeof(*result));
408	if (argp->ctx) {
409		ctx = gssd_find_resource(argp->ctx);
410		if (!ctx) {
411			result->major_status = GSS_S_CONTEXT_EXPIRED;
412			return (TRUE);
413		}
414	}
415	if (argp->cred) {
416		cred = gssd_find_resource(argp->cred);
417		if (!cred) {
418			result->major_status = GSS_S_CREDENTIALS_EXPIRED;
419			return (TRUE);
420		}
421	}
422
423	memset(result, 0, sizeof(*result));
424	result->major_status = gss_accept_sec_context(&result->minor_status,
425	    &ctx, cred, &argp->input_token, argp->input_chan_bindings,
426	    &src_name, &result->mech_type, &result->output_token,
427	    &result->ret_flags, &result->time_rec,
428	    &delegated_cred_handle);
429
430	if (result->major_status == GSS_S_COMPLETE
431	    || result->major_status == GSS_S_CONTINUE_NEEDED) {
432		if (argp->ctx)
433			result->ctx = argp->ctx;
434		else
435			result->ctx = gssd_make_resource(ctx);
436		result->src_name = gssd_make_resource(src_name);
437		result->delegated_cred_handle =
438			gssd_make_resource(delegated_cred_handle);
439	}
440
441	return (TRUE);
442}
443
444bool_t
445gssd_delete_sec_context_1_svc(delete_sec_context_args *argp, delete_sec_context_res *result, struct svc_req *rqstp)
446{
447	gss_ctx_id_t ctx = gssd_find_resource(argp->ctx);
448
449	if (ctx) {
450		result->major_status = gss_delete_sec_context(
451			&result->minor_status, &ctx, &result->output_token);
452		gssd_delete_resource(argp->ctx);
453	} else {
454		result->major_status = GSS_S_COMPLETE;
455		result->minor_status = 0;
456	}
457
458	return (TRUE);
459}
460
461bool_t
462gssd_export_sec_context_1_svc(export_sec_context_args *argp, export_sec_context_res *result, struct svc_req *rqstp)
463{
464	gss_ctx_id_t ctx = gssd_find_resource(argp->ctx);
465
466	if (ctx) {
467		result->major_status = gss_export_sec_context(
468			&result->minor_status, &ctx,
469			&result->interprocess_token);
470		result->format = KGSS_HEIMDAL_1_1;
471		gssd_delete_resource(argp->ctx);
472	} else {
473		result->major_status = GSS_S_FAILURE;
474		result->minor_status = 0;
475		result->interprocess_token.length = 0;
476		result->interprocess_token.value = NULL;
477	}
478
479	return (TRUE);
480}
481
482bool_t
483gssd_import_name_1_svc(import_name_args *argp, import_name_res *result, struct svc_req *rqstp)
484{
485	gss_name_t name;
486
487	result->major_status = gss_import_name(&result->minor_status,
488	    &argp->input_name_buffer, argp->input_name_type, &name);
489
490	if (result->major_status == GSS_S_COMPLETE)
491		result->output_name = gssd_make_resource(name);
492	else
493		result->output_name = 0;
494
495	return (TRUE);
496}
497
498bool_t
499gssd_canonicalize_name_1_svc(canonicalize_name_args *argp, canonicalize_name_res *result, struct svc_req *rqstp)
500{
501	gss_name_t name = gssd_find_resource(argp->input_name);
502	gss_name_t output_name;
503
504	memset(result, 0, sizeof(*result));
505	if (!name) {
506		result->major_status = GSS_S_BAD_NAME;
507		return (TRUE);
508	}
509
510	result->major_status = gss_canonicalize_name(&result->minor_status,
511	    name, argp->mech_type, &output_name);
512
513	if (result->major_status == GSS_S_COMPLETE)
514		result->output_name = gssd_make_resource(output_name);
515	else
516		result->output_name = 0;
517
518	return (TRUE);
519}
520
521bool_t
522gssd_export_name_1_svc(export_name_args *argp, export_name_res *result, struct svc_req *rqstp)
523{
524	gss_name_t name = gssd_find_resource(argp->input_name);
525
526	memset(result, 0, sizeof(*result));
527	if (!name) {
528		result->major_status = GSS_S_BAD_NAME;
529		return (TRUE);
530	}
531
532	result->major_status = gss_export_name(&result->minor_status,
533	    name, &result->exported_name);
534
535	return (TRUE);
536}
537
538bool_t
539gssd_release_name_1_svc(release_name_args *argp, release_name_res *result, struct svc_req *rqstp)
540{
541	gss_name_t name = gssd_find_resource(argp->input_name);
542
543	if (name) {
544		result->major_status = gss_release_name(&result->minor_status,
545		    &name);
546		gssd_delete_resource(argp->input_name);
547	} else {
548		result->major_status = GSS_S_COMPLETE;
549		result->minor_status = 0;
550	}
551
552	return (TRUE);
553}
554
555bool_t
556gssd_pname_to_uid_1_svc(pname_to_uid_args *argp, pname_to_uid_res *result, struct svc_req *rqstp)
557{
558	gss_name_t name = gssd_find_resource(argp->pname);
559	uid_t uid;
560	char buf[128];
561	struct passwd pwd, *pw;
562
563	memset(result, 0, sizeof(*result));
564	if (name) {
565		result->major_status =
566			gss_pname_to_uid(&result->minor_status,
567			    name, argp->mech, &uid);
568		if (result->major_status == GSS_S_COMPLETE) {
569			result->uid = uid;
570			getpwuid_r(uid, &pwd, buf, sizeof(buf), &pw);
571			if (pw) {
572				int len = NGRPS;
573				int groups[NGRPS];
574				result->gid = pw->pw_gid;
575				getgrouplist(pw->pw_name, pw->pw_gid,
576				    groups, &len);
577				result->gidlist.gidlist_len = len;
578				result->gidlist.gidlist_val =
579					mem_alloc(len * sizeof(int));
580				memcpy(result->gidlist.gidlist_val, groups,
581				    len * sizeof(int));
582			} else {
583				result->gid = 65534;
584				result->gidlist.gidlist_len = 0;
585				result->gidlist.gidlist_val = NULL;
586			}
587		}
588	} else {
589		result->major_status = GSS_S_BAD_NAME;
590		result->minor_status = 0;
591	}
592
593	return (TRUE);
594}
595
596bool_t
597gssd_acquire_cred_1_svc(acquire_cred_args *argp, acquire_cred_res *result, struct svc_req *rqstp)
598{
599	gss_name_t desired_name = GSS_C_NO_NAME;
600	gss_cred_id_t cred;
601	char ccname[PATH_MAX + 5 + 1], *cp, *cp2;
602	int gotone;
603
604	memset(result, 0, sizeof(*result));
605	if (ccfile_dirlist[0] != '\0' && argp->desired_name == 0) {
606		/*
607		 * For the "-s" case and no name provided as an
608		 * argument, search the directory list for an appropriate
609		 * credential cache file. If the search fails, return failure.
610		 */
611		gotone = 0;
612		cp = ccfile_dirlist;
613		do {
614			cp2 = strchr(cp, ':');
615			if (cp2 != NULL)
616				*cp2 = '\0';
617			gotone = find_ccache_file(cp, argp->uid, ccname);
618			if (gotone != 0)
619				break;
620			if (cp2 != NULL)
621				*cp2++ = ':';
622			cp = cp2;
623		} while (cp != NULL && *cp != '\0');
624		if (gotone == 0) {
625			result->major_status = GSS_S_CREDENTIALS_EXPIRED;
626			return (TRUE);
627		}
628	} else {
629		/*
630		 * If there wasn't a "-s" option or the name has
631		 * been provided as an argument, do it the old way.
632		 * When a name is provided, it will normally exist in the
633		 * default keytab file and the uid will be root.
634		 */
635		if (argp->desired_name != 0 && argp->uid != 0) {
636			if (debug_level == 0)
637				syslog(LOG_ERR, "gss_acquire_cred:"
638				    " principal_name for non-root");
639			else
640				fprintf(stderr, "gss_acquire_cred:"
641				    " principal_name for non-root\n");
642		}
643		snprintf(ccname, sizeof(ccname), "FILE:/tmp/krb5cc_%d",
644		    (int) argp->uid);
645	}
646	setenv("KRB5CCNAME", ccname, TRUE);
647
648	if (argp->desired_name) {
649		desired_name = gssd_find_resource(argp->desired_name);
650		if (!desired_name) {
651			result->major_status = GSS_S_BAD_NAME;
652			return (TRUE);
653		}
654	}
655
656	result->major_status = gss_acquire_cred(&result->minor_status,
657	    desired_name, argp->time_req, argp->desired_mechs,
658	    argp->cred_usage, &cred, &result->actual_mechs, &result->time_rec);
659
660	if (result->major_status == GSS_S_COMPLETE)
661		result->output_cred = gssd_make_resource(cred);
662	else
663		result->output_cred = 0;
664
665	return (TRUE);
666}
667
668bool_t
669gssd_set_cred_option_1_svc(set_cred_option_args *argp, set_cred_option_res *result, struct svc_req *rqstp)
670{
671	gss_cred_id_t cred = gssd_find_resource(argp->cred);
672
673	memset(result, 0, sizeof(*result));
674	if (!cred) {
675		result->major_status = GSS_S_CREDENTIALS_EXPIRED;
676		return (TRUE);
677	}
678
679	result->major_status = gss_set_cred_option(&result->minor_status,
680	    &cred, argp->option_name, &argp->option_value);
681
682	return (TRUE);
683}
684
685bool_t
686gssd_release_cred_1_svc(release_cred_args *argp, release_cred_res *result, struct svc_req *rqstp)
687{
688	gss_cred_id_t cred = gssd_find_resource(argp->cred);
689
690	if (cred) {
691		result->major_status = gss_release_cred(&result->minor_status,
692		    &cred);
693		gssd_delete_resource(argp->cred);
694	} else {
695		result->major_status = GSS_S_COMPLETE;
696		result->minor_status = 0;
697	}
698
699	return (TRUE);
700}
701
702bool_t
703gssd_display_status_1_svc(display_status_args *argp, display_status_res *result, struct svc_req *rqstp)
704{
705
706	result->message_context = argp->message_context;
707	result->major_status = gss_display_status(&result->minor_status,
708	    argp->status_value, argp->status_type, argp->mech_type,
709	    &result->message_context, &result->status_string);
710
711	return (TRUE);
712}
713
714int
715gssd_1_freeresult(SVCXPRT *transp, xdrproc_t xdr_result, caddr_t result)
716{
717	/*
718	 * We don't use XDR to free the results - anything which was
719	 * allocated came from GSS-API. We use xdr_result to figure
720	 * out what to do.
721	 */
722	OM_uint32 junk;
723
724	if (xdr_result == (xdrproc_t) xdr_init_sec_context_res) {
725		init_sec_context_res *p = (init_sec_context_res *) result;
726		gss_release_buffer(&junk, &p->output_token);
727	} else if (xdr_result == (xdrproc_t) xdr_accept_sec_context_res) {
728		accept_sec_context_res *p = (accept_sec_context_res *) result;
729		gss_release_buffer(&junk, &p->output_token);
730	} else if (xdr_result == (xdrproc_t) xdr_delete_sec_context_res) {
731		delete_sec_context_res *p = (delete_sec_context_res *) result;
732		gss_release_buffer(&junk, &p->output_token);
733	} else if (xdr_result == (xdrproc_t) xdr_export_sec_context_res) {
734		export_sec_context_res *p = (export_sec_context_res *) result;
735		if (p->interprocess_token.length)
736			memset(p->interprocess_token.value, 0,
737			    p->interprocess_token.length);
738		gss_release_buffer(&junk, &p->interprocess_token);
739	} else if (xdr_result == (xdrproc_t) xdr_export_name_res) {
740		export_name_res *p = (export_name_res *) result;
741		gss_release_buffer(&junk, &p->exported_name);
742	} else if (xdr_result == (xdrproc_t) xdr_acquire_cred_res) {
743		acquire_cred_res *p = (acquire_cred_res *) result;
744		gss_release_oid_set(&junk, &p->actual_mechs);
745	} else if (xdr_result == (xdrproc_t) xdr_pname_to_uid_res) {
746		pname_to_uid_res *p = (pname_to_uid_res *) result;
747		if (p->gidlist.gidlist_val)
748			free(p->gidlist.gidlist_val);
749	} else if (xdr_result == (xdrproc_t) xdr_display_status_res) {
750		display_status_res *p = (display_status_res *) result;
751		gss_release_buffer(&junk, &p->status_string);
752	}
753
754	return (TRUE);
755}
756
757/*
758 * Search a directory for the most likely candidate to be used as the
759 * credential cache for a uid. If successful, return 1 and fill the
760 * file's path id into "rpath". Otherwise, return 0.
761 */
762static int
763find_ccache_file(const char *dirpath, uid_t uid, char *rpath)
764{
765	DIR *dirp;
766	struct dirent *dp;
767	struct stat sb;
768	time_t exptime, oexptime;
769	int gotone, len, rating, orating;
770	char namepath[PATH_MAX + 5 + 1];
771	char retpath[PATH_MAX + 5 + 1];
772
773	dirp = opendir(dirpath);
774	if (dirp == NULL)
775		return (0);
776	gotone = 0;
777	orating = 0;
778	oexptime = 0;
779	while ((dp = readdir(dirp)) != NULL) {
780		len = snprintf(namepath, sizeof(namepath), "%s/%s", dirpath,
781		    dp->d_name);
782		if (len < sizeof(namepath) &&
783		    strstr(dp->d_name, ccfile_substring) != NULL &&
784		    lstat(namepath, &sb) >= 0 &&
785		    sb.st_uid == uid &&
786		    S_ISREG(sb.st_mode)) {
787			len = snprintf(namepath, sizeof(namepath), "FILE:%s/%s",
788			    dirpath, dp->d_name);
789			if (len < sizeof(namepath) &&
790			    is_a_valid_tgt_cache(namepath, uid, &rating,
791			    &exptime) != 0) {
792				if (gotone == 0 || rating > orating ||
793				    (rating == orating && exptime > oexptime)) {
794					orating = rating;
795					oexptime = exptime;
796					strcpy(retpath, namepath);
797					gotone = 1;
798				}
799			}
800		}
801	}
802	closedir(dirp);
803	if (gotone != 0) {
804		strcpy(rpath, retpath);
805		return (1);
806	}
807	return (0);
808}
809
810/*
811 * Try to determine if the file is a valid tgt cache file.
812 * Check that the file has a valid tgt for a principal.
813 * If it does, return 1, otherwise return 0.
814 * It also returns a "rating" and the expiry time for the TGT, when found.
815 * This "rating" is higher based on heuristics that make it more
816 * likely to be the correct credential cache file to use. It can
817 * be used by the caller, along with expiry time, to select from
818 * multiple credential cache files.
819 */
820static int
821is_a_valid_tgt_cache(const char *filepath, uid_t uid, int *retrating,
822    time_t *retexptime)
823{
824#ifndef WITHOUT_KERBEROS
825	krb5_context context;
826	krb5_principal princ;
827	krb5_ccache ccache;
828	krb5_error_code retval;
829	krb5_cc_cursor curse;
830	krb5_creds krbcred;
831	int gotone, orating, rating, ret;
832	struct passwd *pw;
833	char *cp, *cp2, *pname;
834	time_t exptime;
835
836	/* Find a likely name for the uid principal. */
837	pw = getpwuid(uid);
838
839	/*
840	 * Do a bunch of krb5 library stuff to try and determine if
841	 * this file is a credentials cache with an appropriate TGT
842	 * in it.
843	 */
844	retval = krb5_init_context(&context);
845	if (retval != 0)
846		return (0);
847	retval = krb5_cc_resolve(context, filepath, &ccache);
848	if (retval != 0) {
849		krb5_free_context(context);
850		return (0);
851	}
852	ret = 0;
853	orating = 0;
854	exptime = 0;
855	retval = krb5_cc_start_seq_get(context, ccache, &curse);
856	if (retval == 0) {
857		while ((retval = krb5_cc_next_cred(context, ccache, &curse,
858		    &krbcred)) == 0) {
859			gotone = 0;
860			rating = 0;
861			retval = krb5_unparse_name(context, krbcred.server,
862			    &pname);
863			if (retval == 0) {
864				cp = strchr(pname, '/');
865				if (cp != NULL) {
866					*cp++ = '\0';
867					if (strcmp(pname, "krbtgt") == 0 &&
868					    krbcred.times.endtime > time(NULL)
869					    ) {
870						gotone = 1;
871						/*
872						 * Test to see if this is a
873						 * tgt for cross-realm auth.
874						 * Rate it higher, if it is not.
875						 */
876						cp2 = strchr(cp, '@');
877						if (cp2 != NULL) {
878							*cp2++ = '\0';
879							if (strcmp(cp, cp2) ==
880							    0)
881								rating++;
882						}
883					}
884				}
885				free(pname);
886			}
887			if (gotone != 0) {
888				retval = krb5_unparse_name(context,
889				    krbcred.client, &pname);
890				if (retval == 0) {
891					cp = strchr(pname, '@');
892					if (cp != NULL) {
893						*cp++ = '\0';
894						if (pw != NULL && strcmp(pname,
895						    pw->pw_name) == 0)
896							rating++;
897						if (strchr(pname, '/') == NULL)
898							rating++;
899						if (pref_realm[0] != '\0' &&
900						    strcmp(cp, pref_realm) == 0)
901							rating++;
902					}
903				}
904				free(pname);
905				if (rating > orating) {
906					orating = rating;
907					exptime = krbcred.times.endtime;
908				} else if (rating == orating &&
909				    krbcred.times.endtime > exptime)
910					exptime = krbcred.times.endtime;
911				ret = 1;
912			}
913			krb5_free_cred_contents(context, &krbcred);
914		}
915		krb5_cc_end_seq_get(context, ccache, &curse);
916	}
917	krb5_cc_close(context, ccache);
918	krb5_free_context(context);
919	if (ret != 0) {
920		*retrating = orating;
921		*retexptime = exptime;
922	}
923	return (ret);
924#else /* WITHOUT_KERBEROS */
925	return (0);
926#endif /* !WITHOUT_KERBEROS */
927}
928
929