-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathuserns.c
98 lines (79 loc) · 2.63 KB
/
userns.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
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <linux/limits.h>
#include "userns.h"
#define UID 1000
// Write to a file
int write_to_file(char* path_to_file, char *line_to_write){
FILE *f = fopen(path_to_file,"w");
if (f == NULL){
fprintf(stderr,"[" RED("-") "] Could not open %s for writing\n", path_to_file);
return -1;
}
if (fwrite(line_to_write, 1, strlen(line_to_write), f) == 0){
fprintf(stderr,"[" RED("-") "] Could not write to %s\n", path_to_file);
return -1;
}
if (fclose(f) != 0){
fprintf(stderr,"[" RED("-") "] Could not close %s\n", path_to_file);
return -1;
}
return 0;
}
// Prepare User Namespace
int prepare_userns(int pid){
char* path;
char* line;
/* Write UID to /proc/pid/uid_map
Format:
0 UID 1
This ensures that under isolated conditions, we have UID 1
*/
if ((asprintf(&path, "/proc/%d/uid_map", pid) < 0) || (asprintf(&line, "0 %d 1\n", UID) < 0)){
fprintf(stderr,"[" RED("-") "] out of memory\n");
return -1;
}
// Write tp uid_map
if (write_to_file(path, line) != 0){
fprintf(stderr,"[" RED("-") "] Could not prepare " RED("uid_map") "\n");
return -1;
}
// Zero out memory
if(memset(path, 0, (int)sizeof(path)) == NULL || memset(line, 0, (int)sizeof(line)) == NULL){
fprintf(stderr,"[" RED("-") "] The function " RED("memset()") " failed\n");
return -1;
}
// Disable the setgroups system call
if ((asprintf(&path, "/proc/%d/setgroups", pid) < 0) || (asprintf(&line, "deny") < 0)){
fprintf(stderr,"[" RED("-") "] out of memory\n");
return -1;
}
// Write tp uid_map
if (write_to_file(path, line) != 0){
fprintf(stderr,"[" RED("-") "] Could not disable " RED("setgroups") " syscall\n");
return -1;
}
// Zero out memory
if(memset(path, 0, (int)sizeof(path)) == NULL || memset(line, 0, (int)sizeof(line)) == NULL){
fprintf(stderr,"[" RED("-") "] The function " RED("memset()") " failed\n");
return -1;
}
/* Write UID to /proc/pid/gid_map
Format:
0 UID 1
This ensures that under isolated conditions, we have GID 1
*/
if ((asprintf(&path, "/proc/%d/gid_map", pid) < 0) || (asprintf(&line, "0 %d 1\n", UID) < 0)){
fprintf(stderr,"[" RED("-") "] out of memory\n");
return -1;
}
// Write tp uid_map
if (write_to_file(path, line) != 0){
fprintf(stderr,"[" RED("-") "] Could not prepare " RED("gid_map") "\n");
return -1;
}
free(path);
free(line);
return 0;
}