3 * Copyright 2013 CE Strake <strake888@gmail.com>
5 * See http://refspecs.linuxfoundation.org/LSB_4.1.0/LSB-Core-generic/LSB-Core-generic/su.html
6 * TODO: log su attempts
8 USE_SU(NEWTOY(su, "lmpc:s:", TOYFLAG_BIN|TOYFLAG_ROOTONLY))
13 depends on TOYBOX_SHADOW
15 usage: su [-lmp] [-c CMD] [-s SHELL] [USER [ARGS...]]
17 Switch to user (or root) and run shell (with optional command line).
20 -c command to pass to shell with -c
22 -(m|p) preserve environment
33 static char *snapshot_env(char *name)
35 char *s = getenv(name);
37 if (s) return xmprintf("%s=%s", name, s);
44 char *name, *passhash = 0, **argu, **argv;
48 if (*toys.optargs && !strcmp("-", *toys.optargs)) {
49 toys.optflags |= FLAG_l;
53 if (*toys.optargs) name = *(toys.optargs++);
56 if (!(shp = getspnam(name))) perror_exit("no '%s'", name);
58 if (*shp->sp_pwdp != '$') goto deny;
59 if (read_password(toybuf, sizeof(toybuf), "Password: ")) goto deny;
60 passhash = crypt(toybuf, shp->sp_pwdp);
61 memset(toybuf, 0, sizeof(toybuf));
62 if (!passhash || strcmp(passhash, shp->sp_pwdp)) goto deny;
68 argv = argu = xmalloc(sizeof(char *)*(toys.optc + 4));
69 *(argv++) = TT.s ? TT.s : up->pw_shell;
71 if (toys.optflags & FLAG_l) {
73 char *stuff[] = {snapshot_env("TERM"), snapshot_env("DISPLAY"),
74 snapshot_env("COLORTERM"), snapshot_env("XAUTHORITY")};
77 for (i=0; i < ARRAY_LEN(stuff); i++) if (stuff[i]) putenv(stuff[i]);
80 } else unsetenv("IFS");
81 setenv("PATH", "/sbin:/bin:/usr/sbin:/usr/bin", 1);
82 if (!(toys.optflags & (FLAG_m|FLAG_p))) {
83 setenv("HOME", up->pw_dir, 1);
84 setenv("SHELL", up->pw_shell, 1);
85 setenv("USER", up->pw_name, 1);
86 setenv("LOGNAME", up->pw_name, 1);
87 } else unsetenv("IFS");
89 if (toys.optflags & FLAG_c) {
93 while ((*(argv++) = *(toys.optargs++)));
95 perror_exit("can't exec %s", *argu);