xref: /netbsd-src/usr.bin/su/su.c (revision 7d62b00eb9ad855ffcd7da46b41e23feb5476fac)
1 /*	$NetBSD: su.c,v 1.74 2021/10/30 11:25:30 nia 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("@(#) Copyright (c) 1988\
35  The Regents of the University of California.  All rights reserved.");
36 #endif /* not lint */
37 
38 #ifndef lint
39 #if 0
40 static char sccsid[] = "@(#)su.c	8.3 (Berkeley) 4/2/94";*/
41 #else
42 __RCSID("$NetBSD: su.c,v 1.74 2021/10/30 11:25:30 nia Exp $");
43 #endif
44 #endif /* not lint */
45 
46 #include <sys/param.h>
47 #include <sys/time.h>
48 #include <sys/resource.h>
49 #include <err.h>
50 #include <errno.h>
51 #include <grp.h>
52 #include <paths.h>
53 #include <pwd.h>
54 #include <stdio.h>
55 #ifdef SKEY
56 #include <skey.h>
57 #endif
58 #include <stdlib.h>
59 #include <string.h>
60 #include <syslog.h>
61 #include <time.h>
62 #include <tzfile.h>
63 #include <unistd.h>
64 #include <util.h>
65 
66 #ifdef LOGIN_CAP
67 #include <login_cap.h>
68 #endif
69 
70 #ifdef KERBEROS5
71 #include <krb5.h>
72 #endif
73 
74 #ifdef ALLOW_GROUP_CHANGE
75 #include "grutil.h"
76 #endif
77 #include "suutil.h"
78 
79 #ifdef KERBEROS5
80 #define	ARGSTRX	"-Kdflm"
81 static int kerberos5(char *, const char *, uid_t);
82 int use_kerberos = 1;
83 #else
84 #define	ARGSTRX	"-dflm"
85 #endif
86 
87 #ifndef	SU_GROUP
88 #define	SU_GROUP	"wheel"
89 #endif
90 
91 #define GROUP_PASSWORD	"Group Password:"
92 
93 #ifdef LOGIN_CAP
94 #define ARGSTR	ARGSTRX "c:"
95 #else
96 #define ARGSTR ARGSTRX
97 #endif
98 
99 static int check_ingroup(int, const char *, const char *, int);
100 
101 int
102 main(int argc, char **argv)
103 {
104 	extern char **environ;
105 	struct passwd *pwd;
106 	char *p;
107 #ifdef BSD4_4
108 	struct timeval tp;
109 #endif
110 	uid_t ruid;
111 	int asme, ch, asthem, fastlogin, prio, gohome;
112 	enum { UNSET, YES, NO } iscsh = UNSET;
113 	const char *user, *shell, *avshell;
114 	char *username, **np;
115 #ifdef SU_ROOTAUTH
116 	char *userpass;
117 #endif
118 	char *class;
119 	char shellbuf[MAXPATHLEN], avshellbuf[MAXPATHLEN];
120 	time_t pw_warntime = _PASSWORD_WARNDAYS * SECSPERDAY;
121 #ifdef LOGIN_CAP
122 	login_cap_t *lc;
123 #endif
124 #ifdef ALLOW_GROUP_CHANGE
125 	char *gname;
126 #endif
127 
128 	(void)setprogname(argv[0]);
129 	asme = asthem = fastlogin = 0;
130 	gohome = 1;
131 	shell = class = NULL;
132 	while ((ch = getopt(argc, argv, ARGSTR)) != -1)
133 		switch((char)ch) {
134 #ifdef KERBEROS5
135 		case 'K':
136 			use_kerberos = 0;
137 			break;
138 #endif
139 #ifdef LOGIN_CAP
140 		case 'c':
141 			class = optarg;
142 			break;
143 #endif
144 		case 'd':
145 			asme = 0;
146 			asthem = 1;
147 			gohome = 0;
148 			break;
149 		case 'f':
150 			fastlogin = 1;
151 			break;
152 		case '-':
153 		case 'l':
154 			asme = 0;
155 			asthem = 1;
156 			break;
157 		case 'm':
158 			asme = 1;
159 			asthem = 0;
160 			break;
161 		case '?':
162 		default:
163 			(void)fprintf(stderr,
164 #ifdef ALLOW_GROUP_CHANGE
165 			    "usage: %s [%s] [login[:group] [shell arguments]]\n",
166 #else
167 			    "usage: %s [%s] [login [shell arguments]]\n",
168 #endif
169 			    getprogname(), ARGSTR);
170 			exit(EXIT_FAILURE);
171 		}
172 	argv += optind;
173 
174 	/* Lower the priority so su runs faster */
175 	errno = 0;
176 	prio = getpriority(PRIO_PROCESS, 0);
177 	if (errno)
178 		prio = 0;
179 	if (prio > -2)
180 		(void)setpriority(PRIO_PROCESS, 0, -2);
181 	openlog("su", 0, LOG_AUTH);
182 
183 	/* get current login name and shell */
184 	ruid = getuid();
185 	username = getlogin();
186 	if (username == NULL || (pwd = getpwnam(username)) == NULL ||
187 	    pwd->pw_uid != ruid)
188 		pwd = getpwuid(ruid);
189 	if (pwd == NULL)
190 		errx(EXIT_FAILURE, "who are you?");
191 	username = estrdup(pwd->pw_name);
192 #ifdef SU_ROOTAUTH
193 	userpass = estrdup(pwd->pw_passwd);
194 #endif
195 
196 	if (asme) {
197 		if (pwd->pw_shell && *pwd->pw_shell) {
198 			(void)estrlcpy(shellbuf, pwd->pw_shell, sizeof(shellbuf));
199 			shell = shellbuf;
200 		} else {
201 			shell = _PATH_BSHELL;
202 			iscsh = NO;
203 		}
204 	}
205 	/* get target login information, default to root */
206 	user = *argv ? *argv : "root";
207 	np = *argv ? argv : argv - 1;
208 
209 #ifdef ALLOW_GROUP_CHANGE
210 	if ((p = strchr(user, ':')) != NULL) {
211 		*p = '\0';
212 		gname = ++p;
213 	}
214 	else
215 		gname = NULL;
216 
217 #ifdef ALLOW_EMPTY_USER
218 	if (user[0] == '\0' && gname != NULL)
219 		user = username;
220 #endif
221 #endif
222 	if ((pwd = getpwnam(user)) == NULL)
223 		errx(EXIT_FAILURE, "unknown login `%s'", user);
224 
225 #ifdef LOGIN_CAP
226 	/* force the usage of specified class */
227 	if (class) {
228 		if (ruid)
229 			errx(EXIT_FAILURE, "Only root may use -c");
230 
231 		pwd->pw_class = class;
232 	}
233 	if ((lc = login_getclass(pwd->pw_class)) == NULL)
234 		errx(EXIT_FAILURE, "Unknown class %s", pwd->pw_class);
235 
236 	pw_warntime = (time_t)login_getcaptime(lc, "password-warn",
237 	    _PASSWORD_WARNDAYS * SECSPERDAY,
238 	    _PASSWORD_WARNDAYS * SECSPERDAY);
239 #endif
240 
241 	if (ruid
242 #ifdef KERBEROS5
243 	    && (!use_kerberos || kerberos5(username, user, pwd->pw_uid))
244 #endif
245 	    ) {
246 		char *pass = pwd->pw_passwd;
247 		int ok = pwd->pw_uid != 0;
248 
249 #ifdef SU_ROOTAUTH
250 		/*
251 		 * Allow those in group rootauth to su to root, by supplying
252 		 * their own password.
253 		 */
254 		if (!ok) {
255 			if ((ok = check_ingroup(-1, SU_ROOTAUTH, username, 0))) {
256 				pass = userpass;
257 				user = username;
258 			}
259 		}
260 #endif
261 		/*
262 		 * Only allow those in group SU_GROUP to su to root,
263 		 * but only if that group has any members.
264 		 * If SU_GROUP has no members, allow anyone to su root
265 		 */
266 		if (!ok)
267 			ok = check_ingroup(-1, SU_GROUP, username, 1);
268 		if (!ok)
269 			errx(EXIT_FAILURE,
270 	    "you are not listed in the correct secondary group (%s) to su %s.",
271 					    SU_GROUP, user);
272 		/* if target requires a password, verify it */
273 		if (*pass && pwd->pw_uid != ruid) {	/* XXX - OK? */
274 			p = getpass("Password:");
275 #ifdef SKEY
276 			if (strcasecmp(p, "s/key") == 0) {
277 				if (skey_haskey(user))
278 					errx(EXIT_FAILURE,
279 					    "Sorry, you have no s/key.");
280 				else {
281 					if (skey_authenticate(user)) {
282 						goto badlogin;
283 					}
284 				}
285 
286 			} else
287 #endif
288 			if (consttime_memequal(pass,
289 			    crypt(p, pass), strlen(pass)) == 0) {
290 #ifdef SKEY
291  badlogin:
292 #endif
293 				(void)fprintf(stderr, "Sorry\n");
294 				syslog(LOG_WARNING,
295 					"BAD SU %s to %s%s", username,
296 					pwd->pw_name, ontty());
297 				exit(EXIT_FAILURE);
298 			}
299 		}
300 	}
301 
302 	if (asme) {
303 		/* if asme and non-standard target shell, must be root */
304 		if (chshell(pwd->pw_shell) == 0 && ruid)
305 			errx(EXIT_FAILURE, "permission denied (shell).");
306 	} else if (pwd->pw_shell && *pwd->pw_shell) {
307 		shell = pwd->pw_shell;
308 		iscsh = UNSET;
309 	} else {
310 		shell = _PATH_BSHELL;
311 		iscsh = NO;
312 	}
313 
314 	if ((p = strrchr(shell, '/')) != NULL)
315 		avshell = p+1;
316 	else
317 		avshell = shell;
318 
319 	/* if we're forking a csh, we want to slightly muck the args */
320 	if (iscsh == UNSET)
321 		iscsh = strstr(avshell, "csh") ? YES : NO;
322 
323 	/* set permissions */
324 #ifdef LOGIN_CAP
325 # ifdef ALLOW_GROUP_CHANGE
326 	/* if we aren't changing users, keep the current group members */
327 	if (ruid != pwd->pw_uid &&
328 	    setusercontext(lc, pwd, pwd->pw_uid, LOGIN_SETGROUP) == -1)
329 		err(EXIT_FAILURE, "setting user context");
330 
331 	addgroup(lc, gname, pwd, ruid, GROUP_PASSWORD);
332 
333 	if (setusercontext(lc, pwd, pwd->pw_uid,
334 		(u_int)(asthem ? (LOGIN_SETPRIORITY | LOGIN_SETUMASK) : 0) |
335 		LOGIN_SETRESOURCES | LOGIN_SETUSER) == -1)
336 		err(EXIT_FAILURE, "setting user context");
337 # else
338 	if (setusercontext(lc, pwd, pwd->pw_uid,
339 		(u_int)(asthem ? (LOGIN_SETPRIORITY | LOGIN_SETUMASK) : 0) |
340 		LOGIN_SETRESOURCES | LOGIN_SETGROUP | LOGIN_SETUSER) == -1)
341 		err(EXIT_FAILURE, "setting user context");
342 # endif
343 #else
344 	if (setgid(pwd->pw_gid) == -1)
345 		err(EXIT_FAILURE, "setgid");
346 	/* if we aren't changing users, keep the current group members */
347 	if (ruid != pwd->pw_uid && initgroups(user, pwd->pw_gid) != 0)
348 		errx(EXIT_FAILURE, "initgroups failed");
349 # ifdef ALLOW_GROUP_CHANGE
350 	addgroup(/*EMPTY*/, gname, pwd, ruid, GROUP_PASSWORD);
351 # endif
352 	if (setuid(pwd->pw_uid) == -1)
353 		err(EXIT_FAILURE, "setuid");
354 #endif
355 
356 	if (!asme) {
357 		if (asthem) {
358 			p = getenv("TERM");
359 			/* Create an empty environment */
360 			environ = emalloc(sizeof(char *));
361 			environ[0] = NULL;
362 #ifdef LOGIN_CAP
363 			if (setusercontext(lc, pwd, pwd->pw_uid,
364 				LOGIN_SETPATH) == -1)
365 				err(EXIT_FAILURE, "setting user context");
366 #else
367 			(void)setenv("PATH", _PATH_DEFPATH, 1);
368 #endif
369 			if (p)
370 				(void)setenv("TERM", p, 1);
371 			if (gohome && chdir(pwd->pw_dir) == -1)
372 				errx(EXIT_FAILURE, "no directory");
373 		}
374 
375 		if (asthem || pwd->pw_uid) {
376 			(void)setenv("LOGNAME", pwd->pw_name, 1);
377 			(void)setenv("USER", pwd->pw_name, 1);
378 		}
379 		(void)setenv("HOME", pwd->pw_dir, 1);
380 		(void)setenv("SHELL", shell, 1);
381 	}
382 	(void)setenv("SU_FROM", username, 1);
383 
384 	if (iscsh == YES) {
385 		if (fastlogin)
386 			*np-- = __UNCONST("-f");
387 		if (asme)
388 			*np-- = __UNCONST("-m");
389 	} else {
390 		if (fastlogin)
391 			(void)unsetenv("ENV");
392 	}
393 
394 	if (asthem) {
395 		avshellbuf[0] = '-';
396 		(void)estrlcpy(avshellbuf + 1, avshell, sizeof(avshellbuf) - 1);
397 		avshell = avshellbuf;
398 	} else if (iscsh == YES) {
399 		/* csh strips the first character... */
400 		avshellbuf[0] = '_';
401 		(void)estrlcpy(avshellbuf + 1, avshell, sizeof(avshellbuf) - 1);
402 		avshell = avshellbuf;
403 	}
404 	*np = __UNCONST(avshell);
405 
406 #ifdef BSD4_4
407 	if (pwd->pw_change || pwd->pw_expire)
408 		(void)gettimeofday(&tp, NULL);
409 	if (pwd->pw_change) {
410 		if (tp.tv_sec >= pwd->pw_change) {
411 			(void)printf("%s -- %s's password has expired.\n",
412 				     (ruid ? "Sorry" : "Note"), user);
413 			if (ruid != 0)
414 				exit(EXIT_FAILURE);
415 		} else if (pwd->pw_change - tp.tv_sec < pw_warntime)
416 			(void)printf("Warning: %s's password expires on %s",
417 				     user, ctime(&pwd->pw_change));
418 	}
419 	if (pwd->pw_expire) {
420 		if (tp.tv_sec >= pwd->pw_expire) {
421 			(void)printf("%s -- %s's account has expired.\n",
422 				     (ruid ? "Sorry" : "Note"), user);
423 			if (ruid != 0)
424 				exit(EXIT_FAILURE);
425 		} else if (pwd->pw_expire - tp.tv_sec <
426 		    _PASSWORD_WARNDAYS * SECSPERDAY)
427 			(void)printf("Warning: %s's account expires on %s",
428 				     user, ctime(&pwd->pw_expire));
429 	}
430 #endif
431 	if (ruid != 0)
432 		syslog(LOG_NOTICE, "%s to %s%s",
433 		    username, pwd->pw_name, ontty());
434 
435 	/* Raise our priority back to what we had before */
436 	(void)setpriority(PRIO_PROCESS, 0, prio);
437 
438 	(void)execv(shell, np);
439 	err(EXIT_FAILURE, "%s", shell);
440 	/* NOTREACHED */
441 }
442 
443 
444 #ifdef KERBEROS5
445 static int
446 kerberos5(char *username, const char *user, uid_t uid)
447 {
448 	krb5_error_code ret;
449 	krb5_context context;
450 	krb5_principal princ = NULL;
451 	krb5_ccache ccache, ccache2;
452 	char *cc_name;
453 	const char *filename;
454 
455 	ret = krb5_init_context(&context);
456 	if (ret)
457 		return 1;
458 
459 	if (strcmp(user, "root") == 0)
460 		ret = krb5_make_principal(context, &princ,
461 					  NULL, username, "root", NULL);
462 	else
463 		ret = krb5_make_principal(context, &princ,
464 					  NULL, user, NULL);
465 	if (ret)
466 		goto fail;
467 	if (!krb5_kuserok(context, princ, user) && !uid) {
468 		warnx("kerberos5: not in %s's ACL.", user);
469 		goto fail;
470 	}
471 	ret = krb5_cc_new_unique(context, krb5_mcc_ops.prefix, NULL, &ccache);
472 	if (ret)
473 		goto fail;
474 	ret = krb5_verify_user_lrealm(context, princ, ccache, NULL, TRUE,
475 				      NULL);
476 	if (ret) {
477 		krb5_cc_destroy(context, ccache);
478 		switch (ret) {
479 		case KRB5_LIBOS_PWDINTR :
480 			break;
481 		case KRB5KRB_AP_ERR_BAD_INTEGRITY:
482 		case KRB5KRB_AP_ERR_MODIFIED:
483 			krb5_warnx(context, "Password incorrect");
484 			break;
485 		default :
486 			krb5_warn(context, ret, "krb5_verify_user");
487 			break;
488 		}
489 		goto fail;
490 	}
491 	ret = krb5_cc_new_unique(context, krb5_mcc_ops.prefix, NULL, &ccache2);
492 	if (ret) {
493 		krb5_cc_destroy(context, ccache);
494 		goto fail;
495 	}
496 	ret = krb5_cc_copy_cache(context, ccache, ccache2);
497 	if (ret) {
498 		krb5_cc_destroy(context, ccache);
499 		krb5_cc_destroy(context, ccache2);
500 		goto fail;
501 	}
502 
503 	filename = krb5_cc_get_name(context, ccache2);
504 	(void)easprintf(&cc_name, "%s:%s", krb5_cc_get_type(context, ccache2),
505 		 filename);
506 	if (chown(filename, uid, NOGROUP) == -1) {
507 		warn("chown %s", filename);
508 		free(cc_name);
509 		krb5_cc_destroy(context, ccache);
510 		krb5_cc_destroy(context, ccache2);
511 		goto fail;
512 	}
513 
514 	(void)setenv("KRB5CCNAME", cc_name, 1);
515 	free(cc_name);
516 	krb5_cc_close(context, ccache2);
517 	krb5_cc_destroy(context, ccache);
518 	return 0;
519 
520  fail:
521 	if (princ != NULL)
522 		krb5_free_principal(context, princ);
523 	krb5_free_context(context);
524 	return 1;
525 }
526 #endif /* KERBEROS5 */
527 
528 static int
529 check_ingroup(int gid, const char *gname, const char *user, int ifempty)
530 {
531 	struct group *gr;
532 	char **g;
533 #ifdef SU_INDIRECT_GROUP
534 	char **gr_mem;
535 	int n = 0;
536 	int i = 0;
537 #endif
538 	int ok = 0;
539 
540 	if (gname == NULL)
541 		gr = getgrgid((gid_t) gid);
542 	else
543 		gr = getgrnam(gname);
544 
545 	/*
546 	 * XXX we are relying on the fact that we only set ifempty when
547 	 * calling to check for SU_GROUP and that is the only time a
548 	 * missing group is acceptable.
549 	 */
550 	if (gr == NULL)
551 		return ifempty;
552 	if (!*gr->gr_mem)		/* empty */
553 		return ifempty;
554 
555 	/*
556 	 * Ok, first see if user is in gr_mem
557 	 */
558 	for (g = gr->gr_mem; *g; ++g) {
559 		if (strcmp(*g, user) == 0)
560 			return 1;	/* ok */
561 #ifdef SU_INDIRECT_GROUP
562 		++n;			/* count them */
563 #endif
564 	}
565 #ifdef SU_INDIRECT_GROUP
566 	/*
567 	 * No.
568 	 * Now we need to duplicate the gr_mem list, and recurse for
569 	 * each member to see if it is a group, and if so whether user is
570 	 * in it.
571 	 */
572 	gr_mem = NULL;
573 	ereallocarr(&gr_mem, n + 1, sizeof(char *));
574 	for (g = gr->gr_mem, i = 0; *g; ++g) {
575 		gr_mem[i] = estrdup(*g);
576 		i++;
577 	}
578 	gr_mem[i++] = NULL;
579 
580 	for (g = gr_mem; ok == 0 && *g; ++g) {
581 		/*
582 		 * If we get this far we don't accept empty/missing groups.
583 		 */
584 		ok = check_ingroup(-1, *g, user, 0);
585 	}
586 	for (g = gr_mem; *g; ++g) {
587 		free(*g);
588 	}
589 	free(gr_mem);
590 #endif
591 	return ok;
592 }
593