forked from timwr/CVE-2016-5195
-
Notifications
You must be signed in to change notification settings - Fork 0
/
run.c
105 lines (96 loc) · 2.56 KB
/
run.c
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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include "selinux.h"
#include <sys/types.h>
#include <pwd.h>
#include <grp.h>
int main(int argc, char **argv)
{
int uid, gid, c, i = 0, d = 0;
char *cntx = NULL;
struct passwd *pw;
struct group *gr;
// default root uid/gid
uid = -1;
gid = -1;
while ((c = getopt (argc, argv, "dc:u:g:")) != -1) {
i++;
switch (c) {
case 'd':
// set debug
d = 1;
break;
case 'c':
cntx = optarg;
break;
case 'u':
if (sscanf(optarg,"%i",&uid) != 1) {
pw = getpwnam(optarg);
if (pw == NULL) {
fprintf(stderr, "Invalid user (%s)\n", optarg);
return 1;
}
uid = pw->pw_uid;
if (d) {
fprintf(stderr, "Resolved '%s' user into %d uid\n", optarg, uid);
}
}
break;
case 'g':
if (sscanf(optarg,"%i",&gid) != 1) {
gr = getgrnam(optarg);
if (gr == NULL) {
fprintf(stderr, "Invalid group (%s)\n", optarg);
return 1;
}
gid = gr->gr_gid;
if (d) {
fprintf(stderr, "Resolved '%s' group into %d gid\n", optarg, gid);
}
}
break;
case '?':
if (optopt == 'u')
fprintf (stderr, "Option -%c requires an argument.\n", optopt);
else if (optopt == 'g')
fprintf (stderr, "Option -%c requires an argument.\n", optopt);
else if (optopt == 'c')
fprintf (stderr, "Option -%c requires an argument.\n", optopt);
else if (isprint (optopt))
fprintf (stderr, "Unknown option `-%c'.\n", optopt);
else
fprintf (stderr, "Unknown option character `\\x%x'.\n", optopt);
return 1;
default:
fprintf (stderr, "Abort\n");
return 1;
}
}
// if uid was not set, we will use current one
if (uid == -1) {
uid = getuid();
if (d) {
fprintf(stderr, "uid was not set, setting current %d\n", uid);
}
}
// set gid=uid when it was not set
if (gid == -1) {
gid = uid;
if (d) {
fprintf(stderr, "did was not set, setting uid's %d\n", uid);
}
}
if (d) {
fprintf(stderr, "uid=%d gid=%d, cntx=%s\n",uid, gid, cntx);
}
if (setresgid(gid, gid, gid) || setresuid(uid, uid, uid)) {
printf("setresgid(%d)/setresuid(%d) failed\n", gid, uid);
}
if (cntx != NULL && setcon(cntx)) {
printf("Failed to set '%s' SELinux context\n", cntx);
}
execvp(argv[i*2+1-d], argv+i*2+1-d);
return 0;
}