1/*
2 * binfmt_misc.c
3 *
4 * Copyright (C) 1997 Richard G��nther
5 *
6 * binfmt_misc detects binaries via a magic or filename extension and invokes
7 * a specified wrapper. See Documentation/binfmt_misc.txt for more details.
8 */
9
10#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
11
12#include <linux/kernel.h>
13#include <linux/module.h>
14#include <linux/init.h>
15#include <linux/sched.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/syscalls.h>
26#include <linux/fs.h>
27#include <linux/uaccess.h>
28
29#ifdef DEBUG
30# define USE_DEBUG 1
31#else
32# define USE_DEBUG 0
33#endif
34
35enum {
36	VERBOSE_STATUS = 1 /* make it zero to save 400 bytes kernel memory */
37};
38
39static LIST_HEAD(entries);
40static int enabled = 1;
41
42enum {Enabled, Magic};
43#define MISC_FMT_PRESERVE_ARGV0 (1 << 31)
44#define MISC_FMT_OPEN_BINARY (1 << 30)
45#define MISC_FMT_CREDENTIALS (1 << 29)
46
47typedef struct {
48	struct list_head list;
49	unsigned long flags;		/* type, status, etc. */
50	int offset;			/* offset of magic */
51	int size;			/* size of magic/mask */
52	char *magic;			/* magic or filename extension */
53	char *mask;			/* mask, NULL for exact match */
54	char *interpreter;		/* filename of interpreter */
55	char *name;
56	struct dentry *dentry;
57} Node;
58
59static DEFINE_RWLOCK(entries_lock);
60static struct file_system_type bm_fs_type;
61static struct vfsmount *bm_mnt;
62static int entry_count;
63
64/*
65 * Max length of the register string.  Determined by:
66 *  - 7 delimiters
67 *  - name:   ~50 bytes
68 *  - type:   1 byte
69 *  - offset: 3 bytes (has to be smaller than BINPRM_BUF_SIZE)
70 *  - magic:  128 bytes (512 in escaped form)
71 *  - mask:   128 bytes (512 in escaped form)
72 *  - interp: ~50 bytes
73 *  - flags:  5 bytes
74 * Round that up a bit, and then back off to hold the internal data
75 * (like struct Node).
76 */
77#define MAX_REGISTER_LENGTH 1920
78
79/*
80 * Check if we support the binfmt
81 * if we do, return the node, else NULL
82 * locking is done in load_misc_binary
83 */
84static Node *check_file(struct linux_binprm *bprm)
85{
86	char *p = strrchr(bprm->interp, '.');
87	struct list_head *l;
88
89	/* Walk all the registered handlers. */
90	list_for_each(l, &entries) {
91		Node *e = list_entry(l, Node, list);
92		char *s;
93		int j;
94
95		/* Make sure this one is currently enabled. */
96		if (!test_bit(Enabled, &e->flags))
97			continue;
98
99		/* Do matching based on extension if applicable. */
100		if (!test_bit(Magic, &e->flags)) {
101			if (p && !strcmp(e->magic, p + 1))
102				return e;
103			continue;
104		}
105
106		/* Do matching based on magic & mask. */
107		s = bprm->buf + e->offset;
108		if (e->mask) {
109			for (j = 0; j < e->size; j++)
110				if ((*s++ ^ e->magic[j]) & e->mask[j])
111					break;
112		} else {
113			for (j = 0; j < e->size; j++)
114				if ((*s++ ^ e->magic[j]))
115					break;
116		}
117		if (j == e->size)
118			return e;
119	}
120	return NULL;
121}
122
123/*
124 * the loader itself
125 */
126static int load_misc_binary(struct linux_binprm *bprm)
127{
128	Node *fmt;
129	struct file *interp_file = NULL;
130	char iname[BINPRM_BUF_SIZE];
131	const char *iname_addr = iname;
132	int retval;
133	int fd_binary = -1;
134
135	retval = -ENOEXEC;
136	if (!enabled)
137		goto ret;
138
139	/* to keep locking time low, we copy the interpreter string */
140	read_lock(&entries_lock);
141	fmt = check_file(bprm);
142	if (fmt)
143		strlcpy(iname, fmt->interpreter, BINPRM_BUF_SIZE);
144	read_unlock(&entries_lock);
145	if (!fmt)
146		goto ret;
147
148	/* Need to be able to load the file after exec */
149	if (bprm->interp_flags & BINPRM_FLAGS_PATH_INACCESSIBLE)
150		return -ENOENT;
151
152	if (!(fmt->flags & MISC_FMT_PRESERVE_ARGV0)) {
153		retval = remove_arg_zero(bprm);
154		if (retval)
155			goto ret;
156	}
157
158	if (fmt->flags & MISC_FMT_OPEN_BINARY) {
159
160		/* if the binary should be opened on behalf of the
161		 * interpreter than keep it open and assign descriptor
162		 * to it
163		 */
164		fd_binary = get_unused_fd_flags(0);
165		if (fd_binary < 0) {
166			retval = fd_binary;
167			goto ret;
168		}
169		fd_install(fd_binary, bprm->file);
170
171		/* if the binary is not readable than enforce mm->dumpable=0
172		   regardless of the interpreter's permissions */
173		would_dump(bprm, bprm->file);
174
175		allow_write_access(bprm->file);
176		bprm->file = NULL;
177
178		/* mark the bprm that fd should be passed to interp */
179		bprm->interp_flags |= BINPRM_FLAGS_EXECFD;
180		bprm->interp_data = fd_binary;
181
182	} else {
183		allow_write_access(bprm->file);
184		fput(bprm->file);
185		bprm->file = NULL;
186	}
187	/* make argv[1] be the path to the binary */
188	retval = copy_strings_kernel(1, &bprm->interp, bprm);
189	if (retval < 0)
190		goto error;
191	bprm->argc++;
192
193	/* add the interp as argv[0] */
194	retval = copy_strings_kernel(1, &iname_addr, bprm);
195	if (retval < 0)
196		goto error;
197	bprm->argc++;
198
199	/* Update interp in case binfmt_script needs it. */
200	retval = bprm_change_interp(iname, bprm);
201	if (retval < 0)
202		goto error;
203
204	interp_file = open_exec(iname);
205	retval = PTR_ERR(interp_file);
206	if (IS_ERR(interp_file))
207		goto error;
208
209	bprm->file = interp_file;
210	if (fmt->flags & MISC_FMT_CREDENTIALS) {
211		/*
212		 * No need to call prepare_binprm(), it's already been
213		 * done.  bprm->buf is stale, update from interp_file.
214		 */
215		memset(bprm->buf, 0, BINPRM_BUF_SIZE);
216		retval = kernel_read(bprm->file, 0, bprm->buf, BINPRM_BUF_SIZE);
217	} else
218		retval = prepare_binprm(bprm);
219
220	if (retval < 0)
221		goto error;
222
223	retval = search_binary_handler(bprm);
224	if (retval < 0)
225		goto error;
226
227ret:
228	return retval;
229error:
230	if (fd_binary > 0)
231		sys_close(fd_binary);
232	bprm->interp_flags = 0;
233	bprm->interp_data = 0;
234	goto ret;
235}
236
237/* Command parsers */
238
239/*
240 * parses and copies one argument enclosed in del from *sp to *dp,
241 * recognising the \x special.
242 * returns pointer to the copied argument or NULL in case of an
243 * error (and sets err) or null argument length.
244 */
245static char *scanarg(char *s, char del)
246{
247	char c;
248
249	while ((c = *s++) != del) {
250		if (c == '\\' && *s == 'x') {
251			s++;
252			if (!isxdigit(*s++))
253				return NULL;
254			if (!isxdigit(*s++))
255				return NULL;
256		}
257	}
258	s[-1] ='\0';
259	return s;
260}
261
262static char *check_special_flags(char *sfs, Node *e)
263{
264	char *p = sfs;
265	int cont = 1;
266
267	/* special flags */
268	while (cont) {
269		switch (*p) {
270		case 'P':
271			pr_debug("register: flag: P (preserve argv0)\n");
272			p++;
273			e->flags |= MISC_FMT_PRESERVE_ARGV0;
274			break;
275		case 'O':
276			pr_debug("register: flag: O (open binary)\n");
277			p++;
278			e->flags |= MISC_FMT_OPEN_BINARY;
279			break;
280		case 'C':
281			pr_debug("register: flag: C (preserve creds)\n");
282			p++;
283			/* this flags also implies the
284			   open-binary flag */
285			e->flags |= (MISC_FMT_CREDENTIALS |
286					MISC_FMT_OPEN_BINARY);
287			break;
288		default:
289			cont = 0;
290		}
291	}
292
293	return p;
294}
295
296/*
297 * This registers a new binary format, it recognises the syntax
298 * ':name:type:offset:magic:mask:interpreter:flags'
299 * where the ':' is the IFS, that can be chosen with the first char
300 */
301static Node *create_entry(const char __user *buffer, size_t count)
302{
303	Node *e;
304	int memsize, err;
305	char *buf, *p;
306	char del;
307
308	pr_debug("register: received %zu bytes\n", count);
309
310	/* some sanity checks */
311	err = -EINVAL;
312	if ((count < 11) || (count > MAX_REGISTER_LENGTH))
313		goto out;
314
315	err = -ENOMEM;
316	memsize = sizeof(Node) + count + 8;
317	e = kmalloc(memsize, GFP_KERNEL);
318	if (!e)
319		goto out;
320
321	p = buf = (char *)e + sizeof(Node);
322
323	memset(e, 0, sizeof(Node));
324	if (copy_from_user(buf, buffer, count))
325		goto efault;
326
327	del = *p++;	/* delimeter */
328
329	pr_debug("register: delim: %#x {%c}\n", del, del);
330
331	/* Pad the buffer with the delim to simplify parsing below. */
332	memset(buf + count, del, 8);
333
334	/* Parse the 'name' field. */
335	e->name = p;
336	p = strchr(p, del);
337	if (!p)
338		goto einval;
339	*p++ = '\0';
340	if (!e->name[0] ||
341	    !strcmp(e->name, ".") ||
342	    !strcmp(e->name, "..") ||
343	    strchr(e->name, '/'))
344		goto einval;
345
346	pr_debug("register: name: {%s}\n", e->name);
347
348	/* Parse the 'type' field. */
349	switch (*p++) {
350	case 'E':
351		pr_debug("register: type: E (extension)\n");
352		e->flags = 1 << Enabled;
353		break;
354	case 'M':
355		pr_debug("register: type: M (magic)\n");
356		e->flags = (1 << Enabled) | (1 << Magic);
357		break;
358	default:
359		goto einval;
360	}
361	if (*p++ != del)
362		goto einval;
363
364	if (test_bit(Magic, &e->flags)) {
365		/* Handle the 'M' (magic) format. */
366		char *s;
367
368		/* Parse the 'offset' field. */
369		s = strchr(p, del);
370		if (!s)
371			goto einval;
372		*s++ = '\0';
373		e->offset = simple_strtoul(p, &p, 10);
374		if (*p++)
375			goto einval;
376		pr_debug("register: offset: %#x\n", e->offset);
377
378		/* Parse the 'magic' field. */
379		e->magic = p;
380		p = scanarg(p, del);
381		if (!p)
382			goto einval;
383		if (!e->magic[0])
384			goto einval;
385		if (USE_DEBUG)
386			print_hex_dump_bytes(
387				KBUILD_MODNAME ": register: magic[raw]: ",
388				DUMP_PREFIX_NONE, e->magic, p - e->magic);
389
390		/* Parse the 'mask' field. */
391		e->mask = p;
392		p = scanarg(p, del);
393		if (!p)
394			goto einval;
395		if (!e->mask[0]) {
396			e->mask = NULL;
397			pr_debug("register:  mask[raw]: none\n");
398		} else if (USE_DEBUG)
399			print_hex_dump_bytes(
400				KBUILD_MODNAME ": register:  mask[raw]: ",
401				DUMP_PREFIX_NONE, e->mask, p - e->mask);
402
403		/*
404		 * Decode the magic & mask fields.
405		 * Note: while we might have accepted embedded NUL bytes from
406		 * above, the unescape helpers here will stop at the first one
407		 * it encounters.
408		 */
409		e->size = string_unescape_inplace(e->magic, UNESCAPE_HEX);
410		if (e->mask &&
411		    string_unescape_inplace(e->mask, UNESCAPE_HEX) != e->size)
412			goto einval;
413		if (e->size + e->offset > BINPRM_BUF_SIZE)
414			goto einval;
415		pr_debug("register: magic/mask length: %i\n", e->size);
416		if (USE_DEBUG) {
417			print_hex_dump_bytes(
418				KBUILD_MODNAME ": register: magic[decoded]: ",
419				DUMP_PREFIX_NONE, e->magic, e->size);
420
421			if (e->mask) {
422				int i;
423				char *masked = kmalloc(e->size, GFP_KERNEL);
424
425				print_hex_dump_bytes(
426					KBUILD_MODNAME ": register:  mask[decoded]: ",
427					DUMP_PREFIX_NONE, e->mask, e->size);
428
429				if (masked) {
430					for (i = 0; i < e->size; ++i)
431						masked[i] = e->magic[i] & e->mask[i];
432					print_hex_dump_bytes(
433						KBUILD_MODNAME ": register:  magic[masked]: ",
434						DUMP_PREFIX_NONE, masked, e->size);
435
436					kfree(masked);
437				}
438			}
439		}
440	} else {
441		/* Handle the 'E' (extension) format. */
442
443		/* Skip the 'offset' field. */
444		p = strchr(p, del);
445		if (!p)
446			goto einval;
447		*p++ = '\0';
448
449		/* Parse the 'magic' field. */
450		e->magic = p;
451		p = strchr(p, del);
452		if (!p)
453			goto einval;
454		*p++ = '\0';
455		if (!e->magic[0] || strchr(e->magic, '/'))
456			goto einval;
457		pr_debug("register: extension: {%s}\n", e->magic);
458
459		/* Skip the 'mask' field. */
460		p = strchr(p, del);
461		if (!p)
462			goto einval;
463		*p++ = '\0';
464	}
465
466	/* Parse the 'interpreter' field. */
467	e->interpreter = p;
468	p = strchr(p, del);
469	if (!p)
470		goto einval;
471	*p++ = '\0';
472	if (!e->interpreter[0])
473		goto einval;
474	pr_debug("register: interpreter: {%s}\n", e->interpreter);
475
476	/* Parse the 'flags' field. */
477	p = check_special_flags(p, e);
478	if (*p == '\n')
479		p++;
480	if (p != buf + count)
481		goto einval;
482
483	return e;
484
485out:
486	return ERR_PTR(err);
487
488efault:
489	kfree(e);
490	return ERR_PTR(-EFAULT);
491einval:
492	kfree(e);
493	return ERR_PTR(-EINVAL);
494}
495
496/*
497 * Set status of entry/binfmt_misc:
498 * '1' enables, '0' disables and '-1' clears entry/binfmt_misc
499 */
500static int parse_command(const char __user *buffer, size_t count)
501{
502	char s[4];
503
504	if (count > 3)
505		return -EINVAL;
506	if (copy_from_user(s, buffer, count))
507		return -EFAULT;
508	if (!count)
509		return 0;
510	if (s[count - 1] == '\n')
511		count--;
512	if (count == 1 && s[0] == '0')
513		return 1;
514	if (count == 1 && s[0] == '1')
515		return 2;
516	if (count == 2 && s[0] == '-' && s[1] == '1')
517		return 3;
518	return -EINVAL;
519}
520
521/* generic stuff */
522
523static void entry_status(Node *e, char *page)
524{
525	char *dp = page;
526	const char *status = "disabled";
527
528	if (test_bit(Enabled, &e->flags))
529		status = "enabled";
530
531	if (!VERBOSE_STATUS) {
532		sprintf(page, "%s\n", status);
533		return;
534	}
535
536	dp += sprintf(dp, "%s\ninterpreter %s\n", status, e->interpreter);
537
538	/* print the special flags */
539	dp += sprintf(dp, "flags: ");
540	if (e->flags & MISC_FMT_PRESERVE_ARGV0)
541		*dp++ = 'P';
542	if (e->flags & MISC_FMT_OPEN_BINARY)
543		*dp++ = 'O';
544	if (e->flags & MISC_FMT_CREDENTIALS)
545		*dp++ = 'C';
546	*dp++ = '\n';
547
548	if (!test_bit(Magic, &e->flags)) {
549		sprintf(dp, "extension .%s\n", e->magic);
550	} else {
551		dp += sprintf(dp, "offset %i\nmagic ", e->offset);
552		dp = bin2hex(dp, e->magic, e->size);
553		if (e->mask) {
554			dp += sprintf(dp, "\nmask ");
555			dp = bin2hex(dp, e->mask, e->size);
556		}
557		*dp++ = '\n';
558		*dp = '\0';
559	}
560}
561
562static struct inode *bm_get_inode(struct super_block *sb, int mode)
563{
564	struct inode *inode = new_inode(sb);
565
566	if (inode) {
567		inode->i_ino = get_next_ino();
568		inode->i_mode = mode;
569		inode->i_atime = inode->i_mtime = inode->i_ctime =
570			current_fs_time(inode->i_sb);
571	}
572	return inode;
573}
574
575static void bm_evict_inode(struct inode *inode)
576{
577	clear_inode(inode);
578	kfree(inode->i_private);
579}
580
581static void kill_node(Node *e)
582{
583	struct dentry *dentry;
584
585	write_lock(&entries_lock);
586	dentry = e->dentry;
587	if (dentry) {
588		list_del_init(&e->list);
589		e->dentry = NULL;
590	}
591	write_unlock(&entries_lock);
592
593	if (dentry) {
594		drop_nlink(d_inode(dentry));
595		d_drop(dentry);
596		dput(dentry);
597		simple_release_fs(&bm_mnt, &entry_count);
598	}
599}
600
601/* /<entry> */
602
603static ssize_t
604bm_entry_read(struct file *file, char __user *buf, size_t nbytes, loff_t *ppos)
605{
606	Node *e = file_inode(file)->i_private;
607	ssize_t res;
608	char *page;
609
610	page = (char *) __get_free_page(GFP_KERNEL);
611	if (!page)
612		return -ENOMEM;
613
614	entry_status(e, page);
615
616	res = simple_read_from_buffer(buf, nbytes, ppos, page, strlen(page));
617
618	free_page((unsigned long) page);
619	return res;
620}
621
622static ssize_t bm_entry_write(struct file *file, const char __user *buffer,
623				size_t count, loff_t *ppos)
624{
625	struct dentry *root;
626	Node *e = file_inode(file)->i_private;
627	int res = parse_command(buffer, count);
628
629	switch (res) {
630	case 1:
631		/* Disable this handler. */
632		clear_bit(Enabled, &e->flags);
633		break;
634	case 2:
635		/* Enable this handler. */
636		set_bit(Enabled, &e->flags);
637		break;
638	case 3:
639		/* Delete this handler. */
640		root = dget(file->f_path.dentry->d_sb->s_root);
641		mutex_lock(&d_inode(root)->i_mutex);
642
643		kill_node(e);
644
645		mutex_unlock(&d_inode(root)->i_mutex);
646		dput(root);
647		break;
648	default:
649		return res;
650	}
651
652	return count;
653}
654
655static const struct file_operations bm_entry_operations = {
656	.read		= bm_entry_read,
657	.write		= bm_entry_write,
658	.llseek		= default_llseek,
659};
660
661/* /register */
662
663static ssize_t bm_register_write(struct file *file, const char __user *buffer,
664			       size_t count, loff_t *ppos)
665{
666	Node *e;
667	struct inode *inode;
668	struct dentry *root, *dentry;
669	struct super_block *sb = file->f_path.dentry->d_sb;
670	int err = 0;
671
672	e = create_entry(buffer, count);
673
674	if (IS_ERR(e))
675		return PTR_ERR(e);
676
677	root = dget(sb->s_root);
678	mutex_lock(&d_inode(root)->i_mutex);
679	dentry = lookup_one_len(e->name, root, strlen(e->name));
680	err = PTR_ERR(dentry);
681	if (IS_ERR(dentry))
682		goto out;
683
684	err = -EEXIST;
685	if (d_really_is_positive(dentry))
686		goto out2;
687
688	inode = bm_get_inode(sb, S_IFREG | 0644);
689
690	err = -ENOMEM;
691	if (!inode)
692		goto out2;
693
694	err = simple_pin_fs(&bm_fs_type, &bm_mnt, &entry_count);
695	if (err) {
696		iput(inode);
697		inode = NULL;
698		goto out2;
699	}
700
701	e->dentry = dget(dentry);
702	inode->i_private = e;
703	inode->i_fop = &bm_entry_operations;
704
705	d_instantiate(dentry, inode);
706	write_lock(&entries_lock);
707	list_add(&e->list, &entries);
708	write_unlock(&entries_lock);
709
710	err = 0;
711out2:
712	dput(dentry);
713out:
714	mutex_unlock(&d_inode(root)->i_mutex);
715	dput(root);
716
717	if (err) {
718		kfree(e);
719		return -EINVAL;
720	}
721	return count;
722}
723
724static const struct file_operations bm_register_operations = {
725	.write		= bm_register_write,
726	.llseek		= noop_llseek,
727};
728
729/* /status */
730
731static ssize_t
732bm_status_read(struct file *file, char __user *buf, size_t nbytes, loff_t *ppos)
733{
734	char *s = enabled ? "enabled\n" : "disabled\n";
735
736	return simple_read_from_buffer(buf, nbytes, ppos, s, strlen(s));
737}
738
739static ssize_t bm_status_write(struct file *file, const char __user *buffer,
740		size_t count, loff_t *ppos)
741{
742	int res = parse_command(buffer, count);
743	struct dentry *root;
744
745	switch (res) {
746	case 1:
747		/* Disable all handlers. */
748		enabled = 0;
749		break;
750	case 2:
751		/* Enable all handlers. */
752		enabled = 1;
753		break;
754	case 3:
755		/* Delete all handlers. */
756		root = dget(file->f_path.dentry->d_sb->s_root);
757		mutex_lock(&d_inode(root)->i_mutex);
758
759		while (!list_empty(&entries))
760			kill_node(list_entry(entries.next, Node, list));
761
762		mutex_unlock(&d_inode(root)->i_mutex);
763		dput(root);
764		break;
765	default:
766		return res;
767	}
768
769	return count;
770}
771
772static const struct file_operations bm_status_operations = {
773	.read		= bm_status_read,
774	.write		= bm_status_write,
775	.llseek		= default_llseek,
776};
777
778/* Superblock handling */
779
780static const struct super_operations s_ops = {
781	.statfs		= simple_statfs,
782	.evict_inode	= bm_evict_inode,
783};
784
785static int bm_fill_super(struct super_block *sb, void *data, int silent)
786{
787	int err;
788	static struct tree_descr bm_files[] = {
789		[2] = {"status", &bm_status_operations, S_IWUSR|S_IRUGO},
790		[3] = {"register", &bm_register_operations, S_IWUSR},
791		/* last one */ {""}
792	};
793
794	err = simple_fill_super(sb, BINFMTFS_MAGIC, bm_files);
795	if (!err)
796		sb->s_op = &s_ops;
797	return err;
798}
799
800static struct dentry *bm_mount(struct file_system_type *fs_type,
801	int flags, const char *dev_name, void *data)
802{
803	return mount_single(fs_type, flags, data, bm_fill_super);
804}
805
806static struct linux_binfmt misc_format = {
807	.module = THIS_MODULE,
808	.load_binary = load_misc_binary,
809};
810
811static struct file_system_type bm_fs_type = {
812	.owner		= THIS_MODULE,
813	.name		= "binfmt_misc",
814	.mount		= bm_mount,
815	.kill_sb	= kill_litter_super,
816};
817MODULE_ALIAS_FS("binfmt_misc");
818
819static int __init init_misc_binfmt(void)
820{
821	int err = register_filesystem(&bm_fs_type);
822	if (!err)
823		insert_binfmt(&misc_format);
824	return err;
825}
826
827static void __exit exit_misc_binfmt(void)
828{
829	unregister_binfmt(&misc_format);
830	unregister_filesystem(&bm_fs_type);
831}
832
833core_initcall(init_misc_binfmt);
834module_exit(exit_misc_binfmt);
835MODULE_LICENSE("GPL");
836