unshare.c 11 KB

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