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#define FOR_nsenter
66#include "toys.h"
67#include <sys/syscall.h>
68#include <linux/sched.h>
69
70#define unshare(flags) syscall(SYS_unshare, flags)
71#define setns(fd, nstype) syscall(SYS_setns, fd, nstype)
72
73GLOBALS(
74 char *Uupnmi[6];
75 long t;
76)
77
78
79#define CLEANUP_nsenter
80#define FOR_unshare
81#include <generated/flags.h>
82
83static void write_ugid_map(char *map, unsigned eugid)
84{
85 int bytes = sprintf(toybuf, "0 %u 1", eugid), fd = xopen(map, O_WRONLY);
86
87 xwrite(fd, toybuf, bytes);
88 xclose(fd);
89}
90
91static void handle_r(int euid, int egid)
92{
93 int fd;
94
95 if ((fd = open("/proc/self/setgroups", O_WRONLY)) >= 0) {
96 xwrite(fd, "deny", 4);
97 close(fd);
98 }
99
100 write_ugid_map("/proc/self/uid_map", euid);
101 write_ugid_map("/proc/self/gid_map", egid);
102}
103
104static int test_r()
105{
106 return toys.optflags & FLAG_r;
107}
108
109static int test_f()
110{
111 return toys.optflags & FLAG_f;
112}
113
114
115#define CLEANUP_unshare
116#define FOR_nsenter
117#include <generated/flags.h>
118
119void unshare_main(void)
120{
121 unsigned flags[]={CLONE_NEWUSER, CLONE_NEWUTS, CLONE_NEWPID, CLONE_NEWNET,
122 CLONE_NEWNS, CLONE_NEWIPC}, f = 0;
123 int i, fd;
124
125
126 if (CFG_UNSHARE && *toys.which->name=='u') {
127
128 int euid = geteuid(), egid = getegid();
129
130
131 if (test_r()) toys.optflags |= FLAG_U;
132
133 for (i = 0; i<ARRAY_LEN(flags); i++)
134 if (toys.optflags & (1<<i)) f |= flags[i];
135
136 if (unshare(f)) perror_exit(0);
137 if (test_r()) handle_r(euid, egid);
138
139 if (test_f()) {
140 toys.exitval = xrun(toys.optargs);
141
142 return;
143 }
144
145 } else if (CFG_NSENTER) {
146 char *nsnames = "user\0uts\0pid\0net\0mnt\0ipc";
147
148 for (i = 0; i<ARRAY_LEN(flags); i++) {
149 char *filename = TT.Uupnmi[i];
150
151 if (toys.optflags & (1<<i)) {
152 if (!filename || !*filename) {
153 if (!(toys.optflags & FLAG_t)) error_exit("need -t or =filename");
154 sprintf(toybuf, "/proc/%ld/ns/%s", TT.t, nsnames);
155 filename = toybuf;
156 }
157
158 if (setns(fd = xopenro(filename), flags[i])) perror_exit("setns");
159 close(fd);
160 }
161 nsnames += strlen(nsnames)+1;
162 }
163
164 if ((toys.optflags & FLAG_p) && !(toys.optflags & FLAG_F)) {
165 toys.exitval = xrun(toys.optargs);
166
167 return;
168 }
169 }
170
171 xexec(toys.optargs);
172}
173
174void nsenter_main(void)
175{
176 unshare_main();
177}
178