binfmt_misc.c 26 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090
  1. // SPDX-License-Identifier: GPL-2.0-only
  2. /*
  3. * binfmt_misc.c
  4. *
  5. * Copyright (C) 1997 Richard Günther
  6. *
  7. * binfmt_misc detects binaries via a magic or filename extension and invokes
  8. * a specified wrapper. See Documentation/admin-guide/binfmt-misc.rst for more details.
  9. */
  10. #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
  11. #include <linux/kernel.h>
  12. #include <linux/module.h>
  13. #include <linux/init.h>
  14. #include <linux/sched/mm.h>
  15. #include <linux/magic.h>
  16. #include <linux/binfmts.h>
  17. #include <linux/slab.h>
  18. #include <linux/ctype.h>
  19. #include <linux/string_helpers.h>
  20. #include <linux/file.h>
  21. #include <linux/pagemap.h>
  22. #include <linux/namei.h>
  23. #include <linux/mount.h>
  24. #include <linux/fs_context.h>
  25. #include <linux/syscalls.h>
  26. #include <linux/fs.h>
  27. #include <linux/uaccess.h>
  28. #include "internal.h"
  29. #ifdef DEBUG
  30. # define USE_DEBUG 1
  31. #else
  32. # define USE_DEBUG 0
  33. #endif
  34. enum {
  35. VERBOSE_STATUS = 1 /* make it zero to save 400 bytes kernel memory */
  36. };
  37. enum {Enabled, Magic};
  38. #define MISC_FMT_PRESERVE_ARGV0 (1UL << 31)
  39. #define MISC_FMT_OPEN_BINARY (1UL << 30)
  40. #define MISC_FMT_CREDENTIALS (1UL << 29)
  41. #define MISC_FMT_OPEN_FILE (1UL << 28)
  42. typedef struct {
  43. struct list_head list;
  44. unsigned long flags; /* type, status, etc. */
  45. int offset; /* offset of magic */
  46. int size; /* size of magic/mask */
  47. char *magic; /* magic or filename extension */
  48. char *mask; /* mask, NULL for exact match */
  49. const char *interpreter; /* filename of interpreter */
  50. char *name;
  51. struct dentry *dentry;
  52. struct file *interp_file;
  53. refcount_t users; /* sync removal with load_misc_binary() */
  54. } Node;
  55. static struct file_system_type bm_fs_type;
  56. /*
  57. * Max length of the register string. Determined by:
  58. * - 7 delimiters
  59. * - name: ~50 bytes
  60. * - type: 1 byte
  61. * - offset: 3 bytes (has to be smaller than BINPRM_BUF_SIZE)
  62. * - magic: 128 bytes (512 in escaped form)
  63. * - mask: 128 bytes (512 in escaped form)
  64. * - interp: ~50 bytes
  65. * - flags: 5 bytes
  66. * Round that up a bit, and then back off to hold the internal data
  67. * (like struct Node).
  68. */
  69. #define MAX_REGISTER_LENGTH 1920
  70. /**
  71. * search_binfmt_handler - search for a binary handler for @bprm
  72. * @misc: handle to binfmt_misc instance
  73. * @bprm: binary for which we are looking for a handler
  74. *
  75. * Search for a binary type handler for @bprm in the list of registered binary
  76. * type handlers.
  77. *
  78. * Return: binary type list entry on success, NULL on failure
  79. */
  80. static Node *search_binfmt_handler(struct binfmt_misc *misc,
  81. struct linux_binprm *bprm)
  82. {
  83. char *p = strrchr(bprm->interp, '.');
  84. Node *e;
  85. /* Walk all the registered handlers. */
  86. list_for_each_entry(e, &misc->entries, list) {
  87. char *s;
  88. int j;
  89. /* Make sure this one is currently enabled. */
  90. if (!test_bit(Enabled, &e->flags))
  91. continue;
  92. /* Do matching based on extension if applicable. */
  93. if (!test_bit(Magic, &e->flags)) {
  94. if (p && !strcmp(e->magic, p + 1))
  95. return e;
  96. continue;
  97. }
  98. /* Do matching based on magic & mask. */
  99. s = bprm->buf + e->offset;
  100. if (e->mask) {
  101. for (j = 0; j < e->size; j++)
  102. if ((*s++ ^ e->magic[j]) & e->mask[j])
  103. break;
  104. } else {
  105. for (j = 0; j < e->size; j++)
  106. if ((*s++ ^ e->magic[j]))
  107. break;
  108. }
  109. if (j == e->size)
  110. return e;
  111. }
  112. return NULL;
  113. }
  114. /**
  115. * get_binfmt_handler - try to find a binary type handler
  116. * @misc: handle to binfmt_misc instance
  117. * @bprm: binary for which we are looking for a handler
  118. *
  119. * Try to find a binfmt handler for the binary type. If one is found take a
  120. * reference to protect against removal via bm_{entry,status}_write().
  121. *
  122. * Return: binary type list entry on success, NULL on failure
  123. */
  124. static Node *get_binfmt_handler(struct binfmt_misc *misc,
  125. struct linux_binprm *bprm)
  126. {
  127. Node *e;
  128. read_lock(&misc->entries_lock);
  129. e = search_binfmt_handler(misc, bprm);
  130. if (e)
  131. refcount_inc(&e->users);
  132. read_unlock(&misc->entries_lock);
  133. return e;
  134. }
  135. /**
  136. * put_binfmt_handler - put binary handler node
  137. * @e: node to put
  138. *
  139. * Free node syncing with load_misc_binary() and defer final free to
  140. * load_misc_binary() in case it is using the binary type handler we were
  141. * requested to remove.
  142. */
  143. static void put_binfmt_handler(Node *e)
  144. {
  145. if (refcount_dec_and_test(&e->users)) {
  146. if (e->flags & MISC_FMT_OPEN_FILE)
  147. filp_close(e->interp_file, NULL);
  148. kfree(e);
  149. }
  150. }
  151. /**
  152. * load_binfmt_misc - load the binfmt_misc of the caller's user namespace
  153. *
  154. * To be called in load_misc_binary() to load the relevant struct binfmt_misc.
  155. * If a user namespace doesn't have its own binfmt_misc mount it can make use
  156. * of its ancestor's binfmt_misc handlers. This mimicks the behavior of
  157. * pre-namespaced binfmt_misc where all registered binfmt_misc handlers where
  158. * available to all user and user namespaces on the system.
  159. *
  160. * Return: the binfmt_misc instance of the caller's user namespace
  161. */
  162. static struct binfmt_misc *load_binfmt_misc(void)
  163. {
  164. const struct user_namespace *user_ns;
  165. struct binfmt_misc *misc;
  166. user_ns = current_user_ns();
  167. while (user_ns) {
  168. /* Pairs with smp_store_release() in bm_fill_super(). */
  169. misc = smp_load_acquire(&user_ns->binfmt_misc);
  170. if (misc)
  171. return misc;
  172. user_ns = user_ns->parent;
  173. }
  174. return &init_binfmt_misc;
  175. }
  176. /*
  177. * the loader itself
  178. */
  179. static int load_misc_binary(struct linux_binprm *bprm)
  180. {
  181. Node *fmt;
  182. struct file *interp_file = NULL;
  183. int retval = -ENOEXEC;
  184. struct binfmt_misc *misc;
  185. misc = load_binfmt_misc();
  186. if (!misc->enabled)
  187. return retval;
  188. fmt = get_binfmt_handler(misc, bprm);
  189. if (!fmt)
  190. return retval;
  191. /* Need to be able to load the file after exec */
  192. retval = -ENOENT;
  193. if (bprm->interp_flags & BINPRM_FLAGS_PATH_INACCESSIBLE)
  194. goto ret;
  195. if (fmt->flags & MISC_FMT_PRESERVE_ARGV0) {
  196. bprm->interp_flags |= BINPRM_FLAGS_PRESERVE_ARGV0;
  197. } else {
  198. retval = remove_arg_zero(bprm);
  199. if (retval)
  200. goto ret;
  201. }
  202. if (fmt->flags & MISC_FMT_OPEN_BINARY)
  203. bprm->have_execfd = 1;
  204. /* make argv[1] be the path to the binary */
  205. retval = copy_string_kernel(bprm->interp, bprm);
  206. if (retval < 0)
  207. goto ret;
  208. bprm->argc++;
  209. /* add the interp as argv[0] */
  210. retval = copy_string_kernel(fmt->interpreter, bprm);
  211. if (retval < 0)
  212. goto ret;
  213. bprm->argc++;
  214. /* Update interp in case binfmt_script needs it. */
  215. retval = bprm_change_interp(fmt->interpreter, bprm);
  216. if (retval < 0)
  217. goto ret;
  218. if (fmt->flags & MISC_FMT_OPEN_FILE) {
  219. interp_file = file_clone_open(fmt->interp_file);
  220. if (!IS_ERR(interp_file))
  221. deny_write_access(interp_file);
  222. } else {
  223. interp_file = open_exec(fmt->interpreter);
  224. }
  225. retval = PTR_ERR(interp_file);
  226. if (IS_ERR(interp_file))
  227. goto ret;
  228. bprm->interpreter = interp_file;
  229. if (fmt->flags & MISC_FMT_CREDENTIALS)
  230. bprm->execfd_creds = 1;
  231. retval = 0;
  232. ret:
  233. /*
  234. * If we actually put the node here all concurrent calls to
  235. * load_misc_binary() will have finished. We also know
  236. * that for the refcount to be zero someone must have concurently
  237. * removed the binary type handler from the list and it's our job to
  238. * free it.
  239. */
  240. put_binfmt_handler(fmt);
  241. return retval;
  242. }
  243. /* Command parsers */
  244. /*
  245. * parses and copies one argument enclosed in del from *sp to *dp,
  246. * recognising the \x special.
  247. * returns pointer to the copied argument or NULL in case of an
  248. * error (and sets err) or null argument length.
  249. */
  250. static char *scanarg(char *s, char del)
  251. {
  252. char c;
  253. while ((c = *s++) != del) {
  254. if (c == '\\' && *s == 'x') {
  255. s++;
  256. if (!isxdigit(*s++))
  257. return NULL;
  258. if (!isxdigit(*s++))
  259. return NULL;
  260. }
  261. }
  262. s[-1] ='\0';
  263. return s;
  264. }
  265. static char *check_special_flags(char *sfs, Node *e)
  266. {
  267. char *p = sfs;
  268. int cont = 1;
  269. /* special flags */
  270. while (cont) {
  271. switch (*p) {
  272. case 'P':
  273. pr_debug("register: flag: P (preserve argv0)\n");
  274. p++;
  275. e->flags |= MISC_FMT_PRESERVE_ARGV0;
  276. break;
  277. case 'O':
  278. pr_debug("register: flag: O (open binary)\n");
  279. p++;
  280. e->flags |= MISC_FMT_OPEN_BINARY;
  281. break;
  282. case 'C':
  283. pr_debug("register: flag: C (preserve creds)\n");
  284. p++;
  285. /* this flags also implies the
  286. open-binary flag */
  287. e->flags |= (MISC_FMT_CREDENTIALS |
  288. MISC_FMT_OPEN_BINARY);
  289. break;
  290. case 'F':
  291. pr_debug("register: flag: F: open interpreter file now\n");
  292. p++;
  293. e->flags |= MISC_FMT_OPEN_FILE;
  294. break;
  295. default:
  296. cont = 0;
  297. }
  298. }
  299. return p;
  300. }
  301. /*
  302. * This registers a new binary format, it recognises the syntax
  303. * ':name:type:offset:magic:mask:interpreter:flags'
  304. * where the ':' is the IFS, that can be chosen with the first char
  305. */
  306. static Node *create_entry(const char __user *buffer, size_t count)
  307. {
  308. Node *e;
  309. int memsize, err;
  310. char *buf, *p;
  311. char del;
  312. pr_debug("register: received %zu bytes\n", count);
  313. /* some sanity checks */
  314. err = -EINVAL;
  315. if ((count < 11) || (count > MAX_REGISTER_LENGTH))
  316. goto out;
  317. err = -ENOMEM;
  318. memsize = sizeof(Node) + count + 8;
  319. e = kmalloc(memsize, GFP_KERNEL_ACCOUNT);
  320. if (!e)
  321. goto out;
  322. p = buf = (char *)e + sizeof(Node);
  323. memset(e, 0, sizeof(Node));
  324. if (copy_from_user(buf, buffer, count))
  325. goto efault;
  326. del = *p++; /* delimeter */
  327. pr_debug("register: delim: %#x {%c}\n", del, del);
  328. /* Pad the buffer with the delim to simplify parsing below. */
  329. memset(buf + count, del, 8);
  330. /* Parse the 'name' field. */
  331. e->name = p;
  332. p = strchr(p, del);
  333. if (!p)
  334. goto einval;
  335. *p++ = '\0';
  336. if (!e->name[0] ||
  337. !strcmp(e->name, ".") ||
  338. !strcmp(e->name, "..") ||
  339. strchr(e->name, '/'))
  340. goto einval;
  341. pr_debug("register: name: {%s}\n", e->name);
  342. /* Parse the 'type' field. */
  343. switch (*p++) {
  344. case 'E':
  345. pr_debug("register: type: E (extension)\n");
  346. e->flags = 1 << Enabled;
  347. break;
  348. case 'M':
  349. pr_debug("register: type: M (magic)\n");
  350. e->flags = (1 << Enabled) | (1 << Magic);
  351. break;
  352. default:
  353. goto einval;
  354. }
  355. if (*p++ != del)
  356. goto einval;
  357. if (test_bit(Magic, &e->flags)) {
  358. /* Handle the 'M' (magic) format. */
  359. char *s;
  360. /* Parse the 'offset' field. */
  361. s = strchr(p, del);
  362. if (!s)
  363. goto einval;
  364. *s = '\0';
  365. if (p != s) {
  366. int r = kstrtoint(p, 10, &e->offset);
  367. if (r != 0 || e->offset < 0)
  368. goto einval;
  369. }
  370. p = s;
  371. if (*p++)
  372. goto einval;
  373. pr_debug("register: offset: %#x\n", e->offset);
  374. /* Parse the 'magic' field. */
  375. e->magic = p;
  376. p = scanarg(p, del);
  377. if (!p)
  378. goto einval;
  379. if (!e->magic[0])
  380. goto einval;
  381. if (USE_DEBUG)
  382. print_hex_dump_bytes(
  383. KBUILD_MODNAME ": register: magic[raw]: ",
  384. DUMP_PREFIX_NONE, e->magic, p - e->magic);
  385. /* Parse the 'mask' field. */
  386. e->mask = p;
  387. p = scanarg(p, del);
  388. if (!p)
  389. goto einval;
  390. if (!e->mask[0]) {
  391. e->mask = NULL;
  392. pr_debug("register: mask[raw]: none\n");
  393. } else if (USE_DEBUG)
  394. print_hex_dump_bytes(
  395. KBUILD_MODNAME ": register: mask[raw]: ",
  396. DUMP_PREFIX_NONE, e->mask, p - e->mask);
  397. /*
  398. * Decode the magic & mask fields.
  399. * Note: while we might have accepted embedded NUL bytes from
  400. * above, the unescape helpers here will stop at the first one
  401. * it encounters.
  402. */
  403. e->size = string_unescape_inplace(e->magic, UNESCAPE_HEX);
  404. if (e->mask &&
  405. string_unescape_inplace(e->mask, UNESCAPE_HEX) != e->size)
  406. goto einval;
  407. if (e->size > BINPRM_BUF_SIZE ||
  408. BINPRM_BUF_SIZE - e->size < e->offset)
  409. goto einval;
  410. pr_debug("register: magic/mask length: %i\n", e->size);
  411. if (USE_DEBUG) {
  412. print_hex_dump_bytes(
  413. KBUILD_MODNAME ": register: magic[decoded]: ",
  414. DUMP_PREFIX_NONE, e->magic, e->size);
  415. if (e->mask) {
  416. int i;
  417. char *masked = kmalloc(e->size, GFP_KERNEL_ACCOUNT);
  418. print_hex_dump_bytes(
  419. KBUILD_MODNAME ": register: mask[decoded]: ",
  420. DUMP_PREFIX_NONE, e->mask, e->size);
  421. if (masked) {
  422. for (i = 0; i < e->size; ++i)
  423. masked[i] = e->magic[i] & e->mask[i];
  424. print_hex_dump_bytes(
  425. KBUILD_MODNAME ": register: magic[masked]: ",
  426. DUMP_PREFIX_NONE, masked, e->size);
  427. kfree(masked);
  428. }
  429. }
  430. }
  431. } else {
  432. /* Handle the 'E' (extension) format. */
  433. /* Skip the 'offset' field. */
  434. p = strchr(p, del);
  435. if (!p)
  436. goto einval;
  437. *p++ = '\0';
  438. /* Parse the 'magic' field. */
  439. e->magic = p;
  440. p = strchr(p, del);
  441. if (!p)
  442. goto einval;
  443. *p++ = '\0';
  444. if (!e->magic[0] || strchr(e->magic, '/'))
  445. goto einval;
  446. pr_debug("register: extension: {%s}\n", e->magic);
  447. /* Skip the 'mask' field. */
  448. p = strchr(p, del);
  449. if (!p)
  450. goto einval;
  451. *p++ = '\0';
  452. }
  453. /* Parse the 'interpreter' field. */
  454. e->interpreter = p;
  455. p = strchr(p, del);
  456. if (!p)
  457. goto einval;
  458. *p++ = '\0';
  459. if (!e->interpreter[0])
  460. goto einval;
  461. pr_debug("register: interpreter: {%s}\n", e->interpreter);
  462. /* Parse the 'flags' field. */
  463. p = check_special_flags(p, e);
  464. if (*p == '\n')
  465. p++;
  466. if (p != buf + count)
  467. goto einval;
  468. return e;
  469. out:
  470. return ERR_PTR(err);
  471. efault:
  472. kfree(e);
  473. return ERR_PTR(-EFAULT);
  474. einval:
  475. kfree(e);
  476. return ERR_PTR(-EINVAL);
  477. }
  478. /*
  479. * Set status of entry/binfmt_misc:
  480. * '1' enables, '0' disables and '-1' clears entry/binfmt_misc
  481. */
  482. static int parse_command(const char __user *buffer, size_t count)
  483. {
  484. char s[4];
  485. if (count > 3)
  486. return -EINVAL;
  487. if (copy_from_user(s, buffer, count))
  488. return -EFAULT;
  489. if (!count)
  490. return 0;
  491. if (s[count - 1] == '\n')
  492. count--;
  493. if (count == 1 && s[0] == '0')
  494. return 1;
  495. if (count == 1 && s[0] == '1')
  496. return 2;
  497. if (count == 2 && s[0] == '-' && s[1] == '1')
  498. return 3;
  499. return -EINVAL;
  500. }
  501. /* generic stuff */
  502. static void entry_status(Node *e, char *page)
  503. {
  504. char *dp = page;
  505. const char *status = "disabled";
  506. if (test_bit(Enabled, &e->flags))
  507. status = "enabled";
  508. if (!VERBOSE_STATUS) {
  509. sprintf(page, "%s\n", status);
  510. return;
  511. }
  512. dp += sprintf(dp, "%s\ninterpreter %s\n", status, e->interpreter);
  513. /* print the special flags */
  514. dp += sprintf(dp, "flags: ");
  515. if (e->flags & MISC_FMT_PRESERVE_ARGV0)
  516. *dp++ = 'P';
  517. if (e->flags & MISC_FMT_OPEN_BINARY)
  518. *dp++ = 'O';
  519. if (e->flags & MISC_FMT_CREDENTIALS)
  520. *dp++ = 'C';
  521. if (e->flags & MISC_FMT_OPEN_FILE)
  522. *dp++ = 'F';
  523. *dp++ = '\n';
  524. if (!test_bit(Magic, &e->flags)) {
  525. sprintf(dp, "extension .%s\n", e->magic);
  526. } else {
  527. dp += sprintf(dp, "offset %i\nmagic ", e->offset);
  528. dp = bin2hex(dp, e->magic, e->size);
  529. if (e->mask) {
  530. dp += sprintf(dp, "\nmask ");
  531. dp = bin2hex(dp, e->mask, e->size);
  532. }
  533. *dp++ = '\n';
  534. *dp = '\0';
  535. }
  536. }
  537. static struct inode *bm_get_inode(struct super_block *sb, int mode)
  538. {
  539. struct inode *inode = new_inode(sb);
  540. if (inode) {
  541. inode->i_ino = get_next_ino();
  542. inode->i_mode = mode;
  543. simple_inode_init_ts(inode);
  544. }
  545. return inode;
  546. }
  547. /**
  548. * i_binfmt_misc - retrieve struct binfmt_misc from a binfmt_misc inode
  549. * @inode: inode of the relevant binfmt_misc instance
  550. *
  551. * This helper retrieves struct binfmt_misc from a binfmt_misc inode. This can
  552. * be done without any memory barriers because we are guaranteed that
  553. * user_ns->binfmt_misc is fully initialized. It was fully initialized when the
  554. * binfmt_misc mount was first created.
  555. *
  556. * Return: struct binfmt_misc of the relevant binfmt_misc instance
  557. */
  558. static struct binfmt_misc *i_binfmt_misc(struct inode *inode)
  559. {
  560. return inode->i_sb->s_user_ns->binfmt_misc;
  561. }
  562. /**
  563. * bm_evict_inode - cleanup data associated with @inode
  564. * @inode: inode to which the data is attached
  565. *
  566. * Cleanup the binary type handler data associated with @inode if a binary type
  567. * entry is removed or the filesystem is unmounted and the super block is
  568. * shutdown.
  569. *
  570. * If the ->evict call was not caused by a super block shutdown but by a write
  571. * to remove the entry or all entries via bm_{entry,status}_write() the entry
  572. * will have already been removed from the list. We keep the list_empty() check
  573. * to make that explicit.
  574. */
  575. static void bm_evict_inode(struct inode *inode)
  576. {
  577. Node *e = inode->i_private;
  578. clear_inode(inode);
  579. if (e) {
  580. struct binfmt_misc *misc;
  581. misc = i_binfmt_misc(inode);
  582. write_lock(&misc->entries_lock);
  583. if (!list_empty(&e->list))
  584. list_del_init(&e->list);
  585. write_unlock(&misc->entries_lock);
  586. put_binfmt_handler(e);
  587. }
  588. }
  589. /**
  590. * unlink_binfmt_dentry - remove the dentry for the binary type handler
  591. * @dentry: dentry associated with the binary type handler
  592. *
  593. * Do the actual filesystem work to remove a dentry for a registered binary
  594. * type handler. Since binfmt_misc only allows simple files to be created
  595. * directly under the root dentry of the filesystem we ensure that we are
  596. * indeed passed a dentry directly beneath the root dentry, that the inode
  597. * associated with the root dentry is locked, and that it is a regular file we
  598. * are asked to remove.
  599. */
  600. static void unlink_binfmt_dentry(struct dentry *dentry)
  601. {
  602. struct dentry *parent = dentry->d_parent;
  603. struct inode *inode, *parent_inode;
  604. /* All entries are immediate descendants of the root dentry. */
  605. if (WARN_ON_ONCE(dentry->d_sb->s_root != parent))
  606. return;
  607. /* We only expect to be called on regular files. */
  608. inode = d_inode(dentry);
  609. if (WARN_ON_ONCE(!S_ISREG(inode->i_mode)))
  610. return;
  611. /* The parent inode must be locked. */
  612. parent_inode = d_inode(parent);
  613. if (WARN_ON_ONCE(!inode_is_locked(parent_inode)))
  614. return;
  615. if (simple_positive(dentry)) {
  616. dget(dentry);
  617. simple_unlink(parent_inode, dentry);
  618. d_delete(dentry);
  619. dput(dentry);
  620. }
  621. }
  622. /**
  623. * remove_binfmt_handler - remove a binary type handler
  624. * @misc: handle to binfmt_misc instance
  625. * @e: binary type handler to remove
  626. *
  627. * Remove a binary type handler from the list of binary type handlers and
  628. * remove its associated dentry. This is called from
  629. * binfmt_{entry,status}_write(). In the future, we might want to think about
  630. * adding a proper ->unlink() method to binfmt_misc instead of forcing caller's
  631. * to use writes to files in order to delete binary type handlers. But it has
  632. * worked for so long that it's not a pressing issue.
  633. */
  634. static void remove_binfmt_handler(struct binfmt_misc *misc, Node *e)
  635. {
  636. write_lock(&misc->entries_lock);
  637. list_del_init(&e->list);
  638. write_unlock(&misc->entries_lock);
  639. unlink_binfmt_dentry(e->dentry);
  640. }
  641. /* /<entry> */
  642. static ssize_t
  643. bm_entry_read(struct file *file, char __user *buf, size_t nbytes, loff_t *ppos)
  644. {
  645. Node *e = file_inode(file)->i_private;
  646. ssize_t res;
  647. char *page;
  648. page = (char *) __get_free_page(GFP_KERNEL);
  649. if (!page)
  650. return -ENOMEM;
  651. entry_status(e, page);
  652. res = simple_read_from_buffer(buf, nbytes, ppos, page, strlen(page));
  653. free_page((unsigned long) page);
  654. return res;
  655. }
  656. static ssize_t bm_entry_write(struct file *file, const char __user *buffer,
  657. size_t count, loff_t *ppos)
  658. {
  659. struct inode *inode = file_inode(file);
  660. Node *e = inode->i_private;
  661. int res = parse_command(buffer, count);
  662. switch (res) {
  663. case 1:
  664. /* Disable this handler. */
  665. clear_bit(Enabled, &e->flags);
  666. break;
  667. case 2:
  668. /* Enable this handler. */
  669. set_bit(Enabled, &e->flags);
  670. break;
  671. case 3:
  672. /* Delete this handler. */
  673. inode = d_inode(inode->i_sb->s_root);
  674. inode_lock(inode);
  675. /*
  676. * In order to add new element or remove elements from the list
  677. * via bm_{entry,register,status}_write() inode_lock() on the
  678. * root inode must be held.
  679. * The lock is exclusive ensuring that the list can't be
  680. * modified. Only load_misc_binary() can access but does so
  681. * read-only. So we only need to take the write lock when we
  682. * actually remove the entry from the list.
  683. */
  684. if (!list_empty(&e->list))
  685. remove_binfmt_handler(i_binfmt_misc(inode), e);
  686. inode_unlock(inode);
  687. break;
  688. default:
  689. return res;
  690. }
  691. return count;
  692. }
  693. static const struct file_operations bm_entry_operations = {
  694. .read = bm_entry_read,
  695. .write = bm_entry_write,
  696. .llseek = default_llseek,
  697. };
  698. /* /register */
  699. static ssize_t bm_register_write(struct file *file, const char __user *buffer,
  700. size_t count, loff_t *ppos)
  701. {
  702. Node *e;
  703. struct inode *inode;
  704. struct super_block *sb = file_inode(file)->i_sb;
  705. struct dentry *root = sb->s_root, *dentry;
  706. struct binfmt_misc *misc;
  707. int err = 0;
  708. struct file *f = NULL;
  709. e = create_entry(buffer, count);
  710. if (IS_ERR(e))
  711. return PTR_ERR(e);
  712. if (e->flags & MISC_FMT_OPEN_FILE) {
  713. const struct cred *old_cred;
  714. /*
  715. * Now that we support unprivileged binfmt_misc mounts make
  716. * sure we use the credentials that the register @file was
  717. * opened with to also open the interpreter. Before that this
  718. * didn't matter much as only a privileged process could open
  719. * the register file.
  720. */
  721. old_cred = override_creds(file->f_cred);
  722. f = open_exec(e->interpreter);
  723. revert_creds(old_cred);
  724. if (IS_ERR(f)) {
  725. pr_notice("register: failed to install interpreter file %s\n",
  726. e->interpreter);
  727. kfree(e);
  728. return PTR_ERR(f);
  729. }
  730. e->interp_file = f;
  731. }
  732. inode_lock(d_inode(root));
  733. dentry = lookup_one_len(e->name, root, strlen(e->name));
  734. err = PTR_ERR(dentry);
  735. if (IS_ERR(dentry))
  736. goto out;
  737. err = -EEXIST;
  738. if (d_really_is_positive(dentry))
  739. goto out2;
  740. inode = bm_get_inode(sb, S_IFREG | 0644);
  741. err = -ENOMEM;
  742. if (!inode)
  743. goto out2;
  744. refcount_set(&e->users, 1);
  745. e->dentry = dget(dentry);
  746. inode->i_private = e;
  747. inode->i_fop = &bm_entry_operations;
  748. d_instantiate(dentry, inode);
  749. misc = i_binfmt_misc(inode);
  750. write_lock(&misc->entries_lock);
  751. list_add(&e->list, &misc->entries);
  752. write_unlock(&misc->entries_lock);
  753. err = 0;
  754. out2:
  755. dput(dentry);
  756. out:
  757. inode_unlock(d_inode(root));
  758. if (err) {
  759. if (f)
  760. filp_close(f, NULL);
  761. kfree(e);
  762. return err;
  763. }
  764. return count;
  765. }
  766. static const struct file_operations bm_register_operations = {
  767. .write = bm_register_write,
  768. .llseek = noop_llseek,
  769. };
  770. /* /status */
  771. static ssize_t
  772. bm_status_read(struct file *file, char __user *buf, size_t nbytes, loff_t *ppos)
  773. {
  774. struct binfmt_misc *misc;
  775. char *s;
  776. misc = i_binfmt_misc(file_inode(file));
  777. s = misc->enabled ? "enabled\n" : "disabled\n";
  778. return simple_read_from_buffer(buf, nbytes, ppos, s, strlen(s));
  779. }
  780. static ssize_t bm_status_write(struct file *file, const char __user *buffer,
  781. size_t count, loff_t *ppos)
  782. {
  783. struct binfmt_misc *misc;
  784. int res = parse_command(buffer, count);
  785. Node *e, *next;
  786. struct inode *inode;
  787. misc = i_binfmt_misc(file_inode(file));
  788. switch (res) {
  789. case 1:
  790. /* Disable all handlers. */
  791. misc->enabled = false;
  792. break;
  793. case 2:
  794. /* Enable all handlers. */
  795. misc->enabled = true;
  796. break;
  797. case 3:
  798. /* Delete all handlers. */
  799. inode = d_inode(file_inode(file)->i_sb->s_root);
  800. inode_lock(inode);
  801. /*
  802. * In order to add new element or remove elements from the list
  803. * via bm_{entry,register,status}_write() inode_lock() on the
  804. * root inode must be held.
  805. * The lock is exclusive ensuring that the list can't be
  806. * modified. Only load_misc_binary() can access but does so
  807. * read-only. So we only need to take the write lock when we
  808. * actually remove the entry from the list.
  809. */
  810. list_for_each_entry_safe(e, next, &misc->entries, list)
  811. remove_binfmt_handler(misc, e);
  812. inode_unlock(inode);
  813. break;
  814. default:
  815. return res;
  816. }
  817. return count;
  818. }
  819. static const struct file_operations bm_status_operations = {
  820. .read = bm_status_read,
  821. .write = bm_status_write,
  822. .llseek = default_llseek,
  823. };
  824. /* Superblock handling */
  825. static void bm_put_super(struct super_block *sb)
  826. {
  827. struct user_namespace *user_ns = sb->s_fs_info;
  828. sb->s_fs_info = NULL;
  829. put_user_ns(user_ns);
  830. }
  831. static const struct super_operations s_ops = {
  832. .statfs = simple_statfs,
  833. .evict_inode = bm_evict_inode,
  834. .put_super = bm_put_super,
  835. };
  836. static int bm_fill_super(struct super_block *sb, struct fs_context *fc)
  837. {
  838. int err;
  839. struct user_namespace *user_ns = sb->s_user_ns;
  840. struct binfmt_misc *misc;
  841. static const struct tree_descr bm_files[] = {
  842. [2] = {"status", &bm_status_operations, S_IWUSR|S_IRUGO},
  843. [3] = {"register", &bm_register_operations, S_IWUSR},
  844. /* last one */ {""}
  845. };
  846. if (WARN_ON(user_ns != current_user_ns()))
  847. return -EINVAL;
  848. /*
  849. * Lazily allocate a new binfmt_misc instance for this namespace, i.e.
  850. * do it here during the first mount of binfmt_misc. We don't need to
  851. * waste memory for every user namespace allocation. It's likely much
  852. * more common to not mount a separate binfmt_misc instance than it is
  853. * to mount one.
  854. *
  855. * While multiple superblocks can exist they are keyed by userns in
  856. * s_fs_info for binfmt_misc. Hence, the vfs guarantees that
  857. * bm_fill_super() is called exactly once whenever a binfmt_misc
  858. * superblock for a userns is created. This in turn lets us conclude
  859. * that when a binfmt_misc superblock is created for the first time for
  860. * a userns there's no one racing us. Therefore we don't need any
  861. * barriers when we dereference binfmt_misc.
  862. */
  863. misc = user_ns->binfmt_misc;
  864. if (!misc) {
  865. /*
  866. * If it turns out that most user namespaces actually want to
  867. * register their own binary type handler and therefore all
  868. * create their own separate binfm_misc mounts we should
  869. * consider turning this into a kmem cache.
  870. */
  871. misc = kzalloc(sizeof(struct binfmt_misc), GFP_KERNEL);
  872. if (!misc)
  873. return -ENOMEM;
  874. INIT_LIST_HEAD(&misc->entries);
  875. rwlock_init(&misc->entries_lock);
  876. /* Pairs with smp_load_acquire() in load_binfmt_misc(). */
  877. smp_store_release(&user_ns->binfmt_misc, misc);
  878. }
  879. /*
  880. * When the binfmt_misc superblock for this userns is shutdown
  881. * ->enabled might have been set to false and we don't reinitialize
  882. * ->enabled again in put_super() as someone might already be mounting
  883. * binfmt_misc again. It also would be pointless since by the time
  884. * ->put_super() is called we know that the binary type list for this
  885. * bintfmt_misc mount is empty making load_misc_binary() return
  886. * -ENOEXEC independent of whether ->enabled is true. Instead, if
  887. * someone mounts binfmt_misc for the first time or again we simply
  888. * reset ->enabled to true.
  889. */
  890. misc->enabled = true;
  891. err = simple_fill_super(sb, BINFMTFS_MAGIC, bm_files);
  892. if (!err)
  893. sb->s_op = &s_ops;
  894. return err;
  895. }
  896. static void bm_free(struct fs_context *fc)
  897. {
  898. if (fc->s_fs_info)
  899. put_user_ns(fc->s_fs_info);
  900. }
  901. static int bm_get_tree(struct fs_context *fc)
  902. {
  903. return get_tree_keyed(fc, bm_fill_super, get_user_ns(fc->user_ns));
  904. }
  905. static const struct fs_context_operations bm_context_ops = {
  906. .free = bm_free,
  907. .get_tree = bm_get_tree,
  908. };
  909. static int bm_init_fs_context(struct fs_context *fc)
  910. {
  911. fc->ops = &bm_context_ops;
  912. return 0;
  913. }
  914. static struct linux_binfmt misc_format = {
  915. .module = THIS_MODULE,
  916. .load_binary = load_misc_binary,
  917. };
  918. static struct file_system_type bm_fs_type = {
  919. .owner = THIS_MODULE,
  920. .name = "binfmt_misc",
  921. .init_fs_context = bm_init_fs_context,
  922. .fs_flags = FS_USERNS_MOUNT,
  923. .kill_sb = kill_litter_super,
  924. };
  925. MODULE_ALIAS_FS("binfmt_misc");
  926. static int __init init_misc_binfmt(void)
  927. {
  928. int err = register_filesystem(&bm_fs_type);
  929. if (!err)
  930. insert_binfmt(&misc_format);
  931. return err;
  932. }
  933. static void __exit exit_misc_binfmt(void)
  934. {
  935. unregister_binfmt(&misc_format);
  936. unregister_filesystem(&bm_fs_type);
  937. }
  938. core_initcall(init_misc_binfmt);
  939. module_exit(exit_misc_binfmt);
  940. MODULE_DESCRIPTION("Kernel support for miscellaneous binaries");
  941. MODULE_LICENSE("GPL");