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