commit: cc0ce1f88dde3153ce506edd17370296b799e101
parent ad5eda7959bcf348aba69f972b493e063fd3a6f5
Author: Haelwenn (lanodan) Monnier <contact@hacktivis.me>
Date: Tue, 1 Nov 2022 17:43:59 +0100
su: Fix getting the username
Diffstat:
M | su.c | 60 | +++++++++++++++++++++++++----------------------------------- |
1 file changed, 25 insertions(+), 35 deletions(-)
diff --git a/su.c b/su.c
@@ -30,7 +30,7 @@ main(int argc, char *argv[])
bool opt_l = false;
bool opt_p = false;
int c = EOF;
- char *username = NULL;
+ char *username = "root";
struct passwd *pwent = NULL;
char *shell = NULL;
char *command = NULL;
@@ -76,16 +76,19 @@ main(int argc, char *argv[])
if(argv[0] && strcmp(argv[0], "-") == 0)
{
- if(argc < 2)
+ opt_l = true;
+
+ if(argc >= 2)
{
- fprintf(stderr, "su: Option - requires an operand\n");
- return 1;
+ username = argv[1];
+ argc -= 2;
+ argv += 2;
+ }
+ else
+ {
+ argc -= 1;
+ argv += 1;
}
-
- opt_l = true;
- username = argv[1];
- argc -= 2;
- argv += 2;
}
if((opt_l && argc > 0) || argc > 1)
@@ -99,18 +102,16 @@ main(int argc, char *argv[])
username = argv[0];
}
- if(username != NULL)
- {
- errno = 0;
- pwent = getpwnam(username);
+ errno = 0;
+ pwent = getpwnam(username);
- if(errno != 0)
- {
- perror("getpwnam");
- return 1;
- }
+ if(errno != 0)
+ {
+ perror("su: getpwnam");
+ return 1;
}
+ fprintf(stderr, "su: Authenticating as %s\n", username);
if(getuid() != 0)
{
char *pw_hash = NULL;
@@ -159,15 +160,13 @@ main(int argc, char *argv[])
if(pwent != NULL)
{
- assert(username != NULL);
-
if(setgid(pwent->pw_gid) < 0)
{
- perror("setgid");
+ perror("su: setgid");
}
if(setuid(pwent->pw_uid) < 0)
{
- perror("setuid");
+ perror("su: setuid");
}
if(pwent->pw_shell != NULL)
@@ -179,9 +178,9 @@ main(int argc, char *argv[])
{
setenv("HOME", pwent->pw_dir, 1);
- if(!opt_l && (chdir(pwent->pw_dir) != 0))
+ if(opt_l)
{
- perror("chdir");
+ if(chdir(pwent->pw_dir) != 0) perror("su: chdir");
}
}
@@ -200,17 +199,8 @@ main(int argc, char *argv[])
shell = "/bin/sh";
}
- if(username != NULL)
- {
- setenv("USER", username, 1);
- setenv("LOGNAME", username, 1);
- }
- else
- {
- setenv("USER", "root", 1);
- setenv("LOGNAME", "root", 1);
- }
-
+ setenv("USER", username, 1);
+ setenv("LOGNAME", username, 1);
setenv("SHELL", shell, 1);
setenv("IFS", " \t\n", 1);