Line 0
Link Here
|
|
|
1 |
#include <stdlib.h> |
2 |
#include <error.h> |
3 |
#include <errno.h> |
4 |
#include <unistd.h> |
5 |
#include <pwd.h> |
6 |
#include <grp.h> |
7 |
#include <linux/types.h> |
8 |
#include <sys/capability.h> |
9 |
#include <sys/prctl.h> |
10 |
|
11 |
#include "dropcap.h" |
12 |
|
13 |
extern void drop_cap (void); |
14 |
|
15 |
void |
16 |
drop_cap (void) |
17 |
{ |
18 |
const char *dir = "/var/resolv"; |
19 |
cap_t caps; |
20 |
uid_t uid = getuid (); |
21 |
gid_t gid = getgid (); |
22 |
|
23 |
if (uid && geteuid()) |
24 |
return; |
25 |
|
26 |
if (setgroups (0, NULL) < 0) |
27 |
error (EXIT_FAILURE, errno, "setgroups"); |
28 |
|
29 |
if (prctl (PR_SET_KEEPCAPS, 1)) |
30 |
error (EXIT_FAILURE, errno, "prctl (PR_SET_KEEPCAPS, 1) failed"); |
31 |
|
32 |
if (!uid) |
33 |
{ |
34 |
const char *user = "iputils"; |
35 |
struct passwd *pw = getpwnam (user); |
36 |
|
37 |
if (!pw) |
38 |
error (EXIT_FAILURE, 0, |
39 |
"lookup of user \"%s\" failed", user); |
40 |
|
41 |
gid = pw->pw_gid; |
42 |
uid = pw->pw_uid; |
43 |
endpwent (); |
44 |
|
45 |
if (!uid) |
46 |
error (EXIT_FAILURE, 0, |
47 |
"user \"%s\" shouldn't be root", user); |
48 |
} |
49 |
|
50 |
if (chroot (dir) < 0) |
51 |
error (EXIT_FAILURE, errno, "chroot to \"%s\" failed", dir); |
52 |
|
53 |
if (chdir ("/") < 0) |
54 |
error (EXIT_FAILURE, errno, "chdir to \"/\" failed"); |
55 |
|
56 |
if (setgid (gid) < 0) |
57 |
error (EXIT_FAILURE, errno, "setgid"); |
58 |
|
59 |
caps = cap_from_text ("cap_setuid,cap_net_raw=ep"); |
60 |
if (!caps) |
61 |
error (EXIT_FAILURE, errno, "cap_from_text failed"); |
62 |
|
63 |
if (cap_set_proc (caps) < 0) |
64 |
error (EXIT_FAILURE, errno, "cap_set_proc failed"); |
65 |
|
66 |
cap_free (caps); |
67 |
|
68 |
if (setreuid (uid, uid) < 0) |
69 |
error (EXIT_FAILURE, errno, "setreuid"); |
70 |
|
71 |
caps = cap_from_text ("cap_net_raw=ep"); |
72 |
if (!caps) |
73 |
error (EXIT_FAILURE, errno, "cap_from_text failed"); |
74 |
|
75 |
if (cap_set_proc (caps) < 0) |
76 |
error (EXIT_FAILURE, errno, "cap_set_proc failed"); |
77 |
|
78 |
cap_free (caps); |
79 |
} |