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