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