-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathsuid.c
153 lines (113 loc) · 2.43 KB
/
suid.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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
#define _GNU_SOURCE /* For setres* */
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
static int real_uid;
static int set_uid;
static int real_gid;
static int set_gid;
void init()
{
real_uid = getuid();
set_uid = geteuid();
real_gid = getgid();
set_gid = getegid();
}
void print(void)
{
int uid, euid;
int gid, egid;
uid = getuid();
euid = geteuid();
gid = getgid();
egid = getegid();
printf("UID/eUID: %d/%d GID/eGID: %d/%d\n", uid, euid, gid, egid);
}
void check_perms(void)
{
printf("Checking root perms! ");
print();
FILE *f = fopen("/etc/shadow", "r");
if (!f) {
printf("We do not have root access permissions\n");
} else {
fclose(f);
printf("Root permissions\n");
}
}
void drop_temporarily(void)
{
/* On systems without setres* use setre*. But make sure it works */
const int gid = getgid(), uid = getuid();
const int egid = getegid(), euid = geteuid();
if (setresuid(uid, uid, euid) != 0)
goto error;
if (setresgid(gid, gid, egid) != 0)
goto error;
/* Paranoid check */
if (geteuid() != getuid() || getegid() != getgid()) {
printf("d_t: fun\n");
goto error;
}
return;
error:
printf("d_t: failure\n");
exit(EXIT_FAILURE);
}
void drop_pernamently(void)
{
/* On systems without setres* use setre*. But make sure it works */
const int gid = getgid(), uid = getuid();
if (setresuid(uid, uid, uid) != 0)
goto error;
if (setresgid(gid, gid, gid) != 0)
goto error;
/* Paranoid check */
if (geteuid() != getuid() || getegid() != getgid()) {
printf("d_t: fun\n");
goto error;
}
return;
error:
printf("d_p: failure\n");
exit(EXIT_FAILURE);
}
void restore(void)
{
/* On systems without setres* use setre*. But make sure it works */
/* 0 should be remembered before! */
if (setresuid(real_uid, set_uid, set_uid) != 0)
goto error;
if (setresgid(real_gid, set_gid, set_gid) != 0)
goto error;
/* Paranoid check */
if (geteuid() != set_uid || getegid() != set_gid) {
printf("d_t: fun\n");
goto error;
}
return;
error:
printf("d_p: failure\n");
exit(EXIT_FAILURE);
}
int main(int argc, char **argv)
{
clearenv();
init();
printf("Initial: ");
print();
check_perms();
printf("* TEMPORARY DROP \n");
drop_temporarily();
check_perms();
printf("* RESTORE \n");
restore();
check_perms();
printf("* PERNAMENT DROP \n");
drop_pernamently();
check_perms();
printf("* RESTORE (we should fail now) \n");
restore();
check_perms();
return 0;
}