unshare.c 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377
  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 (7.2 kb)"
  11. //config: default y
  12. //config: depends on !NOMMU
  13. //config: select LONG_OPTS
  14. //config: help
  15. //config: Run program with some namespaces unshared from parent.
  16. // needs 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_net = 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. #define 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. "net\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. opts = getopt32long(argv, "^" OPT_STR "\0"
  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. , unshare_longopts,
  201. &proc_mnt_target, &prop_str, &setgrp_str,
  202. &ns_ctx_list[NS_MNT_POS].path,
  203. &ns_ctx_list[NS_UTS_POS].path,
  204. &ns_ctx_list[NS_IPC_POS].path,
  205. &ns_ctx_list[NS_NET_POS].path,
  206. &ns_ctx_list[NS_PID_POS].path,
  207. &ns_ctx_list[NS_USR_POS].path
  208. );
  209. argv += optind;
  210. //bb_error_msg("opts:0x%x", opts);
  211. //bb_error_msg("mount:%s", ns_ctx_list[NS_MNT_POS].path);
  212. //bb_error_msg("proc_mnt_target:%s", proc_mnt_target);
  213. //bb_error_msg("prop_str:%s", prop_str);
  214. //bb_error_msg("setgrp_str:%s", setgrp_str);
  215. //exit(1);
  216. if (setgrp_str) {
  217. if (strcmp(setgrp_str, "allow") == 0) {
  218. if (opts & OPT_map_root) {
  219. bb_simple_error_msg_and_die(
  220. "--setgroups=allow and --map-root-user "
  221. "are mutually exclusive"
  222. );
  223. }
  224. } else {
  225. /* It's not "allow", must be "deny" */
  226. if (strcmp(setgrp_str, "deny") != 0)
  227. bb_error_msg_and_die("unrecognized: --%s=%s",
  228. "setgroups", setgrp_str);
  229. }
  230. }
  231. unsflags = 0;
  232. need_mount = 0;
  233. for (i = 0; i < NS_COUNT; i++) {
  234. const struct namespace_descr *ns = &ns_list[i];
  235. struct namespace_ctx *ns_ctx = &ns_ctx_list[i];
  236. if (opts & (1 << i))
  237. unsflags |= ns->flag;
  238. need_mount |= (uintptr_t)(ns_ctx->path);
  239. }
  240. /* need_mount != 0 if at least one FILE was given */
  241. prop_flags = MS_REC | MS_PRIVATE;
  242. /* Silently ignore --propagation if --mount is not requested. */
  243. if (opts & OPT_mount)
  244. prop_flags = parse_propagation(prop_str);
  245. /*
  246. * Special case: if we were requested to unshare the mount namespace
  247. * AND to make any namespace persistent (by bind mounting it) we need
  248. * to spawn a child process which will wait for the parent to call
  249. * unshare(), then mount parent's namespaces while still in the
  250. * previous namespace.
  251. */
  252. fdp.wr = -1;
  253. if (need_mount && (opts & OPT_mount)) {
  254. /*
  255. * Can't use getppid() in child, as we can be unsharing the
  256. * pid namespace.
  257. */
  258. pid_t ppid = getpid();
  259. xpiped_pair(fdp);
  260. child = xfork();
  261. if (child == 0) {
  262. /* Child */
  263. close(fdp.wr);
  264. /* Wait until parent calls unshare() */
  265. read(fdp.rd, ns_ctx_list, 1); /* ...using bogus buffer */
  266. /*close(fdp.rd);*/
  267. /* Mount parent's unshared namespaces. */
  268. mount_namespaces(ppid, ns_ctx_list);
  269. return EXIT_SUCCESS;
  270. }
  271. /* Parent continues */
  272. }
  273. if (unshare(unsflags) != 0)
  274. bb_perror_msg_and_die("unshare(0x%x)", unsflags);
  275. if (fdp.wr >= 0) {
  276. close(fdp.wr); /* Release child */
  277. close(fdp.rd); /* should close fd, to not confuse exec'ed PROG */
  278. }
  279. if (need_mount) {
  280. /* Wait for the child to finish mounting the namespaces. */
  281. if (opts & OPT_mount) {
  282. int exit_status = wait_for_exitstatus(child);
  283. if (WIFEXITED(exit_status) &&
  284. WEXITSTATUS(exit_status) != EXIT_SUCCESS)
  285. return WEXITSTATUS(exit_status);
  286. } else {
  287. /*
  288. * Regular way - we were requested to mount some other
  289. * namespaces: mount them after the call to unshare().
  290. */
  291. mount_namespaces(getpid(), ns_ctx_list);
  292. }
  293. }
  294. /*
  295. * When we're unsharing the pid namespace, it's not the process that
  296. * calls unshare() that is put into the new namespace, but its first
  297. * child. The user may want to use this option to spawn a new process
  298. * that'll become PID 1 in this new namespace.
  299. */
  300. if (opts & OPT_fork) {
  301. xvfork_parent_waits_and_exits();
  302. /* Child continues */
  303. }
  304. if (opts & OPT_map_root) {
  305. char uidmap_buf[sizeof("0 %u 1") + sizeof(int)*3];
  306. /*
  307. * Since Linux 3.19 unprivileged writing of /proc/self/gid_map
  308. * has been disabled unless /proc/self/setgroups is written
  309. * first to permanently disable the ability to call setgroups
  310. * in that user namespace.
  311. */
  312. xopen_xwrite_close(PATH_PROC_SETGROUPS, "deny");
  313. sprintf(uidmap_buf, "0 %u 1", (unsigned)reuid);
  314. xopen_xwrite_close(PATH_PROC_UIDMAP, uidmap_buf);
  315. sprintf(uidmap_buf, "0 %u 1", (unsigned)regid);
  316. xopen_xwrite_close(PATH_PROC_GIDMAP, uidmap_buf);
  317. } else
  318. if (setgrp_str) {
  319. /* Write "allow" or "deny" */
  320. xopen_xwrite_close(PATH_PROC_SETGROUPS, setgrp_str);
  321. }
  322. if (opts & OPT_mount) {
  323. mount_or_die("none", "/", NULL, prop_flags);
  324. }
  325. if (opts & OPT_mount_proc) {
  326. /*
  327. * When creating a new pid namespace, we might want the pid
  328. * subdirectories in /proc to remain consistent with the new
  329. * process IDs. Without --mount-proc the pids in /proc would
  330. * still reflect the old pid namespace. This is why we make
  331. * /proc private here and then do a fresh mount.
  332. */
  333. mount_or_die("none", proc_mnt_target, NULL, MS_PRIVATE | MS_REC);
  334. mount_or_die("proc", proc_mnt_target, "proc", MS_NOSUID | MS_NOEXEC | MS_NODEV);
  335. }
  336. exec_prog_or_SHELL(argv);
  337. }