binfmt_misc.c 25 KB

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