xref: /openbmc/linux/kernel/umh.c (revision 74be2d3b)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * umh - the kernel usermode helper
4  */
5 #include <linux/module.h>
6 #include <linux/sched.h>
7 #include <linux/sched/task.h>
8 #include <linux/binfmts.h>
9 #include <linux/syscalls.h>
10 #include <linux/unistd.h>
11 #include <linux/kmod.h>
12 #include <linux/slab.h>
13 #include <linux/completion.h>
14 #include <linux/cred.h>
15 #include <linux/file.h>
16 #include <linux/fdtable.h>
17 #include <linux/workqueue.h>
18 #include <linux/security.h>
19 #include <linux/mount.h>
20 #include <linux/kernel.h>
21 #include <linux/init.h>
22 #include <linux/resource.h>
23 #include <linux/notifier.h>
24 #include <linux/suspend.h>
25 #include <linux/rwsem.h>
26 #include <linux/ptrace.h>
27 #include <linux/async.h>
28 #include <linux/uaccess.h>
29 
30 #include <trace/events/module.h>
31 
32 #define CAP_BSET	(void *)1
33 #define CAP_PI		(void *)2
34 
35 static kernel_cap_t usermodehelper_bset = CAP_FULL_SET;
36 static kernel_cap_t usermodehelper_inheritable = CAP_FULL_SET;
37 static DEFINE_SPINLOCK(umh_sysctl_lock);
38 static DECLARE_RWSEM(umhelper_sem);
39 
40 static void call_usermodehelper_freeinfo(struct subprocess_info *info)
41 {
42 	if (info->cleanup)
43 		(*info->cleanup)(info);
44 	kfree(info);
45 }
46 
47 static void umh_complete(struct subprocess_info *sub_info)
48 {
49 	struct completion *comp = xchg(&sub_info->complete, NULL);
50 	/*
51 	 * See call_usermodehelper_exec(). If xchg() returns NULL
52 	 * we own sub_info, the UMH_KILLABLE caller has gone away
53 	 * or the caller used UMH_NO_WAIT.
54 	 */
55 	if (comp)
56 		complete(comp);
57 	else
58 		call_usermodehelper_freeinfo(sub_info);
59 }
60 
61 /*
62  * This is the task which runs the usermode application
63  */
64 static int call_usermodehelper_exec_async(void *data)
65 {
66 	struct subprocess_info *sub_info = data;
67 	struct cred *new;
68 	int retval;
69 
70 	spin_lock_irq(&current->sighand->siglock);
71 	flush_signal_handlers(current, 1);
72 	spin_unlock_irq(&current->sighand->siglock);
73 
74 	/*
75 	 * Our parent (unbound workqueue) runs with elevated scheduling
76 	 * priority. Avoid propagating that into the userspace child.
77 	 */
78 	set_user_nice(current, 0);
79 
80 	retval = -ENOMEM;
81 	new = prepare_kernel_cred(current);
82 	if (!new)
83 		goto out;
84 
85 	spin_lock(&umh_sysctl_lock);
86 	new->cap_bset = cap_intersect(usermodehelper_bset, new->cap_bset);
87 	new->cap_inheritable = cap_intersect(usermodehelper_inheritable,
88 					     new->cap_inheritable);
89 	spin_unlock(&umh_sysctl_lock);
90 
91 	if (sub_info->init) {
92 		retval = sub_info->init(sub_info, new);
93 		if (retval) {
94 			abort_creds(new);
95 			goto out;
96 		}
97 	}
98 
99 	commit_creds(new);
100 
101 	if (sub_info->file)
102 		retval = do_execve_file(sub_info->file,
103 					sub_info->argv, sub_info->envp);
104 	else
105 		retval = do_execve(getname_kernel(sub_info->path),
106 				   (const char __user *const __user *)sub_info->argv,
107 				   (const char __user *const __user *)sub_info->envp);
108 out:
109 	sub_info->retval = retval;
110 	/*
111 	 * call_usermodehelper_exec_sync() will call umh_complete
112 	 * if UHM_WAIT_PROC.
113 	 */
114 	if (!(sub_info->wait & UMH_WAIT_PROC))
115 		umh_complete(sub_info);
116 	if (!retval)
117 		return 0;
118 	do_exit(0);
119 }
120 
121 /* Handles UMH_WAIT_PROC.  */
122 static void call_usermodehelper_exec_sync(struct subprocess_info *sub_info)
123 {
124 	pid_t pid;
125 
126 	/* If SIGCLD is ignored kernel_wait4 won't populate the status. */
127 	kernel_sigaction(SIGCHLD, SIG_DFL);
128 	pid = kernel_thread(call_usermodehelper_exec_async, sub_info, SIGCHLD);
129 	if (pid < 0) {
130 		sub_info->retval = pid;
131 	} else {
132 		int ret = -ECHILD;
133 		/*
134 		 * Normally it is bogus to call wait4() from in-kernel because
135 		 * wait4() wants to write the exit code to a userspace address.
136 		 * But call_usermodehelper_exec_sync() always runs as kernel
137 		 * thread (workqueue) and put_user() to a kernel address works
138 		 * OK for kernel threads, due to their having an mm_segment_t
139 		 * which spans the entire address space.
140 		 *
141 		 * Thus the __user pointer cast is valid here.
142 		 */
143 		kernel_wait4(pid, (int __user *)&ret, 0, NULL);
144 
145 		/*
146 		 * If ret is 0, either call_usermodehelper_exec_async failed and
147 		 * the real error code is already in sub_info->retval or
148 		 * sub_info->retval is 0 anyway, so don't mess with it then.
149 		 */
150 		if (ret)
151 			sub_info->retval = ret;
152 	}
153 
154 	/* Restore default kernel sig handler */
155 	kernel_sigaction(SIGCHLD, SIG_IGN);
156 
157 	umh_complete(sub_info);
158 }
159 
160 /*
161  * We need to create the usermodehelper kernel thread from a task that is affine
162  * to an optimized set of CPUs (or nohz housekeeping ones) such that they
163  * inherit a widest affinity irrespective of call_usermodehelper() callers with
164  * possibly reduced affinity (eg: per-cpu workqueues). We don't want
165  * usermodehelper targets to contend a busy CPU.
166  *
167  * Unbound workqueues provide such wide affinity and allow to block on
168  * UMH_WAIT_PROC requests without blocking pending request (up to some limit).
169  *
170  * Besides, workqueues provide the privilege level that caller might not have
171  * to perform the usermodehelper request.
172  *
173  */
174 static void call_usermodehelper_exec_work(struct work_struct *work)
175 {
176 	struct subprocess_info *sub_info =
177 		container_of(work, struct subprocess_info, work);
178 
179 	if (sub_info->wait & UMH_WAIT_PROC) {
180 		call_usermodehelper_exec_sync(sub_info);
181 	} else {
182 		pid_t pid;
183 		/*
184 		 * Use CLONE_PARENT to reparent it to kthreadd; we do not
185 		 * want to pollute current->children, and we need a parent
186 		 * that always ignores SIGCHLD to ensure auto-reaping.
187 		 */
188 		pid = kernel_thread(call_usermodehelper_exec_async, sub_info,
189 				    CLONE_PARENT | SIGCHLD);
190 		if (pid < 0) {
191 			sub_info->retval = pid;
192 			umh_complete(sub_info);
193 		}
194 	}
195 }
196 
197 /*
198  * If set, call_usermodehelper_exec() will exit immediately returning -EBUSY
199  * (used for preventing user land processes from being created after the user
200  * land has been frozen during a system-wide hibernation or suspend operation).
201  * Should always be manipulated under umhelper_sem acquired for write.
202  */
203 static enum umh_disable_depth usermodehelper_disabled = UMH_DISABLED;
204 
205 /* Number of helpers running */
206 static atomic_t running_helpers = ATOMIC_INIT(0);
207 
208 /*
209  * Wait queue head used by usermodehelper_disable() to wait for all running
210  * helpers to finish.
211  */
212 static DECLARE_WAIT_QUEUE_HEAD(running_helpers_waitq);
213 
214 /*
215  * Used by usermodehelper_read_lock_wait() to wait for usermodehelper_disabled
216  * to become 'false'.
217  */
218 static DECLARE_WAIT_QUEUE_HEAD(usermodehelper_disabled_waitq);
219 
220 /*
221  * Time to wait for running_helpers to become zero before the setting of
222  * usermodehelper_disabled in usermodehelper_disable() fails
223  */
224 #define RUNNING_HELPERS_TIMEOUT	(5 * HZ)
225 
226 int usermodehelper_read_trylock(void)
227 {
228 	DEFINE_WAIT(wait);
229 	int ret = 0;
230 
231 	down_read(&umhelper_sem);
232 	for (;;) {
233 		prepare_to_wait(&usermodehelper_disabled_waitq, &wait,
234 				TASK_INTERRUPTIBLE);
235 		if (!usermodehelper_disabled)
236 			break;
237 
238 		if (usermodehelper_disabled == UMH_DISABLED)
239 			ret = -EAGAIN;
240 
241 		up_read(&umhelper_sem);
242 
243 		if (ret)
244 			break;
245 
246 		schedule();
247 		try_to_freeze();
248 
249 		down_read(&umhelper_sem);
250 	}
251 	finish_wait(&usermodehelper_disabled_waitq, &wait);
252 	return ret;
253 }
254 EXPORT_SYMBOL_GPL(usermodehelper_read_trylock);
255 
256 long usermodehelper_read_lock_wait(long timeout)
257 {
258 	DEFINE_WAIT(wait);
259 
260 	if (timeout < 0)
261 		return -EINVAL;
262 
263 	down_read(&umhelper_sem);
264 	for (;;) {
265 		prepare_to_wait(&usermodehelper_disabled_waitq, &wait,
266 				TASK_UNINTERRUPTIBLE);
267 		if (!usermodehelper_disabled)
268 			break;
269 
270 		up_read(&umhelper_sem);
271 
272 		timeout = schedule_timeout(timeout);
273 		if (!timeout)
274 			break;
275 
276 		down_read(&umhelper_sem);
277 	}
278 	finish_wait(&usermodehelper_disabled_waitq, &wait);
279 	return timeout;
280 }
281 EXPORT_SYMBOL_GPL(usermodehelper_read_lock_wait);
282 
283 void usermodehelper_read_unlock(void)
284 {
285 	up_read(&umhelper_sem);
286 }
287 EXPORT_SYMBOL_GPL(usermodehelper_read_unlock);
288 
289 /**
290  * __usermodehelper_set_disable_depth - Modify usermodehelper_disabled.
291  * @depth: New value to assign to usermodehelper_disabled.
292  *
293  * Change the value of usermodehelper_disabled (under umhelper_sem locked for
294  * writing) and wakeup tasks waiting for it to change.
295  */
296 void __usermodehelper_set_disable_depth(enum umh_disable_depth depth)
297 {
298 	down_write(&umhelper_sem);
299 	usermodehelper_disabled = depth;
300 	wake_up(&usermodehelper_disabled_waitq);
301 	up_write(&umhelper_sem);
302 }
303 
304 /**
305  * __usermodehelper_disable - Prevent new helpers from being started.
306  * @depth: New value to assign to usermodehelper_disabled.
307  *
308  * Set usermodehelper_disabled to @depth and wait for running helpers to exit.
309  */
310 int __usermodehelper_disable(enum umh_disable_depth depth)
311 {
312 	long retval;
313 
314 	if (!depth)
315 		return -EINVAL;
316 
317 	down_write(&umhelper_sem);
318 	usermodehelper_disabled = depth;
319 	up_write(&umhelper_sem);
320 
321 	/*
322 	 * From now on call_usermodehelper_exec() won't start any new
323 	 * helpers, so it is sufficient if running_helpers turns out to
324 	 * be zero at one point (it may be increased later, but that
325 	 * doesn't matter).
326 	 */
327 	retval = wait_event_timeout(running_helpers_waitq,
328 					atomic_read(&running_helpers) == 0,
329 					RUNNING_HELPERS_TIMEOUT);
330 	if (retval)
331 		return 0;
332 
333 	__usermodehelper_set_disable_depth(UMH_ENABLED);
334 	return -EAGAIN;
335 }
336 
337 static void helper_lock(void)
338 {
339 	atomic_inc(&running_helpers);
340 	smp_mb__after_atomic();
341 }
342 
343 static void helper_unlock(void)
344 {
345 	if (atomic_dec_and_test(&running_helpers))
346 		wake_up(&running_helpers_waitq);
347 }
348 
349 /**
350  * call_usermodehelper_setup - prepare to call a usermode helper
351  * @path: path to usermode executable
352  * @argv: arg vector for process
353  * @envp: environment for process
354  * @gfp_mask: gfp mask for memory allocation
355  * @cleanup: a cleanup function
356  * @init: an init function
357  * @data: arbitrary context sensitive data
358  *
359  * Returns either %NULL on allocation failure, or a subprocess_info
360  * structure.  This should be passed to call_usermodehelper_exec to
361  * exec the process and free the structure.
362  *
363  * The init function is used to customize the helper process prior to
364  * exec.  A non-zero return code causes the process to error out, exit,
365  * and return the failure to the calling process
366  *
367  * The cleanup function is just before ethe subprocess_info is about to
368  * be freed.  This can be used for freeing the argv and envp.  The
369  * Function must be runnable in either a process context or the
370  * context in which call_usermodehelper_exec is called.
371  */
372 struct subprocess_info *call_usermodehelper_setup(const char *path, char **argv,
373 		char **envp, gfp_t gfp_mask,
374 		int (*init)(struct subprocess_info *info, struct cred *new),
375 		void (*cleanup)(struct subprocess_info *info),
376 		void *data)
377 {
378 	struct subprocess_info *sub_info;
379 	sub_info = kzalloc(sizeof(struct subprocess_info), gfp_mask);
380 	if (!sub_info)
381 		goto out;
382 
383 	INIT_WORK(&sub_info->work, call_usermodehelper_exec_work);
384 
385 #ifdef CONFIG_STATIC_USERMODEHELPER
386 	sub_info->path = CONFIG_STATIC_USERMODEHELPER_PATH;
387 #else
388 	sub_info->path = path;
389 #endif
390 	sub_info->argv = argv;
391 	sub_info->envp = envp;
392 
393 	sub_info->cleanup = cleanup;
394 	sub_info->init = init;
395 	sub_info->data = data;
396   out:
397 	return sub_info;
398 }
399 EXPORT_SYMBOL(call_usermodehelper_setup);
400 
401 /**
402  * call_usermodehelper_exec - start a usermode application
403  * @sub_info: information about the subprocessa
404  * @wait: wait for the application to finish and return status.
405  *        when UMH_NO_WAIT don't wait at all, but you get no useful error back
406  *        when the program couldn't be exec'ed. This makes it safe to call
407  *        from interrupt context.
408  *
409  * Runs a user-space application.  The application is started
410  * asynchronously if wait is not set, and runs as a child of system workqueues.
411  * (ie. it runs with full root capabilities and optimized affinity).
412  *
413  * Note: successful return value does not guarantee the helper was called at
414  * all. You can't rely on sub_info->{init,cleanup} being called even for
415  * UMH_WAIT_* wait modes as STATIC_USERMODEHELPER_PATH="" turns all helpers
416  * into a successful no-op.
417  */
418 int call_usermodehelper_exec(struct subprocess_info *sub_info, int wait)
419 {
420 	DECLARE_COMPLETION_ONSTACK(done);
421 	int retval = 0;
422 
423 	if (!sub_info->path) {
424 		call_usermodehelper_freeinfo(sub_info);
425 		return -EINVAL;
426 	}
427 	helper_lock();
428 	if (usermodehelper_disabled) {
429 		retval = -EBUSY;
430 		goto out;
431 	}
432 
433 	/*
434 	 * If there is no binary for us to call, then just return and get out of
435 	 * here.  This allows us to set STATIC_USERMODEHELPER_PATH to "" and
436 	 * disable all call_usermodehelper() calls.
437 	 */
438 	if (strlen(sub_info->path) == 0)
439 		goto out;
440 
441 	/*
442 	 * Set the completion pointer only if there is a waiter.
443 	 * This makes it possible to use umh_complete to free
444 	 * the data structure in case of UMH_NO_WAIT.
445 	 */
446 	sub_info->complete = (wait == UMH_NO_WAIT) ? NULL : &done;
447 	sub_info->wait = wait;
448 
449 	queue_work(system_unbound_wq, &sub_info->work);
450 	if (wait == UMH_NO_WAIT)	/* task has freed sub_info */
451 		goto unlock;
452 
453 	if (wait & UMH_KILLABLE) {
454 		retval = wait_for_completion_killable(&done);
455 		if (!retval)
456 			goto wait_done;
457 
458 		/* umh_complete() will see NULL and free sub_info */
459 		if (xchg(&sub_info->complete, NULL))
460 			goto unlock;
461 		/* fallthrough, umh_complete() was already called */
462 	}
463 
464 	wait_for_completion(&done);
465 wait_done:
466 	retval = sub_info->retval;
467 out:
468 	call_usermodehelper_freeinfo(sub_info);
469 unlock:
470 	helper_unlock();
471 	return retval;
472 }
473 EXPORT_SYMBOL(call_usermodehelper_exec);
474 
475 /**
476  * call_usermodehelper() - prepare and start a usermode application
477  * @path: path to usermode executable
478  * @argv: arg vector for process
479  * @envp: environment for process
480  * @wait: wait for the application to finish and return status.
481  *        when UMH_NO_WAIT don't wait at all, but you get no useful error back
482  *        when the program couldn't be exec'ed. This makes it safe to call
483  *        from interrupt context.
484  *
485  * This function is the equivalent to use call_usermodehelper_setup() and
486  * call_usermodehelper_exec().
487  */
488 int call_usermodehelper(const char *path, char **argv, char **envp, int wait)
489 {
490 	struct subprocess_info *info;
491 	gfp_t gfp_mask = (wait == UMH_NO_WAIT) ? GFP_ATOMIC : GFP_KERNEL;
492 
493 	info = call_usermodehelper_setup(path, argv, envp, gfp_mask,
494 					 NULL, NULL, NULL);
495 	if (info == NULL)
496 		return -ENOMEM;
497 
498 	return call_usermodehelper_exec(info, wait);
499 }
500 EXPORT_SYMBOL(call_usermodehelper);
501 
502 static int proc_cap_handler(struct ctl_table *table, int write,
503 			 void *buffer, size_t *lenp, loff_t *ppos)
504 {
505 	struct ctl_table t;
506 	unsigned long cap_array[_KERNEL_CAPABILITY_U32S];
507 	kernel_cap_t new_cap;
508 	int err, i;
509 
510 	if (write && (!capable(CAP_SETPCAP) ||
511 		      !capable(CAP_SYS_MODULE)))
512 		return -EPERM;
513 
514 	/*
515 	 * convert from the global kernel_cap_t to the ulong array to print to
516 	 * userspace if this is a read.
517 	 */
518 	spin_lock(&umh_sysctl_lock);
519 	for (i = 0; i < _KERNEL_CAPABILITY_U32S; i++)  {
520 		if (table->data == CAP_BSET)
521 			cap_array[i] = usermodehelper_bset.cap[i];
522 		else if (table->data == CAP_PI)
523 			cap_array[i] = usermodehelper_inheritable.cap[i];
524 		else
525 			BUG();
526 	}
527 	spin_unlock(&umh_sysctl_lock);
528 
529 	t = *table;
530 	t.data = &cap_array;
531 
532 	/*
533 	 * actually read or write and array of ulongs from userspace.  Remember
534 	 * these are least significant 32 bits first
535 	 */
536 	err = proc_doulongvec_minmax(&t, write, buffer, lenp, ppos);
537 	if (err < 0)
538 		return err;
539 
540 	/*
541 	 * convert from the sysctl array of ulongs to the kernel_cap_t
542 	 * internal representation
543 	 */
544 	for (i = 0; i < _KERNEL_CAPABILITY_U32S; i++)
545 		new_cap.cap[i] = cap_array[i];
546 
547 	/*
548 	 * Drop everything not in the new_cap (but don't add things)
549 	 */
550 	if (write) {
551 		spin_lock(&umh_sysctl_lock);
552 		if (table->data == CAP_BSET)
553 			usermodehelper_bset = cap_intersect(usermodehelper_bset, new_cap);
554 		if (table->data == CAP_PI)
555 			usermodehelper_inheritable = cap_intersect(usermodehelper_inheritable, new_cap);
556 		spin_unlock(&umh_sysctl_lock);
557 	}
558 
559 	return 0;
560 }
561 
562 struct ctl_table usermodehelper_table[] = {
563 	{
564 		.procname	= "bset",
565 		.data		= CAP_BSET,
566 		.maxlen		= _KERNEL_CAPABILITY_U32S * sizeof(unsigned long),
567 		.mode		= 0600,
568 		.proc_handler	= proc_cap_handler,
569 	},
570 	{
571 		.procname	= "inheritable",
572 		.data		= CAP_PI,
573 		.maxlen		= _KERNEL_CAPABILITY_U32S * sizeof(unsigned long),
574 		.mode		= 0600,
575 		.proc_handler	= proc_cap_handler,
576 	},
577 	{ }
578 };
579