Home | History | Annotate | Line # | Download | only in su
su.c revision 1.62
      1 /*	$NetBSD: su.c,v 1.62 2005/01/08 22:16:23 manu Exp $	*/
      2 
      3 /*
      4  * Copyright (c) 1988 The Regents of the University of California.
      5  * All rights reserved.
      6  *
      7  * Redistribution and use in source and binary forms, with or without
      8  * modification, are permitted provided that the following conditions
      9  * are met:
     10  * 1. Redistributions of source code must retain the above copyright
     11  *    notice, this list of conditions and the following disclaimer.
     12  * 2. Redistributions in binary form must reproduce the above copyright
     13  *    notice, this list of conditions and the following disclaimer in the
     14  *    documentation and/or other materials provided with the distribution.
     15  * 3. Neither the name of the University nor the names of its contributors
     16  *    may be used to endorse or promote products derived from this software
     17  *    without specific prior written permission.
     18  *
     19  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
     20  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     21  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     22  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
     23  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     24  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     25  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     26  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     27  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     28  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     29  * SUCH DAMAGE.
     30  */
     31 
     32 #include <sys/cdefs.h>
     33 #ifndef lint
     34 __COPYRIGHT(
     35     "@(#) Copyright (c) 1988 The Regents of the University of California.\n\
     36  All rights reserved.\n");
     37 #endif /* not lint */
     38 
     39 #ifndef lint
     40 #if 0
     41 static char sccsid[] = "@(#)su.c	8.3 (Berkeley) 4/2/94";*/
     42 #else
     43 __RCSID("$NetBSD: su.c,v 1.62 2005/01/08 22:16:23 manu Exp $");
     44 #endif
     45 #endif /* not lint */
     46 
     47 #include <sys/param.h>
     48 #include <sys/time.h>
     49 #ifdef USE_PAM
     50 #include <sys/wait.h>
     51 #endif
     52 #include <sys/resource.h>
     53 #include <err.h>
     54 #include <errno.h>
     55 #include <grp.h>
     56 #include <paths.h>
     57 #include <pwd.h>
     58 #include <stdio.h>
     59 #ifdef SKEY
     60 #include <skey.h>
     61 #endif
     62 #include <stdlib.h>
     63 #include <string.h>
     64 #include <syslog.h>
     65 #include <time.h>
     66 #include <tzfile.h>
     67 #include <unistd.h>
     68 
     69 #ifdef USE_PAM
     70 #include <security/pam_appl.h>
     71 #include <security/openpam.h>   /* for openpam_ttyconv() */
     72 
     73 static pam_handle_t *pamh;
     74 static struct pam_conv pamc;
     75 
     76 #define fatal(x) do { \
     77 	if (pam_err == PAM_SUCCESS) \
     78 		pam_end(pamh, pam_err); \
     79 	err x;  \
     80 } while (/*CONSTCOND*/ 0)
     81 #define fatalx(x) do { \
     82 	if (pam_err == PAM_SUCCESS) \
     83 		pam_end(pamh, pam_err); \
     84 	errx x; \
     85 } while (/*CONSTCOND*/ 0)
     86 
     87 #else
     88 #define fatal(x) err x
     89 #define fatalx(x) errx x
     90 
     91 #endif
     92 
     93 #ifdef LOGIN_CAP
     94 #include <login_cap.h>
     95 #endif
     96 
     97 #ifdef KERBEROS
     98 #include <des.h>
     99 #include <krb.h>
    100 #include <netdb.h>
    101 
    102 static int kerberos __P((char *, char *, int));
    103 static int koktologin __P((char *, char *, char *));
    104 
    105 #endif
    106 
    107 #ifdef KERBEROS5
    108 #include <krb5.h>
    109 
    110 static int kerberos5 __P((char *, char *, int));
    111 
    112 #endif
    113 
    114 #if defined(KERBEROS) || defined(KERBEROS5)
    115 
    116 #define	ARGSTRX	"-Kdflm"
    117 
    118 int use_kerberos = 1;
    119 
    120 #else
    121 #define	ARGSTRX	"-dflm"
    122 #endif
    123 
    124 #ifndef	SU_GROUP
    125 #define	SU_GROUP	"wheel"
    126 #endif
    127 
    128 #ifdef LOGIN_CAP
    129 #define ARGSTR	ARGSTRX "c:"
    130 #else
    131 #define ARGSTR ARGSTRX
    132 #endif
    133 
    134 int main __P((int, char **));
    135 
    136 static int chshell __P((const char *));
    137 static char *ontty __P((void));
    138 static int check_ingroup __P((int, const char *, const char *, int));
    139 
    140 
    141 int
    142 main(argc, argv)
    143 	int argc;
    144 	char **argv;
    145 {
    146 	extern char **environ;
    147 	struct passwd *pwd;
    148 	char *p;
    149 #ifdef BSD4_4
    150 	struct timeval tp;
    151 #endif
    152 	uid_t ruid;
    153 	int asme, ch, asthem, fastlogin, prio, gohome;
    154 	enum { UNSET, YES, NO } iscsh = UNSET;
    155 	char *user, *shell, *avshell, *username, **np;
    156 	char *userpass, *class;
    157 	char shellbuf[MAXPATHLEN], avshellbuf[MAXPATHLEN];
    158 	time_t pw_warntime = _PASSWORD_WARNDAYS * SECSPERDAY;
    159 #ifdef LOGIN_CAP
    160 	login_cap_t *lc;
    161 #endif
    162 #ifdef USE_PAM
    163 	char **pam_envlist, **pam_env;
    164 	char hostname[MAXHOSTNAMELEN];
    165 	const char **usernamep;
    166 	char *tty;
    167 	int pam_err, status;
    168 	pid_t pid;
    169 #ifdef notdef
    170 	extern int _openpam_debug;
    171 	_openpam_debug = 1;
    172 #endif
    173 #endif
    174 
    175 	asme = asthem = fastlogin = 0;
    176 	gohome = 1;
    177 	shell = class = NULL;
    178 	while ((ch = getopt(argc, argv, ARGSTR)) != -1)
    179 		switch((char)ch) {
    180 #if defined(KERBEROS) || defined(KERBEROS5)
    181 		case 'K':
    182 			use_kerberos = 0;
    183 			break;
    184 #endif
    185 #ifdef LOGIN_CAP
    186 		case 'c':
    187 			class = optarg;
    188 			break;
    189 #endif
    190 		case 'd':
    191 			asme = 0;
    192 			asthem = 1;
    193 			gohome = 0;
    194 			break;
    195 		case 'f':
    196 			fastlogin = 1;
    197 			break;
    198 		case '-':
    199 		case 'l':
    200 			asme = 0;
    201 			asthem = 1;
    202 			break;
    203 		case 'm':
    204 			asme = 1;
    205 			asthem = 0;
    206 			break;
    207 		case '?':
    208 		default:
    209 			(void)fprintf(stderr,
    210 			    "usage: %s [%s] [login [shell arguments]]\n",
    211 			    getprogname(), ARGSTR);
    212 			exit(1);
    213 		}
    214 	argv += optind;
    215 
    216 	/* Lower the priority so su runs faster */
    217 	errno = 0;
    218 	prio = getpriority(PRIO_PROCESS, 0);
    219 	if (errno)
    220 		prio = 0;
    221 	if (prio > -2)
    222 		(void)setpriority(PRIO_PROCESS, 0, -2);
    223 	openlog("su", 0, LOG_AUTH);
    224 
    225 	/* get current login name and shell */
    226 	ruid = getuid();
    227 	username = getlogin();
    228 	/* get target login information, default to root */
    229 	user = *argv ? *argv : "root";
    230 
    231 #ifdef USE_PAM
    232 	pamc.conv = &openpam_ttyconv;
    233 	pam_start("su", user, &pamc, &pamh);
    234 
    235 	/* Fill in hostname, username and tty */
    236 	if ((pam_err = pam_set_item(pamh, PAM_RUSER, username)) != PAM_SUCCESS)
    237 		goto pam_failed;
    238 
    239 	gethostname(hostname, sizeof(hostname));
    240 	if ((pam_err = pam_set_item(pamh, PAM_RHOST, hostname)) != PAM_SUCCESS)
    241 		goto pam_failed;
    242 
    243 	tty = ttyname(STDERR_FILENO);
    244 	if ((pam_err = pam_set_item(pamh, PAM_TTY, tty)) != PAM_SUCCESS)
    245 		goto pam_failed;
    246 
    247 	/* authentication */
    248 	if ((pam_err = pam_authenticate(pamh, 0)) != PAM_SUCCESS)
    249 		goto pam_failed;
    250 
    251 	if ((pam_err = pam_acct_mgmt(pamh, 0)) == PAM_NEW_AUTHTOK_REQD)
    252 		pam_err = pam_chauthtok(pamh, PAM_CHANGE_EXPIRED_AUTHTOK);
    253 	if (pam_err != PAM_SUCCESS)
    254 		goto pam_failed;
    255 
    256 	/* Get user credentials */
    257 	if ((pam_err = pam_setcred(pamh, PAM_ESTABLISH_CRED)) != PAM_SUCCESS)
    258 		goto pam_failed;
    259 
    260 	/* Open the session */
    261 	if ((pam_err = pam_open_session(pamh, 0)) != PAM_SUCCESS)
    262 		goto pam_failed;
    263 
    264 	/* New user name? */
    265 	usernamep = (const char **)&username;
    266 	pam_err = pam_get_item(pamh, PAM_USER, (const void **)usernamep);
    267 	if (pam_err != PAM_SUCCESS)
    268 		goto pam_failed;
    269 
    270 pam_failed:
    271 	/*
    272 	 * If PAM is broken, fallback to plain old authentication.
    273 	 * Do not do that on authentication errors.
    274 	 */
    275 	switch(pam_err) {
    276 	case PAM_SUCCESS:
    277 		break;
    278 
    279 	case PAM_ABORT:
    280 	case PAM_BUF_ERR:
    281 	case PAM_SYMBOL_ERR:
    282 	case PAM_SYSTEM_ERR:
    283 		warnx("PAM failed: %s", pam_strerror(pamh, pam_err));
    284 		warnx("fallback to plain old authentication");
    285 		pam_end(pamh, pam_err);
    286 		username = getlogin();
    287 		break;
    288 
    289 	default:
    290 		fatalx((1, "Sorry: %s\n", pam_strerror(pamh, pam_err)));
    291 		break;
    292 	}
    293 
    294 	/*
    295 	 * Now any failure should use fatal/fatalx instead of err/errx
    296 	 * so that pam_end() is called on errors.
    297 	 */
    298 #endif
    299 	if (username == NULL || (pwd = getpwnam(username)) == NULL ||
    300 	    pwd->pw_uid != ruid)
    301 		pwd = getpwuid(ruid);
    302 	if (pwd == NULL)
    303 		fatalx((1, "who are you?"));
    304 
    305 	username = strdup(pwd->pw_name);
    306 	userpass = strdup(pwd->pw_passwd);
    307 	if (username == NULL || userpass == NULL)
    308 		fatal((1, "strdup"));
    309 
    310 #ifdef USE_PAM
    311 	/* Get PAM environment */
    312 	if ((pam_err == PAM_SUCCESS) &&
    313 	    ((pam_envlist = pam_getenvlist(pamh)) != NULL)) {
    314 		for (pam_env = pam_envlist; *pam_env != NULL; ++pam_env) {
    315 			putenv(*pam_env);
    316 			free(*pam_env);
    317 		}
    318 		free(pam_envlist);
    319 	}
    320 #endif
    321 
    322 	if (asme) {
    323 		if (pwd->pw_shell && *pwd->pw_shell) {
    324 			strlcpy(shellbuf, pwd->pw_shell, sizeof(shellbuf));
    325 			shell = shellbuf;
    326 		} else {
    327 			shell = _PATH_BSHELL;
    328 			iscsh = NO;
    329 		}
    330 	}
    331 	np = *argv ? argv : argv-1;
    332 
    333 	if ((pwd = getpwnam(user)) == NULL)
    334 		fatalx((1, "unknown login %s", user));
    335 
    336 #ifdef LOGIN_CAP
    337 	/* force the usage of specified class */
    338 	if (class) {
    339 		if (ruid)
    340 			fatalx((1, "Only root may use -c"));
    341 
    342 		pwd->pw_class = class;
    343 	}
    344 	lc = login_getclass(pwd->pw_class);
    345 
    346 	pw_warntime = login_getcaptime(lc, "password-warn",
    347                                     _PASSWORD_WARNDAYS * SECSPERDAY,
    348                                     _PASSWORD_WARNDAYS * SECSPERDAY);
    349 #endif
    350 
    351 	if (ruid
    352 #ifdef USE_PAM
    353 	    && (pam_err != PAM_SUCCESS)
    354 #endif
    355 #ifdef KERBEROS5
    356 	    && (!use_kerberos || kerberos5(username, user, pwd->pw_uid))
    357 #endif
    358 #ifdef KERBEROS
    359 	    && (!use_kerberos || kerberos(username, user, pwd->pw_uid))
    360 #endif
    361 	    ) {
    362 		char *pass = pwd->pw_passwd;
    363 		int ok = pwd->pw_uid != 0;
    364 
    365 #ifdef SU_ROOTAUTH
    366 		/*
    367 		 * Allow those in group rootauth to su to root, by supplying
    368 		 * their own password.
    369 		 */
    370 		if (!ok) {
    371 			if ((ok = check_ingroup(-1, SU_ROOTAUTH, username, 0))) {
    372 				pass = userpass;
    373 				user = username;
    374 			}
    375 		}
    376 #endif
    377 		/*
    378 		 * Only allow those in group SU_GROUP to su to root,
    379 		 * but only if that group has any members.
    380 		 * If SU_GROUP has no members, allow anyone to su root
    381 		 */
    382 		if (!ok) {
    383 			ok = check_ingroup(-1, SU_GROUP, username, 1);
    384 		}
    385 		if (!ok)
    386 			fatalx((1,
    387 	    "you are not listed in the correct secondary group (%s) to su %s.",
    388 					    SU_GROUP, user));
    389 		/* if target requires a password, verify it */
    390 		if (*pass) {
    391 			p = getpass("Password:");
    392 #ifdef SKEY
    393 			if (strcasecmp(p, "s/key") == 0) {
    394 				if (skey_haskey(user)) {
    395 					fatalx((1,
    396 					    "Sorry, you have no s/key."));
    397 				} else {
    398 					if (skey_authenticate(user)) {
    399 						goto badlogin;
    400 					}
    401 				}
    402 
    403 			} else
    404 #endif
    405 			if (strcmp(pass, crypt(p, pass))) {
    406 #ifdef SKEY
    407 badlogin:
    408 #endif
    409 				fprintf(stderr, "Sorry\n");
    410 				syslog(LOG_WARNING,
    411 					"BAD SU %s to %s%s", username,
    412 					pwd->pw_name, ontty());
    413 				exit(1);
    414 			}
    415 		}
    416 	}
    417 
    418 	if (asme) {
    419 		/* if asme and non-standard target shell, must be root */
    420 		if (!chshell(pwd->pw_shell) && ruid)
    421 			fatalx((1,"permission denied (shell)."));
    422 	} else if (pwd->pw_shell && *pwd->pw_shell) {
    423 		shell = pwd->pw_shell;
    424 		iscsh = UNSET;
    425 	} else {
    426 		shell = _PATH_BSHELL;
    427 		iscsh = NO;
    428 	}
    429 
    430 	if ((p = strrchr(shell, '/')) != NULL)
    431 		avshell = p+1;
    432 	else
    433 		avshell = shell;
    434 
    435 	/* if we're forking a csh, we want to slightly muck the args */
    436 	if (iscsh == UNSET)
    437 		iscsh = strstr(avshell, "csh") ? YES : NO;
    438 
    439 #ifdef USE_PAM
    440 	/*
    441 	 * If PAM is in use, we must release PAM resources and close
    442 	 * the session after su child exits. That requires a fork now,
    443 	 * before we drop the root privs (needed for PAM)
    444 	 */
    445 	if (pam_err == PAM_SUCCESS) {
    446 		switch(pid = fork()) {
    447 		case -1:
    448 			fatal((1, "fork"));
    449 			break;
    450 		case 0:		/* child */
    451 			break;
    452 		default:	/* parent */
    453 			waitpid(pid, &status, 0);
    454 			pam_err = pam_close_session(pamh, 0);
    455 			pam_end(pamh, pam_err);
    456 
    457 			exit(WEXITSTATUS(status));
    458 			break;
    459 		}
    460 	}
    461 
    462 	/*
    463 	 * Everything here happens in the child, it should not
    464 	 * do any PAM operation anymore (don't use fatal/fatalx)
    465 	 */
    466 #endif
    467 	/* set permissions */
    468 #ifdef LOGIN_CAP
    469 	if (setusercontext(lc, pwd, pwd->pw_uid,
    470 	    (asthem ? (LOGIN_SETPRIORITY | LOGIN_SETUMASK) : 0) |
    471 	    LOGIN_SETRESOURCES | LOGIN_SETGROUP | LOGIN_SETUSER))
    472 		err(1, "setting user context");
    473 #else
    474 	if (setgid(pwd->pw_gid) < 0)
    475 		err(1, "setgid");
    476 	if (initgroups(user, pwd->pw_gid))
    477 		errx(1, "initgroups failed");
    478 	if (setuid(pwd->pw_uid) < 0)
    479 		err(1, "setuid");
    480 #endif
    481 
    482 	if (!asme) {
    483 		if (asthem) {
    484 			p = getenv("TERM");
    485 			/* Create an empty environment */
    486 			if ((environ = malloc(sizeof(char *))) == NULL)
    487 				err(1, NULL);
    488 			environ[0] = NULL;
    489 #ifdef LOGIN_CAP
    490 			if (setusercontext(lc, pwd, pwd->pw_uid, LOGIN_SETPATH))
    491 				err(1, "setting user context");
    492 #else
    493 			(void)setenv("PATH", _PATH_DEFPATH, 1);
    494 #endif
    495 			if (p)
    496 				(void)setenv("TERM", p, 1);
    497 			if (gohome && chdir(pwd->pw_dir) < 0)
    498 				errx(1, "no directory");
    499 		}
    500 
    501 		if (asthem || pwd->pw_uid)
    502 			(void)setenv("USER", pwd->pw_name, 1);
    503 		(void)setenv("HOME", pwd->pw_dir, 1);
    504 		(void)setenv("SHELL", shell, 1);
    505 	}
    506 	(void)setenv("SU_FROM", username, 1);
    507 
    508 	if (iscsh == YES) {
    509 		if (fastlogin)
    510 			*np-- = "-f";
    511 		if (asme)
    512 			*np-- = "-m";
    513 	} else {
    514 		if (fastlogin)
    515 			unsetenv("ENV");
    516 	}
    517 
    518 	if (asthem) {
    519 		avshellbuf[0] = '-';
    520 		(void)strlcpy(avshellbuf+1, avshell, sizeof(avshellbuf) - 1);
    521 		avshell = avshellbuf;
    522 	} else if (iscsh == YES) {
    523 		/* csh strips the first character... */
    524 		avshellbuf[0] = '_';
    525 		(void)strlcpy(avshellbuf+1, avshell, sizeof(avshellbuf) - 1);
    526 		avshell = avshellbuf;
    527 	}
    528 	*np = avshell;
    529 
    530 #ifdef BSD4_4
    531 	if (pwd->pw_change || pwd->pw_expire)
    532 		(void)gettimeofday(&tp, (struct timezone *)NULL);
    533 	if (pwd->pw_change) {
    534 		if (tp.tv_sec >= pwd->pw_change) {
    535 			(void)printf("%s -- %s's password has expired.\n",
    536 				     (ruid ? "Sorry" : "Note"), user);
    537 			if (ruid != 0)
    538 				exit(1);
    539 		} else if (pwd->pw_change - tp.tv_sec < pw_warntime)
    540 			(void)printf("Warning: %s's password expires on %s",
    541 				     user, ctime(&pwd->pw_change));
    542 	}
    543 	if (pwd->pw_expire) {
    544 		if (tp.tv_sec >= pwd->pw_expire) {
    545 			(void)printf("%s -- %s's account has expired.\n",
    546 				     (ruid ? "Sorry" : "Note"), user);
    547 			if (ruid != 0)
    548 				exit(1);
    549 		} else if (pwd->pw_expire - tp.tv_sec <
    550 		    _PASSWORD_WARNDAYS * SECSPERDAY)
    551 			(void)printf("Warning: %s's account expires on %s",
    552 				     user, ctime(&pwd->pw_expire));
    553  	}
    554 #endif
    555 	if (ruid != 0)
    556 		syslog(LOG_NOTICE, "%s to %s%s",
    557 		    username, pwd->pw_name, ontty());
    558 
    559 	/* Raise our priority back to what we had before */
    560 	(void)setpriority(PRIO_PROCESS, 0, prio);
    561 
    562 	execv(shell, np);
    563 	err(1, "%s", shell);
    564         /* NOTREACHED */
    565 }
    566 
    567 static int
    568 chshell(sh)
    569 	const char *sh;
    570 {
    571 	const char *cp;
    572 
    573 	setusershell();
    574 	while ((cp = getusershell()) != NULL)
    575 		if (!strcmp(cp, sh))
    576 			return (1);
    577 	return (0);
    578 }
    579 
    580 static char *
    581 ontty()
    582 {
    583 	char *p;
    584 	static char buf[MAXPATHLEN + 4];
    585 
    586 	buf[0] = 0;
    587 	if ((p = ttyname(STDERR_FILENO)) != NULL)
    588 		(void)snprintf(buf, sizeof buf, " on %s", p);
    589 	return (buf);
    590 }
    591 
    592 #ifdef KERBEROS5
    593 static int
    594 kerberos5(username, user, uid)
    595 	char *username, *user;
    596 	int uid;
    597 {
    598 	krb5_error_code ret;
    599 	krb5_context context;
    600 	krb5_principal princ = NULL;
    601 	krb5_ccache ccache, ccache2;
    602 	char *cc_name;
    603 	const char *filename;
    604 
    605 	ret = krb5_init_context(&context);
    606 	if (ret)
    607 		return (1);
    608 
    609 	if (strcmp (user, "root") == 0)
    610 		ret = krb5_make_principal(context, &princ,
    611 					  NULL, username, "root", NULL);
    612 	else
    613 		ret = krb5_make_principal(context, &princ,
    614 					  NULL, user, NULL);
    615 	if (ret)
    616 		goto fail;
    617 	if (!krb5_kuserok(context, princ, user) && !uid) {
    618 		warnx ("kerberos5: not in %s's ACL.", user);
    619 		goto fail;
    620 	}
    621 	ret = krb5_cc_gen_new(context, &krb5_mcc_ops, &ccache);
    622 	if (ret)
    623 		goto fail;
    624 	ret = krb5_verify_user_lrealm(context, princ, ccache, NULL, TRUE,
    625 				      NULL);
    626 	if (ret) {
    627 		krb5_cc_destroy(context, ccache);
    628 		switch (ret) {
    629 		case KRB5_LIBOS_PWDINTR :
    630 			break;
    631 		case KRB5KRB_AP_ERR_BAD_INTEGRITY:
    632 		case KRB5KRB_AP_ERR_MODIFIED:
    633 			krb5_warnx(context, "Password incorrect");
    634 			break;
    635 		default :
    636 			krb5_warn(context, ret, "krb5_verify_user");
    637 			break;
    638 		}
    639 		goto fail;
    640 	}
    641 	ret = krb5_cc_gen_new(context, &krb5_fcc_ops, &ccache2);
    642 	if (ret) {
    643 		krb5_cc_destroy(context, ccache);
    644 		goto fail;
    645 	}
    646 	ret = krb5_cc_copy_cache(context, ccache, ccache2);
    647 	if (ret) {
    648 		krb5_cc_destroy(context, ccache);
    649 		krb5_cc_destroy(context, ccache2);
    650 		goto fail;
    651 	}
    652 
    653 	filename = krb5_cc_get_name(context, ccache2);
    654 	asprintf(&cc_name, "%s:%s", krb5_cc_get_type(context, ccache2),
    655 		 filename);
    656 	if (chown (filename, uid, -1) < 0) {
    657 		warn("chown %s", filename);
    658 		free(cc_name);
    659 		krb5_cc_destroy(context, ccache);
    660 		krb5_cc_destroy(context, ccache2);
    661 		goto fail;
    662 	}
    663 
    664 	setenv("KRB5CCNAME", cc_name, 1);
    665 	free(cc_name);
    666 	krb5_cc_close(context, ccache2);
    667 	krb5_cc_destroy(context, ccache);
    668 	return (0);
    669 
    670  fail:
    671 	if (princ != NULL)
    672 		krb5_free_principal (context, princ);
    673 	krb5_free_context (context);
    674 	return (1);
    675 }
    676 #endif
    677 
    678 #ifdef KERBEROS
    679 static int
    680 kerberos(username, user, uid)
    681 	char *username, *user;
    682 	int uid;
    683 {
    684 	KTEXT_ST ticket;
    685 	AUTH_DAT authdata;
    686 	struct hostent *hp;
    687 	int kerno;
    688 	u_long faddr;
    689 	char lrealm[REALM_SZ], krbtkfile[MAXPATHLEN];
    690 	char hostname[MAXHOSTNAMELEN + 1], savehost[MAXHOSTNAMELEN + 1];
    691 
    692 	if (krb_get_lrealm(lrealm, 1) != KSUCCESS)
    693 		return (1);
    694 	if (koktologin(username, lrealm, user) && !uid) {
    695 		warnx("kerberos: not in %s's ACL.", user);
    696 		return (1);
    697 	}
    698 	(void)snprintf(krbtkfile, sizeof krbtkfile, "%s_%s_%d", TKT_ROOT,
    699 	    user, getuid());
    700 
    701 	(void)setenv("KRBTKFILE", krbtkfile, 1);
    702 	(void)krb_set_tkt_string(krbtkfile);
    703 	/*
    704 	 * Set real as well as effective ID to 0 for the moment,
    705 	 * to make the kerberos library do the right thing.
    706 	 */
    707 	if (setuid(0) < 0) {
    708 		warn("setuid");
    709 		return (1);
    710 	}
    711 
    712 	/*
    713 	 * Little trick here -- if we are su'ing to root,
    714 	 * we need to get a ticket for "xxx.root", where xxx represents
    715 	 * the name of the person su'ing.  Otherwise (non-root case),
    716 	 * we need to get a ticket for "yyy.", where yyy represents
    717 	 * the name of the person being su'd to, and the instance is null
    718 	 *
    719 	 * We should have a way to set the ticket lifetime,
    720 	 * with a system default for root.
    721 	 */
    722 	{
    723 		char prompt[128];
    724 		char passw[256];
    725 
    726 		(void)snprintf (prompt, sizeof(prompt),
    727 			  "%s's Password: ",
    728 			  krb_unparse_name_long ((uid == 0 ? username : user),
    729 						 (uid == 0 ? "root" : ""),
    730 						 lrealm));
    731 		if (des_read_pw_string (passw, sizeof (passw), prompt, 0)) {
    732 			memset (passw, 0, sizeof (passw));
    733 			return (1);
    734 		}
    735 		if (strlen(passw) == 0)
    736 			return (1); /* Empty passwords are not allowed */
    737 
    738 		kerno = krb_get_pw_in_tkt((uid == 0 ? username : user),
    739 					  (uid == 0 ? "root" : ""), lrealm,
    740 					  KRB_TICKET_GRANTING_TICKET,
    741 					  lrealm,
    742 					  DEFAULT_TKT_LIFE,
    743 					  passw);
    744 		memset (passw, 0, strlen (passw));
    745 	}
    746 
    747 	if (kerno != KSUCCESS) {
    748 		if (kerno == KDC_PR_UNKNOWN) {
    749 			warnx("kerberos: principal unknown: %s.%s@%s",
    750 				(uid == 0 ? username : user),
    751 				(uid == 0 ? "root" : ""), lrealm);
    752 			return (1);
    753 		}
    754 		warnx("kerberos: unable to su: %s", krb_err_txt[kerno]);
    755 		syslog(LOG_WARNING,
    756 		    "BAD Kerberos SU: %s to %s%s: %s",
    757 		    username, user, ontty(), krb_err_txt[kerno]);
    758 		return (1);
    759 	}
    760 
    761 	if (chown(krbtkfile, uid, -1) < 0) {
    762 		warn("chown");
    763 		(void)unlink(krbtkfile);
    764 		return (1);
    765 	}
    766 
    767 	(void)setpriority(PRIO_PROCESS, 0, -2);
    768 
    769 	if (gethostname(hostname, sizeof(hostname)) == -1) {
    770 		warn("gethostname");
    771 		dest_tkt();
    772 		return (1);
    773 	}
    774 	hostname[sizeof(hostname) - 1] = '\0';
    775 
    776 	(void)strlcpy(savehost, krb_get_phost(hostname), sizeof(savehost));
    777 	savehost[sizeof(savehost) - 1] = '\0';
    778 
    779 	kerno = krb_mk_req(&ticket, "rcmd", savehost, lrealm, 33);
    780 
    781 	if (kerno == KDC_PR_UNKNOWN) {
    782 		warnx("Warning: TGT not verified.");
    783 		syslog(LOG_WARNING,
    784 		    "%s to %s%s, TGT not verified (%s); %s.%s not registered?",
    785 		    username, user, ontty(), krb_err_txt[kerno],
    786 		    "rcmd", savehost);
    787 	} else if (kerno != KSUCCESS) {
    788 		warnx("Unable to use TGT: %s", krb_err_txt[kerno]);
    789 		syslog(LOG_WARNING, "failed su: %s to %s%s: %s",
    790 		    username, user, ontty(), krb_err_txt[kerno]);
    791 		dest_tkt();
    792 		return (1);
    793 	} else {
    794 		if (!(hp = gethostbyname(hostname))) {
    795 			warnx("can't get addr of %s", hostname);
    796 			dest_tkt();
    797 			return (1);
    798 		}
    799 		memmove((char *)&faddr, (char *)hp->h_addr, sizeof(faddr));
    800 
    801 		if ((kerno = krb_rd_req(&ticket, "rcmd", savehost, faddr,
    802 		    &authdata, "")) != KSUCCESS) {
    803 			warnx("kerberos: unable to verify rcmd ticket: %s",
    804 			    krb_err_txt[kerno]);
    805 			syslog(LOG_WARNING,
    806 			    "failed su: %s to %s%s: %s", username,
    807 			     user, ontty(), krb_err_txt[kerno]);
    808 			dest_tkt();
    809 			return (1);
    810 		}
    811 	}
    812 	return (0);
    813 }
    814 
    815 static int
    816 koktologin(name, realm, toname)
    817 	char *name, *realm, *toname;
    818 {
    819 	return krb_kuserok(name,
    820 			   strcmp (toname, "root") == 0 ? "root" : "",
    821 			   realm,
    822 			   toname);
    823 }
    824 #endif
    825 
    826 static int
    827 check_ingroup (gid, gname, user, ifempty)
    828 	int gid;
    829 	const char *gname;
    830 	const char *user;
    831 	int ifempty;
    832 {
    833 	struct group *gr;
    834 	char **g;
    835 #ifdef SU_INDIRECT_GROUP
    836 	char **gr_mem;
    837 	int n = 0;
    838 	int i = 0;
    839 #endif
    840 	int ok = 0;
    841 
    842 	if (gname == NULL)
    843 		gr = getgrgid((gid_t) gid);
    844 	else
    845 		gr = getgrnam(gname);
    846 
    847 	/*
    848 	 * XXX we are relying on the fact that we only set ifempty when
    849 	 * calling to check for SU_GROUP and that is the only time a
    850 	 * missing group is acceptable.
    851 	 */
    852 	if (gr == NULL)
    853 		return ifempty;
    854 	if (!*gr->gr_mem)		/* empty */
    855 		return ifempty;
    856 
    857 	/*
    858 	 * Ok, first see if user is in gr_mem
    859 	 */
    860 	for (g = gr->gr_mem; *g; ++g) {
    861 		if (strcmp(*g, user) == 0)
    862 			return 1;	/* ok */
    863 #ifdef SU_INDIRECT_GROUP
    864 		++n;			/* count them */
    865 #endif
    866 	}
    867 #ifdef SU_INDIRECT_GROUP
    868 	/*
    869 	 * No.
    870 	 * Now we need to duplicate the gr_mem list, and recurse for
    871 	 * each member to see if it is a group, and if so whether user is
    872 	 * in it.
    873 	 */
    874 	gr_mem = malloc((n + 1) * sizeof (char *));
    875 	for  (g = gr->gr_mem, i = 0; *g; ++g) {
    876 		gr_mem[i] = strdup(*g);
    877 		if (!gr_mem[i])
    878 			err(1, "strdup");
    879 		i++;
    880 	}
    881 	gr_mem[i++] = NULL;
    882 
    883 	for  (g = gr_mem; ok == 0 && *g; ++g) {
    884 		/*
    885 		 * If we get this far we don't accept empty/missing groups.
    886 		 */
    887 		ok = check_ingroup(-1, *g, user, 0);
    888 	}
    889 	for  (g = gr_mem; *g; ++g) {
    890 		free(*g);
    891 	}
    892 	free(gr_mem);
    893 #endif
    894 	return ok;
    895 }
    896