gssd.c revision 293446
190075Sobrien/*-
250397Sobrien * Copyright (c) 2008 Isilon Inc http://www.isilon.com/
3169689Skan * Authors: Doug Rabson <dfr@rabson.org>
4169689Skan * Developed with Red Inc: Alfred Perlstein <alfred@freebsd.org>
550397Sobrien *
690075Sobrien * Redistribution and use in source and binary forms, with or without
750397Sobrien * modification, are permitted provided that the following conditions
890075Sobrien * are met:
990075Sobrien * 1. Redistributions of source code must retain the above copyright
1090075Sobrien *    notice, this list of conditions and the following disclaimer.
1190075Sobrien * 2. Redistributions in binary form must reproduce the above copyright
1250397Sobrien *    notice, this list of conditions and the following disclaimer in the
1390075Sobrien *    documentation and/or other materials provided with the distribution.
1490075Sobrien *
1590075Sobrien * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
1690075Sobrien * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
1750397Sobrien * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
1850397Sobrien * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
1990075Sobrien * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
20169689Skan * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
21169689Skan * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
2250397Sobrien * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
2350397Sobrien * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
2450397Sobrien * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
2550397Sobrien * SUCH DAMAGE.
2650397Sobrien */
2750397Sobrien
2850397Sobrien#include <sys/cdefs.h>
2950397Sobrien__FBSDID("$FreeBSD: stable/10/usr.sbin/gssd/gssd.c 293446 2016-01-08 23:58:32Z jpaetzel $");
3090075Sobrien
3190075Sobrien#include <sys/param.h>
3250397Sobrien#include <sys/stat.h>
3350397Sobrien#include <sys/linker.h>
3450397Sobrien#include <sys/module.h>
3590075Sobrien#include <sys/queue.h>
3650397Sobrien#include <sys/syslog.h>
3750397Sobrien#include <ctype.h>
3850397Sobrien#include <dirent.h>
3950397Sobrien#include <err.h>
4050397Sobrien#include <errno.h>
4150397Sobrien#ifndef WITHOUT_KERBEROS
42169689Skan#include <krb5.h>
43169689Skan#endif
44169689Skan#include <pwd.h>
45169689Skan#include <signal.h>
46169689Skan#include <stdarg.h>
47169689Skan#include <stdio.h>
4850397Sobrien#include <stdlib.h>
49117395Skan#include <string.h>
5050397Sobrien#include <unistd.h>
5150397Sobrien#include <gssapi/gssapi.h>
5250397Sobrien#include <rpc/rpc.h>
5350397Sobrien#include <rpc/rpc_com.h>
5450397Sobrien
55169689Skan#include "gssd.h"
56169689Skan
57169689Skan#ifndef _PATH_GSS_MECH
58169689Skan#define _PATH_GSS_MECH	"/etc/gss/mech"
59169689Skan#endif
60169689Skan#ifndef _PATH_GSSDSOCK
6150397Sobrien#define _PATH_GSSDSOCK	"/var/run/gssd.sock"
6250397Sobrien#endif
63169689Skan#define GSSD_CREDENTIAL_CACHE_FILE	"/tmp/krb5cc_gssd"
6450397Sobrien
6550397Sobrienstruct gss_resource {
66169689Skan	LIST_ENTRY(gss_resource) gr_link;
67169689Skan	uint64_t	gr_id;	/* indentifier exported to kernel */
68169689Skan	void*		gr_res;	/* GSS-API resource pointer */
69169689Skan};
70169689SkanLIST_HEAD(gss_resource_list, gss_resource) gss_resources;
71169689Skanint gss_resource_count;
72169689Skanuint32_t gss_next_id;
7350397Sobrienuint32_t gss_start_time;
74169689Skanint debug_level;
75169689Skanstatic char ccfile_dirlist[PATH_MAX + 1], ccfile_substring[NAME_MAX + 1];
76169689Skanstatic char pref_realm[1024];
77169689Skanstatic int verbose;
78169689Skanstatic int use_old_des;
7950397Sobrienstatic int hostbased_initiator_cred;
80169689Skan#ifndef WITHOUT_KERBEROS
81169689Skan/* 1.2.752.43.13.14 */
82169689Skanstatic gss_OID_desc gss_krb5_set_allowable_enctypes_x_desc =
83169689Skan{6, (void *) "\x2a\x85\x70\x2b\x0d\x0e"};
84169689Skanstatic gss_OID GSS_KRB5_SET_ALLOWABLE_ENCTYPES_X =
8550397Sobrien    &gss_krb5_set_allowable_enctypes_x_desc;
8690075Sobrienstatic gss_OID_desc gss_krb5_mech_oid_x_desc =
87169689Skan{9, (void *) "\x2a\x86\x48\x86\xf7\x12\x01\x02\x02" };
88169689Skanstatic gss_OID GSS_KRB5_MECH_OID_X =
89169689Skan    &gss_krb5_mech_oid_x_desc;
90169689Skan#endif
9190075Sobrien
92169689Skanstatic void gssd_load_mech(void);
93169689Skanstatic int find_ccache_file(const char *, uid_t, char *);
94169689Skanstatic int is_a_valid_tgt_cache(const char *, uid_t, int *, time_t *);
95169689Skanstatic void gssd_verbose_out(const char *, ...);
96169689Skan#ifndef WITHOUT_KERBEROS
9790075Sobrienstatic krb5_error_code gssd_get_cc_from_keytab(const char *);
9890075Sobrienstatic OM_uint32 gssd_get_user_cred(OM_uint32 *, uid_t, gss_cred_id_t *);
9990075Sobrien#endif
100169689Skanvoid gssd_terminate(int);
101169689Skan
10250397Sobrienextern void gssd_1(struct svc_req *rqstp, SVCXPRT *transp);
10390075Sobrienextern int gssd_syscall(char *path);
10450397Sobrien
10550397Sobrienint
10690075Sobrienmain(int argc, char **argv)
10750397Sobrien{
108169689Skan	/*
10950397Sobrien	 * We provide an RPC service on a local-domain socket. The
11050397Sobrien	 * kernel's GSS-API code will pass what it can't handle
11150397Sobrien	 * directly to us.
11250397Sobrien	 */
11350397Sobrien	struct sockaddr_un sun;
11450397Sobrien	int fd, oldmask, ch, debug;
11590075Sobrien	SVCXPRT *xprt;
11650397Sobrien
11750397Sobrien	/*
11850397Sobrien	 * Initialize the credential cache file name substring and the
11950397Sobrien	 * search directory list.
12050397Sobrien	 */
12150397Sobrien	strlcpy(ccfile_substring, "krb5cc_", sizeof(ccfile_substring));
12290075Sobrien	ccfile_dirlist[0] = '\0';
12390075Sobrien	pref_realm[0] = '\0';
12490075Sobrien	debug = 0;
12590075Sobrien	verbose = 0;
12690075Sobrien	while ((ch = getopt(argc, argv, "dhovs:c:r:")) != -1) {
12790075Sobrien		switch (ch) {
12890075Sobrien		case 'd':
12990075Sobrien			debug_level++;
13090075Sobrien			break;
13190075Sobrien		case 'h':
13290075Sobrien#ifndef WITHOUT_KERBEROS
13350397Sobrien			/*
134117395Skan			 * Enable use of a host based initiator credential
13550397Sobrien			 * in the default keytab file.
136169689Skan			 */
13790075Sobrien			hostbased_initiator_cred = 1;
138169689Skan#else
13990075Sobrien			errx(1, "This option not available when built"
14090075Sobrien			    " without MK_KERBEROS\n");
14190075Sobrien#endif
14290075Sobrien			break;
14390075Sobrien		case 'o':
14490075Sobrien#ifndef WITHOUT_KERBEROS
14590075Sobrien			/*
146117395Skan			 * Force use of DES and the old type of GSSAPI token.
14790075Sobrien			 */
14890075Sobrien			use_old_des = 1;
14990075Sobrien#else
15090075Sobrien			errx(1, "This option not available when built"
15190075Sobrien			    " without MK_KERBEROS\n");
15290075Sobrien#endif
15390075Sobrien			break;
15490075Sobrien		case 'v':
15590075Sobrien			verbose = 1;
15690075Sobrien			break;
15790075Sobrien		case 's':
158117395Skan#ifndef WITHOUT_KERBEROS
15990075Sobrien			/*
16090075Sobrien			 * Set the directory search list. This enables use of
16190075Sobrien			 * find_ccache_file() to search the directories for a
16290075Sobrien			 * suitable credentials cache file.
16390075Sobrien			 */
16490075Sobrien			strlcpy(ccfile_dirlist, optarg, sizeof(ccfile_dirlist));
165117395Skan#else
166169689Skan			errx(1, "This option not available when built"
167117395Skan			    " without MK_KERBEROS\n");
168117395Skan#endif
169117395Skan			break;
17090075Sobrien		case 'c':
17190075Sobrien			/*
172117395Skan			 * Specify a non-default credential cache file
17390075Sobrien			 * substring.
17490075Sobrien			 */
17590075Sobrien			strlcpy(ccfile_substring, optarg,
17690075Sobrien			    sizeof(ccfile_substring));
17790075Sobrien			break;
178117395Skan		case 'r':
17990075Sobrien			/*
18090075Sobrien			 * Set the preferred realm for the credential cache tgt.
18190075Sobrien			 */
18290075Sobrien			strlcpy(pref_realm, optarg, sizeof(pref_realm));
18390075Sobrien			break;
18490075Sobrien		default:
18590075Sobrien			fprintf(stderr,
18690075Sobrien			    "usage: %s [-d] [-s dir-list] [-c file-substring]"
18790075Sobrien			    " [-r preferred-realm]\n", argv[0]);
18890075Sobrien			exit(1);
18990075Sobrien			break;
19090075Sobrien		}
19190075Sobrien	}
19290075Sobrien
19390075Sobrien	gssd_load_mech();
19490075Sobrien
19590075Sobrien	if (!debug_level) {
19690075Sobrien		daemon(0, 0);
19790075Sobrien		signal(SIGINT, SIG_IGN);
19890075Sobrien		signal(SIGQUIT, SIG_IGN);
19990075Sobrien		signal(SIGHUP, SIG_IGN);
200169689Skan	}
20190075Sobrien	signal(SIGTERM, gssd_terminate);
20290075Sobrien
20390075Sobrien	memset(&sun, 0, sizeof sun);
20490075Sobrien	sun.sun_family = AF_LOCAL;
20590075Sobrien	unlink(_PATH_GSSDSOCK);
20690075Sobrien	strcpy(sun.sun_path, _PATH_GSSDSOCK);
20790075Sobrien	sun.sun_len = SUN_LEN(&sun);
208117395Skan	fd = socket(AF_LOCAL, SOCK_STREAM, 0);
20990075Sobrien	if (!fd) {
21090075Sobrien		if (debug_level == 0) {
21190075Sobrien			syslog(LOG_ERR, "Can't create local gssd socket");
21290075Sobrien			exit(1);
21390075Sobrien		}
214117395Skan		err(1, "Can't create local gssd socket");
215169689Skan	}
21690075Sobrien	oldmask = umask(S_IXUSR|S_IRWXG|S_IRWXO);
21790075Sobrien	if (bind(fd, (struct sockaddr *) &sun, sun.sun_len) < 0) {
21890075Sobrien		if (debug_level == 0) {
21990075Sobrien			syslog(LOG_ERR, "Can't bind local gssd socket");
22090075Sobrien			exit(1);
22190075Sobrien		}
22290075Sobrien		err(1, "Can't bind local gssd socket");
22390075Sobrien	}
22490075Sobrien	umask(oldmask);
22590075Sobrien	if (listen(fd, SOMAXCONN) < 0) {
22690075Sobrien		if (debug_level == 0) {
22790075Sobrien			syslog(LOG_ERR, "Can't listen on local gssd socket");
22890075Sobrien			exit(1);
22990075Sobrien		}
230117395Skan		err(1, "Can't listen on local gssd socket");
23190075Sobrien	}
23290075Sobrien	xprt = svc_vc_create(fd, RPC_MAXDATASIZE, RPC_MAXDATASIZE);
233169689Skan	if (!xprt) {
23490075Sobrien		if (debug_level == 0) {
23590075Sobrien			syslog(LOG_ERR,
23690075Sobrien			    "Can't create transport for local gssd socket");
23790075Sobrien			exit(1);
238117395Skan		}
23990075Sobrien		err(1, "Can't create transport for local gssd socket");
24090075Sobrien	}
24190075Sobrien	if (!svc_reg(xprt, GSSD, GSSDVERS, gssd_1, NULL)) {
242169689Skan		if (debug_level == 0) {
24390075Sobrien			syslog(LOG_ERR,
24490075Sobrien			    "Can't register service for local gssd socket");
24590075Sobrien			exit(1);
24690075Sobrien		}
24790075Sobrien		err(1, "Can't register service for local gssd socket");
24890075Sobrien	}
24990075Sobrien
250117395Skan	LIST_INIT(&gss_resources);
25190075Sobrien	gss_next_id = 1;
25290075Sobrien	gss_start_time = time(0);
253169689Skan
25490075Sobrien	gssd_syscall(_PATH_GSSDSOCK);
255117395Skan	svc_run();
25690075Sobrien	gssd_syscall("");
25790075Sobrien
25890075Sobrien	return (0);
25990075Sobrien}
260117395Skan
26190075Sobrienstatic void
26290075Sobriengssd_load_mech(void)
26390075Sobrien{
264169689Skan	FILE		*fp;
26590075Sobrien	char		buf[256];
26690075Sobrien	char		*p;
26790075Sobrien	char		*name, *oid, *lib, *kobj;
26890075Sobrien
26990075Sobrien	fp = fopen(_PATH_GSS_MECH, "r");
27090075Sobrien	if (!fp)
27190075Sobrien		return;
27290075Sobrien
27390075Sobrien	while (fgets(buf, sizeof(buf), fp)) {
27490075Sobrien		if (*buf == '#')
27590075Sobrien			continue;
27690075Sobrien		p = buf;
27790075Sobrien		name = strsep(&p, "\t\n ");
278117395Skan		if (p) while (isspace(*p)) p++;
27990075Sobrien		oid = strsep(&p, "\t\n ");
28090075Sobrien		if (p) while (isspace(*p)) p++;
28190075Sobrien		lib = strsep(&p, "\t\n ");
28290075Sobrien		if (p) while (isspace(*p)) p++;
28390075Sobrien		kobj = strsep(&p, "\t\n ");
284169689Skan		if (!name || !oid || !lib || !kobj)
28590075Sobrien			continue;
28690075Sobrien
28790075Sobrien		if (strcmp(kobj, "-")) {
28890075Sobrien			/*
28990075Sobrien			 * Attempt to load the kernel module if its
29090075Sobrien			 * not already present.
29190075Sobrien			 */
29290075Sobrien			if (modfind(kobj) < 0) {
29390075Sobrien				if (kldload(kobj) < 0) {
29490075Sobrien					fprintf(stderr,
29590075Sobrien			"%s: can't find or load kernel module %s for %s\n",
29690075Sobrien					    getprogname(), kobj, name);
297117395Skan				}
29890075Sobrien			}
29990075Sobrien		}
300169689Skan	}
30190075Sobrien	fclose(fp);
30290075Sobrien}
30390075Sobrien
30490075Sobrienstatic void *
30590075Sobriengssd_find_resource(uint64_t id)
30690075Sobrien{
30790075Sobrien	struct gss_resource *gr;
308117395Skan
30990075Sobrien	if (!id)
31090075Sobrien		return (NULL);
311169689Skan
31290075Sobrien	LIST_FOREACH(gr, &gss_resources, gr_link)
31390075Sobrien		if (gr->gr_id == id)
31490075Sobrien			return (gr->gr_res);
31590075Sobrien
31690075Sobrien	return (NULL);
31790075Sobrien}
318117395Skan
31990075Sobrienstatic uint64_t
32090075Sobriengssd_make_resource(void *res)
321169689Skan{
32290075Sobrien	struct gss_resource *gr;
32390075Sobrien
32490075Sobrien	if (!res)
32590075Sobrien		return (0);
32690075Sobrien
32790075Sobrien	gr = malloc(sizeof(struct gss_resource));
32890075Sobrien	if (!gr)
329117395Skan		return (0);
33090075Sobrien	gr->gr_id = (gss_next_id++) + ((uint64_t) gss_start_time << 32);
33190075Sobrien	gr->gr_res = res;
332169689Skan	LIST_INSERT_HEAD(&gss_resources, gr, gr_link);
33390075Sobrien	gss_resource_count++;
33490075Sobrien	if (debug_level > 1)
33590075Sobrien		printf("%d resources allocated\n", gss_resource_count);
33690075Sobrien
33790075Sobrien	return (gr->gr_id);
33890075Sobrien}
33990075Sobrien
340117395Skanstatic void
34190075Sobriengssd_delete_resource(uint64_t id)
34290075Sobrien{
343169689Skan	struct gss_resource *gr;
34490075Sobrien
34590075Sobrien	LIST_FOREACH(gr, &gss_resources, gr_link) {
34690075Sobrien		if (gr->gr_id == id) {
34790075Sobrien			LIST_REMOVE(gr, gr_link);
34890075Sobrien			free(gr);
34990075Sobrien			gss_resource_count--;
35090075Sobrien			if (debug_level > 1)
35190075Sobrien				printf("%d resources allocated\n",
35290075Sobrien				    gss_resource_count);
353117395Skan			return;
35490075Sobrien		}
35590075Sobrien	}
356169689Skan}
357117395Skan
35890075Sobrienstatic void
35990075Sobriengssd_verbose_out(const char *fmt, ...)
36090075Sobrien{
36190075Sobrien	va_list ap;
36290075Sobrien
36390075Sobrien	if (verbose != 0) {
364117395Skan		va_start(ap, fmt);
36590075Sobrien		if (debug_level == 0)
36690075Sobrien			vsyslog(LOG_INFO | LOG_DAEMON, fmt, ap);
367169689Skan		else
36890075Sobrien			vfprintf(stderr, fmt, ap);
36990075Sobrien		va_end(ap);
37090075Sobrien	}
37190075Sobrien}
37290075Sobrien
37390075Sobrienbool_t
374117395Skangssd_null_1_svc(void *argp, void *result, struct svc_req *rqstp)
37590075Sobrien{
37690075Sobrien
377169689Skan	gssd_verbose_out("gssd_null: done\n");
378117395Skan	return (TRUE);
37990075Sobrien}
38090075Sobrien
38190075Sobrienbool_t
38290075Sobriengssd_init_sec_context_1_svc(init_sec_context_args *argp, init_sec_context_res *result, struct svc_req *rqstp)
38390075Sobrien{
38490075Sobrien	gss_cred_id_t cred = GSS_C_NO_CREDENTIAL;
385117395Skan	gss_ctx_id_t ctx = GSS_C_NO_CONTEXT;
38690075Sobrien	gss_name_t name = GSS_C_NO_NAME;
38790075Sobrien	char ccname[PATH_MAX + 5 + 1], *cp, *cp2;
388169689Skan	int gotone, gotcred;
38990075Sobrien	OM_uint32 min_stat;
39090075Sobrien#ifndef WITHOUT_KERBEROS
39190075Sobrien	gss_buffer_desc principal_desc;
39290075Sobrien	char enctype[sizeof(uint32_t)];
39390075Sobrien	int key_enctype;
39490075Sobrien	OM_uint32 maj_stat;
395117395Skan#endif
39690075Sobrien
39790075Sobrien	memset(result, 0, sizeof(*result));
398169689Skan	if (hostbased_initiator_cred != 0 && argp->cred != 0 &&
39990075Sobrien	    argp->uid == 0) {
40090075Sobrien		/*
40190075Sobrien		 * These credentials are for a host based initiator name
40290075Sobrien		 * in a keytab file, which should now have credentials
40390075Sobrien		 * in /tmp/krb5cc_gssd, because gss_acquire_cred() did
40490075Sobrien		 * the equivalent of "kinit -k".
40590075Sobrien		 */
40690075Sobrien		snprintf(ccname, sizeof(ccname), "FILE:%s",
40790075Sobrien		    GSSD_CREDENTIAL_CACHE_FILE);
40850397Sobrien	} else if (ccfile_dirlist[0] != '\0' && argp->cred == 0) {
40950397Sobrien		/*
41050397Sobrien		 * For the "-s" case and no credentials provided as an
41150397Sobrien		 * argument, search the directory list for an appropriate
41250397Sobrien		 * credential cache file. If the search fails, return failure.
41350397Sobrien		 */
41450397Sobrien		gotone = 0;
41550397Sobrien		cp = ccfile_dirlist;
416169689Skan		do {
41750397Sobrien			cp2 = strchr(cp, ':');
41850397Sobrien			if (cp2 != NULL)
41950397Sobrien				*cp2 = '\0';
42050397Sobrien			gotone = find_ccache_file(cp, argp->uid, ccname);
42150397Sobrien			if (gotone != 0)
422117395Skan				break;
42350397Sobrien			if (cp2 != NULL)
424169689Skan				*cp2++ = ':';
42550397Sobrien			cp = cp2;
42650397Sobrien		} while (cp != NULL && *cp != '\0');
42750397Sobrien		if (gotone == 0) {
42850397Sobrien			result->major_status = GSS_S_CREDENTIALS_EXPIRED;
42950397Sobrien			gssd_verbose_out("gssd_init_sec_context: -s no"
43050397Sobrien			    " credential cache file found for uid=%d\n",
43150397Sobrien			    (int)argp->uid);
43250397Sobrien			return (TRUE);
43390075Sobrien		}
434169689Skan	} else {
435169689Skan		/*
43650397Sobrien		 * If there wasn't a "-s" option or the credentials have
43750397Sobrien		 * been provided as an argument, do it the old way.
43850397Sobrien		 * When credentials are provided, the uid should be root.
43950397Sobrien		 */
44050397Sobrien		if (argp->cred != 0 && argp->uid != 0) {
44150397Sobrien			if (debug_level == 0)
442169689Skan				syslog(LOG_ERR, "gss_init_sec_context:"
44350397Sobrien				    " cred for non-root");
44490075Sobrien			else
44550397Sobrien				fprintf(stderr, "gss_init_sec_context:"
44650397Sobrien				    " cred for non-root\n");
44750397Sobrien		}
44850397Sobrien		snprintf(ccname, sizeof(ccname), "FILE:/tmp/krb5cc_%d",
44950397Sobrien		    (int) argp->uid);
45050397Sobrien	}
45150397Sobrien	setenv("KRB5CCNAME", ccname, TRUE);
452169689Skan
45350397Sobrien	if (argp->cred) {
45450397Sobrien		cred = gssd_find_resource(argp->cred);
45550397Sobrien		if (!cred) {
45650397Sobrien			result->major_status = GSS_S_CREDENTIALS_EXPIRED;
45750397Sobrien			gssd_verbose_out("gssd_init_sec_context: cred"
45850397Sobrien			    " resource not found\n");
45950397Sobrien			return (TRUE);
46050397Sobrien		}
461169689Skan	}
46250397Sobrien	if (argp->ctx) {
46350397Sobrien		ctx = gssd_find_resource(argp->ctx);
46450397Sobrien		if (!ctx) {
46550397Sobrien			result->major_status = GSS_S_CONTEXT_EXPIRED;
46650397Sobrien			gssd_verbose_out("gssd_init_sec_context: context"
46750397Sobrien			    " resource not found\n");
468169689Skan			return (TRUE);
46950397Sobrien		}
47050397Sobrien	}
47150397Sobrien	if (argp->name) {
47250397Sobrien		name = gssd_find_resource(argp->name);
47350397Sobrien		if (!name) {
47450397Sobrien			result->major_status = GSS_S_BAD_NAME;
47550397Sobrien			gssd_verbose_out("gssd_init_sec_context: name"
47650397Sobrien			    " resource not found\n");
477169689Skan			return (TRUE);
47850397Sobrien		}
47950397Sobrien	}
48050397Sobrien	gotcred = 0;
48150397Sobrien
48250397Sobrien#ifndef WITHOUT_KERBEROS
48350397Sobrien	if (use_old_des != 0) {
48450397Sobrien		if (cred == GSS_C_NO_CREDENTIAL) {
48550397Sobrien			/* Acquire a credential for the uid. */
486169689Skan			maj_stat = gssd_get_user_cred(&min_stat, argp->uid,
48750397Sobrien			    &cred);
48850397Sobrien			if (maj_stat == GSS_S_COMPLETE)
48950397Sobrien				gotcred = 1;
49050397Sobrien			else
491169689Skan				gssd_verbose_out("gssd_init_sec_context: "
492169689Skan				    "get user cred failed uid=%d major=0x%x "
493169689Skan				    "minor=%d\n", (int)argp->uid,
494169689Skan				    (unsigned int)maj_stat, (int)min_stat);
495169689Skan		}
496169689Skan		if (cred != GSS_C_NO_CREDENTIAL) {
497169689Skan			key_enctype = ETYPE_DES_CBC_CRC;
498169689Skan			enctype[0] = (key_enctype >> 24) & 0xff;
499169689Skan			enctype[1] = (key_enctype >> 16) & 0xff;
500169689Skan			enctype[2] = (key_enctype >> 8) & 0xff;
501169689Skan			enctype[3] = key_enctype & 0xff;
502169689Skan			principal_desc.length = sizeof(enctype);
503169689Skan			principal_desc.value = enctype;
504169689Skan			result->major_status = gss_set_cred_option(
505169689Skan			    &result->minor_status, &cred,
506169689Skan			    GSS_KRB5_SET_ALLOWABLE_ENCTYPES_X,
507169689Skan			    &principal_desc);
508169689Skan			gssd_verbose_out("gssd_init_sec_context: set allowable "
509169689Skan			    "enctype major=0x%x minor=%d\n",
510169689Skan			    (unsigned int)result->major_status,
511169689Skan			    (int)result->minor_status);
512169689Skan			if (result->major_status != GSS_S_COMPLETE) {
513169689Skan				if (gotcred != 0)
514169689Skan					gss_release_cred(&min_stat, &cred);
515169689Skan				return (TRUE);
516169689Skan			}
517169689Skan		}
518169689Skan	}
519169689Skan#endif
520169689Skan	result->major_status = gss_init_sec_context(&result->minor_status,
521169689Skan	    cred, &ctx, name, argp->mech_type,
522169689Skan	    argp->req_flags, argp->time_req, argp->input_chan_bindings,
523169689Skan	    &argp->input_token, &result->actual_mech_type,
524169689Skan	    &result->output_token, &result->ret_flags, &result->time_rec);
525169689Skan	gssd_verbose_out("gssd_init_sec_context: done major=0x%x minor=%d"
526169689Skan	    " uid=%d\n", (unsigned int)result->major_status,
527169689Skan	    (int)result->minor_status, (int)argp->uid);
528169689Skan	if (gotcred != 0)
529169689Skan		gss_release_cred(&min_stat, &cred);
530169689Skan
531169689Skan	if (result->major_status == GSS_S_COMPLETE
532169689Skan	    || result->major_status == GSS_S_CONTINUE_NEEDED) {
533169689Skan		if (argp->ctx)
534169689Skan			result->ctx = argp->ctx;
535169689Skan		else
536169689Skan			result->ctx = gssd_make_resource(ctx);
537169689Skan	}
538169689Skan
539169689Skan	return (TRUE);
540169689Skan}
541169689Skan
542169689Skanbool_t
543169689Skangssd_accept_sec_context_1_svc(accept_sec_context_args *argp, accept_sec_context_res *result, struct svc_req *rqstp)
544169689Skan{
545169689Skan	gss_ctx_id_t ctx = GSS_C_NO_CONTEXT;
546169689Skan	gss_cred_id_t cred = GSS_C_NO_CREDENTIAL;
547169689Skan	gss_name_t src_name;
548169689Skan	gss_cred_id_t delegated_cred_handle;
549169689Skan
55090075Sobrien	memset(result, 0, sizeof(*result));
55190075Sobrien	if (argp->ctx) {
552169689Skan		ctx = gssd_find_resource(argp->ctx);
553169689Skan		if (!ctx) {
55490075Sobrien			result->major_status = GSS_S_CONTEXT_EXPIRED;
555			gssd_verbose_out("gssd_accept_sec_context: ctx"
556			    " resource not found\n");
557			return (TRUE);
558		}
559	}
560	if (argp->cred) {
561		cred = gssd_find_resource(argp->cred);
562		if (!cred) {
563			result->major_status = GSS_S_CREDENTIALS_EXPIRED;
564			gssd_verbose_out("gssd_accept_sec_context: cred"
565			    " resource not found\n");
566			return (TRUE);
567		}
568	}
569
570	memset(result, 0, sizeof(*result));
571	result->major_status = gss_accept_sec_context(&result->minor_status,
572	    &ctx, cred, &argp->input_token, argp->input_chan_bindings,
573	    &src_name, &result->mech_type, &result->output_token,
574	    &result->ret_flags, &result->time_rec,
575	    &delegated_cred_handle);
576	gssd_verbose_out("gssd_accept_sec_context: done major=0x%x minor=%d\n",
577	    (unsigned int)result->major_status, (int)result->minor_status);
578
579	if (result->major_status == GSS_S_COMPLETE
580	    || result->major_status == GSS_S_CONTINUE_NEEDED) {
581		if (argp->ctx)
582			result->ctx = argp->ctx;
583		else
584			result->ctx = gssd_make_resource(ctx);
585		result->src_name = gssd_make_resource(src_name);
586		result->delegated_cred_handle =
587			gssd_make_resource(delegated_cred_handle);
588	}
589
590	return (TRUE);
591}
592
593bool_t
594gssd_delete_sec_context_1_svc(delete_sec_context_args *argp, delete_sec_context_res *result, struct svc_req *rqstp)
595{
596	gss_ctx_id_t ctx = gssd_find_resource(argp->ctx);
597
598	if (ctx) {
599		result->major_status = gss_delete_sec_context(
600			&result->minor_status, &ctx, &result->output_token);
601		gssd_delete_resource(argp->ctx);
602	} else {
603		result->major_status = GSS_S_COMPLETE;
604		result->minor_status = 0;
605	}
606	gssd_verbose_out("gssd_delete_sec_context: done major=0x%x minor=%d\n",
607	    (unsigned int)result->major_status, (int)result->minor_status);
608
609	return (TRUE);
610}
611
612bool_t
613gssd_export_sec_context_1_svc(export_sec_context_args *argp, export_sec_context_res *result, struct svc_req *rqstp)
614{
615	gss_ctx_id_t ctx = gssd_find_resource(argp->ctx);
616
617	if (ctx) {
618		result->major_status = gss_export_sec_context(
619			&result->minor_status, &ctx,
620			&result->interprocess_token);
621		result->format = KGSS_HEIMDAL_1_1;
622		gssd_delete_resource(argp->ctx);
623	} else {
624		result->major_status = GSS_S_FAILURE;
625		result->minor_status = 0;
626		result->interprocess_token.length = 0;
627		result->interprocess_token.value = NULL;
628	}
629	gssd_verbose_out("gssd_export_sec_context: done major=0x%x minor=%d\n",
630	    (unsigned int)result->major_status, (int)result->minor_status);
631
632	return (TRUE);
633}
634
635bool_t
636gssd_import_name_1_svc(import_name_args *argp, import_name_res *result, struct svc_req *rqstp)
637{
638	gss_name_t name;
639
640	result->major_status = gss_import_name(&result->minor_status,
641	    &argp->input_name_buffer, argp->input_name_type, &name);
642	gssd_verbose_out("gssd_import_name: done major=0x%x minor=%d\n",
643	    (unsigned int)result->major_status, (int)result->minor_status);
644
645	if (result->major_status == GSS_S_COMPLETE)
646		result->output_name = gssd_make_resource(name);
647	else
648		result->output_name = 0;
649
650	return (TRUE);
651}
652
653bool_t
654gssd_canonicalize_name_1_svc(canonicalize_name_args *argp, canonicalize_name_res *result, struct svc_req *rqstp)
655{
656	gss_name_t name = gssd_find_resource(argp->input_name);
657	gss_name_t output_name;
658
659	memset(result, 0, sizeof(*result));
660	if (!name) {
661		result->major_status = GSS_S_BAD_NAME;
662		return (TRUE);
663	}
664
665	result->major_status = gss_canonicalize_name(&result->minor_status,
666	    name, argp->mech_type, &output_name);
667	gssd_verbose_out("gssd_canonicalize_name: done major=0x%x minor=%d\n",
668	    (unsigned int)result->major_status, (int)result->minor_status);
669
670	if (result->major_status == GSS_S_COMPLETE)
671		result->output_name = gssd_make_resource(output_name);
672	else
673		result->output_name = 0;
674
675	return (TRUE);
676}
677
678bool_t
679gssd_export_name_1_svc(export_name_args *argp, export_name_res *result, struct svc_req *rqstp)
680{
681	gss_name_t name = gssd_find_resource(argp->input_name);
682
683	memset(result, 0, sizeof(*result));
684	if (!name) {
685		result->major_status = GSS_S_BAD_NAME;
686		gssd_verbose_out("gssd_export_name: name resource not found\n");
687		return (TRUE);
688	}
689
690	result->major_status = gss_export_name(&result->minor_status,
691	    name, &result->exported_name);
692	gssd_verbose_out("gssd_export_name: done major=0x%x minor=%d\n",
693	    (unsigned int)result->major_status, (int)result->minor_status);
694
695	return (TRUE);
696}
697
698bool_t
699gssd_release_name_1_svc(release_name_args *argp, release_name_res *result, struct svc_req *rqstp)
700{
701	gss_name_t name = gssd_find_resource(argp->input_name);
702
703	if (name) {
704		result->major_status = gss_release_name(&result->minor_status,
705		    &name);
706		gssd_delete_resource(argp->input_name);
707	} else {
708		result->major_status = GSS_S_COMPLETE;
709		result->minor_status = 0;
710	}
711	gssd_verbose_out("gssd_release_name: done major=0x%x minor=%d\n",
712	    (unsigned int)result->major_status, (int)result->minor_status);
713
714	return (TRUE);
715}
716
717bool_t
718gssd_pname_to_uid_1_svc(pname_to_uid_args *argp, pname_to_uid_res *result, struct svc_req *rqstp)
719{
720	gss_name_t name = gssd_find_resource(argp->pname);
721	uid_t uid;
722	char buf[1024], *bufp;
723	struct passwd pwd, *pw;
724	size_t buflen;
725	int error;
726	static size_t buflen_hint = 1024;
727
728	memset(result, 0, sizeof(*result));
729	if (name) {
730		result->major_status =
731			gss_pname_to_uid(&result->minor_status,
732			    name, argp->mech, &uid);
733		if (result->major_status == GSS_S_COMPLETE) {
734			result->uid = uid;
735			buflen = buflen_hint;
736			for (;;) {
737				pw = NULL;
738				bufp = buf;
739				if (buflen > sizeof(buf))
740					bufp = malloc(buflen);
741				if (bufp == NULL)
742					break;
743				error = getpwuid_r(uid, &pwd, bufp, buflen,
744				    &pw);
745				if (error != ERANGE)
746					break;
747				if (buflen > sizeof(buf))
748					free(bufp);
749				buflen += 1024;
750				if (buflen > buflen_hint)
751					buflen_hint = buflen;
752			}
753			if (pw) {
754				int len = NGROUPS;
755				int groups[NGROUPS];
756				result->gid = pw->pw_gid;
757				getgrouplist(pw->pw_name, pw->pw_gid,
758				    groups, &len);
759				result->gidlist.gidlist_len = len;
760				result->gidlist.gidlist_val =
761					mem_alloc(len * sizeof(int));
762				memcpy(result->gidlist.gidlist_val, groups,
763				    len * sizeof(int));
764				gssd_verbose_out("gssd_pname_to_uid: mapped"
765				    " to uid=%d, gid=%d\n", (int)result->uid,
766				    (int)result->gid);
767			} else {
768				result->gid = 65534;
769				result->gidlist.gidlist_len = 0;
770				result->gidlist.gidlist_val = NULL;
771				gssd_verbose_out("gssd_pname_to_uid: mapped"
772				    " to uid=%d, but no groups\n",
773				    (int)result->uid);
774			}
775			if (bufp != NULL && buflen > sizeof(buf))
776				free(bufp);
777		} else
778			gssd_verbose_out("gssd_pname_to_uid: failed major=0x%x"
779			    " minor=%d\n", (unsigned int)result->major_status,
780			    (int)result->minor_status);
781	} else {
782		result->major_status = GSS_S_BAD_NAME;
783		result->minor_status = 0;
784		gssd_verbose_out("gssd_pname_to_uid: no name\n");
785	}
786
787	return (TRUE);
788}
789
790bool_t
791gssd_acquire_cred_1_svc(acquire_cred_args *argp, acquire_cred_res *result, struct svc_req *rqstp)
792{
793	gss_name_t desired_name = GSS_C_NO_NAME;
794	gss_cred_id_t cred;
795	char ccname[PATH_MAX + 5 + 1], *cp, *cp2;
796	int gotone;
797#ifndef WITHOUT_KERBEROS
798	gss_buffer_desc namebuf;
799	uint32_t minstat;
800	krb5_error_code kret;
801#endif
802
803	memset(result, 0, sizeof(*result));
804	if (argp->desired_name) {
805		desired_name = gssd_find_resource(argp->desired_name);
806		if (!desired_name) {
807			result->major_status = GSS_S_BAD_NAME;
808			gssd_verbose_out("gssd_acquire_cred: no desired name"
809			    " found\n");
810			return (TRUE);
811		}
812	}
813
814#ifndef WITHOUT_KERBEROS
815	if (hostbased_initiator_cred != 0 && argp->desired_name != 0 &&
816	    argp->uid == 0 && argp->cred_usage == GSS_C_INITIATE) {
817		/* This is a host based initiator name in the keytab file. */
818		snprintf(ccname, sizeof(ccname), "FILE:%s",
819		    GSSD_CREDENTIAL_CACHE_FILE);
820		setenv("KRB5CCNAME", ccname, TRUE);
821		result->major_status = gss_display_name(&result->minor_status,
822		    desired_name, &namebuf, NULL);
823		gssd_verbose_out("gssd_acquire_cred: desired name for host "
824		    "based initiator cred major=0x%x minor=%d\n",
825		    (unsigned int)result->major_status,
826		    (int)result->minor_status);
827		if (result->major_status != GSS_S_COMPLETE)
828			return (TRUE);
829		if (namebuf.length > PATH_MAX + 5) {
830			result->minor_status = 0;
831			result->major_status = GSS_S_FAILURE;
832			return (TRUE);
833		}
834		memcpy(ccname, namebuf.value, namebuf.length);
835		ccname[namebuf.length] = '\0';
836		if ((cp = strchr(ccname, '@')) != NULL)
837			*cp = '/';
838		kret = gssd_get_cc_from_keytab(ccname);
839		gssd_verbose_out("gssd_acquire_cred: using keytab entry for "
840		    "%s, kerberos ret=%d\n", ccname, (int)kret);
841		gss_release_buffer(&minstat, &namebuf);
842		if (kret != 0) {
843			result->minor_status = kret;
844			result->major_status = GSS_S_FAILURE;
845			return (TRUE);
846		}
847	} else
848#endif /* !WITHOUT_KERBEROS */
849	if (ccfile_dirlist[0] != '\0' && argp->desired_name == 0) {
850		/*
851		 * For the "-s" case and no name provided as an
852		 * argument, search the directory list for an appropriate
853		 * credential cache file. If the search fails, return failure.
854		 */
855		gotone = 0;
856		cp = ccfile_dirlist;
857		do {
858			cp2 = strchr(cp, ':');
859			if (cp2 != NULL)
860				*cp2 = '\0';
861			gotone = find_ccache_file(cp, argp->uid, ccname);
862			if (gotone != 0)
863				break;
864			if (cp2 != NULL)
865				*cp2++ = ':';
866			cp = cp2;
867		} while (cp != NULL && *cp != '\0');
868		if (gotone == 0) {
869			result->major_status = GSS_S_CREDENTIALS_EXPIRED;
870			gssd_verbose_out("gssd_acquire_cred: no cred cache"
871			    " file found\n");
872			return (TRUE);
873		}
874		setenv("KRB5CCNAME", ccname, TRUE);
875	} else {
876		/*
877		 * If there wasn't a "-s" option or the name has
878		 * been provided as an argument, do it the old way.
879		 * When a name is provided, it will normally exist in the
880		 * default keytab file and the uid will be root.
881		 */
882		if (argp->desired_name != 0 && argp->uid != 0) {
883			if (debug_level == 0)
884				syslog(LOG_ERR, "gss_acquire_cred:"
885				    " principal_name for non-root");
886			else
887				fprintf(stderr, "gss_acquire_cred:"
888				    " principal_name for non-root\n");
889		}
890		snprintf(ccname, sizeof(ccname), "FILE:/tmp/krb5cc_%d",
891		    (int) argp->uid);
892		setenv("KRB5CCNAME", ccname, TRUE);
893	}
894
895	result->major_status = gss_acquire_cred(&result->minor_status,
896	    desired_name, argp->time_req, argp->desired_mechs,
897	    argp->cred_usage, &cred, &result->actual_mechs, &result->time_rec);
898	gssd_verbose_out("gssd_acquire_cred: done major=0x%x minor=%d\n",
899	    (unsigned int)result->major_status, (int)result->minor_status);
900
901	if (result->major_status == GSS_S_COMPLETE)
902		result->output_cred = gssd_make_resource(cred);
903	else
904		result->output_cred = 0;
905
906	return (TRUE);
907}
908
909bool_t
910gssd_set_cred_option_1_svc(set_cred_option_args *argp, set_cred_option_res *result, struct svc_req *rqstp)
911{
912	gss_cred_id_t cred = gssd_find_resource(argp->cred);
913
914	memset(result, 0, sizeof(*result));
915	if (!cred) {
916		result->major_status = GSS_S_CREDENTIALS_EXPIRED;
917		gssd_verbose_out("gssd_set_cred: no credentials\n");
918		return (TRUE);
919	}
920
921	result->major_status = gss_set_cred_option(&result->minor_status,
922	    &cred, argp->option_name, &argp->option_value);
923	gssd_verbose_out("gssd_set_cred: done major=0x%x minor=%d\n",
924	    (unsigned int)result->major_status, (int)result->minor_status);
925
926	return (TRUE);
927}
928
929bool_t
930gssd_release_cred_1_svc(release_cred_args *argp, release_cred_res *result, struct svc_req *rqstp)
931{
932	gss_cred_id_t cred = gssd_find_resource(argp->cred);
933
934	if (cred) {
935		result->major_status = gss_release_cred(&result->minor_status,
936		    &cred);
937		gssd_delete_resource(argp->cred);
938	} else {
939		result->major_status = GSS_S_COMPLETE;
940		result->minor_status = 0;
941	}
942	gssd_verbose_out("gssd_release_cred: done major=0x%x minor=%d\n",
943	    (unsigned int)result->major_status, (int)result->minor_status);
944
945	return (TRUE);
946}
947
948bool_t
949gssd_display_status_1_svc(display_status_args *argp, display_status_res *result, struct svc_req *rqstp)
950{
951
952	result->message_context = argp->message_context;
953	result->major_status = gss_display_status(&result->minor_status,
954	    argp->status_value, argp->status_type, argp->mech_type,
955	    &result->message_context, &result->status_string);
956	gssd_verbose_out("gssd_display_status: done major=0x%x minor=%d\n",
957	    (unsigned int)result->major_status, (int)result->minor_status);
958
959	return (TRUE);
960}
961
962int
963gssd_1_freeresult(SVCXPRT *transp, xdrproc_t xdr_result, caddr_t result)
964{
965	/*
966	 * We don't use XDR to free the results - anything which was
967	 * allocated came from GSS-API. We use xdr_result to figure
968	 * out what to do.
969	 */
970	OM_uint32 junk;
971
972	if (xdr_result == (xdrproc_t) xdr_init_sec_context_res) {
973		init_sec_context_res *p = (init_sec_context_res *) result;
974		gss_release_buffer(&junk, &p->output_token);
975	} else if (xdr_result == (xdrproc_t) xdr_accept_sec_context_res) {
976		accept_sec_context_res *p = (accept_sec_context_res *) result;
977		gss_release_buffer(&junk, &p->output_token);
978	} else if (xdr_result == (xdrproc_t) xdr_delete_sec_context_res) {
979		delete_sec_context_res *p = (delete_sec_context_res *) result;
980		gss_release_buffer(&junk, &p->output_token);
981	} else if (xdr_result == (xdrproc_t) xdr_export_sec_context_res) {
982		export_sec_context_res *p = (export_sec_context_res *) result;
983		if (p->interprocess_token.length)
984			memset(p->interprocess_token.value, 0,
985			    p->interprocess_token.length);
986		gss_release_buffer(&junk, &p->interprocess_token);
987	} else if (xdr_result == (xdrproc_t) xdr_export_name_res) {
988		export_name_res *p = (export_name_res *) result;
989		gss_release_buffer(&junk, &p->exported_name);
990	} else if (xdr_result == (xdrproc_t) xdr_acquire_cred_res) {
991		acquire_cred_res *p = (acquire_cred_res *) result;
992		gss_release_oid_set(&junk, &p->actual_mechs);
993	} else if (xdr_result == (xdrproc_t) xdr_pname_to_uid_res) {
994		pname_to_uid_res *p = (pname_to_uid_res *) result;
995		if (p->gidlist.gidlist_val)
996			free(p->gidlist.gidlist_val);
997	} else if (xdr_result == (xdrproc_t) xdr_display_status_res) {
998		display_status_res *p = (display_status_res *) result;
999		gss_release_buffer(&junk, &p->status_string);
1000	}
1001
1002	return (TRUE);
1003}
1004
1005/*
1006 * Search a directory for the most likely candidate to be used as the
1007 * credential cache for a uid. If successful, return 1 and fill the
1008 * file's path id into "rpath". Otherwise, return 0.
1009 */
1010static int
1011find_ccache_file(const char *dirpath, uid_t uid, char *rpath)
1012{
1013	DIR *dirp;
1014	struct dirent *dp;
1015	struct stat sb;
1016	time_t exptime, oexptime;
1017	int gotone, len, rating, orating;
1018	char namepath[PATH_MAX + 5 + 1];
1019	char retpath[PATH_MAX + 5 + 1];
1020
1021	dirp = opendir(dirpath);
1022	if (dirp == NULL)
1023		return (0);
1024	gotone = 0;
1025	orating = 0;
1026	oexptime = 0;
1027	while ((dp = readdir(dirp)) != NULL) {
1028		len = snprintf(namepath, sizeof(namepath), "%s/%s", dirpath,
1029		    dp->d_name);
1030		if (len < sizeof(namepath) &&
1031		    (hostbased_initiator_cred == 0 || strcmp(namepath,
1032		     GSSD_CREDENTIAL_CACHE_FILE) != 0) &&
1033		    strstr(dp->d_name, ccfile_substring) != NULL &&
1034		    lstat(namepath, &sb) >= 0 &&
1035		    sb.st_uid == uid &&
1036		    S_ISREG(sb.st_mode)) {
1037			len = snprintf(namepath, sizeof(namepath), "FILE:%s/%s",
1038			    dirpath, dp->d_name);
1039			if (len < sizeof(namepath) &&
1040			    is_a_valid_tgt_cache(namepath, uid, &rating,
1041			    &exptime) != 0) {
1042				if (gotone == 0 || rating > orating ||
1043				    (rating == orating && exptime > oexptime)) {
1044					orating = rating;
1045					oexptime = exptime;
1046					strcpy(retpath, namepath);
1047					gotone = 1;
1048				}
1049			}
1050		}
1051	}
1052	closedir(dirp);
1053	if (gotone != 0) {
1054		strcpy(rpath, retpath);
1055		return (1);
1056	}
1057	return (0);
1058}
1059
1060/*
1061 * Try to determine if the file is a valid tgt cache file.
1062 * Check that the file has a valid tgt for a principal.
1063 * If it does, return 1, otherwise return 0.
1064 * It also returns a "rating" and the expiry time for the TGT, when found.
1065 * This "rating" is higher based on heuristics that make it more
1066 * likely to be the correct credential cache file to use. It can
1067 * be used by the caller, along with expiry time, to select from
1068 * multiple credential cache files.
1069 */
1070static int
1071is_a_valid_tgt_cache(const char *filepath, uid_t uid, int *retrating,
1072    time_t *retexptime)
1073{
1074#ifndef WITHOUT_KERBEROS
1075	krb5_context context;
1076	krb5_principal princ;
1077	krb5_ccache ccache;
1078	krb5_error_code retval;
1079	krb5_cc_cursor curse;
1080	krb5_creds krbcred;
1081	int gotone, orating, rating, ret;
1082	struct passwd *pw;
1083	char *cp, *cp2, *pname;
1084	time_t exptime;
1085
1086	/* Find a likely name for the uid principal. */
1087	pw = getpwuid(uid);
1088
1089	/*
1090	 * Do a bunch of krb5 library stuff to try and determine if
1091	 * this file is a credentials cache with an appropriate TGT
1092	 * in it.
1093	 */
1094	retval = krb5_init_context(&context);
1095	if (retval != 0)
1096		return (0);
1097	retval = krb5_cc_resolve(context, filepath, &ccache);
1098	if (retval != 0) {
1099		krb5_free_context(context);
1100		return (0);
1101	}
1102	ret = 0;
1103	orating = 0;
1104	exptime = 0;
1105	retval = krb5_cc_start_seq_get(context, ccache, &curse);
1106	if (retval == 0) {
1107		while ((retval = krb5_cc_next_cred(context, ccache, &curse,
1108		    &krbcred)) == 0) {
1109			gotone = 0;
1110			rating = 0;
1111			retval = krb5_unparse_name(context, krbcred.server,
1112			    &pname);
1113			if (retval == 0) {
1114				cp = strchr(pname, '/');
1115				if (cp != NULL) {
1116					*cp++ = '\0';
1117					if (strcmp(pname, "krbtgt") == 0 &&
1118					    krbcred.times.endtime > time(NULL)
1119					    ) {
1120						gotone = 1;
1121						/*
1122						 * Test to see if this is a
1123						 * tgt for cross-realm auth.
1124						 * Rate it higher, if it is not.
1125						 */
1126						cp2 = strchr(cp, '@');
1127						if (cp2 != NULL) {
1128							*cp2++ = '\0';
1129							if (strcmp(cp, cp2) ==
1130							    0)
1131								rating++;
1132						}
1133					}
1134				}
1135				free(pname);
1136			}
1137			if (gotone != 0) {
1138				retval = krb5_unparse_name(context,
1139				    krbcred.client, &pname);
1140				if (retval == 0) {
1141					cp = strchr(pname, '@');
1142					if (cp != NULL) {
1143						*cp++ = '\0';
1144						if (pw != NULL && strcmp(pname,
1145						    pw->pw_name) == 0)
1146							rating++;
1147						if (strchr(pname, '/') == NULL)
1148							rating++;
1149						if (pref_realm[0] != '\0' &&
1150						    strcmp(cp, pref_realm) == 0)
1151							rating++;
1152					}
1153				}
1154				free(pname);
1155				if (rating > orating) {
1156					orating = rating;
1157					exptime = krbcred.times.endtime;
1158				} else if (rating == orating &&
1159				    krbcred.times.endtime > exptime)
1160					exptime = krbcred.times.endtime;
1161				ret = 1;
1162			}
1163			krb5_free_cred_contents(context, &krbcred);
1164		}
1165		krb5_cc_end_seq_get(context, ccache, &curse);
1166	}
1167	krb5_cc_close(context, ccache);
1168	krb5_free_context(context);
1169	if (ret != 0) {
1170		*retrating = orating;
1171		*retexptime = exptime;
1172	}
1173	return (ret);
1174#else /* WITHOUT_KERBEROS */
1175	return (0);
1176#endif /* !WITHOUT_KERBEROS */
1177}
1178
1179#ifndef WITHOUT_KERBEROS
1180/*
1181 * This function attempts to do essentially a "kinit -k" for the principal
1182 * name provided as the argument, so that there will be a TGT in the
1183 * credential cache.
1184 */
1185static krb5_error_code
1186gssd_get_cc_from_keytab(const char *name)
1187{
1188	krb5_error_code ret, opt_ret, princ_ret, cc_ret, kt_ret, cred_ret;
1189	krb5_context context;
1190	krb5_principal principal;
1191	krb5_keytab kt;
1192	krb5_creds cred;
1193	krb5_get_init_creds_opt *opt;
1194	krb5_deltat start_time = 0;
1195	krb5_ccache ccache;
1196
1197	ret = krb5_init_context(&context);
1198	if (ret != 0)
1199		return (ret);
1200	opt_ret = cc_ret = kt_ret = cred_ret = 1;	/* anything non-zero */
1201	princ_ret = ret = krb5_parse_name(context, name, &principal);
1202	if (ret == 0)
1203		opt_ret = ret = krb5_get_init_creds_opt_alloc(context, &opt);
1204	if (ret == 0)
1205		cc_ret = ret = krb5_cc_default(context, &ccache);
1206	if (ret == 0)
1207		ret = krb5_cc_initialize(context, ccache, principal);
1208	if (ret == 0) {
1209		krb5_get_init_creds_opt_set_default_flags(context, "gssd",
1210		    krb5_principal_get_realm(context, principal), opt);
1211		kt_ret = ret = krb5_kt_default(context, &kt);
1212	}
1213	if (ret == 0)
1214		cred_ret = ret = krb5_get_init_creds_keytab(context, &cred,
1215		    principal, kt, start_time, NULL, opt);
1216	if (ret == 0)
1217		ret = krb5_cc_store_cred(context, ccache, &cred);
1218	if (kt_ret == 0)
1219		krb5_kt_close(context, kt);
1220	if (cc_ret == 0)
1221		krb5_cc_close(context, ccache);
1222	if (opt_ret == 0)
1223		krb5_get_init_creds_opt_free(context, opt);
1224	if (princ_ret == 0)
1225		krb5_free_principal(context, principal);
1226	if (cred_ret == 0)
1227		krb5_free_cred_contents(context, &cred);
1228	krb5_free_context(context);
1229	return (ret);
1230}
1231
1232/*
1233 * Acquire a gss credential for a uid.
1234 */
1235static OM_uint32
1236gssd_get_user_cred(OM_uint32 *min_statp, uid_t uid, gss_cred_id_t *credp)
1237{
1238	gss_buffer_desc principal_desc;
1239	gss_name_t name;
1240	OM_uint32 maj_stat, min_stat;
1241	gss_OID_set mechlist;
1242	struct passwd *pw;
1243
1244	pw = getpwuid(uid);
1245	if (pw == NULL) {
1246		*min_statp = 0;
1247		return (GSS_S_FAILURE);
1248	}
1249
1250	/*
1251	 * The mechanism must be set to KerberosV for acquisition
1252	 * of credentials to work reliably.
1253	 */
1254	maj_stat = gss_create_empty_oid_set(min_statp, &mechlist);
1255	if (maj_stat != GSS_S_COMPLETE)
1256		return (maj_stat);
1257	maj_stat = gss_add_oid_set_member(min_statp, GSS_KRB5_MECH_OID_X,
1258	    &mechlist);
1259	if (maj_stat != GSS_S_COMPLETE) {
1260		gss_release_oid_set(&min_stat, &mechlist);
1261		return (maj_stat);
1262	}
1263
1264	principal_desc.value = (void *)pw->pw_name;
1265	principal_desc.length = strlen(pw->pw_name);
1266	maj_stat = gss_import_name(min_statp, &principal_desc,
1267	    GSS_C_NT_USER_NAME, &name);
1268	if (maj_stat != GSS_S_COMPLETE) {
1269		gss_release_oid_set(&min_stat, &mechlist);
1270		return (maj_stat);
1271	}
1272	/* Acquire the credentials. */
1273	maj_stat = gss_acquire_cred(min_statp, name, 0, mechlist,
1274	    GSS_C_INITIATE, credp, NULL, NULL);
1275	gss_release_name(&min_stat, &name);
1276	gss_release_oid_set(&min_stat, &mechlist);
1277	return (maj_stat);
1278}
1279#endif /* !WITHOUT_KERBEROS */
1280
1281void gssd_terminate(int sig __unused)
1282{
1283
1284#ifndef WITHOUT_KERBEROS
1285	if (hostbased_initiator_cred != 0)
1286		unlink(GSSD_CREDENTIAL_CACHE_FILE);
1287#endif
1288	gssd_syscall("");
1289	exit(0);
1290}
1291
1292