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