-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnonroot.c
More file actions
47 lines (45 loc) · 1.21 KB
/
nonroot.c
File metadata and controls
47 lines (45 loc) · 1.21 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
#include <unistd.h>
#include <sys/types.h>
#include <pwd.h>
/* Print an error message and call exit() */
void error_exit(const char *msg)
{
fprintf(stderr, "nonroot: %s\n", msg);
if(errno) {
fprintf(stderr, "%s\n", strerror(errno));
}
exit(EXIT_FAILURE);
}
int main(int argc, char *argv[])
{
if(argc < 3) {
fprintf(stderr, "usage: nonroot username executable [args...] \n");
return EXIT_FAILURE;
}
char *username = argv[1];
/* Look the user up */
struct passwd *user = getpwnam(username);
if(!user) {
error_exit("Invalid user");
}
/* Don't allow UID/GID zero, for extra safety */
if(user->pw_uid == 0 || user->pw_gid == 0) {
error_exit("UID or GID is zero. Specify a non-root user.");
}
/* Change user and group */
if(setgid(user->pw_gid)) {
error_exit("Failed to switch user");
}
if(setuid(user->pw_uid)) {
error_exit("Failed to switch user");
}
/* Execute command */
char **new_argv = argv + 2;
execvp(new_argv[0], new_argv);
/* Only returns on error! */
error_exit("Failed to execute the command");
}