utils.c 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615
  1. // SPDX-License-Identifier: GPL-2.0
  2. #ifndef _GNU_SOURCE
  3. #define _GNU_SOURCE
  4. #endif
  5. #include <fcntl.h>
  6. #include <sys/types.h>
  7. #include <dirent.h>
  8. #include <grp.h>
  9. #include <linux/limits.h>
  10. #include <sched.h>
  11. #include <stdio.h>
  12. #include <stdlib.h>
  13. #include <sys/eventfd.h>
  14. #include <sys/fsuid.h>
  15. #include <sys/prctl.h>
  16. #include <sys/socket.h>
  17. #include <sys/stat.h>
  18. #include <sys/types.h>
  19. #include <sys/wait.h>
  20. #include <sys/xattr.h>
  21. #include <sys/mount.h>
  22. #include "kselftest.h"
  23. #include "wrappers.h"
  24. #include "utils.h"
  25. #define MAX_USERNS_LEVEL 32
  26. #define syserror(format, ...) \
  27. ({ \
  28. fprintf(stderr, "%m - " format "\n", ##__VA_ARGS__); \
  29. (-errno); \
  30. })
  31. #define syserror_set(__ret__, format, ...) \
  32. ({ \
  33. typeof(__ret__) __internal_ret__ = (__ret__); \
  34. errno = labs(__ret__); \
  35. fprintf(stderr, "%m - " format "\n", ##__VA_ARGS__); \
  36. __internal_ret__; \
  37. })
  38. #define STRLITERALLEN(x) (sizeof(""x"") - 1)
  39. #define INTTYPE_TO_STRLEN(type) \
  40. (2 + (sizeof(type) <= 1 \
  41. ? 3 \
  42. : sizeof(type) <= 2 \
  43. ? 5 \
  44. : sizeof(type) <= 4 \
  45. ? 10 \
  46. : sizeof(type) <= 8 ? 20 : sizeof(int[-2 * (sizeof(type) > 8)])))
  47. #define list_for_each(__iterator, __list) \
  48. for (__iterator = (__list)->next; __iterator != __list; __iterator = __iterator->next)
  49. typedef enum idmap_type_t {
  50. ID_TYPE_UID,
  51. ID_TYPE_GID
  52. } idmap_type_t;
  53. struct id_map {
  54. idmap_type_t map_type;
  55. __u32 nsid;
  56. __u32 hostid;
  57. __u32 range;
  58. };
  59. struct list {
  60. void *elem;
  61. struct list *next;
  62. struct list *prev;
  63. };
  64. struct userns_hierarchy {
  65. int fd_userns;
  66. int fd_event;
  67. unsigned int level;
  68. struct list id_map;
  69. };
  70. static inline void list_init(struct list *list)
  71. {
  72. list->elem = NULL;
  73. list->next = list->prev = list;
  74. }
  75. static inline int list_empty(const struct list *list)
  76. {
  77. return list == list->next;
  78. }
  79. static inline void __list_add(struct list *new, struct list *prev, struct list *next)
  80. {
  81. next->prev = new;
  82. new->next = next;
  83. new->prev = prev;
  84. prev->next = new;
  85. }
  86. static inline void list_add_tail(struct list *head, struct list *list)
  87. {
  88. __list_add(list, head->prev, head);
  89. }
  90. static inline void list_del(struct list *list)
  91. {
  92. struct list *next, *prev;
  93. next = list->next;
  94. prev = list->prev;
  95. next->prev = prev;
  96. prev->next = next;
  97. }
  98. static ssize_t read_nointr(int fd, void *buf, size_t count)
  99. {
  100. ssize_t ret;
  101. do {
  102. ret = read(fd, buf, count);
  103. } while (ret < 0 && errno == EINTR);
  104. return ret;
  105. }
  106. static ssize_t write_nointr(int fd, const void *buf, size_t count)
  107. {
  108. ssize_t ret;
  109. do {
  110. ret = write(fd, buf, count);
  111. } while (ret < 0 && errno == EINTR);
  112. return ret;
  113. }
  114. #define __STACK_SIZE (8 * 1024 * 1024)
  115. static pid_t do_clone(int (*fn)(void *), void *arg, int flags)
  116. {
  117. void *stack;
  118. stack = malloc(__STACK_SIZE);
  119. if (!stack)
  120. return -ENOMEM;
  121. #ifdef __ia64__
  122. return __clone2(fn, stack, __STACK_SIZE, flags | SIGCHLD, arg, NULL);
  123. #else
  124. return clone(fn, stack + __STACK_SIZE, flags | SIGCHLD, arg, NULL);
  125. #endif
  126. }
  127. static int get_userns_fd_cb(void *data)
  128. {
  129. for (;;)
  130. pause();
  131. _exit(0);
  132. }
  133. static int wait_for_pid(pid_t pid)
  134. {
  135. int status, ret;
  136. again:
  137. ret = waitpid(pid, &status, 0);
  138. if (ret == -1) {
  139. if (errno == EINTR)
  140. goto again;
  141. return -1;
  142. }
  143. if (!WIFEXITED(status))
  144. return -1;
  145. return WEXITSTATUS(status);
  146. }
  147. static int write_id_mapping(idmap_type_t map_type, pid_t pid, const char *buf, size_t buf_size)
  148. {
  149. int fd = -EBADF, setgroups_fd = -EBADF;
  150. int fret = -1;
  151. int ret;
  152. char path[STRLITERALLEN("/proc/") + INTTYPE_TO_STRLEN(pid_t) +
  153. STRLITERALLEN("/setgroups") + 1];
  154. if (geteuid() != 0 && map_type == ID_TYPE_GID) {
  155. ret = snprintf(path, sizeof(path), "/proc/%d/setgroups", pid);
  156. if (ret < 0 || ret >= sizeof(path))
  157. goto out;
  158. setgroups_fd = open(path, O_WRONLY | O_CLOEXEC);
  159. if (setgroups_fd < 0 && errno != ENOENT) {
  160. syserror("Failed to open \"%s\"", path);
  161. goto out;
  162. }
  163. if (setgroups_fd >= 0) {
  164. ret = write_nointr(setgroups_fd, "deny\n", STRLITERALLEN("deny\n"));
  165. if (ret != STRLITERALLEN("deny\n")) {
  166. syserror("Failed to write \"deny\" to \"/proc/%d/setgroups\"", pid);
  167. goto out;
  168. }
  169. }
  170. }
  171. ret = snprintf(path, sizeof(path), "/proc/%d/%cid_map", pid, map_type == ID_TYPE_UID ? 'u' : 'g');
  172. if (ret < 0 || ret >= sizeof(path))
  173. goto out;
  174. fd = open(path, O_WRONLY | O_CLOEXEC);
  175. if (fd < 0) {
  176. syserror("Failed to open \"%s\"", path);
  177. goto out;
  178. }
  179. ret = write_nointr(fd, buf, buf_size);
  180. if (ret != buf_size) {
  181. syserror("Failed to write %cid mapping to \"%s\"",
  182. map_type == ID_TYPE_UID ? 'u' : 'g', path);
  183. goto out;
  184. }
  185. fret = 0;
  186. out:
  187. close(fd);
  188. close(setgroups_fd);
  189. return fret;
  190. }
  191. static int map_ids_from_idmap(struct list *idmap, pid_t pid)
  192. {
  193. int fill, left;
  194. char mapbuf[4096] = {};
  195. bool had_entry = false;
  196. idmap_type_t map_type, u_or_g;
  197. if (list_empty(idmap))
  198. return 0;
  199. for (map_type = ID_TYPE_UID, u_or_g = 'u';
  200. map_type <= ID_TYPE_GID; map_type++, u_or_g = 'g') {
  201. char *pos = mapbuf;
  202. int ret;
  203. struct list *iterator;
  204. list_for_each(iterator, idmap) {
  205. struct id_map *map = iterator->elem;
  206. if (map->map_type != map_type)
  207. continue;
  208. had_entry = true;
  209. left = 4096 - (pos - mapbuf);
  210. fill = snprintf(pos, left, "%u %u %u\n", map->nsid, map->hostid, map->range);
  211. /*
  212. * The kernel only takes <= 4k for writes to
  213. * /proc/<pid>/{g,u}id_map
  214. */
  215. if (fill <= 0 || fill >= left)
  216. return syserror_set(-E2BIG, "Too many %cid mappings defined", u_or_g);
  217. pos += fill;
  218. }
  219. if (!had_entry)
  220. continue;
  221. ret = write_id_mapping(map_type, pid, mapbuf, pos - mapbuf);
  222. if (ret < 0)
  223. return syserror("Failed to write mapping: %s", mapbuf);
  224. memset(mapbuf, 0, sizeof(mapbuf));
  225. }
  226. return 0;
  227. }
  228. static int get_userns_fd_from_idmap(struct list *idmap)
  229. {
  230. int ret;
  231. pid_t pid;
  232. char path_ns[STRLITERALLEN("/proc/") + INTTYPE_TO_STRLEN(pid_t) +
  233. STRLITERALLEN("/ns/user") + 1];
  234. pid = do_clone(get_userns_fd_cb, NULL, CLONE_NEWUSER | CLONE_NEWNS);
  235. if (pid < 0)
  236. return -errno;
  237. ret = map_ids_from_idmap(idmap, pid);
  238. if (ret < 0)
  239. return ret;
  240. ret = snprintf(path_ns, sizeof(path_ns), "/proc/%d/ns/user", pid);
  241. if (ret < 0 || (size_t)ret >= sizeof(path_ns))
  242. ret = -EIO;
  243. else
  244. ret = open(path_ns, O_RDONLY | O_CLOEXEC | O_NOCTTY);
  245. (void)kill(pid, SIGKILL);
  246. (void)wait_for_pid(pid);
  247. return ret;
  248. }
  249. int get_userns_fd(unsigned long nsid, unsigned long hostid, unsigned long range)
  250. {
  251. struct list head, uid_mapl, gid_mapl;
  252. struct id_map uid_map = {
  253. .map_type = ID_TYPE_UID,
  254. .nsid = nsid,
  255. .hostid = hostid,
  256. .range = range,
  257. };
  258. struct id_map gid_map = {
  259. .map_type = ID_TYPE_GID,
  260. .nsid = nsid,
  261. .hostid = hostid,
  262. .range = range,
  263. };
  264. list_init(&head);
  265. uid_mapl.elem = &uid_map;
  266. gid_mapl.elem = &gid_map;
  267. list_add_tail(&head, &uid_mapl);
  268. list_add_tail(&head, &gid_mapl);
  269. return get_userns_fd_from_idmap(&head);
  270. }
  271. bool switch_ids(uid_t uid, gid_t gid)
  272. {
  273. if (setgroups(0, NULL))
  274. return syserror("failure: setgroups");
  275. if (setresgid(gid, gid, gid))
  276. return syserror("failure: setresgid");
  277. if (setresuid(uid, uid, uid))
  278. return syserror("failure: setresuid");
  279. /* Ensure we can access proc files from processes we can ptrace. */
  280. if (prctl(PR_SET_DUMPABLE, 1, 0, 0, 0))
  281. return syserror("failure: make dumpable");
  282. return true;
  283. }
  284. static int create_userns_hierarchy(struct userns_hierarchy *h);
  285. static int userns_fd_cb(void *data)
  286. {
  287. struct userns_hierarchy *h = data;
  288. char c;
  289. int ret;
  290. ret = read_nointr(h->fd_event, &c, 1);
  291. if (ret < 0)
  292. return syserror("failure: read from socketpair");
  293. /* Only switch ids if someone actually wrote a mapping for us. */
  294. if (c == '1') {
  295. if (!switch_ids(0, 0))
  296. return syserror("failure: switch ids to 0");
  297. }
  298. ret = write_nointr(h->fd_event, "1", 1);
  299. if (ret < 0)
  300. return syserror("failure: write to socketpair");
  301. ret = create_userns_hierarchy(++h);
  302. if (ret < 0)
  303. return syserror("failure: userns level %d", h->level);
  304. return 0;
  305. }
  306. static int create_userns_hierarchy(struct userns_hierarchy *h)
  307. {
  308. int fret = -1;
  309. char c;
  310. int fd_socket[2];
  311. int fd_userns = -EBADF, ret = -1;
  312. ssize_t bytes;
  313. pid_t pid;
  314. char path[256];
  315. if (h->level == MAX_USERNS_LEVEL)
  316. return 0;
  317. ret = socketpair(AF_LOCAL, SOCK_STREAM | SOCK_CLOEXEC, 0, fd_socket);
  318. if (ret < 0)
  319. return syserror("failure: create socketpair");
  320. /* Note the CLONE_FILES | CLONE_VM when mucking with fds and memory. */
  321. h->fd_event = fd_socket[1];
  322. pid = do_clone(userns_fd_cb, h, CLONE_NEWUSER | CLONE_FILES | CLONE_VM);
  323. if (pid < 0) {
  324. syserror("failure: userns level %d", h->level);
  325. goto out_close;
  326. }
  327. ret = map_ids_from_idmap(&h->id_map, pid);
  328. if (ret < 0) {
  329. kill(pid, SIGKILL);
  330. syserror("failure: writing id mapping for userns level %d for %d", h->level, pid);
  331. goto out_wait;
  332. }
  333. if (!list_empty(&h->id_map))
  334. bytes = write_nointr(fd_socket[0], "1", 1); /* Inform the child we wrote a mapping. */
  335. else
  336. bytes = write_nointr(fd_socket[0], "0", 1); /* Inform the child we didn't write a mapping. */
  337. if (bytes < 0) {
  338. kill(pid, SIGKILL);
  339. syserror("failure: write to socketpair");
  340. goto out_wait;
  341. }
  342. /* Wait for child to set*id() and become dumpable. */
  343. bytes = read_nointr(fd_socket[0], &c, 1);
  344. if (bytes < 0) {
  345. kill(pid, SIGKILL);
  346. syserror("failure: read from socketpair");
  347. goto out_wait;
  348. }
  349. snprintf(path, sizeof(path), "/proc/%d/ns/user", pid);
  350. fd_userns = open(path, O_RDONLY | O_CLOEXEC);
  351. if (fd_userns < 0) {
  352. kill(pid, SIGKILL);
  353. syserror("failure: open userns level %d for %d", h->level, pid);
  354. goto out_wait;
  355. }
  356. fret = 0;
  357. out_wait:
  358. if (!wait_for_pid(pid) && !fret) {
  359. h->fd_userns = fd_userns;
  360. fd_userns = -EBADF;
  361. }
  362. out_close:
  363. if (fd_userns >= 0)
  364. close(fd_userns);
  365. close(fd_socket[0]);
  366. close(fd_socket[1]);
  367. return fret;
  368. }
  369. static int write_file(const char *path, const char *val)
  370. {
  371. int fd = open(path, O_WRONLY);
  372. size_t len = strlen(val);
  373. int ret;
  374. if (fd == -1) {
  375. ksft_print_msg("opening %s for write: %s\n", path, strerror(errno));
  376. return -1;
  377. }
  378. ret = write(fd, val, len);
  379. if (ret == -1) {
  380. ksft_print_msg("writing to %s: %s\n", path, strerror(errno));
  381. return -1;
  382. }
  383. if (ret != len) {
  384. ksft_print_msg("short write to %s\n", path);
  385. return -1;
  386. }
  387. ret = close(fd);
  388. if (ret == -1) {
  389. ksft_print_msg("closing %s\n", path);
  390. return -1;
  391. }
  392. return 0;
  393. }
  394. int setup_userns(void)
  395. {
  396. int ret;
  397. char buf[32];
  398. uid_t uid = getuid();
  399. gid_t gid = getgid();
  400. ret = unshare(CLONE_NEWNS|CLONE_NEWUSER);
  401. if (ret) {
  402. ksft_exit_fail_msg("unsharing mountns and userns: %s\n",
  403. strerror(errno));
  404. return ret;
  405. }
  406. sprintf(buf, "0 %d 1", uid);
  407. ret = write_file("/proc/self/uid_map", buf);
  408. if (ret)
  409. return ret;
  410. ret = write_file("/proc/self/setgroups", "deny");
  411. if (ret)
  412. return ret;
  413. sprintf(buf, "0 %d 1", gid);
  414. ret = write_file("/proc/self/gid_map", buf);
  415. if (ret)
  416. return ret;
  417. ret = mount("", "/", NULL, MS_REC|MS_PRIVATE, NULL);
  418. if (ret) {
  419. ksft_print_msg("making mount tree private: %s\n", strerror(errno));
  420. return ret;
  421. }
  422. return 0;
  423. }
  424. int enter_userns(void)
  425. {
  426. int ret;
  427. char buf[32];
  428. uid_t uid = getuid();
  429. gid_t gid = getgid();
  430. ret = unshare(CLONE_NEWUSER);
  431. if (ret)
  432. return ret;
  433. sprintf(buf, "0 %d 1", uid);
  434. ret = write_file("/proc/self/uid_map", buf);
  435. if (ret)
  436. return ret;
  437. ret = write_file("/proc/self/setgroups", "deny");
  438. if (ret)
  439. return ret;
  440. sprintf(buf, "0 %d 1", gid);
  441. ret = write_file("/proc/self/gid_map", buf);
  442. if (ret)
  443. return ret;
  444. return 0;
  445. }
  446. /* caps_down - lower all effective caps */
  447. int caps_down(void)
  448. {
  449. bool fret = false;
  450. cap_t caps = NULL;
  451. int ret = -1;
  452. caps = cap_get_proc();
  453. if (!caps)
  454. goto out;
  455. ret = cap_clear_flag(caps, CAP_EFFECTIVE);
  456. if (ret)
  457. goto out;
  458. ret = cap_set_proc(caps);
  459. if (ret)
  460. goto out;
  461. fret = true;
  462. out:
  463. cap_free(caps);
  464. return fret;
  465. }
  466. /* cap_down - lower an effective cap */
  467. int cap_down(cap_value_t down)
  468. {
  469. bool fret = false;
  470. cap_t caps = NULL;
  471. cap_value_t cap = down;
  472. int ret = -1;
  473. caps = cap_get_proc();
  474. if (!caps)
  475. goto out;
  476. ret = cap_set_flag(caps, CAP_EFFECTIVE, 1, &cap, 0);
  477. if (ret)
  478. goto out;
  479. ret = cap_set_proc(caps);
  480. if (ret)
  481. goto out;
  482. fret = true;
  483. out:
  484. cap_free(caps);
  485. return fret;
  486. }
  487. uint64_t get_unique_mnt_id(const char *path)
  488. {
  489. struct statx sx;
  490. int ret;
  491. ret = statx(AT_FDCWD, path, 0, STATX_MNT_ID_UNIQUE, &sx);
  492. if (ret == -1) {
  493. ksft_print_msg("retrieving unique mount ID for %s: %s\n", path,
  494. strerror(errno));
  495. return 0;
  496. }
  497. if (!(sx.stx_mask & STATX_MNT_ID_UNIQUE)) {
  498. ksft_print_msg("no unique mount ID available for %s\n", path);
  499. return 0;
  500. }
  501. return sx.stx_mnt_id;
  502. }