f1a9cdf194c43f4d66d15d55860b890c03272255
[oweals/busybox.git] / util-linux / unshare.c
1 /* vi: set sw=4 ts=4: */
2 /*
3  * Mini unshare implementation for busybox.
4  *
5  * Copyright (C) 2016 by Bartosz Golaszewski <bartekgola@gmail.com>
6  *
7  * Licensed under GPLv2 or later, see file LICENSE in this source tree.
8  */
9
10 //config:config UNSHARE
11 //config:       bool "unshare"
12 //config:       default y
13 //config:       depends on LONG_OPTS && !NOMMU
14 //config:       select PLATFORM_LINUX
15 //config:       help
16 //config:         Run program with some namespaces unshared from parent.
17
18 // depends on LONG_OPTS: it is awkward to exclude code which handles --propagation
19 // and --setgroups based on LONG_OPTS, so instead applet requires LONG_OPTS.
20 // depends on !NOMMU: we need fork()
21
22 //applet:IF_UNSHARE(APPLET(unshare, BB_DIR_USR_BIN, BB_SUID_DROP))
23
24 //kbuild:lib-$(CONFIG_UNSHARE) += unshare.o
25
26 //usage:#define unshare_trivial_usage
27 //usage:       "[OPTIONS] [PROG [ARGS]]"
28 //usage:#define unshare_full_usage "\n"
29 //usage:     "\n        -m, --mount[=FILE]      Unshare mount namespace"
30 //usage:     "\n        -u, --uts[=FILE]        Unshare UTS namespace (hostname etc.)"
31 //usage:     "\n        -i, --ipc[=FILE]        Unshare System V IPC namespace"
32 //usage:     "\n        -n, --net[=FILE]        Unshare network namespace"
33 //usage:     "\n        -p, --pid[=FILE]        Unshare PID namespace"
34 //usage:     "\n        -U, --user[=FILE}       Unshare user namespace"
35 //usage:     "\n        -f, --fork              Fork before execing PROG"
36 //usage:     "\n        -r, --map-root-user     Map current user to root (implies -u)"
37 //usage:     "\n        --mount-proc[=DIR]      Mount /proc filesystem first (implies -m)"
38 //usage:     "\n        --propagation slave|shared|private|unchanged"
39 //usage:     "\n                                Modify mount propagation in mount namespace"
40 //usage:     "\n        --setgroups allow|deny  Control the setgroups syscall in user namespaces"
41
42 #include <sched.h>
43 #include <sys/mount.h>
44 #include "libbb.h"
45
46 static void mount_or_die(const char *source, const char *target,
47                  const char *fstype, unsigned long mountflags)
48 {
49         if (mount(source, target, fstype, mountflags, NULL)) {
50                 bb_perror_msg_and_die("can't mount %s on %s (flags:0x%lx)",
51                         source, target, mountflags);
52                 /* fstype is always either NULL or "proc".
53                  * "proc" is only used to mount /proc.
54                  * No need to clutter up error message with fstype,
55                  * it is easily deductible.
56                  */
57         }
58 }
59
60 // TODO: move to libbb
61 static int wait_for_exitstatus(pid_t pid)
62 {
63         int exit_status, n;
64
65         n = safe_waitpid(pid, &exit_status, 0);
66         if (n < 0)
67                 bb_perror_msg_and_die("waitpid");
68         return exit_status;
69 }
70
71 /*
72  * Longest possible path to a procfs file used in unshare. Must be able to
73  * contain the '/proc/' string, the '/ns/user' string which is the longest
74  * namespace name and a 32-bit integer representing the process ID.
75  */
76 #define PATH_PROC_SETGROUPS     "/proc/self/setgroups"
77 #define PATH_PROC_UIDMAP        "/proc/self/uid_map"
78 #define PATH_PROC_GIDMAP        "/proc/self/gid_map"
79
80 struct namespace_descr {
81         int flag;
82         const char nsfile4[4];
83 };
84
85 struct namespace_ctx {
86         char *path;
87 };
88
89 enum {
90         OPT_mount       = 1 << 0,
91         OPT_uts         = 1 << 1,
92         OPT_ipc         = 1 << 2,
93         OPT_network     = 1 << 3,
94         OPT_pid         = 1 << 4,
95         OPT_user        = 1 << 5, /* OPT_user, NS_USR_POS, and ns_list[] index must match! */
96         OPT_fork        = 1 << 6,
97         OPT_map_root    = 1 << 7,
98         OPT_mount_proc  = 1 << 8,
99         OPT_propagation = 1 << 9,
100         OPT_setgroups   = 1 << 10,
101 };
102 enum {
103         NS_MNT_POS = 0,
104         NS_UTS_POS,
105         NS_IPC_POS,
106         NS_NET_POS,
107         NS_PID_POS,
108         NS_USR_POS, /* OPT_user, NS_USR_POS, and ns_list[] index must match! */
109         NS_COUNT,
110 };
111 static const struct namespace_descr ns_list[] = {
112         { CLONE_NEWNS,   "mnt"  },
113         { CLONE_NEWUTS,  "uts"  },
114         { CLONE_NEWIPC,  "ipc"  },
115         { CLONE_NEWNET,  "net"  },
116         { CLONE_NEWPID,  "pid"  },
117         { CLONE_NEWUSER, "user" }, /* OPT_user, NS_USR_POS, and ns_list[] index must match! */
118 };
119
120 /*
121  * Upstream unshare doesn't support short options for --mount-proc,
122  * --propagation, --setgroups.
123  * Optional arguments (namespace mountpoints) exist only for long opts,
124  * we are forced to use "fake" letters for them.
125  * '+': stop at first non-option.
126  */
127 static const char opt_str[] = "+muinpU""fr""\xfd::""\xfe:""\xff:";
128 static const char unshare_longopts[] ALIGN1 =
129         "mount\0"               Optional_argument       "\xf0"
130         "uts\0"                 Optional_argument       "\xf1"
131         "ipc\0"                 Optional_argument       "\xf2"
132         "network\0"             Optional_argument       "\xf3"
133         "pid\0"                 Optional_argument       "\xf4"
134         "user\0"                Optional_argument       "\xf5"
135         "fork\0"                No_argument             "f"
136         "map-root-user\0"       No_argument             "r"
137         "mount-proc\0"          Optional_argument       "\xfd"
138         "propagation\0"         Required_argument       "\xfe"
139         "setgroups\0"           Required_argument       "\xff"
140 ;
141
142 /* Ugly-looking string reuse trick */
143 #define PRIVATE_STR   "private\0""unchanged\0""shared\0""slave\0"
144 #define PRIVATE_UNCHANGED_SHARED_SLAVE   PRIVATE_STR
145
146 static unsigned long parse_propagation(const char *prop_str)
147 {
148         int i = index_in_strings(PRIVATE_UNCHANGED_SHARED_SLAVE, prop_str);
149         if (i < 0)
150                 bb_error_msg_and_die("unrecognized: --%s=%s", "propagation", prop_str);
151         if (i == 0)
152                 return MS_REC | MS_PRIVATE;
153         if (i == 1)
154                 return 0;
155         if (i == 2)
156                 return MS_REC | MS_SHARED;
157         return MS_REC | MS_SLAVE;
158 }
159
160 static void mount_namespaces(pid_t pid, struct namespace_ctx *ns_ctx_list)
161 {
162         const struct namespace_descr *ns;
163         struct namespace_ctx *ns_ctx;
164         int i;
165
166         for (i = 0; i < NS_COUNT; i++) {
167                 char nsf[sizeof("/proc/%u/ns/AAAA") + sizeof(int)*3];
168
169                 ns = &ns_list[i];
170                 ns_ctx = &ns_ctx_list[i];
171                 if (!ns_ctx->path)
172                         continue;
173                 sprintf(nsf, "/proc/%u/ns/%.4s", (unsigned)pid, ns->nsfile4);
174                 mount_or_die(nsf, ns_ctx->path, NULL, MS_BIND);
175         }
176 }
177
178 int unshare_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
179 int unshare_main(int argc UNUSED_PARAM, char **argv)
180 {
181         int i;
182         unsigned int opts;
183         int unsflags;
184         uintptr_t need_mount;
185         const char *proc_mnt_target;
186         const char *prop_str;
187         const char *setgrp_str;
188         unsigned long prop_flags;
189         uid_t reuid = geteuid();
190         gid_t regid = getegid();
191         struct fd_pair fdp;
192         pid_t child = child; /* for compiler */
193         struct namespace_ctx ns_ctx_list[NS_COUNT];
194
195         memset(ns_ctx_list, 0, sizeof(ns_ctx_list));
196         proc_mnt_target = "/proc";
197         prop_str = PRIVATE_STR;
198         setgrp_str = NULL;
199
200         opt_complementary =
201                 "\xf0""m" /* long opts (via their "fake chars") imply short opts */
202                 ":\xf1""u"
203                 ":\xf2""i"
204                 ":\xf3""n"
205                 ":\xf4""p"
206                 ":\xf5""U"
207                 ":ru"      /* --map-root-user or -r implies -u */
208                 ":\xfd""m" /* --mount-proc implies -m */
209         ;
210         applet_long_options = unshare_longopts;
211         opts = getopt32(argv, opt_str,
212                         &proc_mnt_target, &prop_str, &setgrp_str,
213                         &ns_ctx_list[NS_MNT_POS].path,
214                         &ns_ctx_list[NS_UTS_POS].path,
215                         &ns_ctx_list[NS_IPC_POS].path,
216                         &ns_ctx_list[NS_NET_POS].path,
217                         &ns_ctx_list[NS_PID_POS].path,
218                         &ns_ctx_list[NS_USR_POS].path
219         );
220         argv += optind;
221         //bb_error_msg("opts:0x%x", opts);
222         //bb_error_msg("mount:%s", ns_ctx_list[NS_MNT_POS].path);
223         //bb_error_msg("proc_mnt_target:%s", proc_mnt_target);
224         //bb_error_msg("prop_str:%s", prop_str);
225         //bb_error_msg("setgrp_str:%s", setgrp_str);
226         //exit(1);
227
228         if (setgrp_str) {
229                 if (strcmp(setgrp_str, "allow") == 0) {
230                         if (opts & OPT_map_root) {
231                                 bb_error_msg_and_die(
232                                         "--setgroups=allow and --map-root-user "
233                                         "are mutually exclusive"
234                                 );
235                         }
236                 } else {
237                         /* It's not "allow", must be "deny" */
238                         if (strcmp(setgrp_str, "deny") != 0)
239                                 bb_error_msg_and_die("unrecognized: --%s=%s",
240                                         "setgroups", setgrp_str);
241                 }
242         }
243
244         unsflags = 0;
245         need_mount = 0;
246         for (i = 0; i < NS_COUNT; i++) {
247                 const struct namespace_descr *ns = &ns_list[i];
248                 struct namespace_ctx *ns_ctx = &ns_ctx_list[i];
249
250                 if (opts & (1 << i))
251                         unsflags |= ns->flag;
252
253                 need_mount |= (uintptr_t)(ns_ctx->path);
254         }
255         /* need_mount != 0 if at least one FILE was given */
256
257         prop_flags = MS_REC | MS_PRIVATE;
258         /* Silently ignore --propagation if --mount is not requested. */
259         if (opts & OPT_mount)
260                 prop_flags = parse_propagation(prop_str);
261
262         /*
263          * Special case: if we were requested to unshare the mount namespace
264          * AND to make any namespace persistent (by bind mounting it) we need
265          * to spawn a child process which will wait for the parent to call
266          * unshare(), then mount parent's namespaces while still in the
267          * previous namespace.
268          */
269         fdp.wr = -1;
270         if (need_mount && (opts & OPT_mount)) {
271                 /*
272                  * Can't use getppid() in child, as we can be unsharing the
273                  * pid namespace.
274                  */
275                 pid_t ppid = getpid();
276
277                 xpiped_pair(fdp);
278
279                 child = xfork();
280                 if (child == 0) {
281                         /* Child */
282                         close(fdp.wr);
283
284                         /* Wait until parent calls unshare() */
285                         read(fdp.rd, ns_ctx_list, 1); /* ...using bogus buffer */
286                         /*close(fdp.rd);*/
287
288                         /* Mount parent's unshared namespaces. */
289                         mount_namespaces(ppid, ns_ctx_list);
290                         return EXIT_SUCCESS;
291                 }
292                 /* Parent continues */
293         }
294
295         if (unshare(unsflags) != 0)
296                 bb_perror_msg_and_die("unshare(0x%x)", unsflags);
297
298         if (fdp.wr >= 0) {
299                 close(fdp.wr); /* Release child */
300                 /*close(fdp.rd);*/
301         }
302
303         if (need_mount) {
304                 /* Wait for the child to finish mounting the namespaces. */
305                 if (opts & OPT_mount) {
306                         int exit_status = wait_for_exitstatus(child);
307                         if (WIFEXITED(exit_status) &&
308                             WEXITSTATUS(exit_status) != EXIT_SUCCESS)
309                                 return WEXITSTATUS(exit_status);
310                 } else {
311                         /*
312                          * Regular way - we were requested to mount some other
313                          * namespaces: mount them after the call to unshare().
314                          */
315                         mount_namespaces(getpid(), ns_ctx_list);
316                 }
317         }
318
319         /*
320          * When we're unsharing the pid namespace, it's not the process that
321          * calls unshare() that is put into the new namespace, but its first
322          * child. The user may want to use this option to spawn a new process
323          * that'll become PID 1 in this new namespace.
324          */
325         if (opts & OPT_fork) {
326                 pid_t pid = xfork();
327                 if (pid > 0) {
328                         /* Parent */
329                         int exit_status = wait_for_exitstatus(pid);
330                         if (WIFSIGNALED(exit_status))
331                                 kill_myself_with_sig(WTERMSIG(exit_status));
332                         return WEXITSTATUS(exit_status);
333                 }
334                 /* Child continues */
335         }
336
337         if (opts & OPT_map_root) {
338                 char uidmap_buf[sizeof("%u 0 1") + sizeof(int)*3];
339
340                 /*
341                  * Since Linux 3.19 unprivileged writing of /proc/self/gid_map
342                  * has been disabled unless /proc/self/setgroups is written
343                  * first to permanently disable the ability to call setgroups
344                  * in that user namespace.
345                  */
346                 xopen_xwrite_close(PATH_PROC_SETGROUPS, "deny");
347                 sprintf(uidmap_buf, "%u 0 1", (unsigned)reuid);
348                 xopen_xwrite_close(PATH_PROC_UIDMAP, uidmap_buf);
349                 sprintf(uidmap_buf, "%u 0 1", (unsigned)regid);
350                 xopen_xwrite_close(PATH_PROC_GIDMAP, uidmap_buf);
351         } else
352         if (setgrp_str) {
353                 /* Write "allow" or "deny" */
354                 xopen_xwrite_close(PATH_PROC_SETGROUPS, setgrp_str);
355         }
356
357         if (opts & OPT_mount) {
358                 mount_or_die("none", "/", NULL, prop_flags);
359         }
360
361         if (opts & OPT_mount_proc) {
362                 /*
363                  * When creating a new pid namespace, we might want the pid
364                  * subdirectories in /proc to remain consistent with the new
365                  * process IDs. Without --mount-proc the pids in /proc would
366                  * still reflect the old pid namespace. This is why we make
367                  * /proc private here and then do a fresh mount.
368                  */
369                 mount_or_die("none", proc_mnt_target, NULL, MS_PRIVATE | MS_REC);
370                 mount_or_die("proc", proc_mnt_target, "proc", MS_NOSUID | MS_NOEXEC | MS_NODEV);
371         }
372
373         if (argv[0]) {
374                 BB_EXECVP_or_die(argv);
375         }
376         /* unshare from util-linux 2.27.1, despite not documenting it,
377          * runs a login shell (argv0="-sh") if no PROG is given
378          */
379         run_shell(getenv("SHELL"), /*login:*/ 1, NULL, NULL);
380 }